code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #ifdef USE_LWIPSOCK #include <lwip/netdb.h> #else #include <netdb.h> #endif #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #ifndef HAVE_SOCKET #error "We can't compile without socket() support!" #endif #include <limits.h> #ifdef USE_LIBIDN2 #include <idn2.h> #elif defined(USE_WIN32_IDN) /* prototype for curl_win32_idn_to_ascii() */ bool curl_win32_idn_to_ascii(const char *in, char **out); #endif /* USE_LIBIDN2 */ #include "urldata.h" #include "netrc.h" #include "formdata.h" #include "mime.h" #include "vtls/vtls.h" #include "hostip.h" #include "transfer.h" #include "sendf.h" #include "progress.h" #include "cookie.h" #include "strcase.h" #include "strerror.h" #include "escape.h" #include "strtok.h" #include "share.h" #include "content_encoding.h" #include "http_digest.h" #include "http_negotiate.h" #include "select.h" #include "multiif.h" #include "easyif.h" #include "speedcheck.h" #include "warnless.h" #include "non-ascii.h" #include "inet_pton.h" #include "getinfo.h" #include "urlapi-int.h" /* And now for the protocols */ #include "ftp.h" #include "dict.h" #include "telnet.h" #include "tftp.h" #include "http.h" #include "http2.h" #include "file.h" #include "curl_ldap.h" #include "ssh.h" #include "imap.h" #include "url.h" #include "connect.h" #include "inet_ntop.h" #include "http_ntlm.h" #include "socks.h" #include "curl_rtmp.h" #include "gopher.h" #include "http_proxy.h" #include "conncache.h" #include "multihandle.h" #include "dotdot.h" #include "strdup.h" #include "setopt.h" #include "altsvc.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" static void conn_free(struct connectdata *conn); static void free_idnconverted_hostname(struct hostname *host); static unsigned int get_protocol_family(unsigned int protocol); /* Some parts of the code (e.g. chunked encoding) assume this buffer has at * more than just a few bytes to play with. Don't let it become too small or * bad things will happen. */ #if READBUFFER_SIZE < READBUFFER_MIN # error READBUFFER_SIZE is too small #endif /* * Protocol table. */ static const struct Curl_handler * const protocols[] = { #ifndef CURL_DISABLE_HTTP &Curl_handler_http, #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) &Curl_handler_https, #endif #ifndef CURL_DISABLE_FTP &Curl_handler_ftp, #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) &Curl_handler_ftps, #endif #ifndef CURL_DISABLE_TELNET &Curl_handler_telnet, #endif #ifndef CURL_DISABLE_DICT &Curl_handler_dict, #endif #ifndef CURL_DISABLE_LDAP &Curl_handler_ldap, #if !defined(CURL_DISABLE_LDAPS) && \ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) &Curl_handler_ldaps, #endif #endif #ifndef CURL_DISABLE_FILE &Curl_handler_file, #endif #ifndef CURL_DISABLE_TFTP &Curl_handler_tftp, #endif #if defined(USE_SSH) &Curl_handler_scp, #endif #if defined(USE_SSH) &Curl_handler_sftp, #endif #ifndef CURL_DISABLE_IMAP &Curl_handler_imap, #ifdef USE_SSL &Curl_handler_imaps, #endif #endif #ifndef CURL_DISABLE_POP3 &Curl_handler_pop3, #ifdef USE_SSL &Curl_handler_pop3s, #endif #endif #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \ (CURL_SIZEOF_CURL_OFF_T > 4) && \ (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO)) &Curl_handler_smb, #ifdef USE_SSL &Curl_handler_smbs, #endif #endif #ifndef CURL_DISABLE_SMTP &Curl_handler_smtp, #ifdef USE_SSL &Curl_handler_smtps, #endif #endif #ifndef CURL_DISABLE_RTSP &Curl_handler_rtsp, #endif #ifndef CURL_DISABLE_GOPHER &Curl_handler_gopher, #endif #ifdef USE_LIBRTMP &Curl_handler_rtmp, &Curl_handler_rtmpt, &Curl_handler_rtmpe, &Curl_handler_rtmpte, &Curl_handler_rtmps, &Curl_handler_rtmpts, #endif (struct Curl_handler *) NULL }; /* * Dummy handler for undefined protocol schemes. */ static const struct Curl_handler Curl_handler_dummy = { "<no protocol>", /* scheme */ ZERO_NULL, /* setup_connection */ ZERO_NULL, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ 0, /* defport */ 0, /* protocol */ PROTOPT_NONE /* flags */ }; void Curl_freeset(struct Curl_easy *data) { /* Free all dynamic strings stored in the data->set substructure. */ enum dupstring i; for(i = (enum dupstring)0; i < STRING_LAST; i++) { Curl_safefree(data->set.str[i]); } if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; if(data->change.url_alloc) { Curl_safefree(data->change.url); data->change.url_alloc = FALSE; } data->change.url = NULL; Curl_mime_cleanpart(&data->set.mimepost); } /* free the URL pieces */ static void up_free(struct Curl_easy *data) { struct urlpieces *up = &data->state.up; Curl_safefree(up->scheme); Curl_safefree(up->hostname); Curl_safefree(up->port); Curl_safefree(up->user); Curl_safefree(up->password); Curl_safefree(up->options); Curl_safefree(up->path); Curl_safefree(up->query); curl_url_cleanup(data->state.uh); data->state.uh = NULL; } /* * This is the internal function curl_easy_cleanup() calls. This should * cleanup and free all resources associated with this sessionhandle. * * NOTE: if we ever add something that attempts to write to a socket or * similar here, we must ignore SIGPIPE first. It is currently only done * when curl_easy_perform() is invoked. */ CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; if(!data) return CURLE_OK; Curl_expire_clear(data); /* shut off timers */ m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) { /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); data->multi_easy = NULL; } /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is "just in case" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; up_free(data); Curl_safefree(data->state.buffer); Curl_safefree(data->state.headerbuff); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, 1); #ifdef USE_ALTSVC Curl_altsvc_save(data->asi, data->set.str[STRING_ALTSVC]); Curl_altsvc_cleanup(data->asi); data->asi = NULL; #endif #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) Curl_http_auth_cleanup_digest(data); #endif Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; } /* * Initialize the UserDefined fields within a Curl_easy. * This may be safely called on a new or existing Curl_easy. */ CURLcode Curl_init_userdefined(struct Curl_easy *data) { struct UserDefined *set = &data->set; CURLcode result = CURLE_OK; set->out = stdout; /* default output to stdout */ set->in_set = stdin; /* default input from stdin */ set->err = stderr; /* default stderr to stderr */ /* use fwrite as default function to store output */ set->fwrite_func = (curl_write_callback)fwrite; /* use fread as default function to read input */ set->fread_func_set = (curl_read_callback)fread; set->is_fread_set = 0; set->is_fwrite_set = 0; set->seek_func = ZERO_NULL; set->seek_client = ZERO_NULL; /* conversion callbacks for non-ASCII hosts */ set->convfromnetwork = ZERO_NULL; set->convtonetwork = ZERO_NULL; set->convfromutf8 = ZERO_NULL; set->filesize = -1; /* we don't know the size */ set->postfieldsize = -1; /* unknown size */ set->maxredirs = -1; /* allow any amount by default */ set->httpreq = HTTPREQ_GET; /* Default HTTP request */ set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */ #ifndef CURL_DISABLE_FILE set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */ set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */ set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */ set->ftp_filemethod = FTPFILE_MULTICWD; #endif set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */ /* Set the default size of the SSL session ID cache */ set->general_ssl.max_ssl_sessions = 5; set->proxyport = 0; set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */ set->httpauth = CURLAUTH_BASIC; /* defaults to basic */ set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */ /* SOCKS5 proxy auth defaults to username/password + GSS-API */ set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI; /* make libcurl quiet by default: */ set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */ Curl_mime_initpart(&set->mimepost, data); /* * libcurl 7.10 introduced SSL verification *by default*! This needs to be * switched off unless wanted. */ set->ssl.primary.verifypeer = TRUE; set->ssl.primary.verifyhost = TRUE; #ifdef USE_TLS_SRP set->ssl.authtype = CURL_TLSAUTH_NONE; #endif set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth type */ set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by default */ set->proxy_ssl = set->ssl; set->new_file_perms = 0644; /* Default permissions */ set->new_directory_perms = 0755; /* Default permissions */ /* for the *protocols fields we don't use the CURLPROTO_ALL convenience define since we internally only use the lower 16 bits for the passed in bitmask to not conflict with the private bits */ set->allowed_protocols = CURLPROTO_ALL; set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */ ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB | CURLPROTO_SMBS); #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) /* * disallow unprotected protection negotiation NEC reference implementation * seem not to follow rfc1961 section 4.3/4.4 */ set->socks5_gssapi_nec = FALSE; #endif /* Set the default CA cert bundle/path detected/specified at build time. * * If Schannel is the selected SSL backend then these locations are * ignored. We allow setting CA location for schannel only when explicitly * specified by the user via CURLOPT_CAINFO / --cacert. */ if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) { #if defined(CURL_CA_BUNDLE) result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE); if(result) return result; result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY], CURL_CA_BUNDLE); if(result) return result; #endif #if defined(CURL_CA_PATH) result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH); if(result) return result; result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH); if(result) return result; #endif } set->wildcard_enabled = FALSE; set->chunk_bgn = ZERO_NULL; set->chunk_end = ZERO_NULL; set->tcp_keepalive = FALSE; set->tcp_keepintvl = 60; set->tcp_keepidle = 60; set->tcp_fastopen = FALSE; set->tcp_nodelay = TRUE; set->ssl_enable_npn = TRUE; set->ssl_enable_alpn = TRUE; set->expect_100_timeout = 1000L; /* Wait for a second by default. */ set->sep_headers = TRUE; /* separated header lists by default */ set->buffer_size = READBUFFER_SIZE; set->upload_buffer_size = UPLOADBUFFER_DEFAULT; set->happy_eyeballs_timeout = CURL_HET_DEFAULT; set->fnmatch = ZERO_NULL; set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT; set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */ set->maxage_conn = 118; set->http09_allowed = TRUE; set->httpversion = #ifdef USE_NGHTTP2 CURL_HTTP_VERSION_2TLS #else CURL_HTTP_VERSION_1_1 #endif ; Curl_http2_init_userset(set); return result; } /** * Curl_open() * * @param curl is a pointer to a sessionhandle pointer that gets set by this * function. * @return CURLcode */ CURLcode Curl_open(struct Curl_easy **curl) { CURLcode result; struct Curl_easy *data; /* Very simple start-up: alloc the struct, init it with zeroes and return */ data = calloc(1, sizeof(struct Curl_easy)); if(!data) { /* this is a very serious error */ DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n")); return CURLE_OUT_OF_MEMORY; } data->magic = CURLEASY_MAGIC_NUMBER; result = Curl_resolver_init(data, &data->state.resolver); if(result) { DEBUGF(fprintf(stderr, "Error: resolver_init failed\n")); free(data); return result; } /* We do some initial setup here, all those fields that can't be just 0 */ data->state.buffer = malloc(READBUFFER_SIZE + 1); if(!data->state.buffer) { DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n")); result = CURLE_OUT_OF_MEMORY; } else { data->state.headerbuff = malloc(HEADERSIZE); if(!data->state.headerbuff) { DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n")); result = CURLE_OUT_OF_MEMORY; } else { result = Curl_init_userdefined(data); data->state.headersize = HEADERSIZE; Curl_convert_init(data); Curl_initinfo(data); /* most recent connection is not yet defined */ data->state.lastconnect = NULL; data->progress.flags |= PGRS_HIDE; data->state.current_speed = -1; /* init to negative == impossible */ Curl_http2_init_state(&data->state); } } if(result) { Curl_resolver_cleanup(data->state.resolver); free(data->state.buffer); free(data->state.headerbuff); Curl_freeset(data); free(data); data = NULL; } else *curl = data; return result; } #ifdef USE_RECV_BEFORE_SEND_WORKAROUND static void conn_reset_postponed_data(struct connectdata *conn, int num) { struct postponed_data * const psnd = &(conn->postponed[num]); if(psnd->buffer) { DEBUGASSERT(psnd->allocated_size > 0); DEBUGASSERT(psnd->recv_size <= psnd->allocated_size); DEBUGASSERT(psnd->recv_size ? (psnd->recv_processed < psnd->recv_size) : (psnd->recv_processed == 0)); DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD); free(psnd->buffer); psnd->buffer = NULL; psnd->allocated_size = 0; psnd->recv_size = 0; psnd->recv_processed = 0; #ifdef DEBUGBUILD psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */ #endif /* DEBUGBUILD */ } else { DEBUGASSERT(psnd->allocated_size == 0); DEBUGASSERT(psnd->recv_size == 0); DEBUGASSERT(psnd->recv_processed == 0); DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD); } } static void conn_reset_all_postponed_data(struct connectdata *conn) { conn_reset_postponed_data(conn, 0); conn_reset_postponed_data(conn, 1); } #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ /* Use "do-nothing" macro instead of function when workaround not used */ #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ static void conn_shutdown(struct connectdata *conn) { if(!conn) return; infof(conn->data, "Closing connection %ld\n", conn->connection_id); DEBUGASSERT(conn->data); /* possible left-overs from the async name resolvers */ Curl_resolver_cancel(conn); /* close the SSL stuff before we close any sockets since they will/may write to the sockets */ Curl_ssl_close(conn, FIRSTSOCKET); Curl_ssl_close(conn, SECONDARYSOCKET); /* close possibly still open sockets */ if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]); if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET]) Curl_closesocket(conn, conn->sock[FIRSTSOCKET]); if(CURL_SOCKET_BAD != conn->tempsock[0]) Curl_closesocket(conn, conn->tempsock[0]); if(CURL_SOCKET_BAD != conn->tempsock[1]) Curl_closesocket(conn, conn->tempsock[1]); /* unlink ourselves. this should be called last since other shutdown procedures need a valid conn->data and this may clear it. */ Curl_conncache_remove_conn(conn->data, conn, TRUE); } static void conn_free(struct connectdata *conn) { if(!conn) return; free_idnconverted_hostname(&conn->host); free_idnconverted_hostname(&conn->conn_to_host); free_idnconverted_hostname(&conn->http_proxy.host); free_idnconverted_hostname(&conn->socks_proxy.host); Curl_safefree(conn->user); Curl_safefree(conn->passwd); Curl_safefree(conn->oauth_bearer); Curl_safefree(conn->options); Curl_safefree(conn->http_proxy.user); Curl_safefree(conn->socks_proxy.user); Curl_safefree(conn->http_proxy.passwd); Curl_safefree(conn->socks_proxy.passwd); Curl_safefree(conn->allocptr.proxyuserpwd); Curl_safefree(conn->allocptr.uagent); Curl_safefree(conn->allocptr.userpwd); Curl_safefree(conn->allocptr.accept_encoding); Curl_safefree(conn->allocptr.te); Curl_safefree(conn->allocptr.rangeline); Curl_safefree(conn->allocptr.ref); Curl_safefree(conn->allocptr.host); Curl_safefree(conn->allocptr.cookiehost); Curl_safefree(conn->allocptr.rtsp_transport); Curl_safefree(conn->trailer); Curl_safefree(conn->host.rawalloc); /* host name buffer */ Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */ Curl_safefree(conn->hostname_resolve); Curl_safefree(conn->secondaryhostname); Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */ Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */ Curl_safefree(conn->connect_state); conn_reset_all_postponed_data(conn); Curl_llist_destroy(&conn->easyq, NULL); Curl_safefree(conn->localdev); Curl_free_primary_ssl_config(&conn->ssl_config); Curl_free_primary_ssl_config(&conn->proxy_ssl_config); #ifdef USE_UNIX_SOCKETS Curl_safefree(conn->unix_domain_socket); #endif #ifdef USE_SSL Curl_safefree(conn->ssl_extra); #endif free(conn); /* free all the connection oriented data */ } /* * Disconnects the given connection. Note the connection may not be the * primary connection, like when freeing room in the connection cache or * killing of a dead old connection. * * A connection needs an easy handle when closing down. We support this passed * in separately since the connection to get closed here is often already * disassociated from an easy handle. * * This function MUST NOT reset state in the Curl_easy struct if that * isn't strictly bound to the life-time of *this* particular connection. * */ CURLcode Curl_disconnect(struct Curl_easy *data, struct connectdata *conn, bool dead_connection) { if(!conn) return CURLE_OK; /* this is closed and fine already */ if(!data) { DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n")); return CURLE_OK; } /* * If this connection isn't marked to force-close, leave it open if there * are other users of it */ if(CONN_INUSE(conn) && !dead_connection) { DEBUGF(infof(data, "Curl_disconnect when inuse: %zu\n", CONN_INUSE(conn))); return CURLE_OK; } if(conn->dns_entry != NULL) { Curl_resolv_unlock(data, conn->dns_entry); conn->dns_entry = NULL; } Curl_hostcache_prune(data); /* kill old DNS cache entries */ #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) /* Cleanup NTLM connection-related data */ Curl_http_auth_cleanup_ntlm(conn); #endif #if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) /* Cleanup NEGOTIATE connection-related data */ Curl_http_auth_cleanup_negotiate(conn); #endif /* the protocol specific disconnect handler and conn_shutdown need a transfer for the connection! */ conn->data = data; if(conn->bits.connect_only) /* treat the connection as dead in CONNECT_ONLY situations */ dead_connection = TRUE; if(conn->handler->disconnect) /* This is set if protocol-specific cleanups should be made */ conn->handler->disconnect(conn, dead_connection); conn_shutdown(conn); conn_free(conn); return CURLE_OK; } /* * This function should return TRUE if the socket is to be assumed to * be dead. Most commonly this happens when the server has closed the * connection due to inactivity. */ static bool SocketIsDead(curl_socket_t sock) { int sval; bool ret_val = TRUE; sval = SOCKET_READABLE(sock, 0); if(sval == 0) /* timeout */ ret_val = FALSE; return ret_val; } /* * IsMultiplexingPossible() * * Return a bitmask with the available multiplexing options for the given * requested connection. */ static int IsMultiplexingPossible(const struct Curl_easy *handle, const struct connectdata *conn) { int avail = 0; /* If a HTTP protocol and multiplexing is enabled */ if((conn->handler->protocol & PROTO_FAMILY_HTTP) && (!conn->bits.protoconnstart || !conn->bits.close)) { if(Curl_multiplex_wanted(handle->multi) && (handle->set.httpversion >= CURL_HTTP_VERSION_2)) /* allows HTTP/2 */ avail |= CURLPIPE_MULTIPLEX; } return avail; } #ifndef CURL_DISABLE_PROXY static bool proxy_info_matches(const struct proxy_info* data, const struct proxy_info* needle) { if((data->proxytype == needle->proxytype) && (data->port == needle->port) && Curl_safe_strcasecompare(data->host.name, needle->host.name)) return TRUE; return FALSE; } #else /* disabled, won't get called */ #define proxy_info_matches(x,y) FALSE #endif /* * This function checks if the given connection is dead and extracts it from * the connection cache if so. * * When this is called as a Curl_conncache_foreach() callback, the connection * cache lock is held! * * Returns TRUE if the connection was dead and extracted. */ static bool extract_if_dead(struct connectdata *conn, struct Curl_easy *data) { if(!CONN_INUSE(conn) && !conn->data) { /* The check for a dead socket makes sense only if the connection isn't in use */ bool dead; if(conn->handler->connection_check) { /* The protocol has a special method for checking the state of the connection. Use it to check if the connection is dead. */ unsigned int state; struct Curl_easy *olddata = conn->data; conn->data = data; /* use this transfer for now */ state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD); conn->data = olddata; dead = (state & CONNRESULT_DEAD); } else { /* Use the general method for determining the death of a connection */ dead = SocketIsDead(conn->sock[FIRSTSOCKET]); } if(dead) { infof(data, "Connection %ld seems to be dead!\n", conn->connection_id); Curl_conncache_remove_conn(data, conn, FALSE); return TRUE; } } return FALSE; } struct prunedead { struct Curl_easy *data; struct connectdata *extracted; }; /* * Wrapper to use extract_if_dead() function in Curl_conncache_foreach() * */ static int call_extract_if_dead(struct connectdata *conn, void *param) { struct prunedead *p = (struct prunedead *)param; if(extract_if_dead(conn, p->data)) { /* stop the iteration here, pass back the connection that was extracted */ p->extracted = conn; return 1; } return 0; /* continue iteration */ } /* * This function scans the connection cache for half-open/dead connections, * closes and removes them. * The cleanup is done at most once per second. */ static void prune_dead_connections(struct Curl_easy *data) { struct curltime now = Curl_now(); time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup); if(elapsed >= 1000L) { struct prunedead prune; prune.data = data; prune.extracted = NULL; while(Curl_conncache_foreach(data, data->state.conn_cache, &prune, call_extract_if_dead)) { /* disconnect it */ (void)Curl_disconnect(data, prune.extracted, /* dead_connection */TRUE); } data->state.conn_cache->last_cleanup = now; } } /* A connection has to have been idle for a shorter time than 'maxage_conn' to be subject for reuse. The success rate is just too low after this. */ static bool conn_maxage(struct Curl_easy *data, struct connectdata *conn, struct curltime now) { if(!conn->data) { timediff_t idletime = Curl_timediff(now, conn->lastused); idletime /= 1000; /* integer seconds is fine */ if(idletime/1000 > data->set.maxage_conn) { infof(data, "Too old connection (%ld seconds), disconnect it\n", idletime); return TRUE; } } return FALSE; } /* * Given one filled in connection struct (named needle), this function should * detect if there already is one that has all the significant details * exactly the same and thus should be used instead. * * If there is a match, this function returns TRUE - and has marked the * connection as 'in-use'. It must later be called with ConnectionDone() to * return back to 'idle' (unused) state. * * The force_reuse flag is set if the connection must be used. */ static bool ConnectionExists(struct Curl_easy *data, struct connectdata *needle, struct connectdata **usethis, bool *force_reuse, bool *waitpipe) { struct connectdata *check; struct connectdata *chosen = 0; bool foundPendingCandidate = FALSE; bool canmultiplex = IsMultiplexingPossible(data, needle); struct connectbundle *bundle; struct curltime now = Curl_now(); #ifdef USE_NTLM bool wantNTLMhttp = ((data->state.authhost.want & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && (needle->handler->protocol & PROTO_FAMILY_HTTP)); bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd && ((data->state.authproxy.want & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && (needle->handler->protocol & PROTO_FAMILY_HTTP))); #endif *force_reuse = FALSE; *waitpipe = FALSE; /* Look up the bundle with all the connections to this particular host. Locks the connection cache, beware of early returns! */ bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache); if(bundle) { /* Max pipe length is zero (unlimited) for multiplexed connections */ struct curl_llist_element *curr; infof(data, "Found bundle for host %s: %p [%s]\n", (needle->bits.conn_to_host ? needle->conn_to_host.name : needle->host.name), (void *)bundle, (bundle->multiuse == BUNDLE_MULTIPLEX ? "can multiplex" : "serially")); /* We can't multiplex if we don't know anything about the server */ if(canmultiplex) { if(bundle->multiuse == BUNDLE_UNKNOWN) { if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) { infof(data, "Server doesn't support multiplex yet, wait\n"); *waitpipe = TRUE; Curl_conncache_unlock(data); return FALSE; /* no re-use */ } infof(data, "Server doesn't support multiplex (yet)\n"); canmultiplex = FALSE; } if((bundle->multiuse == BUNDLE_MULTIPLEX) && !Curl_multiplex_wanted(data->multi)) { infof(data, "Could multiplex, but not asked to!\n"); canmultiplex = FALSE; } if(bundle->multiuse == BUNDLE_NO_MULTIUSE) { infof(data, "Can not multiplex, even if we wanted to!\n"); canmultiplex = FALSE; } } curr = bundle->conn_list.head; while(curr) { bool match = FALSE; size_t multiplexed; /* * Note that if we use a HTTP proxy in normal mode (no tunneling), we * check connections to that proxy and not to the actual remote server. */ check = curr->ptr; curr = curr->next; if(check->bits.connect_only) /* connect-only connections will not be reused */ continue; if(conn_maxage(data, check, now) || extract_if_dead(check, data)) { /* disconnect it */ (void)Curl_disconnect(data, check, /* dead_connection */TRUE); continue; } multiplexed = CONN_INUSE(check) && (bundle->multiuse == BUNDLE_MULTIPLEX); if(canmultiplex) { if(check->bits.protoconnstart && check->bits.close) continue; } else { if(multiplexed) { /* can only happen within multi handles, and means that another easy handle is using this connection */ continue; } if(Curl_resolver_asynch()) { /* ip_addr_str[0] is NUL only if the resolving of the name hasn't completed yet and until then we don't re-use this connection */ if(!check->ip_addr_str[0]) { infof(data, "Connection #%ld is still name resolving, can't reuse\n", check->connection_id); continue; } } if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) || check->bits.close) { if(!check->bits.close) foundPendingCandidate = TRUE; /* Don't pick a connection that hasn't connected yet or that is going to get closed. */ infof(data, "Connection #%ld isn't open enough, can't reuse\n", check->connection_id); continue; } } #ifdef USE_UNIX_SOCKETS if(needle->unix_domain_socket) { if(!check->unix_domain_socket) continue; if(strcmp(needle->unix_domain_socket, check->unix_domain_socket)) continue; if(needle->abstract_unix_socket != check->abstract_unix_socket) continue; } else if(check->unix_domain_socket) continue; #endif if((needle->handler->flags&PROTOPT_SSL) != (check->handler->flags&PROTOPT_SSL)) /* don't do mixed SSL and non-SSL connections */ if(get_protocol_family(check->handler->protocol) != needle->handler->protocol || !check->tls_upgraded) /* except protocols that have been upgraded via TLS */ continue; if(needle->bits.httpproxy != check->bits.httpproxy || needle->bits.socksproxy != check->bits.socksproxy) continue; if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy, &check->socks_proxy)) continue; if(needle->bits.conn_to_host != check->bits.conn_to_host) /* don't mix connections that use the "connect to host" feature and * connections that don't use this feature */ continue; if(needle->bits.conn_to_port != check->bits.conn_to_port) /* don't mix connections that use the "connect to port" feature and * connections that don't use this feature */ continue; if(needle->bits.httpproxy) { if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy)) continue; if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy) continue; if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) { /* use https proxy */ if(needle->handler->flags&PROTOPT_SSL) { /* use double layer ssl */ if(!Curl_ssl_config_matches(&needle->proxy_ssl_config, &check->proxy_ssl_config)) continue; if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete) continue; } else { if(!Curl_ssl_config_matches(&needle->ssl_config, &check->ssl_config)) continue; if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) continue; } } } if(!canmultiplex && check->data) /* this request can't be multiplexed but the checked connection is already in use so we skip it */ continue; if(CONN_INUSE(check) && check->data && (check->data->multi != needle->data->multi)) /* this could be subject for multiplex use, but only if they belong to * the same multi handle */ continue; if(needle->localdev || needle->localport) { /* If we are bound to a specific local end (IP+port), we must not re-use a random other one, although if we didn't ask for a particular one we can reuse one that was bound. This comparison is a bit rough and too strict. Since the input parameters can be specified in numerous ways and still end up the same it would take a lot of processing to make it really accurate. Instead, this matching will assume that re-uses of bound connections will most likely also re-use the exact same binding parameters and missing out a few edge cases shouldn't hurt anyone very much. */ if((check->localport != needle->localport) || (check->localportrange != needle->localportrange) || (needle->localdev && (!check->localdev || strcmp(check->localdev, needle->localdev)))) continue; } if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) { /* This protocol requires credentials per connection, so verify that we're using the same name and password as well */ if(strcmp(needle->user, check->user) || strcmp(needle->passwd, check->passwd)) { /* one of them was different */ continue; } } if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) || needle->bits.tunnel_proxy) { /* The requested connection does not use a HTTP proxy or it uses SSL or it is a non-SSL protocol tunneled or it is a non-SSL protocol which is allowed to be upgraded via TLS */ if((strcasecompare(needle->handler->scheme, check->handler->scheme) || (get_protocol_family(check->handler->protocol) == needle->handler->protocol && check->tls_upgraded)) && (!needle->bits.conn_to_host || strcasecompare( needle->conn_to_host.name, check->conn_to_host.name)) && (!needle->bits.conn_to_port || needle->conn_to_port == check->conn_to_port) && strcasecompare(needle->host.name, check->host.name) && needle->remote_port == check->remote_port) { /* The schemes match or the the protocol family is the same and the previous connection was TLS upgraded, and the hostname and host port match */ if(needle->handler->flags & PROTOPT_SSL) { /* This is a SSL connection so verify that we're using the same SSL options as well */ if(!Curl_ssl_config_matches(&needle->ssl_config, &check->ssl_config)) { DEBUGF(infof(data, "Connection #%ld has different SSL parameters, " "can't reuse\n", check->connection_id)); continue; } if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) { foundPendingCandidate = TRUE; DEBUGF(infof(data, "Connection #%ld has not started SSL connect, " "can't reuse\n", check->connection_id)); continue; } } match = TRUE; } } else { /* The requested connection is using the same HTTP proxy in normal mode (no tunneling) */ match = TRUE; } if(match) { #if defined(USE_NTLM) /* If we are looking for an HTTP+NTLM connection, check if this is already authenticating with the right credentials. If not, keep looking so that we can reuse NTLM connections if possible. (Especially we must not reuse the same connection if partway through a handshake!) */ if(wantNTLMhttp) { if(strcmp(needle->user, check->user) || strcmp(needle->passwd, check->passwd)) continue; } else if(check->http_ntlm_state != NTLMSTATE_NONE) { /* Connection is using NTLM auth but we don't want NTLM */ continue; } /* Same for Proxy NTLM authentication */ if(wantProxyNTLMhttp) { /* Both check->http_proxy.user and check->http_proxy.passwd can be * NULL */ if(!check->http_proxy.user || !check->http_proxy.passwd) continue; if(strcmp(needle->http_proxy.user, check->http_proxy.user) || strcmp(needle->http_proxy.passwd, check->http_proxy.passwd)) continue; } else if(check->proxy_ntlm_state != NTLMSTATE_NONE) { /* Proxy connection is using NTLM auth but we don't want NTLM */ continue; } if(wantNTLMhttp || wantProxyNTLMhttp) { /* Credentials are already checked, we can use this connection */ chosen = check; if((wantNTLMhttp && (check->http_ntlm_state != NTLMSTATE_NONE)) || (wantProxyNTLMhttp && (check->proxy_ntlm_state != NTLMSTATE_NONE))) { /* We must use this connection, no other */ *force_reuse = TRUE; break; } /* Continue look up for a better connection */ continue; } #endif if(canmultiplex) { /* We can multiplex if we want to. Let's continue looking for the optimal connection to use. */ if(!multiplexed) { /* We have the optimal connection. Let's stop looking. */ chosen = check; break; } #ifdef USE_NGHTTP2 /* If multiplexed, make sure we don't go over concurrency limit */ if(check->bits.multiplex) { /* Multiplexed connections can only be HTTP/2 for now */ struct http_conn *httpc = &check->proto.httpc; if(multiplexed >= httpc->settings.max_concurrent_streams) { infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n", multiplexed); continue; } } #endif /* When not multiplexed, we have a match here! */ chosen = check; infof(data, "Multiplexed connection found!\n"); break; } else { /* We have found a connection. Let's stop searching. */ chosen = check; break; } } } } if(chosen) { /* mark it as used before releasing the lock */ chosen->data = data; /* own it! */ Curl_conncache_unlock(data); *usethis = chosen; return TRUE; /* yes, we found one to use! */ } Curl_conncache_unlock(data); if(foundPendingCandidate && data->set.pipewait) { infof(data, "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n"); *waitpipe = TRUE; } return FALSE; /* no matching connecting exists */ } /* after a TCP connection to the proxy has been verified, this function does the next magic step. Note: this function's sub-functions call failf() */ CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; if(conn->bits.socksproxy) { #ifndef CURL_DISABLE_PROXY /* for the secondary socket (FTP), use the "connect to host" * but ignore the "connect to port" (use the secondary port) */ const char * const host = conn->bits.httpproxy ? conn->http_proxy.host.name : conn->bits.conn_to_host ? conn->conn_to_host.name : sockindex == SECONDARYSOCKET ? conn->secondaryhostname : conn->host.name; const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port : sockindex == SECONDARYSOCKET ? conn->secondary_port : conn->bits.conn_to_port ? conn->conn_to_port : conn->remote_port; conn->bits.socksproxy_connecting = TRUE; switch(conn->socks_proxy.proxytype) { case CURLPROXY_SOCKS5: case CURLPROXY_SOCKS5_HOSTNAME: result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd, host, port, sockindex, conn); break; case CURLPROXY_SOCKS4: case CURLPROXY_SOCKS4A: result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex, conn); break; default: failf(conn->data, "unknown proxytype option given"); result = CURLE_COULDNT_CONNECT; } /* switch proxytype */ conn->bits.socksproxy_connecting = FALSE; #else (void)sockindex; #endif /* CURL_DISABLE_PROXY */ } return result; } /* * verboseconnect() displays verbose information after a connect */ #ifndef CURL_DISABLE_VERBOSE_STRINGS void Curl_verboseconnect(struct connectdata *conn) { if(conn->data->set.verbose) infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n", conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname, conn->ip_addr_str, conn->port, conn->connection_id); } #endif int Curl_protocol_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(conn->handler->proto_getsock) return conn->handler->proto_getsock(conn, socks, numsocks); /* Backup getsock logic. Since there is a live socket in use, we must wait for it or it will be removed from watching when the multi_socket API is used. */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } int Curl_doing_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(conn && conn->handler->doing_getsock) return conn->handler->doing_getsock(conn, socks, numsocks); return GETSOCK_BLANK; } /* * We are doing protocol-specific connecting and this is being called over and * over from the multi interface until the connection phase is done on * protocol layer. */ CURLcode Curl_protocol_connecting(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->connecting) { *done = FALSE; result = conn->handler->connecting(conn, done); } else *done = TRUE; return result; } /* * We are DOING this is being called over and over from the multi interface * until the DOING phase is done on protocol layer. */ CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->doing) { *done = FALSE; result = conn->handler->doing(conn, done); } else *done = TRUE; return result; } /* * We have discovered that the TCP connection has been successful, we can now * proceed with some action. * */ CURLcode Curl_protocol_connect(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; *protocol_done = FALSE; if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) { /* We already are connected, get back. This may happen when the connect worked fine in the first call, like when we connect to a local server or proxy. Note that we don't know if the protocol is actually done. Unless this protocol doesn't have any protocol-connect callback, as then we know we're done. */ if(!conn->handler->connecting) *protocol_done = TRUE; return CURLE_OK; } if(!conn->bits.protoconnstart) { result = Curl_proxy_connect(conn, FIRSTSOCKET); if(result) return result; if(CONNECT_FIRSTSOCKET_PROXY_SSL()) /* wait for HTTPS proxy SSL initialization to complete */ return CURLE_OK; if(conn->bits.tunnel_proxy && conn->bits.httpproxy && Curl_connect_ongoing(conn)) /* when using an HTTP tunnel proxy, await complete tunnel establishment before proceeding further. Return CURLE_OK so we'll be called again */ return CURLE_OK; if(conn->handler->connect_it) { /* is there a protocol-specific connect() procedure? */ /* Call the protocol-specific connect function */ result = conn->handler->connect_it(conn, protocol_done); } else *protocol_done = TRUE; /* it has started, possibly even completed but that knowledge isn't stored in this bit! */ if(!result) conn->bits.protoconnstart = TRUE; } return result; /* pass back status */ } /* * Helpers for IDNA conversions. */ static bool is_ASCII_name(const char *hostname) { const unsigned char *ch = (const unsigned char *)hostname; while(*ch) { if(*ch++ & 0x80) return FALSE; } return TRUE; } /* * Strip single trailing dot in the hostname, * primarily for SNI and http host header. */ static void strip_trailing_dot(struct hostname *host) { size_t len; if(!host || !host->name) return; len = strlen(host->name); if(len && (host->name[len-1] == '.')) host->name[len-1] = 0; } /* * Perform any necessary IDN conversion of hostname */ static CURLcode idnconvert_hostname(struct connectdata *conn, struct hostname *host) { struct Curl_easy *data = conn->data; #ifndef USE_LIBIDN2 (void)data; (void)conn; #elif defined(CURL_DISABLE_VERBOSE_STRINGS) (void)conn; #endif /* set the name we use to display the host name */ host->dispname = host->name; /* Check name for non-ASCII and convert hostname to ACE form if we can */ if(!is_ASCII_name(host->name)) { #ifdef USE_LIBIDN2 if(idn2_check_version(IDN2_VERSION)) { char *ace_hostname = NULL; #if IDN2_VERSION_NUMBER >= 0x00140000 /* IDN2_NFC_INPUT: Normalize input string using normalization form C. IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional processing. */ int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL; #else int flags = IDN2_NFC_INPUT; #endif int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags); if(rc == IDN2_OK) { host->encalloc = (char *)ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } else { failf(data, "Failed to convert %s to ACE; %s\n", host->name, idn2_strerror(rc)); return CURLE_URL_MALFORMAT; } } #elif defined(USE_WIN32_IDN) char *ace_hostname = NULL; if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) { host->encalloc = ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } else { failf(data, "Failed to convert %s to ACE;\n", host->name); return CURLE_URL_MALFORMAT; } #else infof(data, "IDN support not present, can't parse Unicode domains\n"); #endif } return CURLE_OK; } /* * Frees data allocated by idnconvert_hostname() */ static void free_idnconverted_hostname(struct hostname *host) { #if defined(USE_LIBIDN2) if(host->encalloc) { idn2_free(host->encalloc); /* must be freed with idn2_free() since this was allocated by libidn */ host->encalloc = NULL; } #elif defined(USE_WIN32_IDN) free(host->encalloc); /* must be freed with free() since this was allocated by curl_win32_idn_to_ascii */ host->encalloc = NULL; #else (void)host; #endif } static void llist_dtor(void *user, void *element) { (void)user; (void)element; /* Do nothing */ } /* * Allocate and initialize a new connectdata object. */ static struct connectdata *allocate_conn(struct Curl_easy *data) { struct connectdata *conn = calloc(1, sizeof(struct connectdata)); if(!conn) return NULL; #ifdef USE_SSL /* The SSL backend-specific data (ssl_backend_data) objects are allocated as a separate array to ensure suitable alignment. Note that these backend pointers can be swapped by vtls (eg ssl backend data becomes proxy backend data). */ { size_t sslsize = Curl_ssl->sizeof_ssl_backend_data; char *ssl = calloc(4, sslsize); if(!ssl) { free(conn); return NULL; } conn->ssl_extra = ssl; conn->ssl[0].backend = (void *)ssl; conn->ssl[1].backend = (void *)(ssl + sslsize); conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize); conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize); } #endif conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined already from start to avoid NULL situations and checks */ /* and we setup a few fields in case we end up actually using this struct */ conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */ conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */ conn->connection_id = -1; /* no ID */ conn->port = -1; /* unknown at this point */ conn->remote_port = -1; /* unknown at this point */ #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD) conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */ /* Default protocol-independent behavior doesn't support persistent connections, so we set this to force-close. Protocols that support this need to set this to FALSE in their "curl_do" functions. */ connclose(conn, "Default to force-close"); /* Store creation time to help future close decision making */ conn->created = Curl_now(); /* Store current time to give a baseline to keepalive connection times. */ conn->keepalive = Curl_now(); /* Store off the configured connection upkeep time. */ conn->upkeep_interval_ms = data->set.upkeep_interval_ms; conn->data = data; /* Setup the association between this connection and the Curl_easy */ conn->http_proxy.proxytype = data->set.proxytype; conn->socks_proxy.proxytype = CURLPROXY_SOCKS4; #if !defined(CURL_DISABLE_PROXY) /* note that these two proxy bits are now just on what looks to be requested, they may be altered down the road */ conn->bits.proxy = (data->set.str[STRING_PROXY] && *data->set.str[STRING_PROXY]) ? TRUE : FALSE; conn->bits.httpproxy = (conn->bits.proxy && (conn->http_proxy.proxytype == CURLPROXY_HTTP || conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 || conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ? TRUE : FALSE; conn->bits.socksproxy = (conn->bits.proxy && !conn->bits.httpproxy) ? TRUE : FALSE; if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) { conn->bits.proxy = TRUE; conn->bits.socksproxy = TRUE; } conn->bits.proxy_user_passwd = (data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE; conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy; #endif /* CURL_DISABLE_PROXY */ conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE; #ifndef CURL_DISABLE_FTP conn->bits.ftp_use_epsv = data->set.ftp_use_epsv; conn->bits.ftp_use_eprt = data->set.ftp_use_eprt; #endif conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus; conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer; conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost; conn->proxy_ssl_config.verifystatus = data->set.proxy_ssl.primary.verifystatus; conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer; conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost; conn->ip_version = data->set.ipver; conn->bits.connect_only = data->set.connect_only; #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \ defined(NTLM_WB_ENABLED) conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD; #endif /* Initialize the easy handle list */ Curl_llist_init(&conn->easyq, (curl_llist_dtor) llist_dtor); #ifdef HAVE_GSSAPI conn->data_prot = PROT_CLEAR; #endif /* Store the local bind parameters that will be used for this connection */ if(data->set.str[STRING_DEVICE]) { conn->localdev = strdup(data->set.str[STRING_DEVICE]); if(!conn->localdev) goto error; } conn->localportrange = data->set.localportrange; conn->localport = data->set.localport; /* the close socket stuff needs to be copied to the connection struct as it may live on without (this specific) Curl_easy */ conn->fclosesocket = data->set.fclosesocket; conn->closesocket_client = data->set.closesocket_client; return conn; error: Curl_llist_destroy(&conn->easyq, NULL); free(conn->localdev); #ifdef USE_SSL free(conn->ssl_extra); #endif free(conn); return NULL; } /* returns the handler if the given scheme is built-in */ const struct Curl_handler *Curl_builtin_scheme(const char *scheme) { const struct Curl_handler * const *pp; const struct Curl_handler *p; /* Scan protocol handler table and match against 'scheme'. The handler may be changed later when the protocol specific setup function is called. */ for(pp = protocols; (p = *pp) != NULL; pp++) if(strcasecompare(p->scheme, scheme)) /* Protocol found in table. Check if allowed */ return p; return NULL; /* not found */ } static CURLcode findprotocol(struct Curl_easy *data, struct connectdata *conn, const char *protostr) { const struct Curl_handler *p = Curl_builtin_scheme(protostr); if(p && /* Protocol found in table. Check if allowed */ (data->set.allowed_protocols & p->protocol)) { /* it is allowed for "normal" request, now do an extra check if this is the result of a redirect */ if(data->state.this_is_a_follow && !(data->set.redir_protocols & p->protocol)) /* nope, get out */ ; else { /* Perform setup complement if some. */ conn->handler = conn->given = p; /* 'port' and 'remote_port' are set in setup_connection_internals() */ return CURLE_OK; } } /* The protocol was not found in the table, but we don't have to assign it to anything since it is already assigned to a dummy-struct in the create_conn() function when the connectdata struct is allocated. */ failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME, protostr); return CURLE_UNSUPPORTED_PROTOCOL; } CURLcode Curl_uc_to_curlcode(CURLUcode uc) { switch(uc) { default: return CURLE_URL_MALFORMAT; case CURLUE_UNSUPPORTED_SCHEME: return CURLE_UNSUPPORTED_PROTOCOL; case CURLUE_OUT_OF_MEMORY: return CURLE_OUT_OF_MEMORY; case CURLUE_USER_NOT_ALLOWED: return CURLE_LOGIN_DENIED; } } /* * Parse URL and fill in the relevant members of the connection struct. */ static CURLcode parseurlandfillconn(struct Curl_easy *data, struct connectdata *conn) { CURLcode result; CURLU *uh; CURLUcode uc; char *hostname; up_free(data); /* cleanup previous leftovers first */ /* parse the URL */ if(data->set.uh) { uh = data->state.uh = curl_url_dup(data->set.uh); } else { uh = data->state.uh = curl_url(); } if(!uh) return CURLE_OUT_OF_MEMORY; if(data->set.str[STRING_DEFAULT_PROTOCOL] && !Curl_is_absolute_url(data->change.url, NULL, MAX_SCHEME_LEN)) { char *url; if(data->change.url_alloc) free(data->change.url); url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL], data->change.url); if(!url) return CURLE_OUT_OF_MEMORY; data->change.url = url; data->change.url_alloc = TRUE; } if(!data->set.uh) { uc = curl_url_set(uh, CURLUPART_URL, data->change.url, CURLU_GUESS_SCHEME | CURLU_NON_SUPPORT_SCHEME | (data->set.disallow_username_in_url ? CURLU_DISALLOW_USER : 0) | (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)); if(uc) { DEBUGF(infof(data, "curl_url_set rejected %s\n", data->change.url)); return Curl_uc_to_curlcode(uc); } } uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0); if(uc) return Curl_uc_to_curlcode(uc); result = findprotocol(data, conn, data->state.up.scheme); if(result) return result; uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user, CURLU_URLDECODE); if(!uc) { conn->user = strdup(data->state.up.user); if(!conn->user) return CURLE_OUT_OF_MEMORY; conn->bits.user_passwd = TRUE; } else if(uc != CURLUE_NO_USER) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password, CURLU_URLDECODE); if(!uc) { conn->passwd = strdup(data->state.up.password); if(!conn->passwd) return CURLE_OUT_OF_MEMORY; conn->bits.user_passwd = TRUE; } else if(uc != CURLUE_NO_PASSWORD) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options, CURLU_URLDECODE); if(!uc) { conn->options = strdup(data->state.up.options); if(!conn->options) return CURLE_OUT_OF_MEMORY; } else if(uc != CURLUE_NO_OPTIONS) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0); if(uc) { if(!strcasecompare("file", data->state.up.scheme)) return CURLE_OUT_OF_MEMORY; } uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0); if(uc) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port, CURLU_DEFAULT_PORT); if(uc) { if(!strcasecompare("file", data->state.up.scheme)) return CURLE_OUT_OF_MEMORY; } else { unsigned long port = strtoul(data->state.up.port, NULL, 10); conn->remote_port = curlx_ultous(port); } (void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0); hostname = data->state.up.hostname; if(!hostname) /* this is for file:// transfers, get a dummy made */ hostname = (char *)""; if(hostname[0] == '[') { /* This looks like an IPv6 address literal. See if there is an address scope. */ char *zoneid; size_t hlen; uc = curl_url_get(uh, CURLUPART_ZONEID, &zoneid, 0); conn->bits.ipv6_ip = TRUE; /* cut off the brackets! */ hostname++; hlen = strlen(hostname); hostname[hlen - 1] = 0; if(!uc && zoneid) { char *endp; unsigned long scope; scope = strtoul(zoneid, &endp, 10); if(!*endp && (scope < UINT_MAX)) { /* A plain number, use it direcly as a scope id. */ conn->scope_id = (unsigned int)scope; } #ifdef HAVE_IF_NAMETOINDEX else { /* Zone identifier is not numeric */ unsigned int scopeidx = 0; scopeidx = if_nametoindex(zoneid); if(!scopeidx) infof(data, "Invalid zoneid id: %s; %s\n", zoneid, strerror(errno)); else conn->scope_id = scopeidx; } #endif /* HAVE_IF_NAMETOINDEX */ free(zoneid); } } /* make sure the connect struct gets its own copy of the host name */ conn->host.rawalloc = strdup(hostname); if(!conn->host.rawalloc) return CURLE_OUT_OF_MEMORY; conn->host.name = conn->host.rawalloc; if(data->set.scope_id) /* Override any scope that was set above. */ conn->scope_id = data->set.scope_id; return CURLE_OK; } /* * If we're doing a resumed transfer, we need to setup our stuff * properly. */ static CURLcode setup_range(struct Curl_easy *data) { struct UrlState *s = &data->state; s->resume_from = data->set.set_resume_from; if(s->resume_from || data->set.str[STRING_SET_RANGE]) { if(s->rangestringalloc) free(s->range); if(s->resume_from) s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from); else s->range = strdup(data->set.str[STRING_SET_RANGE]); s->rangestringalloc = (s->range) ? TRUE : FALSE; if(!s->range) return CURLE_OUT_OF_MEMORY; /* tell ourselves to fetch this range */ s->use_range = TRUE; /* enable range download */ } else s->use_range = FALSE; /* disable range download */ return CURLE_OK; } /* * setup_connection_internals() - * * Setup connection internals specific to the requested protocol in the * Curl_easy. This is inited and setup before the connection is made but * is about the particular protocol that is to be used. * * This MUST get called after proxy magic has been figured out. */ static CURLcode setup_connection_internals(struct connectdata *conn) { const struct Curl_handler * p; CURLcode result; conn->socktype = SOCK_STREAM; /* most of them are TCP streams */ /* Perform setup complement if some. */ p = conn->handler; if(p->setup_connection) { result = (*p->setup_connection)(conn); if(result) return result; p = conn->handler; /* May have changed. */ } if(conn->port < 0) /* we check for -1 here since if proxy was detected already, this was very likely already set to the proxy port */ conn->port = p->defport; return CURLE_OK; } /* * Curl_free_request_state() should free temp data that was allocated in the * Curl_easy for this single request. */ void Curl_free_request_state(struct Curl_easy *data) { Curl_safefree(data->req.protop); Curl_safefree(data->req.newurl); } #ifndef CURL_DISABLE_PROXY /**************************************************************** * Checks if the host is in the noproxy list. returns true if it matches * and therefore the proxy should NOT be used. ****************************************************************/ static bool check_noproxy(const char *name, const char *no_proxy) { /* no_proxy=domain1.dom,host.domain2.dom * (a comma-separated list of hosts which should * not be proxied, or an asterisk to override * all proxy variables) */ if(no_proxy && no_proxy[0]) { size_t tok_start; size_t tok_end; const char *separator = ", "; size_t no_proxy_len; size_t namelen; char *endptr; if(strcasecompare("*", no_proxy)) { return TRUE; } /* NO_PROXY was specified and it wasn't just an asterisk */ no_proxy_len = strlen(no_proxy); if(name[0] == '[') { /* IPv6 numerical address */ endptr = strchr(name, ']'); if(!endptr) return FALSE; name++; namelen = endptr - name; } else namelen = strlen(name); for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) { while(tok_start < no_proxy_len && strchr(separator, no_proxy[tok_start]) != NULL) { /* Look for the beginning of the token. */ ++tok_start; } if(tok_start == no_proxy_len) break; /* It was all trailing separator chars, no more tokens. */ for(tok_end = tok_start; tok_end < no_proxy_len && strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end) /* Look for the end of the token. */ ; /* To match previous behaviour, where it was necessary to specify * ".local.com" to prevent matching "notlocal.com", we will leave * the '.' off. */ if(no_proxy[tok_start] == '.') ++tok_start; if((tok_end - tok_start) <= namelen) { /* Match the last part of the name to the domain we are checking. */ const char *checkn = name + namelen - (tok_end - tok_start); if(strncasecompare(no_proxy + tok_start, checkn, tok_end - tok_start)) { if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') { /* We either have an exact match, or the previous character is a . * so it is within the same domain, so no proxy for this host. */ return TRUE; } } } /* if((tok_end - tok_start) <= namelen) */ } /* for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) */ } /* NO_PROXY was specified and it wasn't just an asterisk */ return FALSE; } #ifndef CURL_DISABLE_HTTP /**************************************************************** * Detect what (if any) proxy to use. Remember that this selects a host * name and is not limited to HTTP proxies only. * The returned pointer must be freed by the caller (unless NULL) ****************************************************************/ static char *detect_proxy(struct connectdata *conn) { char *proxy = NULL; /* If proxy was not specified, we check for default proxy environment * variables, to enable i.e Lynx compliance: * * http_proxy=http://some.server.dom:port/ * https_proxy=http://some.server.dom:port/ * ftp_proxy=http://some.server.dom:port/ * no_proxy=domain1.dom,host.domain2.dom * (a comma-separated list of hosts which should * not be proxied, or an asterisk to override * all proxy variables) * all_proxy=http://some.server.dom:port/ * (seems to exist for the CERN www lib. Probably * the first to check for.) * * For compatibility, the all-uppercase versions of these variables are * checked if the lowercase versions don't exist. */ char proxy_env[128]; const char *protop = conn->handler->scheme; char *envp = proxy_env; char *prox; /* Now, build <protocol>_proxy and check for such a one to use */ while(*protop) *envp++ = (char)tolower((int)*protop++); /* append _proxy */ strcpy(envp, "_proxy"); /* read the protocol proxy: */ prox = curl_getenv(proxy_env); /* * We don't try the uppercase version of HTTP_PROXY because of * security reasons: * * When curl is used in a webserver application * environment (cgi or php), this environment variable can * be controlled by the web server user by setting the * http header 'Proxy:' to some value. * * This can cause 'internal' http/ftp requests to be * arbitrarily redirected by any external attacker. */ if(!prox && !strcasecompare("http_proxy", proxy_env)) { /* There was no lowercase variable, try the uppercase version: */ Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env)); prox = curl_getenv(proxy_env); } envp = proxy_env; if(prox) { proxy = prox; /* use this */ } else { envp = (char *)"all_proxy"; proxy = curl_getenv(envp); /* default proxy to use */ if(!proxy) { envp = (char *)"ALL_PROXY"; proxy = curl_getenv(envp); } } if(proxy) infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy); return proxy; } #endif /* CURL_DISABLE_HTTP */ /* * If this is supposed to use a proxy, we need to figure out the proxy * host name, so that we can re-use an existing connection * that may exist registered to the same proxy host. */ static CURLcode parse_proxy(struct Curl_easy *data, struct connectdata *conn, char *proxy, curl_proxytype proxytype) { char *portptr; long port = -1; char *proxyuser = NULL; char *proxypasswd = NULL; char *host; bool sockstype; CURLUcode uc; struct proxy_info *proxyinfo; CURLU *uhp = curl_url(); CURLcode result = CURLE_OK; char *scheme = NULL; /* When parsing the proxy, allowing non-supported schemes since we have these made up ones for proxies. Guess scheme for URLs without it. */ uc = curl_url_set(uhp, CURLUPART_URL, proxy, CURLU_NON_SUPPORT_SCHEME|CURLU_GUESS_SCHEME); if(!uc) { /* parsed okay as a URL */ uc = curl_url_get(uhp, CURLUPART_SCHEME, &scheme, 0); if(uc) { result = CURLE_OUT_OF_MEMORY; goto error; } if(strcasecompare("https", scheme)) proxytype = CURLPROXY_HTTPS; else if(strcasecompare("socks5h", scheme)) proxytype = CURLPROXY_SOCKS5_HOSTNAME; else if(strcasecompare("socks5", scheme)) proxytype = CURLPROXY_SOCKS5; else if(strcasecompare("socks4a", scheme)) proxytype = CURLPROXY_SOCKS4A; else if(strcasecompare("socks4", scheme) || strcasecompare("socks", scheme)) proxytype = CURLPROXY_SOCKS4; else if(strcasecompare("http", scheme)) ; /* leave it as HTTP or HTTP/1.0 */ else { /* Any other xxx:// reject! */ failf(data, "Unsupported proxy scheme for \'%s\'", proxy); result = CURLE_COULDNT_CONNECT; goto error; } } else { failf(data, "Unsupported proxy syntax in \'%s\'", proxy); result = CURLE_COULDNT_RESOLVE_PROXY; goto error; } #ifdef USE_SSL if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY)) #endif if(proxytype == CURLPROXY_HTTPS) { failf(data, "Unsupported proxy \'%s\', libcurl is built without the " "HTTPS-proxy support.", proxy); result = CURLE_NOT_BUILT_IN; goto error; } sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME || proxytype == CURLPROXY_SOCKS5 || proxytype == CURLPROXY_SOCKS4A || proxytype == CURLPROXY_SOCKS4; proxyinfo = sockstype ? &conn->socks_proxy : &conn->http_proxy; proxyinfo->proxytype = proxytype; /* Is there a username and password given in this proxy url? */ curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE); curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE); if(proxyuser || proxypasswd) { Curl_safefree(proxyinfo->user); proxyinfo->user = proxyuser; Curl_safefree(proxyinfo->passwd); if(!proxypasswd) { proxypasswd = strdup(""); if(!proxypasswd) { result = CURLE_OUT_OF_MEMORY; goto error; } } proxyinfo->passwd = proxypasswd; conn->bits.proxy_user_passwd = TRUE; /* enable it */ } curl_url_get(uhp, CURLUPART_PORT, &portptr, 0); if(portptr) { port = strtol(portptr, NULL, 10); free(portptr); } else { if(data->set.proxyport) /* None given in the proxy string, then get the default one if it is given */ port = data->set.proxyport; else { if(proxytype == CURLPROXY_HTTPS) port = CURL_DEFAULT_HTTPS_PROXY_PORT; else port = CURL_DEFAULT_PROXY_PORT; } } if(port >= 0) { proxyinfo->port = port; if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc) conn->port = port; } /* now, clone the proxy host name */ uc = curl_url_get(uhp, CURLUPART_HOST, &host, CURLU_URLDECODE); if(uc) { result = CURLE_OUT_OF_MEMORY; goto error; } Curl_safefree(proxyinfo->host.rawalloc); proxyinfo->host.rawalloc = host; if(host[0] == '[') { /* this is a numerical IPv6, strip off the brackets */ size_t len = strlen(host); host[len-1] = 0; /* clear the trailing bracket */ host++; } proxyinfo->host.name = host; error: free(scheme); curl_url_cleanup(uhp); return result; } /* * Extract the user and password from the authentication string */ static CURLcode parse_proxy_auth(struct Curl_easy *data, struct connectdata *conn) { char proxyuser[MAX_CURL_USER_LENGTH]=""; char proxypasswd[MAX_CURL_PASSWORD_LENGTH]=""; CURLcode result; if(data->set.str[STRING_PROXYUSERNAME] != NULL) { strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME], MAX_CURL_USER_LENGTH); proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/ } if(data->set.str[STRING_PROXYPASSWORD] != NULL) { strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD], MAX_CURL_PASSWORD_LENGTH); proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/ } result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL, FALSE); if(!result) result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd, NULL, FALSE); return result; } /* create_conn helper to parse and init proxy values. to be called after unix socket init but before any proxy vars are evaluated. */ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn) { char *proxy = NULL; char *socksproxy = NULL; char *no_proxy = NULL; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; /************************************************************* * Extract the user and password from the authentication string *************************************************************/ if(conn->bits.proxy_user_passwd) { result = parse_proxy_auth(data, conn); if(result) goto out; } /************************************************************* * Detect what (if any) proxy to use *************************************************************/ if(data->set.str[STRING_PROXY]) { proxy = strdup(data->set.str[STRING_PROXY]); /* if global proxy is set, this is it */ if(NULL == proxy) { failf(data, "memory shortage"); result = CURLE_OUT_OF_MEMORY; goto out; } } if(data->set.str[STRING_PRE_PROXY]) { socksproxy = strdup(data->set.str[STRING_PRE_PROXY]); /* if global socks proxy is set, this is it */ if(NULL == socksproxy) { failf(data, "memory shortage"); result = CURLE_OUT_OF_MEMORY; goto out; } } if(!data->set.str[STRING_NOPROXY]) { const char *p = "no_proxy"; no_proxy = curl_getenv(p); if(!no_proxy) { p = "NO_PROXY"; no_proxy = curl_getenv(p); } if(no_proxy) { infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy); } } if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ? data->set.str[STRING_NOPROXY] : no_proxy)) { Curl_safefree(proxy); Curl_safefree(socksproxy); } #ifndef CURL_DISABLE_HTTP else if(!proxy && !socksproxy) /* if the host is not in the noproxy list, detect proxy. */ proxy = detect_proxy(conn); #endif /* CURL_DISABLE_HTTP */ Curl_safefree(no_proxy); #ifdef USE_UNIX_SOCKETS /* For the time being do not mix proxy and unix domain sockets. See #1274 */ if(proxy && conn->unix_domain_socket) { free(proxy); proxy = NULL; } #endif if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) { free(proxy); /* Don't bother with an empty proxy string or if the protocol doesn't work with network */ proxy = NULL; } if(socksproxy && (!*socksproxy || (conn->handler->flags & PROTOPT_NONETWORK))) { free(socksproxy); /* Don't bother with an empty socks proxy string or if the protocol doesn't work with network */ socksproxy = NULL; } /*********************************************************************** * If this is supposed to use a proxy, we need to figure out the proxy host * name, proxy type and port number, so that we can re-use an existing * connection that may exist registered to the same proxy host. ***********************************************************************/ if(proxy || socksproxy) { if(proxy) { result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype); Curl_safefree(proxy); /* parse_proxy copies the proxy string */ if(result) goto out; } if(socksproxy) { result = parse_proxy(data, conn, socksproxy, conn->socks_proxy.proxytype); /* parse_proxy copies the socks proxy string */ Curl_safefree(socksproxy); if(result) goto out; } if(conn->http_proxy.host.rawalloc) { #ifdef CURL_DISABLE_HTTP /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */ result = CURLE_UNSUPPORTED_PROTOCOL; goto out; #else /* force this connection's protocol to become HTTP if compatible */ if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) { if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) && !conn->bits.tunnel_proxy) conn->handler = &Curl_handler_http; else /* if not converting to HTTP over the proxy, enforce tunneling */ conn->bits.tunnel_proxy = TRUE; } conn->bits.httpproxy = TRUE; #endif } else { conn->bits.httpproxy = FALSE; /* not a HTTP proxy */ conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */ } if(conn->socks_proxy.host.rawalloc) { if(!conn->http_proxy.host.rawalloc) { /* once a socks proxy */ if(!conn->socks_proxy.user) { conn->socks_proxy.user = conn->http_proxy.user; conn->http_proxy.user = NULL; Curl_safefree(conn->socks_proxy.passwd); conn->socks_proxy.passwd = conn->http_proxy.passwd; conn->http_proxy.passwd = NULL; } } conn->bits.socksproxy = TRUE; } else conn->bits.socksproxy = FALSE; /* not a socks proxy */ } else { conn->bits.socksproxy = FALSE; conn->bits.httpproxy = FALSE; } conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy; if(!conn->bits.proxy) { /* we aren't using the proxy after all... */ conn->bits.proxy = FALSE; conn->bits.httpproxy = FALSE; conn->bits.socksproxy = FALSE; conn->bits.proxy_user_passwd = FALSE; conn->bits.tunnel_proxy = FALSE; } out: free(socksproxy); free(proxy); return result; } #endif /* CURL_DISABLE_PROXY */ /* * Curl_parse_login_details() * * This is used to parse a login string for user name, password and options in * the following formats: * * user * user:password * user:password;options * user;options * user;options:password * :password * :password;options * ;options * ;options:password * * Parameters: * * login [in] - The login string. * len [in] - The length of the login string. * userp [in/out] - The address where a pointer to newly allocated memory * holding the user will be stored upon completion. * passwdp [in/out] - The address where a pointer to newly allocated memory * holding the password will be stored upon completion. * optionsp [in/out] - The address where a pointer to newly allocated memory * holding the options will be stored upon completion. * * Returns CURLE_OK on success. */ CURLcode Curl_parse_login_details(const char *login, const size_t len, char **userp, char **passwdp, char **optionsp) { CURLcode result = CURLE_OK; char *ubuf = NULL; char *pbuf = NULL; char *obuf = NULL; const char *psep = NULL; const char *osep = NULL; size_t ulen; size_t plen; size_t olen; /* Attempt to find the password separator */ if(passwdp) { psep = strchr(login, ':'); /* Within the constraint of the login string */ if(psep >= login + len) psep = NULL; } /* Attempt to find the options separator */ if(optionsp) { osep = strchr(login, ';'); /* Within the constraint of the login string */ if(osep >= login + len) osep = NULL; } /* Calculate the portion lengths */ ulen = (psep ? (size_t)(osep && psep > osep ? osep - login : psep - login) : (osep ? (size_t)(osep - login) : len)); plen = (psep ? (osep && osep > psep ? (size_t)(osep - psep) : (size_t)(login + len - psep)) - 1 : 0); olen = (osep ? (psep && psep > osep ? (size_t)(psep - osep) : (size_t)(login + len - osep)) - 1 : 0); /* Allocate the user portion buffer */ if(userp && ulen) { ubuf = malloc(ulen + 1); if(!ubuf) result = CURLE_OUT_OF_MEMORY; } /* Allocate the password portion buffer */ if(!result && passwdp && plen) { pbuf = malloc(plen + 1); if(!pbuf) { free(ubuf); result = CURLE_OUT_OF_MEMORY; } } /* Allocate the options portion buffer */ if(!result && optionsp && olen) { obuf = malloc(olen + 1); if(!obuf) { free(pbuf); free(ubuf); result = CURLE_OUT_OF_MEMORY; } } if(!result) { /* Store the user portion if necessary */ if(ubuf) { memcpy(ubuf, login, ulen); ubuf[ulen] = '\0'; Curl_safefree(*userp); *userp = ubuf; } /* Store the password portion if necessary */ if(pbuf) { memcpy(pbuf, psep + 1, plen); pbuf[plen] = '\0'; Curl_safefree(*passwdp); *passwdp = pbuf; } /* Store the options portion if necessary */ if(obuf) { memcpy(obuf, osep + 1, olen); obuf[olen] = '\0'; Curl_safefree(*optionsp); *optionsp = obuf; } } return result; } /************************************************************* * Figure out the remote port number and fix it in the URL * * No matter if we use a proxy or not, we have to figure out the remote * port number of various reasons. * * The port number embedded in the URL is replaced, if necessary. *************************************************************/ static CURLcode parse_remote_port(struct Curl_easy *data, struct connectdata *conn) { if(data->set.use_port && data->state.allow_port) { /* if set, we use this instead of the port possibly given in the URL */ char portbuf[16]; CURLUcode uc; conn->remote_port = (unsigned short)data->set.use_port; msnprintf(portbuf, sizeof(portbuf), "%d", conn->remote_port); uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0); if(uc) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } /* * Override the login details from the URL with that in the CURLOPT_USERPWD * option or a .netrc file, if applicable. */ static CURLcode override_login(struct Curl_easy *data, struct connectdata *conn, char **userp, char **passwdp, char **optionsp) { bool user_changed = FALSE; bool passwd_changed = FALSE; CURLUcode uc; if(data->set.use_netrc == CURL_NETRC_REQUIRED && conn->bits.user_passwd) { /* ignore user+password in the URL */ if(*userp) { Curl_safefree(*userp); user_changed = TRUE; } if(*passwdp) { Curl_safefree(*passwdp); passwd_changed = TRUE; } conn->bits.user_passwd = FALSE; /* disable user+password */ } if(data->set.str[STRING_USERNAME]) { free(*userp); *userp = strdup(data->set.str[STRING_USERNAME]); if(!*userp) return CURLE_OUT_OF_MEMORY; conn->bits.user_passwd = TRUE; /* enable user+password */ user_changed = TRUE; } if(data->set.str[STRING_PASSWORD]) { free(*passwdp); *passwdp = strdup(data->set.str[STRING_PASSWORD]); if(!*passwdp) return CURLE_OUT_OF_MEMORY; conn->bits.user_passwd = TRUE; /* enable user+password */ passwd_changed = TRUE; } if(data->set.str[STRING_OPTIONS]) { free(*optionsp); *optionsp = strdup(data->set.str[STRING_OPTIONS]); if(!*optionsp) return CURLE_OUT_OF_MEMORY; } conn->bits.netrc = FALSE; if(data->set.use_netrc != CURL_NETRC_IGNORED && (!*userp || !**userp || !*passwdp || !**passwdp)) { bool netrc_user_changed = FALSE; bool netrc_passwd_changed = FALSE; int ret; ret = Curl_parsenetrc(conn->host.name, userp, passwdp, &netrc_user_changed, &netrc_passwd_changed, data->set.str[STRING_NETRC_FILE]); if(ret > 0) { infof(data, "Couldn't find host %s in the " DOT_CHAR "netrc file; using defaults\n", conn->host.name); } else if(ret < 0) { return CURLE_OUT_OF_MEMORY; } else { /* set bits.netrc TRUE to remember that we got the name from a .netrc file, so that it is safe to use even if we followed a Location: to a different host or similar. */ conn->bits.netrc = TRUE; conn->bits.user_passwd = TRUE; /* enable user+password */ if(netrc_user_changed) { user_changed = TRUE; } if(netrc_passwd_changed) { passwd_changed = TRUE; } } } /* for updated strings, we update them in the URL */ if(user_changed) { uc = curl_url_set(data->state.uh, CURLUPART_USER, *userp, 0); if(uc) return Curl_uc_to_curlcode(uc); } if(passwd_changed) { uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, *passwdp, 0); if(uc) return Curl_uc_to_curlcode(uc); } return CURLE_OK; } /* * Set the login details so they're available in the connection */ static CURLcode set_login(struct connectdata *conn) { CURLcode result = CURLE_OK; const char *setuser = CURL_DEFAULT_USER; const char *setpasswd = CURL_DEFAULT_PASSWORD; /* If our protocol needs a password and we have none, use the defaults */ if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) ; else { setuser = ""; setpasswd = ""; } /* Store the default user */ if(!conn->user) { conn->user = strdup(setuser); if(!conn->user) return CURLE_OUT_OF_MEMORY; } /* Store the default password */ if(!conn->passwd) { conn->passwd = strdup(setpasswd); if(!conn->passwd) result = CURLE_OUT_OF_MEMORY; } /* if there's a user without password, consider password blank */ if(conn->user && !conn->passwd) { conn->passwd = strdup(""); if(!conn->passwd) result = CURLE_OUT_OF_MEMORY; } return result; } /* * Parses a "host:port" string to connect to. * The hostname and the port may be empty; in this case, NULL is returned for * the hostname and -1 for the port. */ static CURLcode parse_connect_to_host_port(struct Curl_easy *data, const char *host, char **hostname_result, int *port_result) { char *host_dup; char *hostptr; char *host_portno; char *portptr; int port = -1; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) data; #endif *hostname_result = NULL; *port_result = -1; if(!host || !*host) return CURLE_OK; host_dup = strdup(host); if(!host_dup) return CURLE_OUT_OF_MEMORY; hostptr = host_dup; /* start scanning for port number at this point */ portptr = hostptr; /* detect and extract RFC6874-style IPv6-addresses */ if(*hostptr == '[') { #ifdef ENABLE_IPV6 char *ptr = ++hostptr; /* advance beyond the initial bracket */ while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.'))) ptr++; if(*ptr == '%') { /* There might be a zone identifier */ if(strncmp("%25", ptr, 3)) infof(data, "Please URL encode %% as %%25, see RFC 6874.\n"); ptr++; /* Allow unreserved characters as defined in RFC 3986 */ while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') || (*ptr == '.') || (*ptr == '_') || (*ptr == '~'))) ptr++; } if(*ptr == ']') /* yeps, it ended nicely with a bracket as well */ *ptr++ = '\0'; else infof(data, "Invalid IPv6 address format\n"); portptr = ptr; /* Note that if this didn't end with a bracket, we still advanced the * hostptr first, but I can't see anything wrong with that as no host * name nor a numeric can legally start with a bracket. */ #else failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!"); free(host_dup); return CURLE_NOT_BUILT_IN; #endif } /* Get port number off server.com:1080 */ host_portno = strchr(portptr, ':'); if(host_portno) { char *endp = NULL; *host_portno = '\0'; /* cut off number from host name */ host_portno++; if(*host_portno) { long portparse = strtol(host_portno, &endp, 10); if((endp && *endp) || (portparse < 0) || (portparse > 65535)) { infof(data, "No valid port number in connect to host string (%s)\n", host_portno); hostptr = NULL; port = -1; } else port = (int)portparse; /* we know it will fit */ } } /* now, clone the cleaned host name */ if(hostptr) { *hostname_result = strdup(hostptr); if(!*hostname_result) { free(host_dup); return CURLE_OUT_OF_MEMORY; } } *port_result = port; free(host_dup); return CURLE_OK; } /* * Parses one "connect to" string in the form: * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT". */ static CURLcode parse_connect_to_string(struct Curl_easy *data, struct connectdata *conn, const char *conn_to_host, char **host_result, int *port_result) { CURLcode result = CURLE_OK; const char *ptr = conn_to_host; int host_match = FALSE; int port_match = FALSE; *host_result = NULL; *port_result = -1; if(*ptr == ':') { /* an empty hostname always matches */ host_match = TRUE; ptr++; } else { /* check whether the URL's hostname matches */ size_t hostname_to_match_len; char *hostname_to_match = aprintf("%s%s%s", conn->bits.ipv6_ip ? "[" : "", conn->host.name, conn->bits.ipv6_ip ? "]" : ""); if(!hostname_to_match) return CURLE_OUT_OF_MEMORY; hostname_to_match_len = strlen(hostname_to_match); host_match = strncasecompare(ptr, hostname_to_match, hostname_to_match_len); free(hostname_to_match); ptr += hostname_to_match_len; host_match = host_match && *ptr == ':'; ptr++; } if(host_match) { if(*ptr == ':') { /* an empty port always matches */ port_match = TRUE; ptr++; } else { /* check whether the URL's port matches */ char *ptr_next = strchr(ptr, ':'); if(ptr_next) { char *endp = NULL; long port_to_match = strtol(ptr, &endp, 10); if((endp == ptr_next) && (port_to_match == conn->remote_port)) { port_match = TRUE; ptr = ptr_next + 1; } } } } if(host_match && port_match) { /* parse the hostname and port to connect to */ result = parse_connect_to_host_port(data, ptr, host_result, port_result); } return result; } /* * Processes all strings in the "connect to" slist, and uses the "connect * to host" and "connect to port" of the first string that matches. */ static CURLcode parse_connect_to_slist(struct Curl_easy *data, struct connectdata *conn, struct curl_slist *conn_to_host) { CURLcode result = CURLE_OK; char *host = NULL; int port = -1; while(conn_to_host && !host && port == -1) { result = parse_connect_to_string(data, conn, conn_to_host->data, &host, &port); if(result) return result; if(host && *host) { conn->conn_to_host.rawalloc = host; conn->conn_to_host.name = host; conn->bits.conn_to_host = TRUE; infof(data, "Connecting to hostname: %s\n", host); } else { /* no "connect to host" */ conn->bits.conn_to_host = FALSE; Curl_safefree(host); } if(port >= 0) { conn->conn_to_port = port; conn->bits.conn_to_port = TRUE; infof(data, "Connecting to port: %d\n", port); } else { /* no "connect to port" */ conn->bits.conn_to_port = FALSE; port = -1; } conn_to_host = conn_to_host->next; } #ifdef USE_ALTSVC if(data->asi && !host && (port == -1) && (conn->handler->protocol == CURLPROTO_HTTPS)) { /* no connect_to match, try alt-svc! */ const char *nhost; int nport; enum alpnid nalpnid; bool hit; host = conn->host.rawalloc; hit = Curl_altsvc_lookup(data->asi, ALPN_h1, host, conn->remote_port, /* from */ &nalpnid, &nhost, &nport /* to */); if(hit) { char *hostd = strdup((char *)nhost); if(!hostd) return CURLE_OUT_OF_MEMORY; conn->conn_to_host.rawalloc = hostd; conn->conn_to_host.name = hostd; conn->bits.conn_to_host = TRUE; conn->conn_to_port = nport; conn->bits.conn_to_port = TRUE; infof(data, "Alt-svc connecting from [%s]%s:%d to [%s]%s:%d\n", Curl_alpnid2str(ALPN_h1), host, conn->remote_port, Curl_alpnid2str(nalpnid), hostd, nport); } } #endif return result; } /************************************************************* * Resolve the address of the server or proxy *************************************************************/ static CURLcode resolve_server(struct Curl_easy *data, struct connectdata *conn, bool *async) { CURLcode result = CURLE_OK; timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); DEBUGASSERT(conn); DEBUGASSERT(data); /************************************************************* * Resolve the name of the server or proxy *************************************************************/ if(conn->bits.reuse) /* We're reusing the connection - no need to resolve anything, and idnconvert_hostname() was called already in create_conn() for the re-use case. */ *async = FALSE; else { /* this is a fresh connect */ int rc; struct Curl_dns_entry *hostaddr; #ifdef USE_UNIX_SOCKETS if(conn->unix_domain_socket) { /* Unix domain sockets are local. The host gets ignored, just use the * specified domain socket address. Do not cache "DNS entries". There is * no DNS involved and we already have the filesystem path available */ const char *path = conn->unix_domain_socket; hostaddr = calloc(1, sizeof(struct Curl_dns_entry)); if(!hostaddr) result = CURLE_OUT_OF_MEMORY; else { bool longpath = FALSE; hostaddr->addr = Curl_unix2addr(path, &longpath, conn->abstract_unix_socket); if(hostaddr->addr) hostaddr->inuse++; else { /* Long paths are not supported for now */ if(longpath) { failf(data, "Unix socket path too long: '%s'", path); result = CURLE_COULDNT_RESOLVE_HOST; } else result = CURLE_OUT_OF_MEMORY; free(hostaddr); hostaddr = NULL; } } } else #endif if(!conn->bits.proxy) { struct hostname *connhost; if(conn->bits.conn_to_host) connhost = &conn->conn_to_host; else connhost = &conn->host; /* If not connecting via a proxy, extract the port from the URL, if it is * there, thus overriding any defaults that might have been set above. */ if(conn->bits.conn_to_port) conn->port = conn->conn_to_port; else conn->port = conn->remote_port; /* Resolve target host right on */ conn->hostname_resolve = strdup(connhost->name); if(!conn->hostname_resolve) return CURLE_OUT_OF_MEMORY; rc = Curl_resolv_timeout(conn, conn->hostname_resolve, (int)conn->port, &hostaddr, timeout_ms); if(rc == CURLRESOLV_PENDING) *async = TRUE; else if(rc == CURLRESOLV_TIMEDOUT) result = CURLE_OPERATION_TIMEDOUT; else if(!hostaddr) { failf(data, "Couldn't resolve host '%s'", connhost->dispname); result = CURLE_COULDNT_RESOLVE_HOST; /* don't return yet, we need to clean up the timeout first */ } } else { /* This is a proxy that hasn't been resolved yet. */ struct hostname * const host = conn->bits.socksproxy ? &conn->socks_proxy.host : &conn->http_proxy.host; /* resolve proxy */ conn->hostname_resolve = strdup(host->name); if(!conn->hostname_resolve) return CURLE_OUT_OF_MEMORY; rc = Curl_resolv_timeout(conn, conn->hostname_resolve, (int)conn->port, &hostaddr, timeout_ms); if(rc == CURLRESOLV_PENDING) *async = TRUE; else if(rc == CURLRESOLV_TIMEDOUT) result = CURLE_OPERATION_TIMEDOUT; else if(!hostaddr) { failf(data, "Couldn't resolve proxy '%s'", host->dispname); result = CURLE_COULDNT_RESOLVE_PROXY; /* don't return yet, we need to clean up the timeout first */ } } DEBUGASSERT(conn->dns_entry == NULL); conn->dns_entry = hostaddr; } return result; } /* * Cleanup the connection just allocated before we can move along and use the * previously existing one. All relevant data is copied over and old_conn is * ready for freeing once this function returns. */ static void reuse_conn(struct connectdata *old_conn, struct connectdata *conn) { free_idnconverted_hostname(&old_conn->http_proxy.host); free_idnconverted_hostname(&old_conn->socks_proxy.host); free(old_conn->http_proxy.host.rawalloc); free(old_conn->socks_proxy.host.rawalloc); /* free the SSL config struct from this connection struct as this was allocated in vain and is targeted for destruction */ Curl_free_primary_ssl_config(&old_conn->ssl_config); Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config); conn->data = old_conn->data; /* get the user+password information from the old_conn struct since it may * be new for this request even when we re-use an existing connection */ conn->bits.user_passwd = old_conn->bits.user_passwd; if(conn->bits.user_passwd) { /* use the new user name and password though */ Curl_safefree(conn->user); Curl_safefree(conn->passwd); conn->user = old_conn->user; conn->passwd = old_conn->passwd; old_conn->user = NULL; old_conn->passwd = NULL; } conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd; if(conn->bits.proxy_user_passwd) { /* use the new proxy user name and proxy password though */ Curl_safefree(conn->http_proxy.user); Curl_safefree(conn->socks_proxy.user); Curl_safefree(conn->http_proxy.passwd); Curl_safefree(conn->socks_proxy.passwd); conn->http_proxy.user = old_conn->http_proxy.user; conn->socks_proxy.user = old_conn->socks_proxy.user; conn->http_proxy.passwd = old_conn->http_proxy.passwd; conn->socks_proxy.passwd = old_conn->socks_proxy.passwd; old_conn->http_proxy.user = NULL; old_conn->socks_proxy.user = NULL; old_conn->http_proxy.passwd = NULL; old_conn->socks_proxy.passwd = NULL; } /* host can change, when doing keepalive with a proxy or if the case is different this time etc */ free_idnconverted_hostname(&conn->host); free_idnconverted_hostname(&conn->conn_to_host); Curl_safefree(conn->host.rawalloc); Curl_safefree(conn->conn_to_host.rawalloc); conn->host = old_conn->host; conn->conn_to_host = old_conn->conn_to_host; conn->conn_to_port = old_conn->conn_to_port; conn->remote_port = old_conn->remote_port; Curl_safefree(conn->hostname_resolve); conn->hostname_resolve = old_conn->hostname_resolve; old_conn->hostname_resolve = NULL; /* persist connection info in session handle */ Curl_persistconninfo(conn); conn_reset_all_postponed_data(old_conn); /* free buffers */ /* re-use init */ conn->bits.reuse = TRUE; /* yes, we're re-using here */ Curl_safefree(old_conn->user); Curl_safefree(old_conn->passwd); Curl_safefree(old_conn->options); Curl_safefree(old_conn->http_proxy.user); Curl_safefree(old_conn->socks_proxy.user); Curl_safefree(old_conn->http_proxy.passwd); Curl_safefree(old_conn->socks_proxy.passwd); Curl_safefree(old_conn->localdev); Curl_llist_destroy(&old_conn->easyq, NULL); #ifdef USE_UNIX_SOCKETS Curl_safefree(old_conn->unix_domain_socket); #endif } /** * create_conn() sets up a new connectdata struct, or re-uses an already * existing one, and resolves host name. * * if this function returns CURLE_OK and *async is set to TRUE, the resolve * response will be coming asynchronously. If *async is FALSE, the name is * already resolved. * * @param data The sessionhandle pointer * @param in_connect is set to the next connection data pointer * @param async is set TRUE when an async DNS resolution is pending * @see Curl_setup_conn() * * *NOTE* this function assigns the conn->data pointer! */ static CURLcode create_conn(struct Curl_easy *data, struct connectdata **in_connect, bool *async) { CURLcode result = CURLE_OK; struct connectdata *conn; struct connectdata *conn_temp = NULL; bool reuse; bool connections_available = TRUE; bool force_reuse = FALSE; bool waitpipe = FALSE; size_t max_host_connections = Curl_multi_max_host_connections(data->multi); size_t max_total_connections = Curl_multi_max_total_connections(data->multi); *async = FALSE; *in_connect = NULL; /************************************************************* * Check input data *************************************************************/ if(!data->change.url) { result = CURLE_URL_MALFORMAT; goto out; } /* First, split up the current URL in parts so that we can use the parts for checking against the already present connections. In order to not have to modify everything at once, we allocate a temporary connection data struct and fill in for comparison purposes. */ conn = allocate_conn(data); if(!conn) { result = CURLE_OUT_OF_MEMORY; goto out; } /* We must set the return variable as soon as possible, so that our parent can cleanup any possible allocs we may have done before any failure */ *in_connect = conn; result = parseurlandfillconn(data, conn); if(result) goto out; if(data->set.str[STRING_BEARER]) { conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]); if(!conn->oauth_bearer) { result = CURLE_OUT_OF_MEMORY; goto out; } } #ifdef USE_UNIX_SOCKETS if(data->set.str[STRING_UNIX_SOCKET_PATH]) { conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]); if(conn->unix_domain_socket == NULL) { result = CURLE_OUT_OF_MEMORY; goto out; } conn->abstract_unix_socket = data->set.abstract_unix_socket; } #endif /* After the unix socket init but before the proxy vars are used, parse and initialize the proxy vars */ #ifndef CURL_DISABLE_PROXY result = create_conn_helper_init_proxy(conn); if(result) goto out; #endif /************************************************************* * If the protocol is using SSL and HTTP proxy is used, we set * the tunnel_proxy bit. *************************************************************/ if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy) conn->bits.tunnel_proxy = TRUE; /************************************************************* * Figure out the remote port number and fix it in the URL *************************************************************/ result = parse_remote_port(data, conn); if(result) goto out; /* Check for overridden login details and set them accordingly so they they are known when protocol->setup_connection is called! */ result = override_login(data, conn, &conn->user, &conn->passwd, &conn->options); if(result) goto out; result = set_login(conn); /* default credentials */ if(result) goto out; /************************************************************* * Process the "connect to" linked list of hostname/port mappings. * Do this after the remote port number has been fixed in the URL. *************************************************************/ result = parse_connect_to_slist(data, conn, data->set.connect_to); if(result) goto out; /************************************************************* * IDN-convert the hostnames *************************************************************/ result = idnconvert_hostname(conn, &conn->host); if(result) goto out; if(conn->bits.conn_to_host) { result = idnconvert_hostname(conn, &conn->conn_to_host); if(result) goto out; } if(conn->bits.httpproxy) { result = idnconvert_hostname(conn, &conn->http_proxy.host); if(result) goto out; } if(conn->bits.socksproxy) { result = idnconvert_hostname(conn, &conn->socks_proxy.host); if(result) goto out; } /************************************************************* * Check whether the host and the "connect to host" are equal. * Do this after the hostnames have been IDN-converted. *************************************************************/ if(conn->bits.conn_to_host && strcasecompare(conn->conn_to_host.name, conn->host.name)) { conn->bits.conn_to_host = FALSE; } /************************************************************* * Check whether the port and the "connect to port" are equal. * Do this after the remote port number has been fixed in the URL. *************************************************************/ if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { conn->bits.conn_to_port = FALSE; } /************************************************************* * If the "connect to" feature is used with an HTTP proxy, * we set the tunnel_proxy bit. *************************************************************/ if((conn->bits.conn_to_host || conn->bits.conn_to_port) && conn->bits.httpproxy) conn->bits.tunnel_proxy = TRUE; /************************************************************* * Setup internals depending on protocol. Needs to be done after * we figured out what/if proxy to use. *************************************************************/ result = setup_connection_internals(conn); if(result) goto out; conn->recv[FIRSTSOCKET] = Curl_recv_plain; conn->send[FIRSTSOCKET] = Curl_send_plain; conn->recv[SECONDARYSOCKET] = Curl_recv_plain; conn->send[SECONDARYSOCKET] = Curl_send_plain; conn->bits.tcp_fastopen = data->set.tcp_fastopen; /*********************************************************************** * file: is a special case in that it doesn't need a network connection ***********************************************************************/ #ifndef CURL_DISABLE_FILE if(conn->handler->flags & PROTOPT_NONETWORK) { bool done; /* this is supposed to be the connect function so we better at least check that the file is present here! */ DEBUGASSERT(conn->handler->connect_it); Curl_persistconninfo(conn); result = conn->handler->connect_it(conn, &done); /* Setup a "faked" transfer that'll do nothing */ if(!result) { conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */ result = Curl_conncache_add_conn(data->state.conn_cache, conn); if(result) goto out; /* * Setup whatever necessary for a resumed transfer */ result = setup_range(data); if(result) { DEBUGASSERT(conn->handler->done); /* we ignore the return code for the protocol-specific DONE */ (void)conn->handler->done(conn, result, FALSE); goto out; } Curl_attach_connnection(data, conn); Curl_setup_transfer(data, -1, -1, FALSE, -1); } /* since we skip do_init() */ Curl_init_do(data, conn); goto out; } #endif /* Get a cloned copy of the SSL config situation stored in the connection struct. But to get this going nicely, we must first make sure that the strings in the master copy are pointing to the correct strings in the session handle strings array! Keep in mind that the pointers in the master copy are pointing to strings that will be freed as part of the Curl_easy struct, but all cloned copies will be separately allocated. */ data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG]; data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY]; data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG]; data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY]; data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; data->set.proxy_ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; data->set.ssl.primary.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST_ORIG]; data->set.proxy_ssl.primary.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST_PROXY]; data->set.ssl.primary.cipher_list13 = data->set.str[STRING_SSL_CIPHER13_LIST_ORIG]; data->set.proxy_ssl.primary.cipher_list13 = data->set.str[STRING_SSL_CIPHER13_LIST_PROXY]; data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG]; data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY]; data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG]; data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY]; data->set.ssl.cert = data->set.str[STRING_CERT_ORIG]; data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY]; data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG]; data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY]; data->set.ssl.key = data->set.str[STRING_KEY_ORIG]; data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY]; data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG]; data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY]; data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG]; data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY]; data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG]; data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY]; #ifdef USE_TLS_SRP data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG]; data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY]; data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG]; data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY]; #endif if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary, &conn->ssl_config)) { result = CURLE_OUT_OF_MEMORY; goto out; } if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary, &conn->proxy_ssl_config)) { result = CURLE_OUT_OF_MEMORY; goto out; } prune_dead_connections(data); /************************************************************* * Check the current list of connections to see if we can * re-use an already existing one or if we have to create a * new one. *************************************************************/ DEBUGASSERT(conn->user); DEBUGASSERT(conn->passwd); /* reuse_fresh is TRUE if we are told to use a new connection by force, but we only acknowledge this option if this is not a re-used connection already (which happens due to follow-location or during a HTTP authentication phase). CONNECT_ONLY transfers also refuse reuse. */ if((data->set.reuse_fresh && !data->state.this_is_a_follow) || data->set.connect_only) reuse = FALSE; else reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe); /* If we found a reusable connection that is now marked as in use, we may still want to open a new connection if we are multiplexing. */ if(reuse && !force_reuse && IsMultiplexingPossible(data, conn_temp)) { size_t multiplexed = CONN_INUSE(conn_temp); if(multiplexed > 0) { infof(data, "Found connection %ld, with %zu requests on it\n", conn_temp->connection_id, multiplexed); if(Curl_conncache_bundle_size(conn_temp) < max_host_connections && Curl_conncache_size(data) < max_total_connections) { /* We want a new connection anyway */ reuse = FALSE; infof(data, "We can reuse, but we want a new connection anyway\n"); Curl_conncache_return_conn(conn_temp); } } } if(reuse) { /* * We already have a connection for this, we got the former connection * in the conn_temp variable and thus we need to cleanup the one we * just allocated before we can move along and use the previously * existing one. */ reuse_conn(conn, conn_temp); #ifdef USE_SSL free(conn->ssl_extra); #endif free(conn); /* we don't need this anymore */ conn = conn_temp; *in_connect = conn; infof(data, "Re-using existing connection! (#%ld) with %s %s\n", conn->connection_id, conn->bits.proxy?"proxy":"host", conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname : conn->http_proxy.host.name ? conn->http_proxy.host.dispname : conn->host.dispname); } else { /* We have decided that we want a new connection. However, we may not be able to do that if we have reached the limit of how many connections we are allowed to open. */ if(conn->handler->flags & PROTOPT_ALPN_NPN) { /* The protocol wants it, so set the bits if enabled in the easy handle (default) */ if(data->set.ssl_enable_alpn) conn->bits.tls_enable_alpn = TRUE; if(data->set.ssl_enable_npn) conn->bits.tls_enable_npn = TRUE; } if(waitpipe) /* There is a connection that *might* become usable for multiplexing "soon", and we wait for that */ connections_available = FALSE; else { /* this gets a lock on the conncache */ struct connectbundle *bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache); if(max_host_connections > 0 && bundle && (bundle->num_connections >= max_host_connections)) { struct connectdata *conn_candidate; /* The bundle is full. Extract the oldest connection. */ conn_candidate = Curl_conncache_extract_bundle(data, bundle); Curl_conncache_unlock(data); if(conn_candidate) (void)Curl_disconnect(data, conn_candidate, /* dead_connection */ FALSE); else { infof(data, "No more connections allowed to host: %zu\n", max_host_connections); connections_available = FALSE; } } else Curl_conncache_unlock(data); } if(connections_available && (max_total_connections > 0) && (Curl_conncache_size(data) >= max_total_connections)) { struct connectdata *conn_candidate; /* The cache is full. Let's see if we can kill a connection. */ conn_candidate = Curl_conncache_extract_oldest(data); if(conn_candidate) (void)Curl_disconnect(data, conn_candidate, /* dead_connection */ FALSE); else { infof(data, "No connections available in cache\n"); connections_available = FALSE; } } if(!connections_available) { infof(data, "No connections available.\n"); conn_free(conn); *in_connect = NULL; result = CURLE_NO_CONNECTION_AVAILABLE; goto out; } else { /* * This is a brand new connection, so let's store it in the connection * cache of ours! */ result = Curl_conncache_add_conn(data->state.conn_cache, conn); if(result) goto out; } #if defined(USE_NTLM) /* If NTLM is requested in a part of this connection, make sure we don't assume the state is fine as this is a fresh connection and NTLM is connection based. */ if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && data->state.authhost.done) { infof(data, "NTLM picked AND auth done set, clear picked!\n"); data->state.authhost.picked = CURLAUTH_NONE; data->state.authhost.done = FALSE; } if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && data->state.authproxy.done) { infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n"); data->state.authproxy.picked = CURLAUTH_NONE; data->state.authproxy.done = FALSE; } #endif } /* Setup and init stuff before DO starts, in preparing for the transfer. */ Curl_init_do(data, conn); /* * Setup whatever necessary for a resumed transfer */ result = setup_range(data); if(result) goto out; /* Continue connectdata initialization here. */ /* * Inherit the proper values from the urldata struct AFTER we have arranged * the persistent connection stuff */ conn->seek_func = data->set.seek_func; conn->seek_client = data->set.seek_client; /************************************************************* * Resolve the address of the server or proxy *************************************************************/ result = resolve_server(data, conn, async); /* Strip trailing dots. resolve_server copied the name. */ strip_trailing_dot(&conn->host); if(conn->bits.httpproxy) strip_trailing_dot(&conn->http_proxy.host); if(conn->bits.socksproxy) strip_trailing_dot(&conn->socks_proxy.host); if(conn->bits.conn_to_host) strip_trailing_dot(&conn->conn_to_host); out: return result; } /* Curl_setup_conn() is called after the name resolve initiated in * create_conn() is all done. * * Curl_setup_conn() also handles reused connections * * conn->data MUST already have been setup fine (in create_conn) */ CURLcode Curl_setup_conn(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; Curl_pgrsTime(data, TIMER_NAMELOOKUP); if(conn->handler->flags & PROTOPT_NONETWORK) { /* nothing to setup when not using a network */ *protocol_done = TRUE; return result; } *protocol_done = FALSE; /* default to not done */ /* set proxy_connect_closed to false unconditionally already here since it is used strictly to provide extra information to a parent function in the case of proxy CONNECT failures and we must make sure we don't have it lingering set from a previous invoke */ conn->bits.proxy_connect_closed = FALSE; /* * Set user-agent. Used for HTTP, but since we can attempt to tunnel * basically anything through a http proxy we can't limit this based on * protocol. */ if(data->set.str[STRING_USERAGENT]) { Curl_safefree(conn->allocptr.uagent); conn->allocptr.uagent = aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]); if(!conn->allocptr.uagent) return CURLE_OUT_OF_MEMORY; } data->req.headerbytecount = 0; #ifdef CURL_DO_LINEEND_CONV data->state.crlf_conversions = 0; /* reset CRLF conversion counter */ #endif /* CURL_DO_LINEEND_CONV */ /* set start time here for timeout purposes in the connect procedure, it is later set again for the progress meter purpose */ conn->now = Curl_now(); if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) { conn->bits.tcpconnect[FIRSTSOCKET] = FALSE; result = Curl_connecthost(conn, conn->dns_entry); if(result) return result; } else { Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */ Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */ conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; *protocol_done = TRUE; Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]); Curl_verboseconnect(conn); } conn->now = Curl_now(); /* time this *after* the connect is done, we set this here perhaps a second time */ return result; } CURLcode Curl_connect(struct Curl_easy *data, bool *asyncp, bool *protocol_done) { CURLcode result; struct connectdata *conn; *asyncp = FALSE; /* assume synchronous resolves by default */ /* init the single-transfer specific data */ Curl_free_request_state(data); memset(&data->req, 0, sizeof(struct SingleRequest)); data->req.maxdownload = -1; /* call the stuff that needs to be called */ result = create_conn(data, &conn, asyncp); if(!result) { if(CONN_INUSE(conn)) /* multiplexed */ *protocol_done = TRUE; else if(!*asyncp) { /* DNS resolution is done: that's either because this is a reused connection, in which case DNS was unnecessary, or because DNS really did finish already (synch resolver/fast async resolve) */ result = Curl_setup_conn(conn, protocol_done); } } if(result == CURLE_NO_CONNECTION_AVAILABLE) { return result; } else if(result && conn) { /* We're not allowed to return failure with memory left allocated in the connectdata struct, free those here */ Curl_disconnect(data, conn, TRUE); } else if(!result && !data->conn) /* FILE: transfers already have the connection attached */ Curl_attach_connnection(data, conn); return result; } /* * Curl_init_do() inits the readwrite session. This is inited each time (in * the DO function before the protocol-specific DO functions are invoked) for * a transfer, sometimes multiple times on the same Curl_easy. Make sure * nothing in here depends on stuff that are setup dynamically for the * transfer. * * Allow this function to get called with 'conn' set to NULL. */ CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn) { struct SingleRequest *k = &data->req; if(conn) { conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */ /* if the protocol used doesn't support wildcards, switch it off */ if(data->state.wildcardmatch && !(conn->handler->flags & PROTOPT_WILDCARD)) data->state.wildcardmatch = FALSE; } data->state.done = FALSE; /* *_done() is not called yet */ data->state.expect100header = FALSE; if(data->set.opt_no_body) /* in HTTP lingo, no body means using the HEAD request... */ data->set.httpreq = HTTPREQ_HEAD; else if(HTTPREQ_HEAD == data->set.httpreq) /* ... but if unset there really is no perfect method that is the "opposite" of HEAD but in reality most people probably think GET then. The important thing is that we can't let it remain HEAD if the opt_no_body is set FALSE since then we'll behave wrong when getting HTTP. */ data->set.httpreq = HTTPREQ_GET; k->start = Curl_now(); /* start time */ k->now = k->start; /* current time is now */ k->header = TRUE; /* assume header */ k->bytecount = 0; k->buf = data->state.buffer; k->hbufp = data->state.headerbuff; k->ignorebody = FALSE; Curl_speedinit(data); Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); return CURLE_OK; } /* * get_protocol_family() * * This is used to return the protocol family for a given protocol. * * Parameters: * * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS. * * Returns the family as a single bit protocol identifier. */ static unsigned int get_protocol_family(unsigned int protocol) { unsigned int family; switch(protocol) { case CURLPROTO_HTTP: case CURLPROTO_HTTPS: family = CURLPROTO_HTTP; break; case CURLPROTO_FTP: case CURLPROTO_FTPS: family = CURLPROTO_FTP; break; case CURLPROTO_SCP: family = CURLPROTO_SCP; break; case CURLPROTO_SFTP: family = CURLPROTO_SFTP; break; case CURLPROTO_TELNET: family = CURLPROTO_TELNET; break; case CURLPROTO_LDAP: case CURLPROTO_LDAPS: family = CURLPROTO_LDAP; break; case CURLPROTO_DICT: family = CURLPROTO_DICT; break; case CURLPROTO_FILE: family = CURLPROTO_FILE; break; case CURLPROTO_TFTP: family = CURLPROTO_TFTP; break; case CURLPROTO_IMAP: case CURLPROTO_IMAPS: family = CURLPROTO_IMAP; break; case CURLPROTO_POP3: case CURLPROTO_POP3S: family = CURLPROTO_POP3; break; case CURLPROTO_SMTP: case CURLPROTO_SMTPS: family = CURLPROTO_SMTP; break; case CURLPROTO_RTSP: family = CURLPROTO_RTSP; break; case CURLPROTO_RTMP: case CURLPROTO_RTMPS: family = CURLPROTO_RTMP; break; case CURLPROTO_RTMPT: case CURLPROTO_RTMPTS: family = CURLPROTO_RTMPT; break; case CURLPROTO_RTMPE: family = CURLPROTO_RTMPE; break; case CURLPROTO_RTMPTE: family = CURLPROTO_RTMPTE; break; case CURLPROTO_GOPHER: family = CURLPROTO_GOPHER; break; case CURLPROTO_SMB: case CURLPROTO_SMBS: family = CURLPROTO_SMB; break; default: family = 0; break; } return family; } /* * Wrapper to call functions in Curl_conncache_foreach() * * Returns always 0. */ static int conn_upkeep(struct connectdata *conn, void *param) { /* Param is unused. */ (void)param; if(conn->handler->connection_check) { /* Do a protocol-specific keepalive check on the connection. */ conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE); } return 0; /* continue iteration */ } CURLcode Curl_upkeep(struct conncache *conn_cache, void *data) { /* Loop over every connection and make connection alive. */ Curl_conncache_foreach(data, conn_cache, data, conn_upkeep); return CURLE_OK; }
YifuLiu/AliOS-Things
components/curl/lib/url.c
C
apache-2.0
130,627
#ifndef HEADER_CURL_URL_H #define HEADER_CURL_URL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #define READBUFFER_SIZE CURL_MAX_WRITE_SIZE #define READBUFFER_MAX CURL_MAX_READ_SIZE #define READBUFFER_MIN 1024 /* The default upload buffer size, should not be smaller than CURL_MAX_WRITE_SIZE, as it needs to hold a full buffer as could be sent in a write callback. The size was 16KB for many years but was bumped to 64KB because it makes libcurl able to do significantly faster uploads in some circumstances. Even larger buffers can help further, but this is deemed a fair memory/speed compromise. */ #define UPLOADBUFFER_DEFAULT 65536 #define UPLOADBUFFER_MAX (2*1024*1024) #define UPLOADBUFFER_MIN CURL_MAX_WRITE_SIZE /* * Prototypes for library-wide functions provided by url.c */ CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn); CURLcode Curl_open(struct Curl_easy **curl); CURLcode Curl_init_userdefined(struct Curl_easy *data); void Curl_freeset(struct Curl_easy * data); /* free the URL pieces */ void Curl_up_free(struct Curl_easy *data); CURLcode Curl_uc_to_curlcode(CURLUcode uc); CURLcode Curl_close(struct Curl_easy *data); /* opposite of curl_open() */ CURLcode Curl_connect(struct Curl_easy *, bool *async, bool *protocol_connect); CURLcode Curl_disconnect(struct Curl_easy *data, struct connectdata *, bool dead_connection); CURLcode Curl_protocol_connect(struct connectdata *conn, bool *done); CURLcode Curl_protocol_connecting(struct connectdata *conn, bool *done); CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done); CURLcode Curl_setup_conn(struct connectdata *conn, bool *protocol_done); void Curl_free_request_state(struct Curl_easy *data); int Curl_protocol_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); int Curl_doing_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); CURLcode Curl_parse_login_details(const char *login, const size_t len, char **userptr, char **passwdptr, char **optionsptr); void Curl_close_connections(struct Curl_easy *data); CURLcode Curl_upkeep(struct conncache *conn_cache, void *data); const struct Curl_handler *Curl_builtin_scheme(const char *scheme); #define CURL_DEFAULT_PROXY_PORT 1080 /* default proxy port unless specified */ #define CURL_DEFAULT_HTTPS_PROXY_PORT 443 /* default https proxy port unless specified */ CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex); #ifdef CURL_DISABLE_VERBOSE_STRINGS #define Curl_verboseconnect(x) Curl_nop_stmt #else void Curl_verboseconnect(struct connectdata *conn); #endif #define CONNECT_PROXY_SSL()\ (conn->http_proxy.proxytype == CURLPROXY_HTTPS &&\ !conn->bits.proxy_ssl_connected[sockindex]) #define CONNECT_FIRSTSOCKET_PROXY_SSL()\ (conn->http_proxy.proxytype == CURLPROXY_HTTPS &&\ !conn->bits.proxy_ssl_connected[FIRSTSOCKET]) #define CONNECT_SECONDARYSOCKET_PROXY_SSL()\ (conn->http_proxy.proxytype == CURLPROXY_HTTPS &&\ !conn->bits.proxy_ssl_connected[SECONDARYSOCKET]) #endif /* HEADER_CURL_URL_H */
YifuLiu/AliOS-Things
components/curl/lib/url.h
C
apache-2.0
4,330
#ifndef HEADER_CURL_URLAPI_INT_H #define HEADER_CURL_URLAPI_INT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* scheme is not URL encoded, the longest libcurl supported ones are... */ #define MAX_SCHEME_LEN 40 bool Curl_is_absolute_url(const char *url, char *scheme, size_t buflen); char *Curl_concat_url(const char *base, const char *relurl); size_t Curl_strlen_url(const char *url, bool relative); void Curl_strcpy_url(char *output, const char *url, bool relative); #ifdef DEBUGBUILD CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname); #endif #endif /* HEADER_CURL_URLAPI_INT_H */
YifuLiu/AliOS-Things
components/curl/lib/urlapi-int.h
C
apache-2.0
1,604
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "urldata.h" #include "urlapi-int.h" #include "strcase.h" #include "dotdot.h" #include "url.h" #include "escape.h" #include "curl_ctype.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* MSDOS/Windows style drive prefix, eg c: in c:foo */ #define STARTS_WITH_DRIVE_PREFIX(str) \ ((('a' <= str[0] && str[0] <= 'z') || \ ('A' <= str[0] && str[0] <= 'Z')) && \ (str[1] == ':')) /* MSDOS/Windows style drive prefix, optionally with * a '|' instead of ':', followed by a slash or NUL */ #define STARTS_WITH_URL_DRIVE_PREFIX(str) \ ((('a' <= (str)[0] && (str)[0] <= 'z') || \ ('A' <= (str)[0] && (str)[0] <= 'Z')) && \ ((str)[1] == ':' || (str)[1] == '|') && \ ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0)) /* Internal representation of CURLU. Point to URL-encoded strings. */ struct Curl_URL { char *scheme; char *user; char *password; char *options; /* IMAP only? */ char *host; char *zoneid; /* for numerical IPv6 addresses */ char *port; char *path; char *query; char *fragment; char *scratch; /* temporary scratch area */ long portnum; /* the numerical version */ }; #define DEFAULT_SCHEME "https" static void free_urlhandle(struct Curl_URL *u) { free(u->scheme); free(u->user); free(u->password); free(u->options); free(u->host); free(u->zoneid); free(u->port); free(u->path); free(u->query); free(u->fragment); free(u->scratch); } /* move the full contents of one handle onto another and free the original */ static void mv_urlhandle(struct Curl_URL *from, struct Curl_URL *to) { free_urlhandle(to); *to = *from; free(from); } /* * Find the separator at the end of the host name, or the '?' in cases like * http://www.url.com?id=2380 */ static const char *find_host_sep(const char *url) { const char *sep; const char *query; /* Find the start of the hostname */ sep = strstr(url, "//"); if(!sep) sep = url; else sep += 2; query = strchr(sep, '?'); sep = strchr(sep, '/'); if(!sep) sep = url + strlen(url); if(!query) query = url + strlen(url); return sep < query ? sep : query; } /* * Decide in an encoding-independent manner whether a character in an * URL must be escaped. The same criterion must be used in strlen_url() * and strcpy_url(). */ static bool urlchar_needs_escaping(int c) { return !(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c)); } /* * strlen_url() returns the length of the given URL if the spaces within the * URL were properly URL encoded. * URL encoding should be skipped for host names, otherwise IDN resolution * will fail. */ static size_t strlen_url(const char *url, bool relative) { const unsigned char *ptr; size_t newlen = 0; bool left = TRUE; /* left side of the ? */ const unsigned char *host_sep = (const unsigned char *) url; if(!relative) host_sep = (const unsigned char *) find_host_sep(url); for(ptr = (unsigned char *)url; *ptr; ptr++) { if(ptr < host_sep) { ++newlen; continue; } switch(*ptr) { case '?': left = FALSE; /* FALLTHROUGH */ default: if(urlchar_needs_escaping(*ptr)) newlen += 2; newlen++; break; case ' ': if(left) newlen += 3; else newlen++; break; } } return newlen; } /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in * the source URL accordingly. * URL encoding should be skipped for host names, otherwise IDN resolution * will fail. */ static void strcpy_url(char *output, const char *url, bool relative) { /* we must add this with whitespace-replacing */ bool left = TRUE; const unsigned char *iptr; char *optr = output; const unsigned char *host_sep = (const unsigned char *) url; if(!relative) host_sep = (const unsigned char *) find_host_sep(url); for(iptr = (unsigned char *)url; /* read from here */ *iptr; /* until zero byte */ iptr++) { if(iptr < host_sep) { *optr++ = *iptr; continue; } switch(*iptr) { case '?': left = FALSE; /* FALLTHROUGH */ default: if(urlchar_needs_escaping(*iptr)) { msnprintf(optr, 4, "%%%02x", *iptr); optr += 3; } else *optr++=*iptr; break; case ' ': if(left) { *optr++='%'; /* add a '%' */ *optr++='2'; /* add a '2' */ *optr++='0'; /* add a '0' */ } else *optr++='+'; /* add a '+' here */ break; } } *optr = 0; /* zero terminate output buffer */ } /* * Returns true if the given URL is absolute (as opposed to relative) within * the buffer size. Returns the scheme in the buffer if TRUE and 'buf' is * non-NULL. */ bool Curl_is_absolute_url(const char *url, char *buf, size_t buflen) { size_t i; #ifdef WIN32 if(STARTS_WITH_DRIVE_PREFIX(url)) return FALSE; #endif for(i = 0; i < buflen && url[i]; ++i) { char s = url[i]; if((s == ':') && (url[i + 1] == '/')) { if(buf) buf[i] = 0; return TRUE; } /* RFC 3986 3.1 explains: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */ else if(ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') ) { if(buf) buf[i] = (char)TOLOWER(s); } else break; } return FALSE; } /* * Concatenate a relative URL to a base URL making it absolute. * URL-encodes any spaces. * The returned pointer must be freed by the caller unless NULL * (returns NULL on out of memory). */ static char *concat_url(const char *base, const char *relurl) { /*** TRY to append this new path to the old URL to the right of the host part. Oh crap, this is doomed to cause problems in the future... */ char *newest; char *protsep; char *pathsep; size_t newlen; bool host_changed = FALSE; const char *useurl = relurl; size_t urllen; /* we must make our own copy of the URL to play with, as it may point to read-only data */ char *url_clone = strdup(base); if(!url_clone) return NULL; /* skip out of this NOW */ /* protsep points to the start of the host name */ protsep = strstr(url_clone, "//"); if(!protsep) protsep = url_clone; else protsep += 2; /* pass the slashes */ if('/' != relurl[0]) { int level = 0; /* First we need to find out if there's a ?-letter in the URL, and cut it and the right-side of that off */ pathsep = strchr(protsep, '?'); if(pathsep) *pathsep = 0; /* we have a relative path to append to the last slash if there's one available, or if the new URL is just a query string (starts with a '?') we append the new one at the end of the entire currently worked out URL */ if(useurl[0] != '?') { pathsep = strrchr(protsep, '/'); if(pathsep) *pathsep = 0; } /* Check if there's any slash after the host name, and if so, remember that position instead */ pathsep = strchr(protsep, '/'); if(pathsep) protsep = pathsep + 1; else protsep = NULL; /* now deal with one "./" or any amount of "../" in the newurl and act accordingly */ if((useurl[0] == '.') && (useurl[1] == '/')) useurl += 2; /* just skip the "./" */ while((useurl[0] == '.') && (useurl[1] == '.') && (useurl[2] == '/')) { level++; useurl += 3; /* pass the "../" */ } if(protsep) { while(level--) { /* cut off one more level from the right of the original URL */ pathsep = strrchr(protsep, '/'); if(pathsep) *pathsep = 0; else { *protsep = 0; break; } } } } else { /* We got a new absolute path for this server */ if((relurl[0] == '/') && (relurl[1] == '/')) { /* the new URL starts with //, just keep the protocol part from the original one */ *protsep = 0; useurl = &relurl[2]; /* we keep the slashes from the original, so we skip the new ones */ host_changed = TRUE; } else { /* cut off the original URL from the first slash, or deal with URLs without slash */ pathsep = strchr(protsep, '/'); if(pathsep) { /* When people use badly formatted URLs, such as "http://www.url.com?dir=/home/daniel" we must not use the first slash, if there's a ?-letter before it! */ char *sep = strchr(protsep, '?'); if(sep && (sep < pathsep)) pathsep = sep; *pathsep = 0; } else { /* There was no slash. Now, since we might be operating on a badly formatted URL, such as "http://www.url.com?id=2380" which doesn't use a slash separator as it is supposed to, we need to check for a ?-letter as well! */ pathsep = strchr(protsep, '?'); if(pathsep) *pathsep = 0; } } } /* If the new part contains a space, this is a mighty stupid redirect but we still make an effort to do "right". To the left of a '?' letter we replace each space with %20 while it is replaced with '+' on the right side of the '?' letter. */ newlen = strlen_url(useurl, !host_changed); urllen = strlen(url_clone); newest = malloc(urllen + 1 + /* possible slash */ newlen + 1 /* zero byte */); if(!newest) { free(url_clone); /* don't leak this */ return NULL; } /* copy over the root url part */ memcpy(newest, url_clone, urllen); /* check if we need to append a slash */ if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0])) ; else newest[urllen++]='/'; /* then append the new piece on the right side */ strcpy_url(&newest[urllen], useurl, !host_changed); free(url_clone); return newest; } /* * parse_hostname_login() * * Parse the login details (user name, password and options) from the URL and * strip them out of the host name * */ static CURLUcode parse_hostname_login(struct Curl_URL *u, const struct Curl_handler *h, char **hostname, unsigned int flags) { CURLUcode result = CURLUE_OK; CURLcode ccode; char *userp = NULL; char *passwdp = NULL; char *optionsp = NULL; /* At this point, we're hoping all the other special cases have * been taken care of, so conn->host.name is at most * [user[:password][;options]]@]hostname * * We need somewhere to put the embedded details, so do that first. */ char *ptr = strchr(*hostname, '@'); char *login = *hostname; if(!ptr) goto out; /* We will now try to extract the * possible login information in a string like: * ftp://user:password@ftp.my.site:8021/README */ *hostname = ++ptr; /* We could use the login information in the URL so extract it. Only parse options if the handler says we should. Note that 'h' might be NULL! */ ccode = Curl_parse_login_details(login, ptr - login - 1, &userp, &passwdp, (h && (h->flags & PROTOPT_URLOPTIONS)) ? &optionsp:NULL); if(ccode) { result = CURLUE_MALFORMED_INPUT; goto out; } if(userp) { if(flags & CURLU_DISALLOW_USER) { /* Option DISALLOW_USER is set and url contains username. */ result = CURLUE_USER_NOT_ALLOWED; goto out; } u->user = userp; } if(passwdp) u->password = passwdp; if(optionsp) u->options = optionsp; return CURLUE_OK; out: free(userp); free(passwdp); free(optionsp); return result; } UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname) { char *portptr = NULL; char endbracket; int len; /* * Find the end of an IPv6 address, either on the ']' ending bracket or * a percent-encoded zone index. */ if(1 == sscanf(hostname, "[%*45[0123456789abcdefABCDEF:.]%c%n", &endbracket, &len)) { if(']' == endbracket) portptr = &hostname[len]; else if('%' == endbracket) { int zonelen = len; if(1 == sscanf(hostname + zonelen, "%*[^]]%c%n", &endbracket, &len)) { if(']' != endbracket) return CURLUE_MALFORMED_INPUT; portptr = &hostname[--zonelen + len + 1]; } else return CURLUE_MALFORMED_INPUT; } else return CURLUE_MALFORMED_INPUT; /* this is a RFC2732-style specified IP-address */ if(portptr && *portptr) { if(*portptr != ':') return CURLUE_MALFORMED_INPUT; } else portptr = NULL; } else portptr = strchr(hostname, ':'); if(portptr) { char *rest; long port; char portbuf[7]; /* Browser behavior adaptation. If there's a colon with no digits after, just cut off the name there which makes us ignore the colon and just use the default port. Firefox, Chrome and Safari all do that. */ if(!portptr[1]) { *portptr = '\0'; return CURLUE_OK; } if(!ISDIGIT(portptr[1])) return CURLUE_BAD_PORT_NUMBER; port = strtol(portptr + 1, &rest, 10); /* Port number must be decimal */ if((port <= 0) || (port > 0xffff)) /* Single unix standard says port numbers are 16 bits long, but we don't treat port zero as OK. */ return CURLUE_BAD_PORT_NUMBER; if(rest[0]) return CURLUE_BAD_PORT_NUMBER; *portptr++ = '\0'; /* cut off the name there */ *rest = 0; /* generate a new port number string to get rid of leading zeroes etc */ msnprintf(portbuf, sizeof(portbuf), "%ld", port); u->portnum = port; u->port = strdup(portbuf); if(!u->port) return CURLUE_OUT_OF_MEMORY; } return CURLUE_OK; } /* scan for byte values < 31 or 127 */ static CURLUcode junkscan(char *part) { if(part) { static const char badbytes[]={ /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x7f, 0x00 /* zero terminate */ }; size_t n = strlen(part); size_t nfine = strcspn(part, badbytes); if(nfine != n) /* since we don't know which part is scanned, return a generic error code */ return CURLUE_MALFORMED_INPUT; } return CURLUE_OK; } static CURLUcode hostname_check(struct Curl_URL *u, char *hostname) { const char *l = NULL; /* accepted characters */ size_t len; size_t hlen = strlen(hostname); if(hostname[0] == '[') { hostname++; l = "0123456789abcdefABCDEF::."; hlen -= 2; } if(l) { /* only valid letters are ok */ len = strspn(hostname, l); if(hlen != len) { if(hostname[len] == '%') { /* this could now be '%[zone id]' */ char zoneid[16]; int i = 0; char *h = &hostname[len + 1]; /* pass '25' if present and is a url encoded percent sign */ if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']')) h += 2; while(*h && (*h != ']') && (i < 15)) zoneid[i++] = *h++; if(!i || (']' != *h)) return CURLUE_MALFORMED_INPUT; zoneid[i] = 0; u->zoneid = strdup(zoneid); if(!u->zoneid) return CURLUE_OUT_OF_MEMORY; hostname[len] = ']'; /* insert end bracket */ hostname[len + 1] = 0; /* terminate the hostname */ } else return CURLUE_MALFORMED_INPUT; /* hostname is fine */ } } else { /* letters from the second string is not ok */ len = strcspn(hostname, " "); if(hlen != len) /* hostname with bad content */ return CURLUE_MALFORMED_INPUT; } if(!hostname[0]) return CURLUE_NO_HOST; return CURLUE_OK; } #define HOSTNAME_END(x) (((x) == '/') || ((x) == '?') || ((x) == '#')) static CURLUcode seturl(const char *url, CURLU *u, unsigned int flags) { char *path; bool path_alloced = FALSE; char *hostname; char *query = NULL; char *fragment = NULL; CURLUcode result; bool url_has_scheme = FALSE; char schemebuf[MAX_SCHEME_LEN + 1]; char *schemep = NULL; size_t schemelen = 0; size_t urllen; const struct Curl_handler *h = NULL; if(!url) return CURLUE_MALFORMED_INPUT; /************************************************************* * Parse the URL. ************************************************************/ /* allocate scratch area */ urllen = strlen(url); if(urllen > CURL_MAX_INPUT_LENGTH) /* excessive input length */ return CURLUE_MALFORMED_INPUT; path = u->scratch = malloc(urllen * 2 + 2); if(!path) return CURLUE_OUT_OF_MEMORY; hostname = &path[urllen + 1]; hostname[0] = 0; if(Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf))) { url_has_scheme = TRUE; schemelen = strlen(schemebuf); } /* handle the file: scheme */ if(url_has_scheme && strcasecompare(schemebuf, "file")) { /* path has been allocated large enough to hold this */ strcpy(path, &url[5]); hostname = NULL; /* no host for file: URLs */ u->scheme = strdup("file"); if(!u->scheme) return CURLUE_OUT_OF_MEMORY; /* Extra handling URLs with an authority component (i.e. that start with * "file://") * * We allow omitted hostname (e.g. file:/<path>) -- valid according to * RFC 8089, but not the (current) WHAT-WG URL spec. */ if(path[0] == '/' && path[1] == '/') { /* swallow the two slashes */ char *ptr = &path[2]; /* * According to RFC 8089, a file: URL can be reliably dereferenced if: * * o it has no/blank hostname, or * * o the hostname matches "localhost" (case-insensitively), or * * o the hostname is a FQDN that resolves to this machine. * * For brevity, we only consider URLs with empty, "localhost", or * "127.0.0.1" hostnames as local. * * Additionally, there is an exception for URLs with a Windows drive * letter in the authority (which was accidentally omitted from RFC 8089 * Appendix E, but believe me, it was meant to be there. --MK) */ if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) { /* the URL includes a host name, it must match "localhost" or "127.0.0.1" to be valid */ if(!checkprefix("localhost/", ptr) && !checkprefix("127.0.0.1/", ptr)) { /* Invalid file://hostname/, expected localhost or 127.0.0.1 or none */ return CURLUE_MALFORMED_INPUT; } ptr += 9; /* now points to the slash after the host */ } path = ptr; } #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__) /* Don't allow Windows drive letters when not in Windows. * This catches both "file:/c:" and "file:c:" */ if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) || STARTS_WITH_URL_DRIVE_PREFIX(path)) { /* File drive letters are only accepted in MSDOS/Windows */ return CURLUE_MALFORMED_INPUT; } #else /* If the path starts with a slash and a drive letter, ditch the slash */ if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) { /* This cannot be done with strcpy, as the memory chunks overlap! */ memmove(path, &path[1], strlen(&path[1]) + 1); } #endif } else { /* clear path */ const char *p; const char *hostp; size_t len; path[0] = 0; if(url_has_scheme) { int i = 0; p = &url[schemelen + 1]; while(p && (*p == '/') && (i < 4)) { p++; i++; } if((i < 1) || (i>3)) /* less than one or more than three slashes */ return CURLUE_MALFORMED_INPUT; schemep = schemebuf; if(!Curl_builtin_scheme(schemep) && !(flags & CURLU_NON_SUPPORT_SCHEME)) return CURLUE_UNSUPPORTED_SCHEME; if(junkscan(schemep)) return CURLUE_MALFORMED_INPUT; } else { /* no scheme! */ if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME))) return CURLUE_MALFORMED_INPUT; if(flags & CURLU_DEFAULT_SCHEME) schemep = (char *) DEFAULT_SCHEME; /* * The URL was badly formatted, let's try without scheme specified. */ p = url; } hostp = p; /* host name starts here */ while(*p && !HOSTNAME_END(*p)) /* find end of host name */ p++; len = p - hostp; if(!len) return CURLUE_MALFORMED_INPUT; memcpy(hostname, hostp, len); hostname[len] = 0; if((flags & CURLU_GUESS_SCHEME) && !schemep) { /* legacy curl-style guess based on host name */ if(checkprefix("ftp.", hostname)) schemep = (char *)"ftp"; else if(checkprefix("dict.", hostname)) schemep = (char *)"dict"; else if(checkprefix("ldap.", hostname)) schemep = (char *)"ldap"; else if(checkprefix("imap.", hostname)) schemep = (char *)"imap"; else if(checkprefix("smtp.", hostname)) schemep = (char *)"smtp"; else if(checkprefix("pop3.", hostname)) schemep = (char *)"pop3"; else schemep = (char *)"http"; } len = strlen(p); memcpy(path, p, len); path[len] = 0; u->scheme = strdup(schemep); if(!u->scheme) return CURLUE_OUT_OF_MEMORY; } /* if this is a known scheme, get some details */ h = Curl_builtin_scheme(u->scheme); if(junkscan(path)) return CURLUE_MALFORMED_INPUT; query = strchr(path, '?'); if(query) *query++ = 0; fragment = strchr(query?query:path, '#'); if(fragment) *fragment++ = 0; if(!path[0]) /* if there's no path set, unset */ path = NULL; else if(!(flags & CURLU_PATH_AS_IS)) { /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */ char *newp = Curl_dedotdotify(path); if(!newp) return CURLUE_OUT_OF_MEMORY; if(strcmp(newp, path)) { /* if we got a new version */ path = newp; path_alloced = TRUE; } else free(newp); } if(path) { u->path = path_alloced?path:strdup(path); if(!u->path) return CURLUE_OUT_OF_MEMORY; } if(hostname) { /* * Parse the login details and strip them out of the host name. */ if(junkscan(hostname)) return CURLUE_MALFORMED_INPUT; result = parse_hostname_login(u, h, &hostname, flags); if(result) return result; result = Curl_parse_port(u, hostname); if(result) return result; result = hostname_check(u, hostname); if(result) return result; u->host = strdup(hostname); if(!u->host) return CURLUE_OUT_OF_MEMORY; } if(query) { u->query = strdup(query); if(!u->query) return CURLUE_OUT_OF_MEMORY; } if(fragment && fragment[0]) { u->fragment = strdup(fragment); if(!u->fragment) return CURLUE_OUT_OF_MEMORY; } free(u->scratch); u->scratch = NULL; return CURLUE_OK; } /* * Parse the URL and set the relevant members of the Curl_URL struct. */ static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags) { CURLUcode result = seturl(url, u, flags); if(result) { free_urlhandle(u); memset(u, 0, sizeof(struct Curl_URL)); } return result; } /* */ CURLU *curl_url(void) { return calloc(sizeof(struct Curl_URL), 1); } void curl_url_cleanup(CURLU *u) { if(u) { free_urlhandle(u); free(u); } } #define DUP(dest, src, name) \ if(src->name) { \ dest->name = strdup(src->name); \ if(!dest->name) \ goto fail; \ } CURLU *curl_url_dup(CURLU *in) { struct Curl_URL *u = calloc(sizeof(struct Curl_URL), 1); if(u) { DUP(u, in, scheme); DUP(u, in, user); DUP(u, in, password); DUP(u, in, options); DUP(u, in, host); DUP(u, in, port); DUP(u, in, path); DUP(u, in, query); DUP(u, in, fragment); u->portnum = in->portnum; } return u; fail: curl_url_cleanup(u); return NULL; } CURLUcode curl_url_get(CURLU *u, CURLUPart what, char **part, unsigned int flags) { char *ptr; CURLUcode ifmissing = CURLUE_UNKNOWN_PART; char portbuf[7]; bool urldecode = (flags & CURLU_URLDECODE)?1:0; bool plusdecode = FALSE; (void)flags; if(!u) return CURLUE_BAD_HANDLE; if(!part) return CURLUE_BAD_PARTPOINTER; *part = NULL; switch(what) { case CURLUPART_SCHEME: ptr = u->scheme; ifmissing = CURLUE_NO_SCHEME; urldecode = FALSE; /* never for schemes */ break; case CURLUPART_USER: ptr = u->user; ifmissing = CURLUE_NO_USER; break; case CURLUPART_PASSWORD: ptr = u->password; ifmissing = CURLUE_NO_PASSWORD; break; case CURLUPART_OPTIONS: ptr = u->options; ifmissing = CURLUE_NO_OPTIONS; break; case CURLUPART_HOST: ptr = u->host; ifmissing = CURLUE_NO_HOST; break; case CURLUPART_ZONEID: ptr = u->zoneid; break; case CURLUPART_PORT: ptr = u->port; ifmissing = CURLUE_NO_PORT; urldecode = FALSE; /* never for port */ if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) { /* there's no stored port number, but asked to deliver a default one for the scheme */ const struct Curl_handler *h = Curl_builtin_scheme(u->scheme); if(h) { msnprintf(portbuf, sizeof(portbuf), "%ld", h->defport); ptr = portbuf; } } else if(ptr && u->scheme) { /* there is a stored port number, but ask to inhibit if it matches the default one for the scheme */ const struct Curl_handler *h = Curl_builtin_scheme(u->scheme); if(h && (h->defport == u->portnum) && (flags & CURLU_NO_DEFAULT_PORT)) ptr = NULL; } break; case CURLUPART_PATH: ptr = u->path; if(!ptr) { ptr = u->path = strdup("/"); if(!u->path) return CURLUE_OUT_OF_MEMORY; } break; case CURLUPART_QUERY: ptr = u->query; ifmissing = CURLUE_NO_QUERY; plusdecode = urldecode; break; case CURLUPART_FRAGMENT: ptr = u->fragment; ifmissing = CURLUE_NO_FRAGMENT; break; case CURLUPART_URL: { char *url; char *scheme; char *options = u->options; char *port = u->port; char *allochost = NULL; if(u->scheme && strcasecompare("file", u->scheme)) { url = aprintf("file://%s%s%s", u->path, u->fragment? "#": "", u->fragment? u->fragment : ""); } else if(!u->host) return CURLUE_NO_HOST; else { const struct Curl_handler *h = NULL; if(u->scheme) scheme = u->scheme; else if(flags & CURLU_DEFAULT_SCHEME) scheme = (char *) DEFAULT_SCHEME; else return CURLUE_NO_SCHEME; if(scheme) { h = Curl_builtin_scheme(scheme); if(!port && (flags & CURLU_DEFAULT_PORT)) { /* there's no stored port number, but asked to deliver a default one for the scheme */ if(h) { msnprintf(portbuf, sizeof(portbuf), "%ld", h->defport); port = portbuf; } } else if(port) { /* there is a stored port number, but asked to inhibit if it matches the default one for the scheme */ if(h && (h->defport == u->portnum) && (flags & CURLU_NO_DEFAULT_PORT)) port = NULL; } } if(h && !(h->flags & PROTOPT_URLOPTIONS)) options = NULL; if((u->host[0] == '[') && u->zoneid) { /* make it '[ host %25 zoneid ]' */ size_t hostlen = strlen(u->host); size_t alen = hostlen + 3 + strlen(u->zoneid) + 1; allochost = malloc(alen); if(!allochost) return CURLUE_OUT_OF_MEMORY; memcpy(allochost, u->host, hostlen - 1); msnprintf(&allochost[hostlen - 1], alen - hostlen + 1, "%%25%s]", u->zoneid); } url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", scheme, u->user ? u->user : "", u->password ? ":": "", u->password ? u->password : "", options ? ";" : "", options ? options : "", (u->user || u->password || options) ? "@": "", allochost ? allochost : u->host, port ? ":": "", port ? port : "", (u->path && (u->path[0] != '/')) ? "/": "", u->path ? u->path : "/", (u->query && u->query[0]) ? "?": "", (u->query && u->query[0]) ? u->query : "", u->fragment? "#": "", u->fragment? u->fragment : ""); free(allochost); } if(!url) return CURLUE_OUT_OF_MEMORY; *part = url; return CURLUE_OK; } default: ptr = NULL; break; } if(ptr) { *part = strdup(ptr); if(!*part) return CURLUE_OUT_OF_MEMORY; if(plusdecode) { /* convert + to space */ char *plus; for(plus = *part; *plus; ++plus) { if(*plus == '+') *plus = ' '; } } if(urldecode) { char *decoded; size_t dlen; CURLcode res = Curl_urldecode(NULL, *part, 0, &decoded, &dlen, TRUE); free(*part); if(res) { *part = NULL; return CURLUE_URLDECODE; } *part = decoded; } return CURLUE_OK; } else return ifmissing; } CURLUcode curl_url_set(CURLU *u, CURLUPart what, const char *part, unsigned int flags) { char **storep = NULL; long port = 0; bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0; bool plusencode = FALSE; bool urlskipslash = FALSE; bool appendquery = FALSE; bool equalsencode = FALSE; if(!u) return CURLUE_BAD_HANDLE; if(!part) { /* setting a part to NULL clears it */ switch(what) { case CURLUPART_URL: break; case CURLUPART_SCHEME: storep = &u->scheme; break; case CURLUPART_USER: storep = &u->user; break; case CURLUPART_PASSWORD: storep = &u->password; break; case CURLUPART_OPTIONS: storep = &u->options; break; case CURLUPART_HOST: storep = &u->host; break; case CURLUPART_ZONEID: storep = &u->zoneid; break; case CURLUPART_PORT: u->portnum = 0; storep = &u->port; break; case CURLUPART_PATH: storep = &u->path; break; case CURLUPART_QUERY: storep = &u->query; break; case CURLUPART_FRAGMENT: storep = &u->fragment; break; default: return CURLUE_UNKNOWN_PART; } if(storep && *storep) { free(*storep); *storep = NULL; } return CURLUE_OK; } switch(what) { case CURLUPART_SCHEME: if(strlen(part) > MAX_SCHEME_LEN) /* too long */ return CURLUE_MALFORMED_INPUT; if(!(flags & CURLU_NON_SUPPORT_SCHEME) && /* verify that it is a fine scheme */ !Curl_builtin_scheme(part)) return CURLUE_UNSUPPORTED_SCHEME; storep = &u->scheme; urlencode = FALSE; /* never */ break; case CURLUPART_USER: storep = &u->user; break; case CURLUPART_PASSWORD: storep = &u->password; break; case CURLUPART_OPTIONS: storep = &u->options; break; case CURLUPART_HOST: storep = &u->host; free(u->zoneid); u->zoneid = NULL; break; case CURLUPART_ZONEID: storep = &u->zoneid; break; case CURLUPART_PORT: { char *endp; urlencode = FALSE; /* never */ port = strtol(part, &endp, 10); /* Port number must be decimal */ if((port <= 0) || (port > 0xffff)) return CURLUE_BAD_PORT_NUMBER; if(*endp) /* weirdly provided number, not good! */ return CURLUE_MALFORMED_INPUT; storep = &u->port; } break; case CURLUPART_PATH: urlskipslash = TRUE; storep = &u->path; break; case CURLUPART_QUERY: plusencode = urlencode; appendquery = (flags & CURLU_APPENDQUERY)?1:0; equalsencode = appendquery; storep = &u->query; break; case CURLUPART_FRAGMENT: storep = &u->fragment; break; case CURLUPART_URL: { /* * Allow a new URL to replace the existing (if any) contents. * * If the existing contents is enough for a URL, allow a relative URL to * replace it. */ CURLUcode result; char *oldurl; char *redired_url; CURLU *handle2; if(Curl_is_absolute_url(part, NULL, MAX_SCHEME_LEN + 1)) { handle2 = curl_url(); if(!handle2) return CURLUE_OUT_OF_MEMORY; result = parseurl(part, handle2, flags); if(!result) mv_urlhandle(handle2, u); else curl_url_cleanup(handle2); return result; } /* extract the full "old" URL to do the redirect on */ result = curl_url_get(u, CURLUPART_URL, &oldurl, flags); if(result) { /* couldn't get the old URL, just use the new! */ handle2 = curl_url(); if(!handle2) return CURLUE_OUT_OF_MEMORY; result = parseurl(part, handle2, flags); if(!result) mv_urlhandle(handle2, u); else curl_url_cleanup(handle2); return result; } /* apply the relative part to create a new URL */ redired_url = concat_url(oldurl, part); free(oldurl); if(!redired_url) return CURLUE_OUT_OF_MEMORY; /* now parse the new URL */ handle2 = curl_url(); if(!handle2) { free(redired_url); return CURLUE_OUT_OF_MEMORY; } result = parseurl(redired_url, handle2, flags); free(redired_url); if(!result) mv_urlhandle(handle2, u); else curl_url_cleanup(handle2); return result; } default: return CURLUE_UNKNOWN_PART; } if(storep) { const char *newp = part; size_t nalloc = strlen(part); if(nalloc > CURL_MAX_INPUT_LENGTH) /* excessive input length */ return CURLUE_MALFORMED_INPUT; if(urlencode) { const unsigned char *i; char *o; bool free_part = FALSE; char *enc = malloc(nalloc * 3 + 1); /* for worst case! */ if(!enc) return CURLUE_OUT_OF_MEMORY; if(plusencode) { /* space to plus */ i = (const unsigned char *)part; for(o = enc; *i; ++o, ++i) *o = (*i == ' ') ? '+' : *i; *o = 0; /* zero terminate */ part = strdup(enc); if(!part) { free(enc); return CURLUE_OUT_OF_MEMORY; } free_part = TRUE; } for(i = (const unsigned char *)part, o = enc; *i; i++) { if(Curl_isunreserved(*i) || ((*i == '/') && urlskipslash) || ((*i == '=') && equalsencode) || ((*i == '+') && plusencode)) { if((*i == '=') && equalsencode) /* only skip the first equals sign */ equalsencode = FALSE; *o = *i; o++; } else { msnprintf(o, 4, "%%%02x", *i); o += 3; } } *o = 0; /* zero terminate */ newp = enc; if(free_part) free((char *)part); } else { char *p; newp = strdup(part); if(!newp) return CURLUE_OUT_OF_MEMORY; p = (char *)newp; while(*p) { /* make sure percent encoded are lower case */ if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) && (ISUPPER(p[1]) || ISUPPER(p[2]))) { p[1] = (char)TOLOWER(p[1]); p[2] = (char)TOLOWER(p[2]); p += 3; } else p++; } } if(appendquery) { /* Append the string onto the old query. Add a '&' separator if none is present at the end of the exsting query already */ size_t querylen = u->query ? strlen(u->query) : 0; bool addamperand = querylen && (u->query[querylen -1] != '&'); if(querylen) { size_t newplen = strlen(newp); char *p = malloc(querylen + addamperand + newplen + 1); if(!p) { free((char *)newp); return CURLUE_OUT_OF_MEMORY; } strcpy(p, u->query); /* original query */ if(addamperand) p[querylen] = '&'; /* ampersand */ strcpy(&p[querylen + addamperand], newp); /* new suffix */ free((char *)newp); free(*storep); *storep = p; return CURLUE_OK; } } if(what == CURLUPART_HOST) { if(hostname_check(u, (char *)newp)) { free((char *)newp); return CURLUE_MALFORMED_INPUT; } } free(*storep); *storep = (char *)newp; } /* set after the string, to make it not assigned if the allocation above fails */ if(port) u->portnum = port; return CURLUE_OK; }
YifuLiu/AliOS-Things
components/curl/lib/urlapi.c
C
apache-2.0
38,206
#ifndef HEADER_CURL_URLDATA_H #define HEADER_CURL_URLDATA_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* This file is for lib internal stuff */ #include "curl_setup.h" #define PORT_FTP 21 #define PORT_FTPS 990 #define PORT_TELNET 23 #define PORT_HTTP 80 #define PORT_HTTPS 443 #define PORT_DICT 2628 #define PORT_LDAP 389 #define PORT_LDAPS 636 #define PORT_TFTP 69 #define PORT_SSH 22 #define PORT_IMAP 143 #define PORT_IMAPS 993 #define PORT_POP3 110 #define PORT_POP3S 995 #define PORT_SMB 445 #define PORT_SMBS 445 #define PORT_SMTP 25 #define PORT_SMTPS 465 /* sometimes called SSMTP */ #define PORT_RTSP 554 #define PORT_RTMP 1935 #define PORT_RTMPT PORT_HTTP #define PORT_RTMPS PORT_HTTPS #define PORT_GOPHER 70 #define DICT_MATCH "/MATCH:" #define DICT_MATCH2 "/M:" #define DICT_MATCH3 "/FIND:" #define DICT_DEFINE "/DEFINE:" #define DICT_DEFINE2 "/D:" #define DICT_DEFINE3 "/LOOKUP:" #define CURL_DEFAULT_USER "anonymous" #define CURL_DEFAULT_PASSWORD "ftp@example.com" /* Convenience defines for checking protocols or their SSL based version. Each protocol handler should only ever have a single CURLPROTO_ in its protocol field. */ #define PROTO_FAMILY_HTTP (CURLPROTO_HTTP|CURLPROTO_HTTPS) #define PROTO_FAMILY_FTP (CURLPROTO_FTP|CURLPROTO_FTPS) #define PROTO_FAMILY_POP3 (CURLPROTO_POP3|CURLPROTO_POP3S) #define PROTO_FAMILY_SMB (CURLPROTO_SMB|CURLPROTO_SMBS) #define PROTO_FAMILY_SMTP (CURLPROTO_SMTP|CURLPROTO_SMTPS) #define DEFAULT_CONNCACHE_SIZE 5 /* length of longest IPv6 address string including the trailing null */ #define MAX_IPADR_LEN sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255") /* Default FTP/IMAP etc response timeout in milliseconds. Symbian OS panics when given a timeout much greater than 1/2 hour. */ #define RESP_TIMEOUT (120*1000) /* Max string intput length is a precaution against abuse and to detect junk input easier and better. */ #define CURL_MAX_INPUT_LENGTH 8000000 #include "cookie.h" #include "psl.h" #include "formdata.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #include "timeval.h" #include <curl/curl.h> #include "http_chunks.h" /* for the structs and enum stuff */ #include "hostip.h" #include "hash.h" #include "splay.h" /* return the count of bytes sent, or -1 on error */ typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */ int sockindex, /* socketindex */ const void *buf, /* data to write */ size_t len, /* max amount to write */ CURLcode *err); /* error to return */ /* return the count of bytes read, or -1 on error */ typedef ssize_t (Curl_recv)(struct connectdata *conn, /* connection data */ int sockindex, /* socketindex */ char *buf, /* store data here */ size_t len, /* max amount to read */ CURLcode *err); /* error to return */ #include "mime.h" #include "imap.h" #include "pop3.h" #include "smtp.h" #include "ftp.h" #include "file.h" #include "ssh.h" #include "http.h" #include "rtsp.h" #include "smb.h" #include "wildcard.h" #include "multihandle.h" #ifdef HAVE_GSSAPI # ifdef HAVE_GSSGNU # include <gss.h> # elif defined HAVE_GSSAPI_GSSAPI_H # include <gssapi/gssapi.h> # else # include <gssapi.h> # endif # ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H # include <gssapi/gssapi_generic.h> # endif #endif #ifdef HAVE_LIBSSH2_H #include <libssh2.h> #include <libssh2_sftp.h> #endif /* HAVE_LIBSSH2_H */ /* Initial size of the buffer to store headers in, it'll be enlarged in case of need. */ #define HEADERSIZE 256 #define CURLEASY_MAGIC_NUMBER 0xc0dedbadU #define GOOD_EASY_HANDLE(x) \ ((x) && ((x)->magic == CURLEASY_MAGIC_NUMBER)) /* the type we use for storing a single boolean bit */ typedef unsigned int bit; #ifdef HAVE_GSSAPI /* Types needed for krb5-ftp connections */ struct krb5buffer { void *data; size_t size; size_t index; bit eof_flag:1; }; enum protection_level { PROT_NONE, /* first in list */ PROT_CLEAR, PROT_SAFE, PROT_CONFIDENTIAL, PROT_PRIVATE, PROT_CMD, PROT_LAST /* last in list */ }; #endif /* enum for the nonblocking SSL connection state machine */ typedef enum { ssl_connect_1, ssl_connect_2, ssl_connect_2_reading, ssl_connect_2_writing, ssl_connect_3, ssl_connect_done } ssl_connect_state; typedef enum { ssl_connection_none, ssl_connection_negotiating, ssl_connection_complete } ssl_connection_state; /* SSL backend-specific data; declared differently by each SSL backend */ struct ssl_backend_data; /* struct for data related to each SSL connection */ struct ssl_connect_data { /* Use ssl encrypted communications TRUE/FALSE, not necessarily using it atm but at least asked to or meaning to use it. See 'state' for the exact current state of the connection. */ ssl_connection_state state; ssl_connect_state connecting_state; #if defined(USE_SSL) struct ssl_backend_data *backend; #endif bit use:1; }; struct ssl_primary_config { long version; /* what version the client wants to use */ long version_max; /* max supported version the client wants to use*/ char *CApath; /* certificate dir (doesn't work on windows) */ char *CAfile; /* certificate to verify peer against */ char *clientcert; char *random_file; /* path to file containing "random" data */ char *egdsocket; /* path to file containing the EGD daemon socket */ char *cipher_list; /* list of ciphers to use */ char *cipher_list13; /* list of TLS 1.3 cipher suites to use */ bit verifypeer:1; /* set TRUE if this is desired */ bit verifyhost:1; /* set TRUE if CN/SAN must match hostname */ bit verifystatus:1; /* set TRUE if certificate status must be checked */ bit sessionid:1; /* cache session IDs or not */ }; struct ssl_config_data { struct ssl_primary_config primary; long certverifyresult; /* result from the certificate verification */ char *CRLfile; /* CRL to check certificate revocation */ char *issuercert;/* optional issuer certificate filename */ curl_ssl_ctx_callback fsslctx; /* function to initialize ssl ctx */ void *fsslctxp; /* parameter for call back */ char *cert; /* client certificate file name */ char *cert_type; /* format for certificate (default: PEM)*/ char *key; /* private key file name */ char *key_type; /* format for private key (default: PEM) */ char *key_passwd; /* plain text private key password */ #ifdef USE_TLS_SRP char *username; /* TLS username (for, e.g., SRP) */ char *password; /* TLS password (for, e.g., SRP) */ enum CURL_TLSAUTH authtype; /* TLS authentication type (default SRP) */ #endif bit certinfo:1; /* gather lots of certificate info */ bit falsestart:1; bit enable_beast:1; /* allow this flaw for interoperability's sake*/ bit no_revoke:1; /* disable SSL certificate revocation checks */ }; struct ssl_general_config { size_t max_ssl_sessions; /* SSL session id cache size */ }; /* information stored about one single SSL session */ struct curl_ssl_session { char *name; /* host name for which this ID was used */ char *conn_to_host; /* host name for the connection (may be NULL) */ const char *scheme; /* protocol scheme used */ void *sessionid; /* as returned from the SSL layer */ size_t idsize; /* if known, otherwise 0 */ long age; /* just a number, the higher the more recent */ int remote_port; /* remote port */ int conn_to_port; /* remote port for the connection (may be -1) */ struct ssl_primary_config ssl_config; /* setup for this session */ }; #ifdef USE_WINDOWS_SSPI #include "curl_sspi.h" #endif /* Struct used for Digest challenge-response authentication */ struct digestdata { #if defined(USE_WINDOWS_SSPI) BYTE *input_token; size_t input_token_len; CtxtHandle *http_context; /* copy of user/passwd used to make the identity for http_context. either may be NULL. */ char *user; char *passwd; #else char *nonce; char *cnonce; char *realm; int algo; char *opaque; char *qop; char *algorithm; int nc; /* nounce count */ bit stale:1; /* set true for re-negotiation */ bit userhash:1; #endif }; typedef enum { NTLMSTATE_NONE, NTLMSTATE_TYPE1, NTLMSTATE_TYPE2, NTLMSTATE_TYPE3, NTLMSTATE_LAST } curlntlm; typedef enum { GSS_AUTHNONE, GSS_AUTHRECV, GSS_AUTHSENT, GSS_AUTHDONE, GSS_AUTHSUCC } curlnegotiate; #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV) #include <iconv.h> #endif /* Struct used for GSSAPI (Kerberos V5) authentication */ #if defined(USE_KERBEROS5) struct kerberos5data { #if defined(USE_WINDOWS_SSPI) CredHandle *credentials; CtxtHandle *context; TCHAR *spn; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; size_t token_max; BYTE *output_token; #else gss_ctx_id_t context; gss_name_t spn; #endif }; #endif /* Struct used for NTLM challenge-response authentication */ #if defined(USE_NTLM) struct ntlmdata { #ifdef USE_WINDOWS_SSPI /* The sslContext is used for the Schannel bindings. The * api is available on the Windows 7 SDK and later. */ #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS CtxtHandle *sslContext; #endif CredHandle *credentials; CtxtHandle *context; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; size_t token_max; BYTE *output_token; BYTE *input_token; size_t input_token_len; TCHAR *spn; #else unsigned int flags; unsigned char nonce[8]; void *target_info; /* TargetInfo received in the ntlm type-2 message */ unsigned int target_info_len; #endif }; #endif /* Struct used for Negotiate (SPNEGO) authentication */ #ifdef USE_SPNEGO struct negotiatedata { #ifdef HAVE_GSSAPI OM_uint32 status; gss_ctx_id_t context; gss_name_t spn; gss_buffer_desc output_token; #else #ifdef USE_WINDOWS_SSPI #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS CtxtHandle *sslContext; #endif DWORD status; CredHandle *credentials; CtxtHandle *context; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; TCHAR *spn; size_t token_max; BYTE *output_token; size_t output_token_length; #endif #endif bool noauthpersist; bool havenoauthpersist; bool havenegdata; bool havemultiplerequests; }; #endif /* * Boolean values that concerns this connection. */ struct ConnectBits { /* always modify bits.close with the connclose() and connkeep() macros! */ bool proxy_ssl_connected[2]; /* TRUE when SSL initialization for HTTPS proxy is complete */ bool tcpconnect[2]; /* the TCP layer (or similar) is connected, this is set the first time on the first connect function call */ bit close:1; /* if set, we close the connection after this request */ bit reuse:1; /* if set, this is a re-used connection */ bit conn_to_host:1; /* if set, this connection has a "connect to host" that overrides the host in the URL */ bit conn_to_port:1; /* if set, this connection has a "connect to port" that overrides the port in the URL (remote port) */ bit proxy:1; /* if set, this transfer is done through a proxy - any type */ bit httpproxy:1; /* if set, this transfer is done through a http proxy */ bit socksproxy:1; /* if set, this transfer is done through a socks proxy */ bit user_passwd:1; /* do we use user+password for this connection? */ bit proxy_user_passwd:1; /* user+password for the proxy? */ bit ipv6_ip:1; /* we communicate with a remote site specified with pure IPv6 IP address */ bit ipv6:1; /* we communicate with a site using an IPv6 address */ bit do_more:1; /* this is set TRUE if the ->curl_do_more() function is supposed to be called, after ->curl_do() */ bit protoconnstart:1;/* the protocol layer has STARTED its operation after the TCP layer connect */ bit retry:1; /* this connection is about to get closed and then re-attempted at another connection. */ bit tunnel_proxy:1; /* if CONNECT is used to "tunnel" through the proxy. This is implicit when SSL-protocols are used through proxies, but can also be enabled explicitly by apps */ bit authneg:1; /* TRUE when the auth phase has started, which means that we are creating a request with an auth header, but it is not the final request in the auth negotiation. */ bit rewindaftersend:1;/* TRUE when the sending couldn't be stopped even though it will be discarded. When the whole send operation is done, we must call the data rewind callback. */ #ifndef CURL_DISABLE_FTP bit ftp_use_epsv:1; /* As set with CURLOPT_FTP_USE_EPSV, but if we find out EPSV doesn't work we disable it for the forthcoming requests */ bit ftp_use_eprt:1; /* As set with CURLOPT_FTP_USE_EPRT, but if we find out EPRT doesn't work we disable it for the forthcoming requests */ bit ftp_use_data_ssl:1; /* Enabled SSL for the data connection */ #endif bit netrc:1; /* name+password provided by netrc */ bit userpwd_in_url:1; /* name+password found in url */ bit stream_was_rewound:1; /* The stream was rewound after a request read past the end of its response byte boundary */ bit proxy_connect_closed:1; /* TRUE if a proxy disconnected the connection in a CONNECT request with auth, so that libcurl should reconnect and continue. */ bit bound:1; /* set true if bind() has already been done on this socket/ connection */ bit type_set:1; /* type= was used in the URL */ bit multiplex:1; /* connection is multiplexed */ bit tcp_fastopen:1; /* use TCP Fast Open */ bit tls_enable_npn:1; /* TLS NPN extension? */ bit tls_enable_alpn:1; /* TLS ALPN extension? */ bit socksproxy_connecting:1; /* connecting through a socks proxy */ bit connect_only:1; }; struct hostname { char *rawalloc; /* allocated "raw" version of the name */ char *encalloc; /* allocated IDN-encoded version of the name */ char *name; /* name to use internally, might be encoded, might be raw */ const char *dispname; /* name to display, as 'name' might be encoded */ }; /* * Flags on the keepon member of the Curl_transfer_keeper */ #define KEEP_NONE 0 #define KEEP_RECV (1<<0) /* there is or may be data to read */ #define KEEP_SEND (1<<1) /* there is or may be data to write */ #define KEEP_RECV_HOLD (1<<2) /* when set, no reading should be done but there might still be data to read */ #define KEEP_SEND_HOLD (1<<3) /* when set, no writing should be done but there might still be data to write */ #define KEEP_RECV_PAUSE (1<<4) /* reading is paused */ #define KEEP_SEND_PAUSE (1<<5) /* writing is paused */ #define KEEP_RECVBITS (KEEP_RECV | KEEP_RECV_HOLD | KEEP_RECV_PAUSE) #define KEEP_SENDBITS (KEEP_SEND | KEEP_SEND_HOLD | KEEP_SEND_PAUSE) struct Curl_async { char *hostname; int port; struct Curl_dns_entry *dns; int status; /* if done is TRUE, this is the status from the callback */ void *os_specific; /* 'struct thread_data' for Windows */ bit done:1; /* set TRUE when the lookup is complete */ }; #define FIRSTSOCKET 0 #define SECONDARYSOCKET 1 /* These function pointer types are here only to allow easier typecasting within the source when we need to cast between data pointers (such as NULL) and function pointers. */ typedef CURLcode (*Curl_do_more_func)(struct connectdata *, int *); typedef CURLcode (*Curl_done_func)(struct connectdata *, CURLcode, bool); enum expect100 { EXP100_SEND_DATA, /* enough waiting, just send the body now */ EXP100_AWAITING_CONTINUE, /* waiting for the 100 Continue header */ EXP100_SENDING_REQUEST, /* still sending the request but will wait for the 100 header once done with the request */ EXP100_FAILED /* used on 417 Expectation Failed */ }; enum upgrade101 { UPGR101_INIT, /* default state */ UPGR101_REQUESTED, /* upgrade requested */ UPGR101_RECEIVED, /* response received */ UPGR101_WORKING /* talking upgraded protocol */ }; struct dohresponse { unsigned char *memory; size_t size; }; /* one of these for each DoH request */ struct dnsprobe { CURL *easy; int dnstype; unsigned char dohbuffer[512]; size_t dohlen; struct dohresponse serverdoh; }; struct dohdata { struct curl_slist *headers; struct dnsprobe probe[2]; unsigned int pending; /* still outstanding requests */ const char *host; int port; }; /* * Request specific data in the easy handle (Curl_easy). Previously, * these members were on the connectdata struct but since a conn struct may * now be shared between different Curl_easys, we store connection-specific * data here. This struct only keeps stuff that's interesting for *this* * request, as it will be cleared between multiple ones */ struct SingleRequest { curl_off_t size; /* -1 if unknown at this point */ curl_off_t maxdownload; /* in bytes, the maximum amount of data to fetch, -1 means unlimited */ curl_off_t bytecount; /* total number of bytes read */ curl_off_t writebytecount; /* number of bytes written */ curl_off_t headerbytecount; /* only count received headers */ curl_off_t deductheadercount; /* this amount of bytes doesn't count when we check if anything has been transferred at the end of a connection. We use this counter to make only a 100 reply (without a following second response code) result in a CURLE_GOT_NOTHING error code */ struct curltime start; /* transfer started at this time */ struct curltime now; /* current time */ enum { HEADER_NORMAL, /* no bad header at all */ HEADER_PARTHEADER, /* part of the chunk is a bad header, the rest is normal data */ HEADER_ALLBAD /* all was believed to be header */ } badheader; /* the header was deemed bad and will be written as body */ int headerline; /* counts header lines to better track the first one */ char *hbufp; /* points at *end* of header line */ size_t hbuflen; char *str; /* within buf */ char *str_start; /* within buf */ char *end_ptr; /* within buf */ char *p; /* within headerbuff */ curl_off_t offset; /* possible resume offset read from the Content-Range: header */ int httpcode; /* error code from the 'HTTP/1.? XXX' or 'RTSP/1.? XXX' line */ struct curltime start100; /* time stamp to wait for the 100 code from */ enum expect100 exp100; /* expect 100 continue state */ enum upgrade101 upgr101; /* 101 upgrade state */ struct contenc_writer_s *writer_stack; /* Content unencoding stack. */ /* See sec 3.5, RFC2616. */ time_t timeofdoc; long bodywrites; char *buf; int keepon; char *location; /* This points to an allocated version of the Location: header data */ char *newurl; /* Set to the new URL to use when a redirect or a retry is wanted */ /* 'upload_present' is used to keep a byte counter of how much data there is still left in the buffer, aimed for upload. */ ssize_t upload_present; /* 'upload_fromhere' is used as a read-pointer when we uploaded parts of a buffer, so the next read should read from where this pointer points to, and the 'upload_present' contains the number of bytes available at this position */ char *upload_fromhere; void *protop; /* Allocated protocol-specific data. Each protocol handler makes sure this points to data it needs. */ #ifndef CURL_DISABLE_DOH struct dohdata doh; /* DoH specific data for this request */ #endif bit header:1; /* incoming data has HTTP header */ bit content_range:1; /* set TRUE if Content-Range: was found */ bit upload_done:1; /* set to TRUE when doing chunked transfer-encoding upload and we're uploading the last chunk */ bit ignorebody:1; /* we read a response-body but we ignore it! */ bit ignorecl:1; /* This HTTP response has no body so we ignore the Content-Length: header */ bit chunk:1; /* if set, this is a chunked transfer-encoding */ bit upload_chunky:1; /* set TRUE if we are doing chunked transfer-encoding on upload */ bit getheader:1; /* TRUE if header parsing is wanted */ bit forbidchunk:1; /* used only to explicitly forbid chunk-upload for specific upload buffers. See readmoredata() in http.c for details. */ }; /* * Specific protocol handler. */ struct Curl_handler { const char *scheme; /* URL scheme name. */ /* Complement to setup_connection_internals(). */ CURLcode (*setup_connection)(struct connectdata *); /* These two functions MUST be set to be protocol dependent */ CURLcode (*do_it)(struct connectdata *, bool *done); Curl_done_func done; /* If the curl_do() function is better made in two halves, this * curl_do_more() function will be called afterwards, if set. For example * for doing the FTP stuff after the PASV/PORT command. */ Curl_do_more_func do_more; /* This function *MAY* be set to a protocol-dependent function that is run * after the connect() and everything is done, as a step in the connection. * The 'done' pointer points to a bool that should be set to TRUE if the * function completes before return. If it doesn't complete, the caller * should call the curl_connecting() function until it is. */ CURLcode (*connect_it)(struct connectdata *, bool *done); /* See above. */ CURLcode (*connecting)(struct connectdata *, bool *done); CURLcode (*doing)(struct connectdata *, bool *done); /* Called from the multi interface during the PROTOCONNECT phase, and it should then return a proper fd set */ int (*proto_getsock)(struct connectdata *conn, curl_socket_t *socks, int numsocks); /* Called from the multi interface during the DOING phase, and it should then return a proper fd set */ int (*doing_getsock)(struct connectdata *conn, curl_socket_t *socks, int numsocks); /* Called from the multi interface during the DO_MORE phase, and it should then return a proper fd set */ int (*domore_getsock)(struct connectdata *conn, curl_socket_t *socks, int numsocks); /* Called from the multi interface during the DO_DONE, PERFORM and WAITPERFORM phases, and it should then return a proper fd set. Not setting this will make libcurl use the generic default one. */ int (*perform_getsock)(const struct connectdata *conn, curl_socket_t *socks, int numsocks); /* This function *MAY* be set to a protocol-dependent function that is run * by the curl_disconnect(), as a step in the disconnection. If the handler * is called because the connection has been considered dead, dead_connection * is set to TRUE. */ CURLcode (*disconnect)(struct connectdata *, bool dead_connection); /* If used, this function gets called from transfer.c:readwrite_data() to allow the protocol to do extra reads/writes */ CURLcode (*readwrite)(struct Curl_easy *data, struct connectdata *conn, ssize_t *nread, bool *readmore); /* This function can perform various checks on the connection. See CONNCHECK_* for more information about the checks that can be performed, and CONNRESULT_* for the results that can be returned. */ unsigned int (*connection_check)(struct connectdata *conn, unsigned int checks_to_perform); long defport; /* Default port. */ unsigned int protocol; /* See CURLPROTO_* - this needs to be the single specific protocol bit */ unsigned int flags; /* Extra particular characteristics, see PROTOPT_* */ }; #define PROTOPT_NONE 0 /* nothing extra */ #define PROTOPT_SSL (1<<0) /* uses SSL */ #define PROTOPT_DUAL (1<<1) /* this protocol uses two connections */ #define PROTOPT_CLOSEACTION (1<<2) /* need action before socket close */ /* some protocols will have to call the underlying functions without regard to what exact state the socket signals. IE even if the socket says "readable", the send function might need to be called while uploading, or vice versa. */ #define PROTOPT_DIRLOCK (1<<3) #define PROTOPT_NONETWORK (1<<4) /* protocol doesn't use the network! */ #define PROTOPT_NEEDSPWD (1<<5) /* needs a password, and if none is set it gets a default */ #define PROTOPT_NOURLQUERY (1<<6) /* protocol can't handle url query strings (?foo=bar) ! */ #define PROTOPT_CREDSPERREQUEST (1<<7) /* requires login credentials per request instead of per connection */ #define PROTOPT_ALPN_NPN (1<<8) /* set ALPN and/or NPN for this */ #define PROTOPT_STREAM (1<<9) /* a protocol with individual logical streams */ #define PROTOPT_URLOPTIONS (1<<10) /* allow options part in the userinfo field of the URL */ #define PROTOPT_PROXY_AS_HTTP (1<<11) /* allow this non-HTTP scheme over a HTTP proxy as HTTP proxies may know this protocol and act as a gateway */ #define PROTOPT_WILDCARD (1<<12) /* protocol supports wildcard matching */ #define CONNCHECK_NONE 0 /* No checks */ #define CONNCHECK_ISDEAD (1<<0) /* Check if the connection is dead. */ #define CONNCHECK_KEEPALIVE (1<<1) /* Perform any keepalive function. */ #define CONNRESULT_NONE 0 /* No extra information. */ #define CONNRESULT_DEAD (1<<0) /* The connection is dead. */ #ifdef USE_RECV_BEFORE_SEND_WORKAROUND struct postponed_data { char *buffer; /* Temporal store for received data during sending, must be freed */ size_t allocated_size; /* Size of temporal store */ size_t recv_size; /* Size of received data during sending */ size_t recv_processed; /* Size of processed part of postponed data */ #ifdef DEBUGBUILD curl_socket_t bindsock;/* Structure must be bound to specific socket, used only for DEBUGASSERT */ #endif /* DEBUGBUILD */ }; #endif /* USE_RECV_BEFORE_SEND_WORKAROUND */ struct proxy_info { struct hostname host; long port; curl_proxytype proxytype; /* what kind of proxy that is in use */ char *user; /* proxy user name string, allocated */ char *passwd; /* proxy password string, allocated */ }; #define CONNECT_BUFFER_SIZE 16384 /* struct for HTTP CONNECT state data */ struct http_connect_state { char connect_buffer[CONNECT_BUFFER_SIZE]; int perline; /* count bytes per line */ int keepon; char *line_start; char *ptr; /* where to store more data */ curl_off_t cl; /* size of content to read and ignore */ enum { TUNNEL_INIT, /* init/default/no tunnel state */ TUNNEL_CONNECT, /* CONNECT has been sent off */ TUNNEL_COMPLETE /* CONNECT response received completely */ } tunnel_state; bit chunked_encoding:1; bit close_connection:1; }; /* * The connectdata struct contains all fields and variables that should be * unique for an entire connection. */ struct connectdata { /* 'data' is the CURRENT Curl_easy using this connection -- take great caution that this might very well vary between different times this connection is used! */ struct Curl_easy *data; struct curl_llist_element bundle_node; /* conncache */ /* chunk is for HTTP chunked encoding, but is in the general connectdata struct only because we can do just about any protocol through a HTTP proxy and a HTTP proxy may in fact respond using chunked encoding */ struct Curl_chunker chunk; curl_closesocket_callback fclosesocket; /* function closing the socket(s) */ void *closesocket_client; /* This is used by the connection cache logic. If this returns TRUE, this handle is still used by one or more easy handles and can only used by any other easy handle without careful consideration (== only for multiplexing) and it cannot be used by another multi handle! */ #define CONN_INUSE(c) ((c)->easyq.size) /**** Fields set when inited and not modified again */ long connection_id; /* Contains a unique number to make it easier to track the connections in the log output */ /* 'dns_entry' is the particular host we use. This points to an entry in the DNS cache and it will not get pruned while locked. It gets unlocked in Curl_done(). This entry will be NULL if the connection is re-used as then there is no name resolve done. */ struct Curl_dns_entry *dns_entry; /* 'ip_addr' is the particular IP we connected to. It points to a struct within the DNS cache, so this pointer is only valid as long as the DNS cache entry remains locked. It gets unlocked in Curl_done() */ Curl_addrinfo *ip_addr; Curl_addrinfo *tempaddr[2]; /* for happy eyeballs */ /* 'ip_addr_str' is the ip_addr data as a human readable string. It remains available as long as the connection does, which is longer than the ip_addr itself. */ char ip_addr_str[MAX_IPADR_LEN]; unsigned int scope_id; /* Scope id for IPv6 */ int socktype; /* SOCK_STREAM or SOCK_DGRAM */ struct hostname host; char *hostname_resolve; /* host name to resolve to address, allocated */ char *secondaryhostname; /* secondary socket host name (ftp) */ struct hostname conn_to_host; /* the host to connect to. valid only if bits.conn_to_host is set */ struct proxy_info socks_proxy; struct proxy_info http_proxy; long port; /* which port to use locally */ int remote_port; /* the remote port, not the proxy port! */ int conn_to_port; /* the remote port to connect to. valid only if bits.conn_to_port is set */ unsigned short secondary_port; /* secondary socket remote port to connect to (ftp) */ /* 'primary_ip' and 'primary_port' get filled with peer's numerical ip address and port number whenever an outgoing connection is *attempted* from the primary socket to a remote address. When more than one address is tried for a connection these will hold data for the last attempt. When the connection is actually established these are updated with data which comes directly from the socket. */ char primary_ip[MAX_IPADR_LEN]; long primary_port; /* 'local_ip' and 'local_port' get filled with local's numerical ip address and port number whenever an outgoing connection is **established** from the primary socket to a remote address. */ char local_ip[MAX_IPADR_LEN]; long local_port; char *user; /* user name string, allocated */ char *passwd; /* password string, allocated */ char *options; /* options string, allocated */ char *oauth_bearer; /* bearer token for OAuth 2.0, allocated */ int httpversion; /* the HTTP version*10 reported by the server */ int rtspversion; /* the RTSP version*10 reported by the server */ struct curltime now; /* "current" time */ struct curltime created; /* creation time */ struct curltime lastused; /* when returned to the connection cache */ curl_socket_t sock[2]; /* two sockets, the second is used for the data transfer when doing FTP */ curl_socket_t tempsock[2]; /* temporary sockets for happy eyeballs */ bool sock_accepted[2]; /* TRUE if the socket on this index was created with accept() */ Curl_recv *recv[2]; Curl_send *send[2]; #ifdef USE_RECV_BEFORE_SEND_WORKAROUND struct postponed_data postponed[2]; /* two buffers for two sockets */ #endif /* USE_RECV_BEFORE_SEND_WORKAROUND */ struct ssl_connect_data ssl[2]; /* this is for ssl-stuff */ struct ssl_connect_data proxy_ssl[2]; /* this is for proxy ssl-stuff */ #ifdef USE_SSL void *ssl_extra; /* separately allocated backend-specific data */ #endif struct ssl_primary_config ssl_config; struct ssl_primary_config proxy_ssl_config; struct ConnectBits bits; /* various state-flags for this connection */ /* connecttime: when connect() is called on the current IP address. Used to be able to track when to move on to try next IP - but only when the multi interface is used. */ struct curltime connecttime; /* The two fields below get set in Curl_connecthost */ int num_addr; /* number of addresses to try to connect to */ time_t timeoutms_per_addr; /* how long time in milliseconds to spend on trying to connect to each IP address */ const struct Curl_handler *handler; /* Connection's protocol handler */ const struct Curl_handler *given; /* The protocol first given */ long ip_version; /* copied from the Curl_easy at creation time */ /* Protocols can use a custom keepalive mechanism to keep connections alive. This allows those protocols to track the last time the keepalive mechanism was used on this connection. */ struct curltime keepalive; long upkeep_interval_ms; /* Time between calls for connection upkeep. */ /**** curl_get() phase fields */ curl_socket_t sockfd; /* socket to read from or CURL_SOCKET_BAD */ curl_socket_t writesockfd; /* socket to write to, it may very well be the same we read from. CURL_SOCKET_BAD disables */ /** Dynamically allocated strings, MUST be freed before this **/ /** struct is killed. **/ struct dynamically_allocated_data { char *proxyuserpwd; char *uagent; char *accept_encoding; char *userpwd; char *rangeline; char *ref; char *host; char *cookiehost; char *rtsp_transport; char *te; /* TE: request header */ } allocptr; #ifdef HAVE_GSSAPI bit sec_complete:1; /* if Kerberos is enabled for this connection */ enum protection_level command_prot; enum protection_level data_prot; enum protection_level request_data_prot; size_t buffer_size; struct krb5buffer in_buffer; void *app_data; const struct Curl_sec_client_mech *mech; struct sockaddr_in local_addr; #endif #if defined(USE_KERBEROS5) /* Consider moving some of the above GSS-API */ struct kerberos5data krb5; /* variables into the structure definition, */ #endif /* however, some of them are ftp specific. */ struct curl_llist easyq; /* List of easy handles using this connection */ curl_seek_callback seek_func; /* function that seeks the input */ void *seek_client; /* pointer to pass to the seek() above */ /*************** Request - specific items ************/ #if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) CtxtHandle *sslContext; #endif #if defined(USE_NTLM) curlntlm http_ntlm_state; curlntlm proxy_ntlm_state; struct ntlmdata ntlm; /* NTLM differs from other authentication schemes because it authenticates connections, not single requests! */ struct ntlmdata proxyntlm; /* NTLM data for proxy */ #if defined(NTLM_WB_ENABLED) /* used for communication with Samba's winbind daemon helper ntlm_auth */ curl_socket_t ntlm_auth_hlpr_socket; pid_t ntlm_auth_hlpr_pid; char *challenge_header; char *response_header; #endif #endif #ifdef USE_SPNEGO curlnegotiate http_negotiate_state; curlnegotiate proxy_negotiate_state; struct negotiatedata negotiate; /* state data for host Negotiate auth */ struct negotiatedata proxyneg; /* state data for proxy Negotiate auth */ #endif /* data used for the asynch name resolve callback */ struct Curl_async async; /* These three are used for chunked-encoding trailer support */ char *trailer; /* allocated buffer to store trailer in */ int trlMax; /* allocated buffer size */ int trlPos; /* index of where to store data */ union { struct ftp_conn ftpc; struct http_conn httpc; struct ssh_conn sshc; struct tftp_state_data *tftpc; struct imap_conn imapc; struct pop3_conn pop3c; struct smtp_conn smtpc; struct rtsp_conn rtspc; struct smb_conn smbc; void *generic; /* RTMP and LDAP use this */ } proto; int cselect_bits; /* bitmask of socket events */ int waitfor; /* current READ/WRITE bits to wait for */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) int socks5_gssapi_enctype; #endif /* When this connection is created, store the conditions for the local end bind. This is stored before the actual bind and before any connection is made and will serve the purpose of being used for comparison reasons so that subsequent bound-requested connections aren't accidentally re-using wrong connections. */ char *localdev; unsigned short localport; int localportrange; struct http_connect_state *connect_state; /* for HTTP CONNECT */ struct connectbundle *bundle; /* The bundle we are member of */ int negnpn; /* APLN or NPN TLS negotiated protocol, CURL_HTTP_VERSION* */ #ifdef USE_UNIX_SOCKETS char *unix_domain_socket; bit abstract_unix_socket:1; #endif bit tls_upgraded:1; /* the two following *_inuse fields are only flags, not counters in any way. If TRUE it means the channel is in use, and if FALSE it means the channel is up for grabs by one. */ bit readchannel_inuse:1; /* whether the read channel is in use by an easy handle */ bit writechannel_inuse:1; /* whether the write channel is in use by an easy handle */ }; /* The end of connectdata. */ /* * Struct to keep statistical and informational data. * All variables in this struct must be initialized/reset in Curl_initinfo(). */ struct PureInfo { int httpcode; /* Recent HTTP, FTP, RTSP or SMTP response code */ int httpproxycode; /* response code from proxy when received separate */ int httpversion; /* the http version number X.Y = X*10+Y */ time_t filetime; /* If requested, this is might get set. Set to -1 if the time was unretrievable. */ curl_off_t header_size; /* size of read header(s) in bytes */ curl_off_t request_size; /* the amount of bytes sent in the request(s) */ unsigned long proxyauthavail; /* what proxy auth types were announced */ unsigned long httpauthavail; /* what host auth types were announced */ long numconnects; /* how many new connection did libcurl created */ char *contenttype; /* the content type of the object */ char *wouldredirect; /* URL this would've been redirected to if asked to */ /* PureInfo members 'conn_primary_ip', 'conn_primary_port', 'conn_local_ip' and, 'conn_local_port' are copied over from the connectdata struct in order to allow curl_easy_getinfo() to return this information even when the session handle is no longer associated with a connection, and also allow curl_easy_reset() to clear this information from the session handle without disturbing information which is still alive, and that might be reused, in the connection cache. */ char conn_primary_ip[MAX_IPADR_LEN]; long conn_primary_port; char conn_local_ip[MAX_IPADR_LEN]; long conn_local_port; const char *conn_scheme; unsigned int conn_protocol; struct curl_certinfo certs; /* info about the certs, only populated in OpenSSL builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ bit timecond:1; /* set to TRUE if the time condition didn't match, which thus made the document NOT get fetched */ }; struct Progress { time_t lastshow; /* time() of the last displayed progress meter or NULL to force redraw at next call */ curl_off_t size_dl; /* total expected size */ curl_off_t size_ul; /* total expected size */ curl_off_t downloaded; /* transferred so far */ curl_off_t uploaded; /* transferred so far */ curl_off_t current_speed; /* uses the currently fastest transfer */ int width; /* screen width at download start */ int flags; /* see progress.h */ time_t timespent; curl_off_t dlspeed; curl_off_t ulspeed; time_t t_nslookup; time_t t_connect; time_t t_appconnect; time_t t_pretransfer; time_t t_starttransfer; time_t t_redirect; struct curltime start; struct curltime t_startsingle; struct curltime t_startop; struct curltime t_acceptdata; /* upload speed limit */ struct curltime ul_limit_start; curl_off_t ul_limit_size; /* download speed limit */ struct curltime dl_limit_start; curl_off_t dl_limit_size; #define CURR_TIME (5 + 1) /* 6 entries for 5 seconds */ curl_off_t speeder[ CURR_TIME ]; struct curltime speeder_time[ CURR_TIME ]; int speeder_c; bit callback:1; /* set when progress callback is used */ bit is_t_startransfer_set:1; }; typedef enum { HTTPREQ_NONE, /* first in list */ HTTPREQ_GET, HTTPREQ_POST, HTTPREQ_POST_FORM, /* we make a difference internally */ HTTPREQ_POST_MIME, /* we make a difference internally */ HTTPREQ_PUT, HTTPREQ_HEAD, HTTPREQ_OPTIONS, HTTPREQ_LAST /* last in list */ } Curl_HttpReq; typedef enum { RTSPREQ_NONE, /* first in list */ RTSPREQ_OPTIONS, RTSPREQ_DESCRIBE, RTSPREQ_ANNOUNCE, RTSPREQ_SETUP, RTSPREQ_PLAY, RTSPREQ_PAUSE, RTSPREQ_TEARDOWN, RTSPREQ_GET_PARAMETER, RTSPREQ_SET_PARAMETER, RTSPREQ_RECORD, RTSPREQ_RECEIVE, RTSPREQ_LAST /* last in list */ } Curl_RtspReq; /* * Values that are generated, temporary or calculated internally for a * "session handle" must be defined within the 'struct UrlState'. This struct * will be used within the Curl_easy struct. When the 'Curl_easy' * struct is cloned, this data MUST NOT be copied. * * Remember that any "state" information goes globally for the curl handle. * Session-data MUST be put in the connectdata struct and here. */ #define MAX_CURL_USER_LENGTH 256 #define MAX_CURL_PASSWORD_LENGTH 256 struct auth { unsigned long want; /* Bitmask set to the authentication methods wanted by app (with CURLOPT_HTTPAUTH or CURLOPT_PROXYAUTH). */ unsigned long picked; unsigned long avail; /* Bitmask for what the server reports to support for this resource */ bit done:1; /* TRUE when the auth phase is done and ready to do the *actual* request */ bit multipass:1; /* TRUE if this is not yet authenticated but within the auth multipass negotiation */ bit iestyle:1; /* TRUE if digest should be done IE-style or FALSE if it should be RFC compliant */ }; struct Curl_http2_dep { struct Curl_http2_dep *next; struct Curl_easy *data; }; /* * This struct is for holding data that was attempted to get sent to the user's * callback but is held due to pausing. One instance per type (BOTH, HEADER, * BODY). */ struct tempbuf { char *buf; /* allocated buffer to keep data in when a write callback returns to make the connection paused */ size_t len; /* size of the 'tempwrite' allocated buffer */ int type; /* type of the 'tempwrite' buffer as a bitmask that is used with Curl_client_write() */ }; /* Timers */ typedef enum { EXPIRE_100_TIMEOUT, EXPIRE_ASYNC_NAME, EXPIRE_CONNECTTIMEOUT, EXPIRE_DNS_PER_NAME, EXPIRE_HAPPY_EYEBALLS_DNS, /* See asyn-ares.c */ EXPIRE_HAPPY_EYEBALLS, EXPIRE_MULTI_PENDING, EXPIRE_RUN_NOW, EXPIRE_SPEEDCHECK, EXPIRE_TIMEOUT, EXPIRE_TOOFAST, EXPIRE_LAST /* not an actual timer, used as a marker only */ } expire_id; typedef enum { TRAILERS_NONE, TRAILERS_INITIALIZED, TRAILERS_SENDING, TRAILERS_DONE } trailers_state; /* * One instance for each timeout an easy handle can set. */ struct time_node { struct curl_llist_element list; struct curltime time; expire_id eid; }; /* individual pieces of the URL */ struct urlpieces { char *scheme; char *hostname; char *port; char *user; char *password; char *options; char *path; char *query; }; struct UrlState { /* Points to the connection cache */ struct conncache *conn_cache; /* buffers to store authentication data in, as parsed from input options */ struct curltime keeps_speed; /* for the progress meter really */ struct connectdata *lastconnect; /* The last connection, NULL if undefined */ char *headerbuff; /* allocated buffer to store headers in */ size_t headersize; /* size of the allocation */ char *buffer; /* download buffer */ char *ulbuf; /* allocated upload buffer or NULL */ curl_off_t current_speed; /* the ProgressShow() function sets this, bytes / second */ char *first_host; /* host name of the first (not followed) request. if set, this should be the host name that we will sent authorization to, no else. Used to make Location: following not keep sending user+password... This is strdup() data. */ int first_remote_port; /* remote port of the first (not followed) request */ struct curl_ssl_session *session; /* array of 'max_ssl_sessions' size */ long sessionage; /* number of the most recent session */ unsigned int tempcount; /* number of entries in use in tempwrite, 0 - 3 */ struct tempbuf tempwrite[3]; /* BOTH, HEADER, BODY */ char *scratch; /* huge buffer[set.buffer_size*2] for upload CRLF replacing */ int os_errno; /* filled in with errno whenever an error occurs */ #ifdef HAVE_SIGNAL /* storage for the previous bag^H^H^HSIGPIPE signal handler :-) */ void (*prev_signal)(int sig); #endif struct digestdata digest; /* state data for host Digest auth */ struct digestdata proxydigest; /* state data for proxy Digest auth */ struct auth authhost; /* auth details for host */ struct auth authproxy; /* auth details for proxy */ void *resolver; /* resolver state, if it is used in the URL state - ares_channel f.e. */ #if defined(USE_OPENSSL) /* void instead of ENGINE to avoid bleeding OpenSSL into this header */ void *engine; #endif /* USE_OPENSSL */ struct curltime expiretime; /* set this with Curl_expire() only */ struct Curl_tree timenode; /* for the splay stuff */ struct curl_llist timeoutlist; /* list of pending timeouts */ struct time_node expires[EXPIRE_LAST]; /* nodes for each expire type */ /* a place to store the most recently set FTP entrypath */ char *most_recent_ftp_entrypath; int httpversion; /* the lowest HTTP version*10 reported by any server involved in this request */ #if !defined(WIN32) && !defined(MSDOS) && !defined(__EMX__) && \ !defined(__SYMBIAN32__) /* do FTP line-end conversions on most platforms */ #define CURL_DO_LINEEND_CONV /* for FTP downloads: track CRLF sequences that span blocks */ bit prev_block_had_trailing_cr:1; /* for FTP downloads: how many CRLFs did we converted to LFs? */ curl_off_t crlf_conversions; #endif char *range; /* range, if used. See README for detailed specification on this syntax. */ curl_off_t resume_from; /* continue [ftp] transfer from here */ /* This RTSP state information survives requests and connections */ long rtsp_next_client_CSeq; /* the session's next client CSeq */ long rtsp_next_server_CSeq; /* the session's next server CSeq */ long rtsp_CSeq_recv; /* most recent CSeq received */ curl_off_t infilesize; /* size of file to upload, -1 means unknown. Copied from set.filesize at start of operation */ size_t drain; /* Increased when this stream has data to read, even if its socket is not necessarily is readable. Decreased when checked. */ curl_read_callback fread_func; /* read callback/function */ void *in; /* CURLOPT_READDATA */ struct Curl_easy *stream_depends_on; int stream_weight; CURLU *uh; /* URL handle for the current parsed URL */ struct urlpieces up; #ifndef CURL_DISABLE_HTTP size_t trailers_bytes_sent; Curl_send_buffer *trailers_buf; /* a buffer containing the compiled trailing headers */ #endif trailers_state trailers_state; /* whether we are sending trailers and what stage are we at */ #ifdef CURLDEBUG bit conncache_lock:1; #endif /* when curl_easy_perform() is called, the multi handle is "owned" by the easy handle so curl_easy_cleanup() on such an easy handle will also close the multi handle! */ bit multi_owned_by_easy:1; bit this_is_a_follow:1; /* this is a followed Location: request */ bit refused_stream:1; /* this was refused, try again */ bit errorbuf:1; /* Set to TRUE if the error buffer is already filled in. This must be set to FALSE every time _easy_perform() is called. */ bit allow_port:1; /* Is set.use_port allowed to take effect or not. This is always set TRUE when curl_easy_perform() is called. */ bit authproblem:1; /* TRUE if there's some problem authenticating */ /* set after initial USER failure, to prevent an authentication loop */ bit ftp_trying_alternative:1; bit wildcardmatch:1; /* enable wildcard matching */ bit expect100header:1; /* TRUE if we added Expect: 100-continue */ bit use_range:1; bit rangestringalloc:1; /* the range string is malloc()'ed */ bit done:1; /* set to FALSE when Curl_init_do() is called and set to TRUE when multi_done() is called, to prevent multi_done() to get invoked twice when the multi interface is used. */ bit stream_depends_e:1; /* set or don't set the Exclusive bit */ bit previouslypending:1; /* this transfer WAS in the multi->pending queue */ }; /* * This 'DynamicStatic' struct defines dynamic states that actually change * values in the 'UserDefined' area, which MUST be taken into consideration * if the UserDefined struct is cloned or similar. You can probably just * copy these, but each one indicate a special action on other data. */ struct DynamicStatic { char *url; /* work URL, copied from UserDefined */ char *referer; /* referer string */ struct curl_slist *cookielist; /* list of cookie files set by curl_easy_setopt(COOKIEFILE) calls */ struct curl_slist *resolve; /* set to point to the set.resolve list when this should be dealt with in pretransfer */ bit url_alloc:1; /* URL string is malloc()'ed */ bit referer_alloc:1; /* referer string is malloc()ed */ bit wildcard_resolve:1; /* Set to true if any resolve change is a wildcard */ }; /* * This 'UserDefined' struct must only contain data that is set once to go * for many (perhaps) independent connections. Values that are generated or * calculated internally for the "session handle" MUST be defined within the * 'struct UrlState' instead. The only exceptions MUST note the changes in * the 'DynamicStatic' struct. * Character pointer fields point to dynamic storage, unless otherwise stated. */ struct Curl_multi; /* declared and used only in multi.c */ enum dupstring { STRING_CERT_ORIG, /* client certificate file name */ STRING_CERT_PROXY, /* client certificate file name */ STRING_CERT_TYPE_ORIG, /* format for certificate (default: PEM)*/ STRING_CERT_TYPE_PROXY, /* format for certificate (default: PEM)*/ STRING_COOKIE, /* HTTP cookie string to send */ STRING_COOKIEJAR, /* dump all cookies to this file */ STRING_CUSTOMREQUEST, /* HTTP/FTP/RTSP request/method to use */ STRING_DEFAULT_PROTOCOL, /* Protocol to use when the URL doesn't specify */ STRING_DEVICE, /* local network interface/address to use */ STRING_ENCODING, /* Accept-Encoding string */ STRING_FTP_ACCOUNT, /* ftp account data */ STRING_FTP_ALTERNATIVE_TO_USER, /* command to send if USER/PASS fails */ STRING_FTPPORT, /* port to send with the FTP PORT command */ STRING_KEY_ORIG, /* private key file name */ STRING_KEY_PROXY, /* private key file name */ STRING_KEY_PASSWD_ORIG, /* plain text private key password */ STRING_KEY_PASSWD_PROXY, /* plain text private key password */ STRING_KEY_TYPE_ORIG, /* format for private key (default: PEM) */ STRING_KEY_TYPE_PROXY, /* format for private key (default: PEM) */ STRING_KRB_LEVEL, /* krb security level */ STRING_NETRC_FILE, /* if not NULL, use this instead of trying to find $HOME/.netrc */ STRING_PROXY, /* proxy to use */ STRING_PRE_PROXY, /* pre socks proxy to use */ STRING_SET_RANGE, /* range, if used */ STRING_SET_REFERER, /* custom string for the HTTP referer field */ STRING_SET_URL, /* what original URL to work on */ STRING_SSL_CAPATH_ORIG, /* CA directory name (doesn't work on windows) */ STRING_SSL_CAPATH_PROXY, /* CA directory name (doesn't work on windows) */ STRING_SSL_CAFILE_ORIG, /* certificate file to verify peer against */ STRING_SSL_CAFILE_PROXY, /* certificate file to verify peer against */ STRING_SSL_PINNEDPUBLICKEY_ORIG, /* public key file to verify peer against */ STRING_SSL_PINNEDPUBLICKEY_PROXY, /* public key file to verify proxy */ STRING_SSL_CIPHER_LIST_ORIG, /* list of ciphers to use */ STRING_SSL_CIPHER_LIST_PROXY, /* list of ciphers to use */ STRING_SSL_CIPHER13_LIST_ORIG, /* list of TLS 1.3 ciphers to use */ STRING_SSL_CIPHER13_LIST_PROXY, /* list of TLS 1.3 ciphers to use */ STRING_SSL_EGDSOCKET, /* path to file containing the EGD daemon socket */ STRING_SSL_RANDOM_FILE, /* path to file containing "random" data */ STRING_USERAGENT, /* User-Agent string */ STRING_SSL_CRLFILE_ORIG, /* crl file to check certificate */ STRING_SSL_CRLFILE_PROXY, /* crl file to check certificate */ STRING_SSL_ISSUERCERT_ORIG, /* issuer cert file to check certificate */ STRING_SSL_ISSUERCERT_PROXY, /* issuer cert file to check certificate */ STRING_SSL_ENGINE, /* name of ssl engine */ STRING_USERNAME, /* <username>, if used */ STRING_PASSWORD, /* <password>, if used */ STRING_OPTIONS, /* <options>, if used */ STRING_PROXYUSERNAME, /* Proxy <username>, if used */ STRING_PROXYPASSWORD, /* Proxy <password>, if used */ STRING_NOPROXY, /* List of hosts which should not use the proxy, if used */ STRING_RTSP_SESSION_ID, /* Session ID to use */ STRING_RTSP_STREAM_URI, /* Stream URI for this request */ STRING_RTSP_TRANSPORT, /* Transport for this session */ #ifdef USE_SSH STRING_SSH_PRIVATE_KEY, /* path to the private key file for auth */ STRING_SSH_PUBLIC_KEY, /* path to the public key file for auth */ STRING_SSH_HOST_PUBLIC_KEY_MD5, /* md5 of host public key in ascii hex */ STRING_SSH_KNOWNHOSTS, /* file name of knownhosts file */ #endif STRING_PROXY_SERVICE_NAME, /* Proxy service name */ STRING_SERVICE_NAME, /* Service name */ STRING_MAIL_FROM, STRING_MAIL_AUTH, #ifdef USE_TLS_SRP STRING_TLSAUTH_USERNAME_ORIG, /* TLS auth <username> */ STRING_TLSAUTH_USERNAME_PROXY, /* TLS auth <username> */ STRING_TLSAUTH_PASSWORD_ORIG, /* TLS auth <password> */ STRING_TLSAUTH_PASSWORD_PROXY, /* TLS auth <password> */ #endif STRING_BEARER, /* <bearer>, if used */ #ifdef USE_UNIX_SOCKETS STRING_UNIX_SOCKET_PATH, /* path to Unix socket, if used */ #endif STRING_TARGET, /* CURLOPT_REQUEST_TARGET */ STRING_DOH, /* CURLOPT_DOH_URL */ #ifdef USE_ALTSVC STRING_ALTSVC, /* CURLOPT_ALTSVC */ #endif /* -- end of zero-terminated strings -- */ STRING_LASTZEROTERMINATED, /* -- below this are pointers to binary data that cannot be strdup'ed. --- */ STRING_COPYPOSTFIELDS, /* if POST, set the fields' values here */ STRING_LAST /* not used, just an end-of-list marker */ }; /* callback that gets called when this easy handle is completed within a multi handle. Only used for internally created transfers, like for example DoH. */ typedef int (*multidone_func)(struct Curl_easy *easy, CURLcode result); struct UserDefined { FILE *err; /* the stderr user data goes here */ void *debugdata; /* the data that will be passed to fdebug */ char *errorbuffer; /* (Static) store failure messages in here */ long proxyport; /* If non-zero, use this port number by default. If the proxy string features a ":[port]" that one will override this. */ void *out; /* CURLOPT_WRITEDATA */ void *in_set; /* CURLOPT_READDATA */ void *writeheader; /* write the header to this if non-NULL */ void *rtp_out; /* write RTP to this if non-NULL */ long use_port; /* which port to use (when not using default) */ unsigned long httpauth; /* kind of HTTP authentication to use (bitmask) */ unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */ unsigned long socks5auth;/* kind of SOCKS5 authentication to use (bitmask) */ long followlocation; /* as in HTTP Location: */ long maxredirs; /* maximum no. of http(s) redirects to follow, set to -1 for infinity */ int keep_post; /* keep POSTs as POSTs after a 30x request; each bit represents a request, from 301 to 303 */ void *postfields; /* if POST, set the fields' values here */ curl_seek_callback seek_func; /* function that seeks the input */ curl_off_t postfieldsize; /* if POST, this might have a size to use instead of strlen(), and then the data *may* be binary (contain zero bytes) */ unsigned short localport; /* local port number to bind to */ int localportrange; /* number of additional port numbers to test in case the 'localport' one can't be bind()ed */ curl_write_callback fwrite_func; /* function that stores the output */ curl_write_callback fwrite_header; /* function that stores headers */ curl_write_callback fwrite_rtp; /* function that stores interleaved RTP */ curl_read_callback fread_func_set; /* function that reads the input */ curl_progress_callback fprogress; /* OLD and deprecated progress callback */ curl_xferinfo_callback fxferinfo; /* progress callback */ curl_debug_callback fdebug; /* function that write informational data */ curl_ioctl_callback ioctl_func; /* function for I/O control */ curl_sockopt_callback fsockopt; /* function for setting socket options */ void *sockopt_client; /* pointer to pass to the socket options callback */ curl_opensocket_callback fopensocket; /* function for checking/translating the address and opening the socket */ void *opensocket_client; curl_closesocket_callback fclosesocket; /* function for closing the socket */ void *closesocket_client; void *seek_client; /* pointer to pass to the seek callback */ /* the 3 curl_conv_callback functions below are used on non-ASCII hosts */ /* function to convert from the network encoding: */ curl_conv_callback convfromnetwork; /* function to convert to the network encoding: */ curl_conv_callback convtonetwork; /* function to convert from UTF-8 encoding: */ curl_conv_callback convfromutf8; void *progress_client; /* pointer to pass to the progress callback */ void *ioctl_client; /* pointer to pass to the ioctl callback */ long timeout; /* in milliseconds, 0 means no timeout */ long connecttimeout; /* in milliseconds, 0 means no timeout */ long accepttimeout; /* in milliseconds, 0 means no timeout */ long happy_eyeballs_timeout; /* in milliseconds, 0 is a valid value */ long server_response_timeout; /* in milliseconds, 0 means no timeout */ long maxage_conn; /* in seconds, max idle time to allow a connection that is to be reused */ long tftp_blksize; /* in bytes, 0 means use default */ curl_off_t filesize; /* size of file to upload, -1 means unknown */ long low_speed_limit; /* bytes/second */ long low_speed_time; /* number of seconds */ curl_off_t max_send_speed; /* high speed limit in bytes/second for upload */ curl_off_t max_recv_speed; /* high speed limit in bytes/second for download */ curl_off_t set_resume_from; /* continue [ftp] transfer from here */ struct curl_slist *headers; /* linked list of extra headers */ struct curl_slist *proxyheaders; /* linked list of extra CONNECT headers */ struct curl_httppost *httppost; /* linked list of old POST data */ curl_mimepart mimepost; /* MIME/POST data. */ struct curl_slist *quote; /* after connection is established */ struct curl_slist *postquote; /* after the transfer */ struct curl_slist *prequote; /* before the transfer, after type */ struct curl_slist *source_quote; /* 3rd party quote */ struct curl_slist *source_prequote; /* in 3rd party transfer mode - before the transfer on source host */ struct curl_slist *source_postquote; /* in 3rd party transfer mode - after the transfer on source host */ struct curl_slist *telnet_options; /* linked list of telnet options */ struct curl_slist *resolve; /* list of names to add/remove from DNS cache */ struct curl_slist *connect_to; /* list of host:port mappings to override the hostname and port to connect to */ curl_TimeCond timecondition; /* kind of time/date comparison */ time_t timevalue; /* what time to compare with */ Curl_HttpReq httpreq; /* what kind of HTTP request (if any) is this */ long httpversion; /* when non-zero, a specific HTTP version requested to be used in the library's request(s) */ struct ssl_config_data ssl; /* user defined SSL stuff */ struct ssl_config_data proxy_ssl; /* user defined SSL stuff for proxy */ struct ssl_general_config general_ssl; /* general user defined SSL stuff */ curl_proxytype proxytype; /* what kind of proxy that is in use */ long dns_cache_timeout; /* DNS cache timeout */ long buffer_size; /* size of receive buffer to use */ size_t upload_buffer_size; /* size of upload buffer to use, keep it >= CURL_MAX_WRITE_SIZE */ void *private_data; /* application-private data */ struct curl_slist *http200aliases; /* linked list of aliases for http200 */ long ipver; /* the CURL_IPRESOLVE_* defines in the public header file 0 - whatever, 1 - v2, 2 - v6 */ curl_off_t max_filesize; /* Maximum file size to download */ #ifndef CURL_DISABLE_FTP curl_ftpfile ftp_filemethod; /* how to get to a file when FTP is used */ curl_ftpauth ftpsslauth; /* what AUTH XXX to be attempted */ curl_ftpccc ftp_ccc; /* FTP CCC options */ #endif int ftp_create_missing_dirs; /* 1 - create directories that don't exist 2 - the same but also allow MKD to fail once */ curl_sshkeycallback ssh_keyfunc; /* key matching callback */ void *ssh_keyfunc_userp; /* custom pointer to callback */ enum CURL_NETRC_OPTION use_netrc; /* defined in include/curl.h */ curl_usessl use_ssl; /* if AUTH TLS is to be attempted etc, for FTP or IMAP or POP3 or others! */ long new_file_perms; /* Permissions to use when creating remote files */ long new_directory_perms; /* Permissions to use when creating remote dirs */ long ssh_auth_types; /* allowed SSH auth types */ char *str[STRING_LAST]; /* array of strings, pointing to allocated memory */ unsigned int scope_id; /* Scope id for IPv6 */ long allowed_protocols; long redir_protocols; struct curl_slist *mail_rcpt; /* linked list of mail recipients */ /* Common RTSP header options */ Curl_RtspReq rtspreq; /* RTSP request type */ long rtspversion; /* like httpversion, for RTSP */ curl_chunk_bgn_callback chunk_bgn; /* called before part of transfer starts */ curl_chunk_end_callback chunk_end; /* called after part transferring stopped */ curl_fnmatch_callback fnmatch; /* callback to decide which file corresponds to pattern (e.g. if WILDCARDMATCH is on) */ void *fnmatch_data; long gssapi_delegation; /* GSS-API credential delegation, see the documentation of CURLOPT_GSSAPI_DELEGATION */ long tcp_keepidle; /* seconds in idle before sending keepalive probe */ long tcp_keepintvl; /* seconds between TCP keepalive probes */ size_t maxconnects; /* Max idle connections in the connection cache */ long expect_100_timeout; /* in milliseconds */ struct Curl_easy *stream_depends_on; int stream_weight; struct Curl_http2_dep *stream_dependents; curl_resolver_start_callback resolver_start; /* optional callback called before resolver start */ void *resolver_start_client; /* pointer to pass to resolver start callback */ long upkeep_interval_ms; /* Time between calls for connection upkeep. */ multidone_func fmultidone; struct Curl_easy *dohfor; /* this is a DoH request for that transfer */ CURLU *uh; /* URL handle for the current parsed URL */ void *trailer_data; /* pointer to pass to trailer data callback */ curl_trailer_callback trailer_callback; /* trailing data callback */ bit is_fread_set:1; /* has read callback been set to non-NULL? */ bit is_fwrite_set:1; /* has write callback been set to non-NULL? */ bit free_referer:1; /* set TRUE if 'referer' points to a string we allocated */ bit tftp_no_options:1; /* do not send TFTP options requests */ bit sep_headers:1; /* handle host and proxy headers separately */ bit cookiesession:1; /* new cookie session? */ bit crlf:1; /* convert crlf on ftp upload(?) */ bit strip_path_slash:1; /* strip off initial slash from path */ bit ssh_compression:1; /* enable SSH compression */ /* Here follows boolean settings that define how to behave during this session. They are STATIC, set by libcurl users or at least initially and they don't change during operations. */ bit get_filetime:1; /* get the time and get of the remote file */ bit tunnel_thru_httpproxy:1; /* use CONNECT through a HTTP proxy */ bit prefer_ascii:1; /* ASCII rather than binary */ bit ftp_append:1; /* append, not overwrite, on upload */ bit ftp_list_only:1; /* switch FTP command for listing directories */ #ifndef CURL_DISABLE_FTP bit ftp_use_port:1; /* use the FTP PORT command */ bit ftp_use_epsv:1; /* if EPSV is to be attempted or not */ bit ftp_use_eprt:1; /* if EPRT is to be attempted or not */ bit ftp_use_pret:1; /* if PRET is to be used before PASV or not */ bit ftp_skip_ip:1; /* skip the IP address the FTP server passes on to us */ #endif bit hide_progress:1; /* don't use the progress meter */ bit http_fail_on_error:1; /* fail on HTTP error codes >= 400 */ bit http_keep_sending_on_error:1; /* for HTTP status codes >= 300 */ bit http_follow_location:1; /* follow HTTP redirects */ bit http_transfer_encoding:1; /* request compressed HTTP transfer-encoding */ bit allow_auth_to_other_hosts:1; bit include_header:1; /* include received protocol headers in data output */ bit http_set_referer:1; /* is a custom referer used */ bit http_auto_referer:1; /* set "correct" referer when following location: */ bit opt_no_body:1; /* as set with CURLOPT_NOBODY */ bit upload:1; /* upload request */ bit verbose:1; /* output verbosity */ bit krb:1; /* Kerberos connection requested */ bit reuse_forbid:1; /* forbidden to be reused, close after use */ bit reuse_fresh:1; /* do not re-use an existing connection */ bit no_signal:1; /* do not use any signal/alarm handler */ bit tcp_nodelay:1; /* whether to enable TCP_NODELAY or not */ bit ignorecl:1; /* ignore content length */ bit connect_only:1; /* make connection, let application use the socket */ bit http_te_skip:1; /* pass the raw body data to the user, even when transfer-encoded (chunked, compressed) */ bit http_ce_skip:1; /* pass the raw body data to the user, even when content-encoded (chunked, compressed) */ bit proxy_transfer_mode:1; /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) bit socks5_gssapi_nec:1; /* Flag to support NEC SOCKS5 server */ #endif bit sasl_ir:1; /* Enable/disable SASL initial response */ bit wildcard_enabled:1; /* enable wildcard matching */ bit tcp_keepalive:1; /* use TCP keepalives */ bit tcp_fastopen:1; /* use TCP Fast Open */ bit ssl_enable_npn:1; /* TLS NPN extension? */ bit ssl_enable_alpn:1;/* TLS ALPN extension? */ bit path_as_is:1; /* allow dotdots? */ bit pipewait:1; /* wait for multiplex status before starting a new connection */ bit suppress_connect_headers:1; /* suppress proxy CONNECT response headers from user callbacks */ bit dns_shuffle_addresses:1; /* whether to shuffle addresses before use */ bit stream_depends_e:1; /* set or don't set the Exclusive bit */ bit haproxyprotocol:1; /* whether to send HAProxy PROXY protocol v1 header */ bit abstract_unix_socket:1; bit disallow_username_in_url:1; /* disallow username in url */ bit doh:1; /* DNS-over-HTTPS enabled */ bit doh_get:1; /* use GET for DoH requests, instead of POST */ bit http09_allowed:1; /* allow HTTP/0.9 responses */ }; struct Names { struct curl_hash *hostcache; enum { HCACHE_NONE, /* not pointing to anything */ HCACHE_MULTI, /* points to a shared one in the multi handle */ HCACHE_SHARED /* points to a shared one in a shared object */ } hostcachetype; }; /* * The 'connectdata' struct MUST have all the connection oriented stuff as we * may have several simultaneous connections and connection structs in memory. * * The 'struct UserDefined' must only contain data that is set once to go for * many (perhaps) independent connections. Values that are generated or * calculated internally for the "session handle" must be defined within the * 'struct UrlState' instead. */ struct Curl_easy { /* first, two fields for the linked list of these */ struct Curl_easy *next; struct Curl_easy *prev; struct connectdata *conn; struct curl_llist_element connect_queue; struct curl_llist_element sh_queue; /* list per Curl_sh_entry */ struct curl_llist_element conn_queue; /* list per connectdata */ CURLMstate mstate; /* the handle's state */ CURLcode result; /* previous result */ struct Curl_message msg; /* A single posted message. */ /* Array with the plain socket numbers this handle takes care of, in no particular order. Note that all sockets are added to the sockhash, where the state etc are also kept. This array is mostly used to detect when a socket is to be removed from the hash. See singlesocket(). */ curl_socket_t sockets[MAX_SOCKSPEREASYHANDLE]; int actions[MAX_SOCKSPEREASYHANDLE]; /* action for each socket in sockets[] */ int numsocks; struct Names dns; struct Curl_multi *multi; /* if non-NULL, points to the multi handle struct to which this "belongs" when used by the multi interface */ struct Curl_multi *multi_easy; /* if non-NULL, points to the multi handle struct to which this "belongs" when used by the easy interface */ struct Curl_share *share; /* Share, handles global variable mutexing */ #ifdef USE_LIBPSL struct PslCache *psl; /* The associated PSL cache. */ #endif struct SingleRequest req; /* Request-specific data */ struct UserDefined set; /* values set by the libcurl user */ struct DynamicStatic change; /* possibly modified userdefined data */ struct CookieInfo *cookies; /* the cookies, read from files and servers. NOTE that the 'cookie' field in the UserDefined struct defines if the "engine" is to be used or not. */ #ifdef USE_ALTSVC struct altsvcinfo *asi; /* the alt-svc cache */ #endif struct Progress progress; /* for all the progress meter data */ struct UrlState state; /* struct for fields used for state info and other dynamic purposes */ #ifndef CURL_DISABLE_FTP struct WildcardData wildcard; /* wildcard download state info */ #endif struct PureInfo info; /* stats, reports and info data */ struct curl_tlssessioninfo tsi; /* Information about the TLS session, only valid after a client has asked for it */ #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV) iconv_t outbound_cd; /* for translating to the network encoding */ iconv_t inbound_cd; /* for translating from the network encoding */ iconv_t utf8_cd; /* for translating to UTF8 */ #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */ unsigned int magic; /* set to a CURLEASY_MAGIC_NUMBER */ }; #define LIBCURL_NAME "libcurl" #endif /* HEADER_CURL_URLDATA_H */
YifuLiu/AliOS-Things
components/curl/lib/urldata.h
C++
apache-2.0
77,226
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC4616 PLAIN authentication * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_POP3) #include <curl/curl.h> #include "urldata.h" #include "vauth/vauth.h" #include "curl_base64.h" #include "curl_md5.h" #include "warnless.h" #include "strtok.h" #include "sendf.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_create_plain_message() * * This is used to generate an already encoded PLAIN message ready * for sending to the recipient. * * Parameters: * * data [in] - The session handle. * authzid [in] - The authorization identity. * authcid [in] - The authentication identity. * passwd [in] - The password. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, const char *authzid, const char *authcid, const char *passwd, char **outptr, size_t *outlen) { CURLcode result; char *plainauth; size_t zlen; size_t clen; size_t plen; size_t plainlen; *outlen = 0; *outptr = NULL; zlen = (authzid == NULL ? 0 : strlen(authzid)); clen = strlen(authcid); plen = strlen(passwd); /* Compute binary message length. Check for overflows. */ if(((zlen + clen) > SIZE_T_MAX/4) || (plen > (SIZE_T_MAX/2 - 2))) return CURLE_OUT_OF_MEMORY; plainlen = zlen + clen + plen + 2; plainauth = malloc(plainlen); if(!plainauth) return CURLE_OUT_OF_MEMORY; /* Calculate the reply */ if(zlen != 0) memcpy(plainauth, authzid, zlen); plainauth[zlen] = '\0'; memcpy(plainauth + zlen + 1, authcid, clen); plainauth[zlen + clen + 1] = '\0'; memcpy(plainauth + zlen + clen + 2, passwd, plen); /* Base64 encode the reply */ result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen); free(plainauth); return result; } /* * Curl_auth_create_login_message() * * This is used to generate an already encoded LOGIN message containing the * user name or password ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * valuep [in] - The user name or user's password. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_login_message(struct Curl_easy *data, const char *valuep, char **outptr, size_t *outlen) { size_t vlen = strlen(valuep); if(!vlen) { /* Calculate an empty reply */ *outptr = strdup("="); if(*outptr) { *outlen = (size_t) 1; return CURLE_OK; } *outlen = 0; return CURLE_OUT_OF_MEMORY; } /* Base64 encode the value */ return Curl_base64_encode(data, valuep, vlen, outptr, outlen); } /* * Curl_auth_create_external_message() * * This is used to generate an already encoded EXTERNAL message containing * the user name ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * user [in] - The user name. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_external_message(struct Curl_easy *data, const char *user, char **outptr, size_t *outlen) { /* This is the same formatting as the login message */ return Curl_auth_create_login_message(data, user, outptr, outlen); } #endif /* if no users */
YifuLiu/AliOS-Things
components/curl/lib/vauth/cleartext.c
C
apache-2.0
5,321
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2195 CRAM-MD5 authentication * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_CRYPTO_AUTH) #include <curl/curl.h> #include "urldata.h" #include "vauth/vauth.h" #include "curl_base64.h" #include "curl_hmac.h" #include "curl_md5.h" #include "warnless.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_decode_cram_md5_message() * * This is used to decode an already encoded CRAM-MD5 challenge message. * * Parameters: * * chlg64 [in] - The base64 encoded challenge message. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_cram_md5_message(const char *chlg64, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t chlg64len = strlen(chlg64); *outptr = NULL; *outlen = 0; /* Decode the challenge if necessary */ if(chlg64len && *chlg64 != '=') result = Curl_base64_decode(chlg64, (unsigned char **) outptr, outlen); return result; } /* * Curl_auth_create_cram_md5_message() * * This is used to generate an already encoded CRAM-MD5 response message ready * for sending to the recipient. * * Parameters: * * data [in] - The session handle. * chlg [in] - The challenge. * userp [in] - The user name. * passwdp [in] - The user's password. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_cram_md5_message(struct Curl_easy *data, const char *chlg, const char *userp, const char *passwdp, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t chlglen = 0; HMAC_context *ctxt; unsigned char digest[MD5_DIGEST_LEN]; char *response; if(chlg) chlglen = strlen(chlg); /* Compute the digest using the password as the key */ ctxt = Curl_HMAC_init(Curl_HMAC_MD5, (const unsigned char *) passwdp, curlx_uztoui(strlen(passwdp))); if(!ctxt) return CURLE_OUT_OF_MEMORY; /* Update the digest with the given challenge */ if(chlglen > 0) Curl_HMAC_update(ctxt, (const unsigned char *) chlg, curlx_uztoui(chlglen)); /* Finalise the digest */ Curl_HMAC_final(ctxt, digest); /* Generate the response */ response = aprintf( "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", userp, digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); if(!response) return CURLE_OUT_OF_MEMORY; /* Base64 encode the response */ result = Curl_base64_encode(data, response, 0, outptr, outlen); free(response); return result; } #endif /* !CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/vauth/cram.c
C
apache-2.0
4,394
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2831 DIGEST-MD5 authentication * RFC7616 DIGEST-SHA256, DIGEST-SHA512-256 authentication * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_CRYPTO_AUTH) #include <curl/curl.h> #include "vauth/vauth.h" #include "vauth/digest.h" #include "urldata.h" #include "curl_base64.h" #include "curl_hmac.h" #include "curl_md5.h" #include "curl_sha256.h" #include "vtls/vtls.h" #include "warnless.h" #include "strtok.h" #include "strcase.h" #include "non-ascii.h" /* included for Curl_convert_... prototypes */ #include "curl_printf.h" #include "rand.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" #if !defined(USE_WINDOWS_SSPI) #define DIGEST_QOP_VALUE_AUTH (1 << 0) #define DIGEST_QOP_VALUE_AUTH_INT (1 << 1) #define DIGEST_QOP_VALUE_AUTH_CONF (1 << 2) #define DIGEST_QOP_VALUE_STRING_AUTH "auth" #define DIGEST_QOP_VALUE_STRING_AUTH_INT "auth-int" #define DIGEST_QOP_VALUE_STRING_AUTH_CONF "auth-conf" /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines. It converts digest text to ASCII so the MD5 will be correct for what ultimately goes over the network. */ #define CURL_OUTPUT_DIGEST_CONV(a, b) \ result = Curl_convert_to_network(a, (char *)b, strlen((const char *)b)); \ if(result) { \ free(b); \ return result; \ } #endif /* !USE_WINDOWS_SSPI */ bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, const char **endptr) { int c; bool starts_with_quote = FALSE; bool escape = FALSE; for(c = DIGEST_MAX_VALUE_LENGTH - 1; (*str && (*str != '=') && c--);) *value++ = *str++; *value = 0; if('=' != *str++) /* eek, no match */ return FALSE; if('\"' == *str) { /* This starts with a quote so it must end with one as well! */ str++; starts_with_quote = TRUE; } for(c = DIGEST_MAX_CONTENT_LENGTH - 1; *str && c--; str++) { switch(*str) { case '\\': if(!escape) { /* possibly the start of an escaped quote */ escape = TRUE; *content++ = '\\'; /* Even though this is an escape character, we still store it as-is in the target buffer */ continue; } break; case ',': if(!starts_with_quote) { /* This signals the end of the content if we didn't get a starting quote and then we do "sloppy" parsing */ c = 0; /* the end */ continue; } break; case '\r': case '\n': /* end of string */ c = 0; continue; case '\"': if(!escape && starts_with_quote) { /* end of string */ c = 0; continue; } break; } escape = FALSE; *content++ = *str; } *content = 0; *endptr = str; return TRUE; } #if !defined(USE_WINDOWS_SSPI) /* Convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/ static void auth_digest_md5_to_ascii(unsigned char *source, /* 16 bytes */ unsigned char *dest) /* 33 bytes */ { int i; for(i = 0; i < 16; i++) msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]); } /* Convert sha256 chunk to RFC7616 -suitable ascii string*/ static void auth_digest_sha256_to_ascii(unsigned char *source, /* 32 bytes */ unsigned char *dest) /* 65 bytes */ { int i; for(i = 0; i < 32; i++) msnprintf((char *) &dest[i * 2], 3, "%02x", source[i]); } /* Perform quoted-string escaping as described in RFC2616 and its errata */ static char *auth_digest_string_quoted(const char *source) { char *dest; const char *s = source; size_t n = 1; /* null terminator */ /* Calculate size needed */ while(*s) { ++n; if(*s == '"' || *s == '\\') { ++n; } ++s; } dest = malloc(n); if(dest) { char *d = dest; s = source; while(*s) { if(*s == '"' || *s == '\\') { *d++ = '\\'; } *d++ = *s++; } *d = 0; } return dest; } /* Retrieves the value for a corresponding key from the challenge string * returns TRUE if the key could be found, FALSE if it does not exists */ static bool auth_digest_get_key_value(const char *chlg, const char *key, char *value, size_t max_val_len, char end_char) { char *find_pos; size_t i; find_pos = strstr(chlg, key); if(!find_pos) return FALSE; find_pos += strlen(key); for(i = 0; *find_pos && *find_pos != end_char && i < max_val_len - 1; ++i) value[i] = *find_pos++; value[i] = '\0'; return TRUE; } static CURLcode auth_digest_get_qop_values(const char *options, int *value) { char *tmp; char *token; char *tok_buf = NULL; /* Initialise the output */ *value = 0; /* Tokenise the list of qop values. Use a temporary clone of the buffer since strtok_r() ruins it. */ tmp = strdup(options); if(!tmp) return CURLE_OUT_OF_MEMORY; token = strtok_r(tmp, ",", &tok_buf); while(token != NULL) { if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) *value |= DIGEST_QOP_VALUE_AUTH; else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) *value |= DIGEST_QOP_VALUE_AUTH_INT; else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF)) *value |= DIGEST_QOP_VALUE_AUTH_CONF; token = strtok_r(NULL, ",", &tok_buf); } free(tmp); return CURLE_OK; } /* * auth_decode_digest_md5_message() * * This is used internally to decode an already encoded DIGEST-MD5 challenge * message into the separate attributes. * * Parameters: * * chlg64 [in] - The base64 encoded challenge message. * nonce [in/out] - The buffer where the nonce will be stored. * nlen [in] - The length of the nonce buffer. * realm [in/out] - The buffer where the realm will be stored. * rlen [in] - The length of the realm buffer. * alg [in/out] - The buffer where the algorithm will be stored. * alen [in] - The length of the algorithm buffer. * qop [in/out] - The buffer where the qop-options will be stored. * qlen [in] - The length of the qop buffer. * * Returns CURLE_OK on success. */ static CURLcode auth_decode_digest_md5_message(const char *chlg64, char *nonce, size_t nlen, char *realm, size_t rlen, char *alg, size_t alen, char *qop, size_t qlen) { CURLcode result = CURLE_OK; unsigned char *chlg = NULL; size_t chlglen = 0; size_t chlg64len = strlen(chlg64); /* Decode the base-64 encoded challenge message */ if(chlg64len && *chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) return CURLE_BAD_CONTENT_ENCODING; /* Retrieve nonce string from the challenge */ if(!auth_digest_get_key_value((char *) chlg, "nonce=\"", nonce, nlen, '\"')) { free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Retrieve realm string from the challenge */ if(!auth_digest_get_key_value((char *) chlg, "realm=\"", realm, rlen, '\"')) { /* Challenge does not have a realm, set empty string [RFC2831] page 6 */ strcpy(realm, ""); } /* Retrieve algorithm string from the challenge */ if(!auth_digest_get_key_value((char *) chlg, "algorithm=", alg, alen, ',')) { free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Retrieve qop-options string from the challenge */ if(!auth_digest_get_key_value((char *) chlg, "qop=\"", qop, qlen, '\"')) { free(chlg); return CURLE_BAD_CONTENT_ENCODING; } free(chlg); return CURLE_OK; } /* * Curl_auth_is_digest_supported() * * This is used to evaluate if DIGEST is supported. * * Parameters: None * * Returns TRUE as DIGEST as handled by libcurl. */ bool Curl_auth_is_digest_supported(void) { return TRUE; } /* * Curl_auth_create_digest_md5_message() * * This is used to generate an already encoded DIGEST-MD5 response message * ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * chlg64 [in] - The base64 encoded challenge message. * userp [in] - The user name. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, const char *chlg64, const char *userp, const char *passwdp, const char *service, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t i; MD5_context *ctxt; char *response = NULL; unsigned char digest[MD5_DIGEST_LEN]; char HA1_hex[2 * MD5_DIGEST_LEN + 1]; char HA2_hex[2 * MD5_DIGEST_LEN + 1]; char resp_hash_hex[2 * MD5_DIGEST_LEN + 1]; char nonce[64]; char realm[128]; char algorithm[64]; char qop_options[64]; int qop_values; char cnonce[33]; char nonceCount[] = "00000001"; char method[] = "AUTHENTICATE"; char qop[] = DIGEST_QOP_VALUE_STRING_AUTH; char *spn = NULL; /* Decode the challenge message */ result = auth_decode_digest_md5_message(chlg64, nonce, sizeof(nonce), realm, sizeof(realm), algorithm, sizeof(algorithm), qop_options, sizeof(qop_options)); if(result) return result; /* We only support md5 sessions */ if(strcmp(algorithm, "md5-sess") != 0) return CURLE_BAD_CONTENT_ENCODING; /* Get the qop-values from the qop-options */ result = auth_digest_get_qop_values(qop_options, &qop_values); if(result) return result; /* We only support auth quality-of-protection */ if(!(qop_values & DIGEST_QOP_VALUE_AUTH)) return CURLE_BAD_CONTENT_ENCODING; /* Generate 32 random hex chars, 32 bytes + 1 zero termination */ result = Curl_rand_hex(data, (unsigned char *)cnonce, sizeof(cnonce)); if(result) return result; /* So far so good, now calculate A1 and H(A1) according to RFC 2831 */ ctxt = Curl_MD5_init(Curl_DIGEST_MD5); if(!ctxt) return CURLE_OUT_OF_MEMORY; Curl_MD5_update(ctxt, (const unsigned char *) userp, curlx_uztoui(strlen(userp))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) realm, curlx_uztoui(strlen(realm))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) passwdp, curlx_uztoui(strlen(passwdp))); Curl_MD5_final(ctxt, digest); ctxt = Curl_MD5_init(Curl_DIGEST_MD5); if(!ctxt) return CURLE_OUT_OF_MEMORY; Curl_MD5_update(ctxt, (const unsigned char *) digest, MD5_DIGEST_LEN); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) nonce, curlx_uztoui(strlen(nonce))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) cnonce, curlx_uztoui(strlen(cnonce))); Curl_MD5_final(ctxt, digest); /* Convert calculated 16 octet hex into 32 bytes string */ for(i = 0; i < MD5_DIGEST_LEN; i++) msnprintf(&HA1_hex[2 * i], 3, "%02x", digest[i]); /* Generate our SPN */ spn = Curl_auth_build_spn(service, realm, NULL); if(!spn) return CURLE_OUT_OF_MEMORY; /* Calculate H(A2) */ ctxt = Curl_MD5_init(Curl_DIGEST_MD5); if(!ctxt) { free(spn); return CURLE_OUT_OF_MEMORY; } Curl_MD5_update(ctxt, (const unsigned char *) method, curlx_uztoui(strlen(method))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) spn, curlx_uztoui(strlen(spn))); Curl_MD5_final(ctxt, digest); for(i = 0; i < MD5_DIGEST_LEN; i++) msnprintf(&HA2_hex[2 * i], 3, "%02x", digest[i]); /* Now calculate the response hash */ ctxt = Curl_MD5_init(Curl_DIGEST_MD5); if(!ctxt) { free(spn); return CURLE_OUT_OF_MEMORY; } Curl_MD5_update(ctxt, (const unsigned char *) HA1_hex, 2 * MD5_DIGEST_LEN); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) nonce, curlx_uztoui(strlen(nonce))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) nonceCount, curlx_uztoui(strlen(nonceCount))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) cnonce, curlx_uztoui(strlen(cnonce))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) qop, curlx_uztoui(strlen(qop))); Curl_MD5_update(ctxt, (const unsigned char *) ":", 1); Curl_MD5_update(ctxt, (const unsigned char *) HA2_hex, 2 * MD5_DIGEST_LEN); Curl_MD5_final(ctxt, digest); for(i = 0; i < MD5_DIGEST_LEN; i++) msnprintf(&resp_hash_hex[2 * i], 3, "%02x", digest[i]); /* Generate the response */ response = aprintf("username=\"%s\",realm=\"%s\",nonce=\"%s\"," "cnonce=\"%s\",nc=\"%s\",digest-uri=\"%s\",response=%s," "qop=%s", userp, realm, nonce, cnonce, nonceCount, spn, resp_hash_hex, qop); free(spn); if(!response) return CURLE_OUT_OF_MEMORY; /* Base64 encode the response */ result = Curl_base64_encode(data, response, 0, outptr, outlen); free(response); return result; } /* * Curl_auth_decode_digest_http_message() * * This is used to decode a HTTP DIGEST challenge message into the separate * attributes. * * Parameters: * * chlg [in] - The challenge message. * digest [in/out] - The digest data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_digest_http_message(const char *chlg, struct digestdata *digest) { bool before = FALSE; /* got a nonce before */ bool foundAuth = FALSE; bool foundAuthInt = FALSE; char *token = NULL; char *tmp = NULL; /* If we already have received a nonce, keep that in mind */ if(digest->nonce) before = TRUE; /* Clean up any former leftovers and initialise to defaults */ Curl_auth_digest_cleanup(digest); for(;;) { char value[DIGEST_MAX_VALUE_LENGTH]; char content[DIGEST_MAX_CONTENT_LENGTH]; /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Extract a value=content pair */ if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { if(strcasecompare(value, "nonce")) { free(digest->nonce); digest->nonce = strdup(content); if(!digest->nonce) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "stale")) { if(strcasecompare(content, "true")) { digest->stale = TRUE; digest->nc = 1; /* we make a new nonce now */ } } else if(strcasecompare(value, "realm")) { free(digest->realm); digest->realm = strdup(content); if(!digest->realm) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "opaque")) { free(digest->opaque); digest->opaque = strdup(content); if(!digest->opaque) return CURLE_OUT_OF_MEMORY; } else if(strcasecompare(value, "qop")) { char *tok_buf = NULL; /* Tokenize the list and choose auth if possible, use a temporary clone of the buffer since strtok_r() ruins it */ tmp = strdup(content); if(!tmp) return CURLE_OUT_OF_MEMORY; token = strtok_r(tmp, ",", &tok_buf); while(token != NULL) { if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) { foundAuth = TRUE; } else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) { foundAuthInt = TRUE; } token = strtok_r(NULL, ",", &tok_buf); } free(tmp); /* Select only auth or auth-int. Otherwise, ignore */ if(foundAuth) { free(digest->qop); digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH); if(!digest->qop) return CURLE_OUT_OF_MEMORY; } else if(foundAuthInt) { free(digest->qop); digest->qop = strdup(DIGEST_QOP_VALUE_STRING_AUTH_INT); if(!digest->qop) return CURLE_OUT_OF_MEMORY; } } else if(strcasecompare(value, "algorithm")) { free(digest->algorithm); digest->algorithm = strdup(content); if(!digest->algorithm) return CURLE_OUT_OF_MEMORY; if(strcasecompare(content, "MD5-sess")) digest->algo = CURLDIGESTALGO_MD5SESS; else if(strcasecompare(content, "MD5")) digest->algo = CURLDIGESTALGO_MD5; else if(strcasecompare(content, "SHA-256")) digest->algo = CURLDIGESTALGO_SHA256; else if(strcasecompare(content, "SHA-256-SESS")) digest->algo = CURLDIGESTALGO_SHA256SESS; else if(strcasecompare(content, "SHA-512-256")) digest->algo = CURLDIGESTALGO_SHA512_256; else if(strcasecompare(content, "SHA-512-256-SESS")) digest->algo = CURLDIGESTALGO_SHA512_256SESS; else return CURLE_BAD_CONTENT_ENCODING; } else if(strcasecompare(value, "userhash")) { if(strcasecompare(content, "true")) { digest->userhash = TRUE; } } else { /* Unknown specifier, ignore it! */ } } else break; /* We're done here */ /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Allow the list to be comma-separated */ if(',' == *chlg) chlg++; } /* We had a nonce since before, and we got another one now without 'stale=true'. This means we provided bad credentials in the previous request */ if(before && !digest->stale) return CURLE_BAD_CONTENT_ENCODING; /* We got this header without a nonce, that's a bad Digest line! */ if(!digest->nonce) return CURLE_BAD_CONTENT_ENCODING; return CURLE_OK; } /* * _Curl_auth_create_digest_http_message() * * This is used to generate a HTTP DIGEST response message ready for sending * to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name. * passwdp [in] - The user's password. * request [in] - The HTTP request. * uripath [in] - The path of the HTTP uri. * digest [in/out] - The digest data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ static CURLcode _Curl_auth_create_digest_http_message( struct Curl_easy *data, const char *userp, const char *passwdp, const unsigned char *request, const unsigned char *uripath, struct digestdata *digest, char **outptr, size_t *outlen, void (*convert_to_ascii)(unsigned char *, unsigned char *), void (*hash)(unsigned char *, const unsigned char *)) { CURLcode result; unsigned char hashbuf[32]; /* 32 bytes/256 bits */ unsigned char request_digest[65]; unsigned char *hashthis; unsigned char ha1[65]; /* 64 digits and 1 zero byte */ unsigned char ha2[65]; /* 64 digits and 1 zero byte */ char userh[65]; char *cnonce = NULL; size_t cnonce_sz = 0; char *userp_quoted; char *response = NULL; char *tmp = NULL; if(!digest->nc) digest->nc = 1; if(!digest->cnonce) { char cnoncebuf[33]; result = Curl_rand_hex(data, (unsigned char *)cnoncebuf, sizeof(cnoncebuf)); if(result) return result; result = Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf), &cnonce, &cnonce_sz); if(result) return result; digest->cnonce = cnonce; } if(digest->userhash) { hashthis = (unsigned char *) aprintf("%s:%s", userp, digest->realm); if(!hashthis) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, hashthis); hash(hashbuf, hashthis); free(hashthis); convert_to_ascii(hashbuf, (unsigned char *)userh); } /* If the algorithm is "MD5" or unspecified (which then defaults to MD5): A1 = unq(username-value) ":" unq(realm-value) ":" passwd If the algorithm is "MD5-sess" then: A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) ":" unq(nonce-value) ":" unq(cnonce-value) */ hashthis = (unsigned char *) aprintf("%s:%s:%s", digest->userhash ? userh : userp, digest->realm, passwdp); if(!hashthis) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, hashthis); /* convert on non-ASCII machines */ hash(hashbuf, hashthis); free(hashthis); convert_to_ascii(hashbuf, ha1); if(digest->algo == CURLDIGESTALGO_MD5SESS || digest->algo == CURLDIGESTALGO_SHA256SESS || digest->algo == CURLDIGESTALGO_SHA512_256SESS) { /* nonce and cnonce are OUTSIDE the hash */ tmp = aprintf("%s:%s:%s", ha1, digest->nonce, digest->cnonce); if(!tmp) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, tmp); /* Convert on non-ASCII machines */ hash(hashbuf, (unsigned char *) tmp); free(tmp); convert_to_ascii(hashbuf, ha1); } /* If the "qop" directive's value is "auth" or is unspecified, then A2 is: A2 = Method ":" digest-uri-value If the "qop" value is "auth-int", then A2 is: A2 = Method ":" digest-uri-value ":" H(entity-body) (The "Method" value is the HTTP request method as specified in section 5.1.1 of RFC 2616) */ hashthis = (unsigned char *) aprintf("%s:%s", request, uripath); if(!hashthis) return CURLE_OUT_OF_MEMORY; if(digest->qop && strcasecompare(digest->qop, "auth-int")) { /* We don't support auth-int for PUT or POST */ char hashed[65]; unsigned char *hashthis2; hash(hashbuf, (const unsigned char *)""); convert_to_ascii(hashbuf, (unsigned char *)hashed); hashthis2 = (unsigned char *)aprintf("%s:%s", hashthis, hashed); free(hashthis); hashthis = hashthis2; } if(!hashthis) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, hashthis); /* convert on non-ASCII machines */ hash(hashbuf, hashthis); free(hashthis); convert_to_ascii(hashbuf, ha2); if(digest->qop) { hashthis = (unsigned char *) aprintf("%s:%s:%08x:%s:%s:%s", ha1, digest->nonce, digest->nc, digest->cnonce, digest->qop, ha2); } else { hashthis = (unsigned char *) aprintf("%s:%s:%s", ha1, digest->nonce, ha2); } if(!hashthis) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, hashthis); /* convert on non-ASCII machines */ hash(hashbuf, hashthis); free(hashthis); convert_to_ascii(hashbuf, request_digest); /* For test case 64 (snooped from a Mozilla 1.3a request) Authorization: Digest username="testuser", realm="testrealm", \ nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" Digest parameters are all quoted strings. Username which is provided by the user will need double quotes and backslashes within it escaped. For the other fields, this shouldn't be an issue. realm, nonce, and opaque are copied as is from the server, escapes and all. cnonce is generated with web-safe characters. uri is already percent encoded. nc is 8 hex characters. algorithm and qop with standard values only contain web-safe characters. */ userp_quoted = auth_digest_string_quoted(digest->userhash ? userh : userp); if(!userp_quoted) return CURLE_OUT_OF_MEMORY; if(digest->qop) { response = aprintf("username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "cnonce=\"%s\", " "nc=%08x, " "qop=%s, " "response=\"%s\"", userp_quoted, digest->realm, digest->nonce, uripath, digest->cnonce, digest->nc, digest->qop, request_digest); if(strcasecompare(digest->qop, "auth")) digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded which tells to the server how many times you are using the same nonce in the qop=auth mode */ } else { response = aprintf("username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "response=\"%s\"", userp_quoted, digest->realm, digest->nonce, uripath, request_digest); } free(userp_quoted); if(!response) return CURLE_OUT_OF_MEMORY; /* Add the optional fields */ if(digest->opaque) { /* Append the opaque */ tmp = aprintf("%s, opaque=\"%s\"", response, digest->opaque); free(response); if(!tmp) return CURLE_OUT_OF_MEMORY; response = tmp; } if(digest->algorithm) { /* Append the algorithm */ tmp = aprintf("%s, algorithm=\"%s\"", response, digest->algorithm); free(response); if(!tmp) return CURLE_OUT_OF_MEMORY; response = tmp; } if(digest->userhash) { /* Append the userhash */ tmp = aprintf("%s, userhash=true", response); free(response); if(!tmp) return CURLE_OUT_OF_MEMORY; response = tmp; } /* Return the output */ *outptr = response; *outlen = strlen(response); return CURLE_OK; } /* * Curl_auth_create_digest_http_message() * * This is used to generate a HTTP DIGEST response message ready for sending * to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name. * passwdp [in] - The user's password. * request [in] - The HTTP request. * uripath [in] - The path of the HTTP uri. * digest [in/out] - The digest data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, const char *userp, const char *passwdp, const unsigned char *request, const unsigned char *uripath, struct digestdata *digest, char **outptr, size_t *outlen) { switch(digest->algo) { case CURLDIGESTALGO_MD5: case CURLDIGESTALGO_MD5SESS: return _Curl_auth_create_digest_http_message(data, userp, passwdp, request, uripath, digest, outptr, outlen, auth_digest_md5_to_ascii, Curl_md5it); case CURLDIGESTALGO_SHA256: case CURLDIGESTALGO_SHA256SESS: case CURLDIGESTALGO_SHA512_256: case CURLDIGESTALGO_SHA512_256SESS: return _Curl_auth_create_digest_http_message(data, userp, passwdp, request, uripath, digest, outptr, outlen, auth_digest_sha256_to_ascii, Curl_sha256it); default: return CURLE_UNSUPPORTED_PROTOCOL; } } /* * Curl_auth_digest_cleanup() * * This is used to clean up the digest specific data. * * Parameters: * * digest [in/out] - The digest data struct being cleaned up. * */ void Curl_auth_digest_cleanup(struct digestdata *digest) { Curl_safefree(digest->nonce); Curl_safefree(digest->cnonce); Curl_safefree(digest->realm); Curl_safefree(digest->opaque); Curl_safefree(digest->qop); Curl_safefree(digest->algorithm); digest->nc = 0; digest->algo = CURLDIGESTALGO_MD5; /* default algorithm */ digest->stale = FALSE; /* default means normal, not stale */ digest->userhash = FALSE; } #endif /* !USE_WINDOWS_SSPI */ #endif /* CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/vauth/digest.c
C
apache-2.0
31,320
#ifndef HEADER_CURL_DIGEST_H #define HEADER_CURL_DIGEST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> #if !defined(CURL_DISABLE_CRYPTO_AUTH) #define DIGEST_MAX_VALUE_LENGTH 256 #define DIGEST_MAX_CONTENT_LENGTH 1024 enum { CURLDIGESTALGO_MD5, CURLDIGESTALGO_MD5SESS, CURLDIGESTALGO_SHA256, CURLDIGESTALGO_SHA256SESS, CURLDIGESTALGO_SHA512_256, CURLDIGESTALGO_SHA512_256SESS }; /* This is used to extract the realm from a challenge message */ bool Curl_auth_digest_get_pair(const char *str, char *value, char *content, const char **endptr); #endif #endif /* HEADER_CURL_DIGEST_H */
YifuLiu/AliOS-Things
components/curl/lib/vauth/digest.h
C
apache-2.0
1,654
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>. * Copyright (C) 2015 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2831 DIGEST-MD5 authentication * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_CRYPTO_AUTH) #include <curl/curl.h> #include "vauth/vauth.h" #include "vauth/digest.h" #include "urldata.h" #include "curl_base64.h" #include "warnless.h" #include "curl_multibyte.h" #include "sendf.h" #include "strdup.h" #include "strcase.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_digest_supported() * * This is used to evaluate if DIGEST is supported. * * Parameters: None * * Returns TRUE if DIGEST is supported by Windows SSPI. */ bool Curl_auth_is_digest_supported(void) { PSecPkgInfo SecurityPackage; SECURITY_STATUS status; /* Query the security package for Digest */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), &SecurityPackage); return (status == SEC_E_OK ? TRUE : FALSE); } /* * Curl_auth_create_digest_md5_message() * * This is used to generate an already encoded DIGEST-MD5 response message * ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * chlg64 [in] - The base64 encoded challenge message. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, const char *chlg64, const char *userp, const char *passwdp, const char *service, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; TCHAR *spn = NULL; size_t chlglen = 0; size_t token_max = 0; unsigned char *input_token = NULL; unsigned char *output_token = NULL; CredHandle credentials; CtxtHandle context; PSecPkgInfo SecurityPackage; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; SecBuffer chlg_buf; SecBuffer resp_buf; SecBufferDesc chlg_desc; SecBufferDesc resp_desc; SECURITY_STATUS status; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ /* Decode the base-64 encoded challenge message */ if(strlen(chlg64) && *chlg64 != '=') { result = Curl_base64_decode(chlg64, &input_token, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!input_token) { infof(data, "DIGEST-MD5 handshake failure (empty challenge message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Query the security package for DigestSSP */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), &SecurityPackage); if(status != SEC_E_OK) { free(input_token); return CURLE_NOT_BUILT_IN; } token_max = SecurityPackage->cbMaxToken; /* Release the package buffer as it is not required anymore */ s_pSecFn->FreeContextBuffer(SecurityPackage); /* Allocate our response buffer */ output_token = malloc(token_max); if(!output_token) { free(input_token); return CURLE_OUT_OF_MEMORY; } /* Generate our SPN */ spn = Curl_auth_build_spn(service, data->conn->host.name, NULL); if(!spn) { free(output_token); free(input_token); return CURLE_OUT_OF_MEMORY; } if(userp && *userp) { /* Populate our identity structure */ result = Curl_create_sspi_identity(userp, passwdp, &identity); if(result) { free(spn); free(output_token); free(input_token); return result; } /* Allow proper cleanup of the identity structure */ p_identity = &identity; } else /* Use the current Windows user */ p_identity = NULL; /* Acquire our credentials handle */ status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT(SP_NAME_DIGEST), SECPKG_CRED_OUTBOUND, NULL, p_identity, NULL, NULL, &credentials, &expiry); if(status != SEC_E_OK) { Curl_sspi_free_identity(p_identity); free(spn); free(output_token); free(input_token); return CURLE_LOGIN_DENIED; } /* Setup the challenge "input" security buffer */ chlg_desc.ulVersion = SECBUFFER_VERSION; chlg_desc.cBuffers = 1; chlg_desc.pBuffers = &chlg_buf; chlg_buf.BufferType = SECBUFFER_TOKEN; chlg_buf.pvBuffer = input_token; chlg_buf.cbBuffer = curlx_uztoul(chlglen); /* Setup the response "output" security buffer */ resp_desc.ulVersion = SECBUFFER_VERSION; resp_desc.cBuffers = 1; resp_desc.pBuffers = &resp_buf; resp_buf.BufferType = SECBUFFER_TOKEN; resp_buf.pvBuffer = output_token; resp_buf.cbBuffer = curlx_uztoul(token_max); /* Generate our response message */ status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, 0, 0, 0, &chlg_desc, 0, &context, &resp_desc, &attrs, &expiry); if(status == SEC_I_COMPLETE_NEEDED || status == SEC_I_COMPLETE_AND_CONTINUE) s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { s_pSecFn->FreeCredentialsHandle(&credentials); Curl_sspi_free_identity(p_identity); free(spn); free(output_token); free(input_token); return CURLE_RECV_ERROR; } /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) output_token, resp_buf.cbBuffer, outptr, outlen); /* Free our handles */ s_pSecFn->DeleteSecurityContext(&context); s_pSecFn->FreeCredentialsHandle(&credentials); /* Free the identity structure */ Curl_sspi_free_identity(p_identity); /* Free the SPN */ free(spn); /* Free the response buffer */ free(output_token); /* Free the decoded challenge message */ free(input_token); return result; } /* * Curl_override_sspi_http_realm() * * This is used to populate the domain in a SSPI identity structure * The realm is extracted from the challenge message and used as the * domain if it is not already explicitly set. * * Parameters: * * chlg [in] - The challenge message. * identity [in/out] - The identity structure. * * Returns CURLE_OK on success. */ CURLcode Curl_override_sspi_http_realm(const char *chlg, SEC_WINNT_AUTH_IDENTITY *identity) { xcharp_u domain, dup_domain; /* If domain is blank or unset, check challenge message for realm */ if(!identity->Domain || !identity->DomainLength) { for(;;) { char value[DIGEST_MAX_VALUE_LENGTH]; char content[DIGEST_MAX_CONTENT_LENGTH]; /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Extract a value=content pair */ if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) { if(strcasecompare(value, "realm")) { /* Setup identity's domain and length */ domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *) content); if(!domain.tchar_ptr) return CURLE_OUT_OF_MEMORY; dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr); if(!dup_domain.tchar_ptr) { Curl_unicodefree(domain.tchar_ptr); return CURLE_OUT_OF_MEMORY; } free(identity->Domain); identity->Domain = dup_domain.tbyte_ptr; identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr)); dup_domain.tchar_ptr = NULL; Curl_unicodefree(domain.tchar_ptr); } else { /* Unknown specifier, ignore it! */ } } else break; /* We're done here */ /* Pass all additional spaces here */ while(*chlg && ISSPACE(*chlg)) chlg++; /* Allow the list to be comma-separated */ if(',' == *chlg) chlg++; } } return CURLE_OK; } /* * Curl_auth_decode_digest_http_message() * * This is used to decode a HTTP DIGEST challenge message into the separate * attributes. * * Parameters: * * chlg [in] - The challenge message. * digest [in/out] - The digest data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_digest_http_message(const char *chlg, struct digestdata *digest) { size_t chlglen = strlen(chlg); /* We had an input token before so if there's another one now that means we provided bad credentials in the previous request or it's stale. */ if(digest->input_token) { bool stale = false; const char *p = chlg; /* Check for the 'stale' directive */ for(;;) { char value[DIGEST_MAX_VALUE_LENGTH]; char content[DIGEST_MAX_CONTENT_LENGTH]; while(*p && ISSPACE(*p)) p++; if(!Curl_auth_digest_get_pair(p, value, content, &p)) break; if(strcasecompare(value, "stale") && strcasecompare(content, "true")) { stale = true; break; } while(*p && ISSPACE(*p)) p++; if(',' == *p) p++; } if(stale) Curl_auth_digest_cleanup(digest); else return CURLE_LOGIN_DENIED; } /* Store the challenge for use later */ digest->input_token = (BYTE *) Curl_memdup(chlg, chlglen + 1); if(!digest->input_token) return CURLE_OUT_OF_MEMORY; digest->input_token_len = chlglen; return CURLE_OK; } /* * Curl_auth_create_digest_http_message() * * This is used to generate a HTTP DIGEST response message ready for sending * to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * request [in] - The HTTP request. * uripath [in] - The path of the HTTP uri. * digest [in/out] - The digest data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, const char *userp, const char *passwdp, const unsigned char *request, const unsigned char *uripath, struct digestdata *digest, char **outptr, size_t *outlen) { size_t token_max; char *resp; BYTE *output_token; size_t output_token_len = 0; PSecPkgInfo SecurityPackage; SecBuffer chlg_buf[5]; SecBufferDesc chlg_desc; SECURITY_STATUS status; (void) data; /* Query the security package for DigestSSP */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST), &SecurityPackage); if(status != SEC_E_OK) return CURLE_NOT_BUILT_IN; token_max = SecurityPackage->cbMaxToken; /* Release the package buffer as it is not required anymore */ s_pSecFn->FreeContextBuffer(SecurityPackage); /* Allocate the output buffer according to the max token size as indicated by the security package */ output_token = malloc(token_max); if(!output_token) { return CURLE_OUT_OF_MEMORY; } /* If the user/passwd that was used to make the identity for http_context has changed then delete that context. */ if((userp && !digest->user) || (!userp && digest->user) || (passwdp && !digest->passwd) || (!passwdp && digest->passwd) || (userp && digest->user && strcmp(userp, digest->user)) || (passwdp && digest->passwd && strcmp(passwdp, digest->passwd))) { if(digest->http_context) { s_pSecFn->DeleteSecurityContext(digest->http_context); Curl_safefree(digest->http_context); } Curl_safefree(digest->user); Curl_safefree(digest->passwd); } if(digest->http_context) { chlg_desc.ulVersion = SECBUFFER_VERSION; chlg_desc.cBuffers = 5; chlg_desc.pBuffers = chlg_buf; chlg_buf[0].BufferType = SECBUFFER_TOKEN; chlg_buf[0].pvBuffer = NULL; chlg_buf[0].cbBuffer = 0; chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; chlg_buf[1].pvBuffer = (void *) request; chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; chlg_buf[2].pvBuffer = (void *) uripath; chlg_buf[2].cbBuffer = curlx_uztoul(strlen((const char *) uripath)); chlg_buf[3].BufferType = SECBUFFER_PKG_PARAMS; chlg_buf[3].pvBuffer = NULL; chlg_buf[3].cbBuffer = 0; chlg_buf[4].BufferType = SECBUFFER_PADDING; chlg_buf[4].pvBuffer = output_token; chlg_buf[4].cbBuffer = curlx_uztoul(token_max); status = s_pSecFn->MakeSignature(digest->http_context, 0, &chlg_desc, 0); if(status == SEC_E_OK) output_token_len = chlg_buf[4].cbBuffer; else { /* delete the context so a new one can be made */ infof(data, "digest_sspi: MakeSignature failed, error 0x%08lx\n", (long)status); s_pSecFn->DeleteSecurityContext(digest->http_context); Curl_safefree(digest->http_context); } } if(!digest->http_context) { CredHandle credentials; SEC_WINNT_AUTH_IDENTITY identity; SEC_WINNT_AUTH_IDENTITY *p_identity; SecBuffer resp_buf; SecBufferDesc resp_desc; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ TCHAR *spn; /* free the copy of user/passwd used to make the previous identity */ Curl_safefree(digest->user); Curl_safefree(digest->passwd); if(userp && *userp) { /* Populate our identity structure */ if(Curl_create_sspi_identity(userp, passwdp, &identity)) { free(output_token); return CURLE_OUT_OF_MEMORY; } /* Populate our identity domain */ if(Curl_override_sspi_http_realm((const char *) digest->input_token, &identity)) { free(output_token); return CURLE_OUT_OF_MEMORY; } /* Allow proper cleanup of the identity structure */ p_identity = &identity; } else /* Use the current Windows user */ p_identity = NULL; if(userp) { digest->user = strdup(userp); if(!digest->user) { free(output_token); return CURLE_OUT_OF_MEMORY; } } if(passwdp) { digest->passwd = strdup(passwdp); if(!digest->passwd) { free(output_token); Curl_safefree(digest->user); return CURLE_OUT_OF_MEMORY; } } /* Acquire our credentials handle */ status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT(SP_NAME_DIGEST), SECPKG_CRED_OUTBOUND, NULL, p_identity, NULL, NULL, &credentials, &expiry); if(status != SEC_E_OK) { Curl_sspi_free_identity(p_identity); free(output_token); return CURLE_LOGIN_DENIED; } /* Setup the challenge "input" security buffer if present */ chlg_desc.ulVersion = SECBUFFER_VERSION; chlg_desc.cBuffers = 3; chlg_desc.pBuffers = chlg_buf; chlg_buf[0].BufferType = SECBUFFER_TOKEN; chlg_buf[0].pvBuffer = digest->input_token; chlg_buf[0].cbBuffer = curlx_uztoul(digest->input_token_len); chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS; chlg_buf[1].pvBuffer = (void *) request; chlg_buf[1].cbBuffer = curlx_uztoul(strlen((const char *) request)); chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS; chlg_buf[2].pvBuffer = NULL; chlg_buf[2].cbBuffer = 0; /* Setup the response "output" security buffer */ resp_desc.ulVersion = SECBUFFER_VERSION; resp_desc.cBuffers = 1; resp_desc.pBuffers = &resp_buf; resp_buf.BufferType = SECBUFFER_TOKEN; resp_buf.pvBuffer = output_token; resp_buf.cbBuffer = curlx_uztoul(token_max); spn = Curl_convert_UTF8_to_tchar((char *) uripath); if(!spn) { s_pSecFn->FreeCredentialsHandle(&credentials); Curl_sspi_free_identity(p_identity); free(output_token); return CURLE_OUT_OF_MEMORY; } /* Allocate our new context handle */ digest->http_context = calloc(1, sizeof(CtxtHandle)); if(!digest->http_context) return CURLE_OUT_OF_MEMORY; /* Generate our response message */ status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn, ISC_REQ_USE_HTTP_STYLE, 0, 0, &chlg_desc, 0, digest->http_context, &resp_desc, &attrs, &expiry); Curl_unicodefree(spn); if(status == SEC_I_COMPLETE_NEEDED || status == SEC_I_COMPLETE_AND_CONTINUE) s_pSecFn->CompleteAuthToken(&credentials, &resp_desc); else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { s_pSecFn->FreeCredentialsHandle(&credentials); Curl_sspi_free_identity(p_identity); free(output_token); Curl_safefree(digest->http_context); return CURLE_OUT_OF_MEMORY; } output_token_len = resp_buf.cbBuffer; s_pSecFn->FreeCredentialsHandle(&credentials); Curl_sspi_free_identity(p_identity); } resp = malloc(output_token_len + 1); if(!resp) { free(output_token); return CURLE_OUT_OF_MEMORY; } /* Copy the generated response */ memcpy(resp, output_token, output_token_len); resp[output_token_len] = 0; /* Return the response */ *outptr = resp; *outlen = output_token_len; /* Free the response buffer */ free(output_token); return CURLE_OK; } /* * Curl_auth_digest_cleanup() * * This is used to clean up the digest specific data. * * Parameters: * * digest [in/out] - The digest data struct being cleaned up. * */ void Curl_auth_digest_cleanup(struct digestdata *digest) { /* Free the input token */ Curl_safefree(digest->input_token); /* Reset any variables */ digest->input_token_len = 0; /* Delete security context */ if(digest->http_context) { s_pSecFn->DeleteSecurityContext(digest->http_context); Curl_safefree(digest->http_context); } /* Free the copy of user/passwd used to make the identity for http_context */ Curl_safefree(digest->user); Curl_safefree(digest->passwd); } #endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_CRYPTO_AUTH */
YifuLiu/AliOS-Things
components/curl/lib/vauth/digest_sspi.c
C
apache-2.0
20,671
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014 - 2019, Steve Holme, <steve_holme@hotmail.com>. * Copyright (C) 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * ***************************************************************************/ #include "curl_setup.h" #if defined(HAVE_GSSAPI) && defined(USE_KERBEROS5) #include <curl/curl.h> #include "vauth/vauth.h" #include "curl_sasl.h" #include "urldata.h" #include "curl_base64.h" #include "curl_gssapi.h" #include "sendf.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_gssapi_supported() * * This is used to evaluate if GSSAPI (Kerberos V5) is supported. * * Parameters: None * * Returns TRUE if Kerberos V5 is supported by the GSS-API library. */ bool Curl_auth_is_gssapi_supported(void) { return TRUE; } /* * Curl_auth_create_gssapi_user_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) user token * message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in[ - The host name. * mutual_auth [in] - Flag specifying whether or not mutual authentication * is enabled. * chlg64 [in] - Pointer to the optional base64 encoded challenge * message. * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *host, const bool mutual_auth, const char *chlg64, struct kerberos5data *krb5, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t chlglen = 0; unsigned char *chlg = NULL; OM_uint32 major_status; OM_uint32 minor_status; OM_uint32 unused_status; gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; (void) userp; (void) passwdp; if(!krb5->spn) { /* Generate our SPN */ char *spn = Curl_auth_build_spn(service, NULL, host); if(!spn) return CURLE_OUT_OF_MEMORY; /* Populate the SPN structure */ spn_token.value = spn; spn_token.length = strlen(spn); /* Import the SPN */ major_status = gss_import_name(&minor_status, &spn_token, GSS_C_NT_HOSTBASED_SERVICE, &krb5->spn); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_import_name() failed: ", major_status, minor_status); free(spn); return CURLE_OUT_OF_MEMORY; } free(spn); } if(chlg64 && *chlg64) { /* Decode the base-64 encoded challenge message */ if(*chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "GSSAPI handshake failure (empty challenge message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Setup the challenge "input" security buffer */ input_token.value = chlg; input_token.length = chlglen; } major_status = Curl_gss_init_sec_context(data, &minor_status, &krb5->context, krb5->spn, &Curl_krb5_mech_oid, GSS_C_NO_CHANNEL_BINDINGS, &input_token, &output_token, mutual_auth, NULL); /* Free the decoded challenge as it is not required anymore */ free(input_token.value); if(GSS_ERROR(major_status)) { if(output_token.value) gss_release_buffer(&unused_status, &output_token); Curl_gss_log_error(data, "gss_init_sec_context() failed: ", major_status, minor_status); return CURLE_RECV_ERROR; } if(output_token.value && output_token.length) { /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) output_token.value, output_token.length, outptr, outlen); gss_release_buffer(&unused_status, &output_token); } else if(mutual_auth) { *outptr = strdup(""); if(!*outptr) result = CURLE_OUT_OF_MEMORY; } return result; } /* * Curl_auth_create_gssapi_security_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) security * token message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * chlg64 [in] - Pointer to the optional base64 encoded challenge message. * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, const char *chlg64, struct kerberos5data *krb5, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t chlglen = 0; size_t messagelen = 0; unsigned char *chlg = NULL; unsigned char *message = NULL; OM_uint32 major_status; OM_uint32 minor_status; OM_uint32 unused_status; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; unsigned int indata = 0; unsigned int outdata = 0; gss_qop_t qop = GSS_C_QOP_DEFAULT; unsigned int sec_layer = 0; unsigned int max_size = 0; gss_name_t username = GSS_C_NO_NAME; gss_buffer_desc username_token; /* Decode the base-64 encoded input message */ if(strlen(chlg64) && *chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "GSSAPI handshake failure (empty security message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Get the fully qualified username back from the context */ major_status = gss_inquire_context(&minor_status, krb5->context, &username, NULL, NULL, NULL, NULL, NULL, NULL); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_inquire_context() failed: ", major_status, minor_status); free(chlg); return CURLE_OUT_OF_MEMORY; } /* Convert the username from internal format to a displayable token */ major_status = gss_display_name(&minor_status, username, &username_token, NULL); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_display_name() failed: ", major_status, minor_status); free(chlg); return CURLE_OUT_OF_MEMORY; } /* Setup the challenge "input" security buffer */ input_token.value = chlg; input_token.length = chlglen; /* Decrypt the inbound challenge and obtain the qop */ major_status = gss_unwrap(&minor_status, krb5->context, &input_token, &output_token, NULL, &qop); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_unwrap() failed: ", major_status, minor_status); gss_release_buffer(&unused_status, &username_token); free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ if(output_token.length != 4) { infof(data, "GSSAPI handshake failure (invalid security data)\n"); gss_release_buffer(&unused_status, &username_token); free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Copy the data out and free the challenge as it is not required anymore */ memcpy(&indata, output_token.value, 4); gss_release_buffer(&unused_status, &output_token); free(chlg); /* Extract the security layer */ sec_layer = indata & 0x000000FF; if(!(sec_layer & GSSAUTH_P_NONE)) { infof(data, "GSSAPI handshake failure (invalid security layer)\n"); gss_release_buffer(&unused_status, &username_token); return CURLE_BAD_CONTENT_ENCODING; } /* Extract the maximum message size the server can receive */ max_size = ntohl(indata & 0xFFFFFF00); if(max_size > 0) { /* The server has told us it supports a maximum receive buffer, however, as we don't require one unless we are encrypting data, we tell the server our receive buffer is zero. */ max_size = 0; } /* Allocate our message */ messagelen = sizeof(outdata) + username_token.length + 1; message = malloc(messagelen); if(!message) { gss_release_buffer(&unused_status, &username_token); return CURLE_OUT_OF_MEMORY; } /* Populate the message with the security layer, client supported receive message size and authorization identity including the 0x00 based terminator. Note: Despite RFC4752 Section 3.1 stating "The authorization identity is not terminated with the zero-valued (%x00) octet." it seems necessary to include it. */ outdata = htonl(max_size) | sec_layer; memcpy(message, &outdata, sizeof(outdata)); memcpy(message + sizeof(outdata), username_token.value, username_token.length); message[messagelen - 1] = '\0'; /* Free the username token as it is not required anymore */ gss_release_buffer(&unused_status, &username_token); /* Setup the "authentication data" security buffer */ input_token.value = message; input_token.length = messagelen; /* Encrypt the data */ major_status = gss_wrap(&minor_status, krb5->context, 0, GSS_C_QOP_DEFAULT, &input_token, NULL, &output_token); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_wrap() failed: ", major_status, minor_status); free(message); return CURLE_OUT_OF_MEMORY; } /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) output_token.value, output_token.length, outptr, outlen); /* Free the output buffer */ gss_release_buffer(&unused_status, &output_token); /* Free the message buffer */ free(message); return result; } /* * Curl_auth_cleanup_gssapi() * * This is used to clean up the GSSAPI (Kerberos V5) specific data. * * Parameters: * * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. * */ void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) { OM_uint32 minor_status; /* Free our security context */ if(krb5->context != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&minor_status, &krb5->context, GSS_C_NO_BUFFER); krb5->context = GSS_C_NO_CONTEXT; } /* Free the SPN */ if(krb5->spn != GSS_C_NO_NAME) { gss_release_name(&minor_status, &krb5->spn); krb5->spn = GSS_C_NO_NAME; } } #endif /* HAVE_GSSAPI && USE_KERBEROS5 */
YifuLiu/AliOS-Things
components/curl/lib/vauth/krb5_gssapi.c
C
apache-2.0
13,081
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014 - 2019, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_WINDOWS_SSPI) && defined(USE_KERBEROS5) #include <curl/curl.h> #include "vauth/vauth.h" #include "urldata.h" #include "curl_base64.h" #include "warnless.h" #include "curl_multibyte.h" #include "sendf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_gssapi_supported() * * This is used to evaluate if GSSAPI (Kerberos V5) is supported. * * Parameters: None * * Returns TRUE if Kerberos V5 is supported by Windows SSPI. */ bool Curl_auth_is_gssapi_supported(void) { PSecPkgInfo SecurityPackage; SECURITY_STATUS status; /* Query the security package for Kerberos */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_KERBEROS), &SecurityPackage); return (status == SEC_E_OK ? TRUE : FALSE); } /* * Curl_auth_create_gssapi_user_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) user token * message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * mutual_auth [in] - Flag specifying whether or not mutual authentication * is enabled. * chlg64 [in] - The optional base64 encoded challenge message. * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *host, const bool mutual_auth, const char *chlg64, struct kerberos5data *krb5, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t chlglen = 0; unsigned char *chlg = NULL; CtxtHandle context; PSecPkgInfo SecurityPackage; SecBuffer chlg_buf; SecBuffer resp_buf; SecBufferDesc chlg_desc; SecBufferDesc resp_desc; SECURITY_STATUS status; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ if(!krb5->spn) { /* Generate our SPN */ krb5->spn = Curl_auth_build_spn(service, host, NULL); if(!krb5->spn) return CURLE_OUT_OF_MEMORY; } if(!krb5->output_token) { /* Query the security package for Kerberos */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_KERBEROS), &SecurityPackage); if(status != SEC_E_OK) { return CURLE_NOT_BUILT_IN; } krb5->token_max = SecurityPackage->cbMaxToken; /* Release the package buffer as it is not required anymore */ s_pSecFn->FreeContextBuffer(SecurityPackage); /* Allocate our response buffer */ krb5->output_token = malloc(krb5->token_max); if(!krb5->output_token) return CURLE_OUT_OF_MEMORY; } if(!krb5->credentials) { /* Do we have credentials to use or are we using single sign-on? */ if(userp && *userp) { /* Populate our identity structure */ result = Curl_create_sspi_identity(userp, passwdp, &krb5->identity); if(result) return result; /* Allow proper cleanup of the identity structure */ krb5->p_identity = &krb5->identity; } else /* Use the current Windows user */ krb5->p_identity = NULL; /* Allocate our credentials handle */ krb5->credentials = calloc(1, sizeof(CredHandle)); if(!krb5->credentials) return CURLE_OUT_OF_MEMORY; /* Acquire our credentials handle */ status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT(SP_NAME_KERBEROS), SECPKG_CRED_OUTBOUND, NULL, krb5->p_identity, NULL, NULL, krb5->credentials, &expiry); if(status != SEC_E_OK) return CURLE_LOGIN_DENIED; /* Allocate our new context handle */ krb5->context = calloc(1, sizeof(CtxtHandle)); if(!krb5->context) return CURLE_OUT_OF_MEMORY; } if(chlg64 && *chlg64) { /* Decode the base-64 encoded challenge message */ if(*chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "GSSAPI handshake failure (empty challenge message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Setup the challenge "input" security buffer */ chlg_desc.ulVersion = SECBUFFER_VERSION; chlg_desc.cBuffers = 1; chlg_desc.pBuffers = &chlg_buf; chlg_buf.BufferType = SECBUFFER_TOKEN; chlg_buf.pvBuffer = chlg; chlg_buf.cbBuffer = curlx_uztoul(chlglen); } /* Setup the response "output" security buffer */ resp_desc.ulVersion = SECBUFFER_VERSION; resp_desc.cBuffers = 1; resp_desc.pBuffers = &resp_buf; resp_buf.BufferType = SECBUFFER_TOKEN; resp_buf.pvBuffer = krb5->output_token; resp_buf.cbBuffer = curlx_uztoul(krb5->token_max); /* Generate our challenge-response message */ status = s_pSecFn->InitializeSecurityContext(krb5->credentials, chlg ? krb5->context : NULL, krb5->spn, (mutual_auth ? ISC_REQ_MUTUAL_AUTH : 0), 0, SECURITY_NATIVE_DREP, chlg ? &chlg_desc : NULL, 0, &context, &resp_desc, &attrs, &expiry); /* Free the decoded challenge as it is not required anymore */ free(chlg); if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { return CURLE_RECV_ERROR; } if(memcmp(&context, krb5->context, sizeof(context))) { s_pSecFn->DeleteSecurityContext(krb5->context); memcpy(krb5->context, &context, sizeof(context)); } if(resp_buf.cbBuffer) { /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) resp_buf.pvBuffer, resp_buf.cbBuffer, outptr, outlen); } else if(mutual_auth) { *outptr = strdup(""); if(!*outptr) result = CURLE_OUT_OF_MEMORY; } return result; } /* * Curl_auth_create_gssapi_security_message() * * This is used to generate an already encoded GSSAPI (Kerberos V5) security * token message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * chlg64 [in] - The optional base64 encoded challenge message. * krb5 [in/out] - The Kerberos 5 data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, const char *chlg64, struct kerberos5data *krb5, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; size_t offset = 0; size_t chlglen = 0; size_t messagelen = 0; size_t appdatalen = 0; unsigned char *chlg = NULL; unsigned char *trailer = NULL; unsigned char *message = NULL; unsigned char *padding = NULL; unsigned char *appdata = NULL; SecBuffer input_buf[2]; SecBuffer wrap_buf[3]; SecBufferDesc input_desc; SecBufferDesc wrap_desc; unsigned long indata = 0; unsigned long outdata = 0; unsigned long qop = 0; unsigned long sec_layer = 0; unsigned long max_size = 0; SecPkgContext_Sizes sizes; SecPkgCredentials_Names names; SECURITY_STATUS status; char *user_name; /* Decode the base-64 encoded input message */ if(strlen(chlg64) && *chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "GSSAPI handshake failure (empty security message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Get our response size information */ status = s_pSecFn->QueryContextAttributes(krb5->context, SECPKG_ATTR_SIZES, &sizes); if(status != SEC_E_OK) { free(chlg); return CURLE_OUT_OF_MEMORY; } /* Get the fully qualified username back from the context */ status = s_pSecFn->QueryCredentialsAttributes(krb5->credentials, SECPKG_CRED_ATTR_NAMES, &names); if(status != SEC_E_OK) { free(chlg); return CURLE_RECV_ERROR; } /* Setup the "input" security buffer */ input_desc.ulVersion = SECBUFFER_VERSION; input_desc.cBuffers = 2; input_desc.pBuffers = input_buf; input_buf[0].BufferType = SECBUFFER_STREAM; input_buf[0].pvBuffer = chlg; input_buf[0].cbBuffer = curlx_uztoul(chlglen); input_buf[1].BufferType = SECBUFFER_DATA; input_buf[1].pvBuffer = NULL; input_buf[1].cbBuffer = 0; /* Decrypt the inbound challenge and obtain the qop */ status = s_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop); if(status != SEC_E_OK) { infof(data, "GSSAPI handshake failure (empty security message)\n"); free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Not 4 octets long so fail as per RFC4752 Section 3.1 */ if(input_buf[1].cbBuffer != 4) { infof(data, "GSSAPI handshake failure (invalid security data)\n"); free(chlg); return CURLE_BAD_CONTENT_ENCODING; } /* Copy the data out and free the challenge as it is not required anymore */ memcpy(&indata, input_buf[1].pvBuffer, 4); s_pSecFn->FreeContextBuffer(input_buf[1].pvBuffer); free(chlg); /* Extract the security layer */ sec_layer = indata & 0x000000FF; if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) { infof(data, "GSSAPI handshake failure (invalid security layer)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Extract the maximum message size the server can receive */ max_size = ntohl(indata & 0xFFFFFF00); if(max_size > 0) { /* The server has told us it supports a maximum receive buffer, however, as we don't require one unless we are encrypting data, we tell the server our receive buffer is zero. */ max_size = 0; } /* Allocate the trailer */ trailer = malloc(sizes.cbSecurityTrailer); if(!trailer) return CURLE_OUT_OF_MEMORY; /* Convert the user name to UTF8 when operating with Unicode */ user_name = Curl_convert_tchar_to_UTF8(names.sUserName); if(!user_name) { free(trailer); return CURLE_OUT_OF_MEMORY; } /* Allocate our message */ messagelen = sizeof(outdata) + strlen(user_name) + 1; message = malloc(messagelen); if(!message) { free(trailer); Curl_unicodefree(user_name); return CURLE_OUT_OF_MEMORY; } /* Populate the message with the security layer, client supported receive message size and authorization identity including the 0x00 based terminator. Note: Despite RFC4752 Section 3.1 stating "The authorization identity is not terminated with the zero-valued (%x00) octet." it seems necessary to include it. */ outdata = htonl(max_size) | sec_layer; memcpy(message, &outdata, sizeof(outdata)); strcpy((char *) message + sizeof(outdata), user_name); Curl_unicodefree(user_name); /* Allocate the padding */ padding = malloc(sizes.cbBlockSize); if(!padding) { free(message); free(trailer); return CURLE_OUT_OF_MEMORY; } /* Setup the "authentication data" security buffer */ wrap_desc.ulVersion = SECBUFFER_VERSION; wrap_desc.cBuffers = 3; wrap_desc.pBuffers = wrap_buf; wrap_buf[0].BufferType = SECBUFFER_TOKEN; wrap_buf[0].pvBuffer = trailer; wrap_buf[0].cbBuffer = sizes.cbSecurityTrailer; wrap_buf[1].BufferType = SECBUFFER_DATA; wrap_buf[1].pvBuffer = message; wrap_buf[1].cbBuffer = curlx_uztoul(messagelen); wrap_buf[2].BufferType = SECBUFFER_PADDING; wrap_buf[2].pvBuffer = padding; wrap_buf[2].cbBuffer = sizes.cbBlockSize; /* Encrypt the data */ status = s_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT, &wrap_desc, 0); if(status != SEC_E_OK) { free(padding); free(message); free(trailer); return CURLE_OUT_OF_MEMORY; } /* Allocate the encryption (wrap) buffer */ appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer + wrap_buf[2].cbBuffer; appdata = malloc(appdatalen); if(!appdata) { free(padding); free(message); free(trailer); return CURLE_OUT_OF_MEMORY; } /* Populate the encryption buffer */ memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer); offset += wrap_buf[0].cbBuffer; memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer); offset += wrap_buf[1].cbBuffer; memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer); /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) appdata, appdatalen, outptr, outlen); /* Free all of our local buffers */ free(appdata); free(padding); free(message); free(trailer); return result; } /* * Curl_auth_cleanup_gssapi() * * This is used to clean up the GSSAPI (Kerberos V5) specific data. * * Parameters: * * krb5 [in/out] - The Kerberos 5 data struct being cleaned up. * */ void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5) { /* Free our security context */ if(krb5->context) { s_pSecFn->DeleteSecurityContext(krb5->context); free(krb5->context); krb5->context = NULL; } /* Free our credentials handle */ if(krb5->credentials) { s_pSecFn->FreeCredentialsHandle(krb5->credentials); free(krb5->credentials); krb5->credentials = NULL; } /* Free our identity */ Curl_sspi_free_identity(krb5->p_identity); krb5->p_identity = NULL; /* Free the SPN and output token */ Curl_safefree(krb5->spn); Curl_safefree(krb5->output_token); /* Reset any variables */ krb5->token_max = 0; } #endif /* USE_WINDOWS_SSPI && USE_KERBEROS5*/
YifuLiu/AliOS-Things
components/curl/lib/vauth/krb5_sspi.c
C
apache-2.0
16,649
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_NTLM) && !defined(USE_WINDOWS_SSPI) /* * NTLM details: * * https://davenport.sourceforge.io/ntlm.html * https://www.innovation.ch/java/ntlm.html */ #define DEBUG_ME 0 #include "urldata.h" #include "non-ascii.h" #include "sendf.h" #include "curl_base64.h" #include "curl_ntlm_core.h" #include "curl_gethostname.h" #include "curl_multibyte.h" #include "warnless.h" #include "rand.h" #include "vtls/vtls.h" /* SSL backend-specific #if branches in this file must be kept in the order documented in curl_ntlm_core. */ #if defined(NTLM_NEEDS_NSS_INIT) #include "vtls/nssg.h" /* for Curl_nss_force_init() */ #endif #define BUILDING_CURL_NTLM_MSGS_C #include "vauth/vauth.h" #include "vauth/ntlm.h" #include "curl_endian.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* "NTLMSSP" signature is always in ASCII regardless of the platform */ #define NTLMSSP_SIGNATURE "\x4e\x54\x4c\x4d\x53\x53\x50" #define SHORTPAIR(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)) #define LONGQUARTET(x) ((int)((x) & 0xff)), ((int)(((x) >> 8) & 0xff)), \ ((int)(((x) >> 16) & 0xff)), ((int)(((x) >> 24) & 0xff)) #if DEBUG_ME # define DEBUG_OUT(x) x static void ntlm_print_flags(FILE *handle, unsigned long flags) { if(flags & NTLMFLAG_NEGOTIATE_UNICODE) fprintf(handle, "NTLMFLAG_NEGOTIATE_UNICODE "); if(flags & NTLMFLAG_NEGOTIATE_OEM) fprintf(handle, "NTLMFLAG_NEGOTIATE_OEM "); if(flags & NTLMFLAG_REQUEST_TARGET) fprintf(handle, "NTLMFLAG_REQUEST_TARGET "); if(flags & (1<<3)) fprintf(handle, "NTLMFLAG_UNKNOWN_3 "); if(flags & NTLMFLAG_NEGOTIATE_SIGN) fprintf(handle, "NTLMFLAG_NEGOTIATE_SIGN "); if(flags & NTLMFLAG_NEGOTIATE_SEAL) fprintf(handle, "NTLMFLAG_NEGOTIATE_SEAL "); if(flags & NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE) fprintf(handle, "NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE "); if(flags & NTLMFLAG_NEGOTIATE_LM_KEY) fprintf(handle, "NTLMFLAG_NEGOTIATE_LM_KEY "); if(flags & NTLMFLAG_NEGOTIATE_NETWARE) fprintf(handle, "NTLMFLAG_NEGOTIATE_NETWARE "); if(flags & NTLMFLAG_NEGOTIATE_NTLM_KEY) fprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM_KEY "); if(flags & (1<<10)) fprintf(handle, "NTLMFLAG_UNKNOWN_10 "); if(flags & NTLMFLAG_NEGOTIATE_ANONYMOUS) fprintf(handle, "NTLMFLAG_NEGOTIATE_ANONYMOUS "); if(flags & NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED) fprintf(handle, "NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED "); if(flags & NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED) fprintf(handle, "NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED "); if(flags & NTLMFLAG_NEGOTIATE_LOCAL_CALL) fprintf(handle, "NTLMFLAG_NEGOTIATE_LOCAL_CALL "); if(flags & NTLMFLAG_NEGOTIATE_ALWAYS_SIGN) fprintf(handle, "NTLMFLAG_NEGOTIATE_ALWAYS_SIGN "); if(flags & NTLMFLAG_TARGET_TYPE_DOMAIN) fprintf(handle, "NTLMFLAG_TARGET_TYPE_DOMAIN "); if(flags & NTLMFLAG_TARGET_TYPE_SERVER) fprintf(handle, "NTLMFLAG_TARGET_TYPE_SERVER "); if(flags & NTLMFLAG_TARGET_TYPE_SHARE) fprintf(handle, "NTLMFLAG_TARGET_TYPE_SHARE "); if(flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) fprintf(handle, "NTLMFLAG_NEGOTIATE_NTLM2_KEY "); if(flags & NTLMFLAG_REQUEST_INIT_RESPONSE) fprintf(handle, "NTLMFLAG_REQUEST_INIT_RESPONSE "); if(flags & NTLMFLAG_REQUEST_ACCEPT_RESPONSE) fprintf(handle, "NTLMFLAG_REQUEST_ACCEPT_RESPONSE "); if(flags & NTLMFLAG_REQUEST_NONNT_SESSION_KEY) fprintf(handle, "NTLMFLAG_REQUEST_NONNT_SESSION_KEY "); if(flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) fprintf(handle, "NTLMFLAG_NEGOTIATE_TARGET_INFO "); if(flags & (1<<24)) fprintf(handle, "NTLMFLAG_UNKNOWN_24 "); if(flags & (1<<25)) fprintf(handle, "NTLMFLAG_UNKNOWN_25 "); if(flags & (1<<26)) fprintf(handle, "NTLMFLAG_UNKNOWN_26 "); if(flags & (1<<27)) fprintf(handle, "NTLMFLAG_UNKNOWN_27 "); if(flags & (1<<28)) fprintf(handle, "NTLMFLAG_UNKNOWN_28 "); if(flags & NTLMFLAG_NEGOTIATE_128) fprintf(handle, "NTLMFLAG_NEGOTIATE_128 "); if(flags & NTLMFLAG_NEGOTIATE_KEY_EXCHANGE) fprintf(handle, "NTLMFLAG_NEGOTIATE_KEY_EXCHANGE "); if(flags & NTLMFLAG_NEGOTIATE_56) fprintf(handle, "NTLMFLAG_NEGOTIATE_56 "); } static void ntlm_print_hex(FILE *handle, const char *buf, size_t len) { const char *p = buf; (void) handle; fprintf(stderr, "0x"); while(len-- > 0) fprintf(stderr, "%02.2x", (unsigned int)*p++); } #else # define DEBUG_OUT(x) Curl_nop_stmt #endif /* * ntlm_decode_type2_target() * * This is used to decode the "target info" in the NTLM type-2 message * received. * * Parameters: * * data [in] - The session handle. * buffer [in] - The decoded type-2 message. * size [in] - The input buffer size, at least 32 bytes. * ntlm [in/out] - The NTLM data struct being used and modified. * * Returns CURLE_OK on success. */ static CURLcode ntlm_decode_type2_target(struct Curl_easy *data, unsigned char *buffer, size_t size, struct ntlmdata *ntlm) { unsigned short target_info_len = 0; unsigned int target_info_offset = 0; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) data; #endif if(size >= 48) { target_info_len = Curl_read16_le(&buffer[40]); target_info_offset = Curl_read32_le(&buffer[44]); if(target_info_len > 0) { if((target_info_offset >= size) || ((target_info_offset + target_info_len) > size) || (target_info_offset < 48)) { infof(data, "NTLM handshake failure (bad type-2 message). " "Target Info Offset Len is set incorrect by the peer\n"); return CURLE_BAD_CONTENT_ENCODING; } ntlm->target_info = malloc(target_info_len); if(!ntlm->target_info) return CURLE_OUT_OF_MEMORY; memcpy(ntlm->target_info, &buffer[target_info_offset], target_info_len); } } ntlm->target_info_len = target_info_len; return CURLE_OK; } /* NTLM message structure notes: A 'short' is a 'network short', a little-endian 16-bit unsigned value. A 'long' is a 'network long', a little-endian, 32-bit unsigned value. A 'security buffer' represents a triplet used to point to a buffer, consisting of two shorts and one long: 1. A 'short' containing the length of the buffer content in bytes. 2. A 'short' containing the allocated space for the buffer in bytes. 3. A 'long' containing the offset to the start of the buffer in bytes, from the beginning of the NTLM message. */ /* * Curl_auth_is_ntlm_supported() * * This is used to evaluate if NTLM is supported. * * Parameters: None * * Returns TRUE as NTLM as handled by libcurl. */ bool Curl_auth_is_ntlm_supported(void) { return TRUE; } /* * Curl_auth_decode_ntlm_type2_message() * * This is used to decode an already encoded NTLM type-2 message. The message * is first decoded from a base64 string into a raw NTLM message and checked * for validity before the appropriate data for creating a type-3 message is * written to the given NTLM data structure. * * Parameters: * * data [in] - The session handle. * type2msg [in] - The base64 encoded type-2 message. * ntlm [in/out] - The NTLM data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, const char *type2msg, struct ntlmdata *ntlm) { static const char type2_marker[] = { 0x02, 0x00, 0x00, 0x00 }; /* NTLM type-2 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x02000000) 12 Target Name security buffer 20 Flags long 24 Challenge 8 bytes (32) Context 8 bytes (two consecutive longs) (*) (40) Target Information security buffer (*) (48) OS Version Structure 8 bytes (*) 32 (48) (56) Start of data block (*) (*) -> Optional */ CURLcode result = CURLE_OK; unsigned char *type2 = NULL; size_t type2_len = 0; #if defined(NTLM_NEEDS_NSS_INIT) /* Make sure the crypto backend is initialized */ result = Curl_nss_force_init(data); if(result) return result; #elif defined(CURL_DISABLE_VERBOSE_STRINGS) (void)data; #endif /* Decode the base-64 encoded type-2 message */ if(strlen(type2msg) && *type2msg != '=') { result = Curl_base64_decode(type2msg, &type2, &type2_len); if(result) return result; } /* Ensure we have a valid type-2 message */ if(!type2) { infof(data, "NTLM handshake failure (empty type-2 message)\n"); return CURLE_BAD_CONTENT_ENCODING; } ntlm->flags = 0; if((type2_len < 32) || (memcmp(type2, NTLMSSP_SIGNATURE, 8) != 0) || (memcmp(type2 + 8, type2_marker, sizeof(type2_marker)) != 0)) { /* This was not a good enough type-2 message */ free(type2); infof(data, "NTLM handshake failure (bad type-2 message)\n"); return CURLE_BAD_CONTENT_ENCODING; } ntlm->flags = Curl_read32_le(&type2[20]); memcpy(ntlm->nonce, &type2[24], 8); if(ntlm->flags & NTLMFLAG_NEGOTIATE_TARGET_INFO) { result = ntlm_decode_type2_target(data, type2, type2_len, ntlm); if(result) { free(type2); infof(data, "NTLM handshake failure (bad type-2 message)\n"); return result; } } DEBUG_OUT({ fprintf(stderr, "**** TYPE2 header flags=0x%08.8lx ", ntlm->flags); ntlm_print_flags(stderr, ntlm->flags); fprintf(stderr, "\n nonce="); ntlm_print_hex(stderr, (char *)ntlm->nonce, 8); fprintf(stderr, "\n****\n"); fprintf(stderr, "**** Header %s\n ", header); }); free(type2); return result; } /* copy the source to the destination and fill in zeroes in every other destination byte! */ static void unicodecpy(unsigned char *dest, const char *src, size_t length) { size_t i; for(i = 0; i < length; i++) { dest[2 * i] = (unsigned char)src[i]; dest[2 * i + 1] = '\0'; } } /* * Curl_auth_create_ntlm_type1_message() * * This is used to generate an already encoded NTLM type-1 message ready for * sending to the recipient using the appropriate compile time crypto API. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *hostname, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { /* NTLM type-1 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x01000000) 12 Flags long (16) Supplied Domain security buffer (*) (24) Supplied Workstation security buffer (*) (32) OS Version Structure 8 bytes (*) (32) (40) Start of data block (*) (*) -> Optional */ size_t size; unsigned char ntlmbuf[NTLM_BUFSIZE]; const char *host = ""; /* empty */ const char *domain = ""; /* empty */ size_t hostlen = 0; size_t domlen = 0; size_t hostoff = 0; size_t domoff = hostoff + hostlen; /* This is 0: remember that host and domain are empty */ (void)userp; (void)passwdp; (void)service, (void)hostname, /* Clean up any former leftovers and initialise to defaults */ Curl_auth_cleanup_ntlm(ntlm); #if defined(USE_NTRESPONSES) && defined(USE_NTLM2SESSION) #define NTLM2FLAG NTLMFLAG_NEGOTIATE_NTLM2_KEY #else #define NTLM2FLAG 0 #endif msnprintf((char *)ntlmbuf, NTLM_BUFSIZE, NTLMSSP_SIGNATURE "%c" "\x01%c%c%c" /* 32-bit type = 1 */ "%c%c%c%c" /* 32-bit NTLM flag field */ "%c%c" /* domain length */ "%c%c" /* domain allocated space */ "%c%c" /* domain name offset */ "%c%c" /* 2 zeroes */ "%c%c" /* host length */ "%c%c" /* host allocated space */ "%c%c" /* host name offset */ "%c%c" /* 2 zeroes */ "%s" /* host name */ "%s", /* domain string */ 0, /* trailing zero */ 0, 0, 0, /* part of type-1 long */ LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), SHORTPAIR(domlen), SHORTPAIR(domlen), SHORTPAIR(domoff), 0, 0, SHORTPAIR(hostlen), SHORTPAIR(hostlen), SHORTPAIR(hostoff), 0, 0, host, /* this is empty */ domain /* this is empty */); /* Initial packet length */ size = 32 + hostlen + domlen; DEBUG_OUT({ fprintf(stderr, "* TYPE1 header flags=0x%02.2x%02.2x%02.2x%02.2x " "0x%08.8x ", LONGQUARTET(NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN), NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); ntlm_print_flags(stderr, NTLMFLAG_NEGOTIATE_OEM | NTLMFLAG_REQUEST_TARGET | NTLMFLAG_NEGOTIATE_NTLM_KEY | NTLM2FLAG | NTLMFLAG_NEGOTIATE_ALWAYS_SIGN); fprintf(stderr, "\n****\n"); }); /* Return with binary blob encoded into base64 */ return Curl_base64_encode(data, (char *)ntlmbuf, size, outptr, outlen); } /* * Curl_auth_create_ntlm_type3_message() * * This is used to generate an already encoded NTLM type-3 message ready for * sending to the recipient using the appropriate compile time crypto API. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { /* NTLM type-3 message structure: Index Description Content 0 NTLMSSP Signature Null-terminated ASCII "NTLMSSP" (0x4e544c4d53535000) 8 NTLM Message Type long (0x03000000) 12 LM/LMv2 Response security buffer 20 NTLM/NTLMv2 Response security buffer 28 Target Name security buffer 36 User Name security buffer 44 Workstation Name security buffer (52) Session Key security buffer (*) (60) Flags long (*) (64) OS Version Structure 8 bytes (*) 52 (64) (72) Start of data block (*) -> Optional */ CURLcode result = CURLE_OK; size_t size; unsigned char ntlmbuf[NTLM_BUFSIZE]; int lmrespoff; unsigned char lmresp[24]; /* fixed-size */ #ifdef USE_NTRESPONSES int ntrespoff; unsigned int ntresplen = 24; unsigned char ntresp[24]; /* fixed-size */ unsigned char *ptr_ntresp = &ntresp[0]; unsigned char *ntlmv2resp = NULL; #endif bool unicode = (ntlm->flags & NTLMFLAG_NEGOTIATE_UNICODE) ? TRUE : FALSE; char host[HOSTNAME_MAX + 1] = ""; const char *user; const char *domain = ""; size_t hostoff = 0; size_t useroff = 0; size_t domoff = 0; size_t hostlen = 0; size_t userlen = 0; size_t domlen = 0; user = strchr(userp, '\\'); if(!user) user = strchr(userp, '/'); if(user) { domain = userp; domlen = (user - domain); user++; } else user = userp; userlen = strlen(user); /* Get the machine's un-qualified host name as NTLM doesn't like the fully qualified domain name */ if(Curl_gethostname(host, sizeof(host))) { infof(data, "gethostname() failed, continuing without!\n"); hostlen = 0; } else { hostlen = strlen(host); } #if defined(USE_NTRESPONSES) && defined(USE_NTLM_V2) if(ntlm->flags & NTLMFLAG_NEGOTIATE_NTLM2_KEY) { unsigned char ntbuffer[0x18]; unsigned char entropy[8]; unsigned char ntlmv2hash[0x18]; result = Curl_rand(data, entropy, 8); if(result) return result; result = Curl_ntlm_core_mk_nt_hash(data, passwdp, ntbuffer); if(result) return result; result = Curl_ntlm_core_mk_ntlmv2_hash(user, userlen, domain, domlen, ntbuffer, ntlmv2hash); if(result) return result; /* LMv2 response */ result = Curl_ntlm_core_mk_lmv2_resp(ntlmv2hash, entropy, &ntlm->nonce[0], lmresp); if(result) return result; /* NTLMv2 response */ result = Curl_ntlm_core_mk_ntlmv2_resp(ntlmv2hash, entropy, ntlm, &ntlmv2resp, &ntresplen); if(result) return result; ptr_ntresp = ntlmv2resp; } else #endif #if defined(USE_NTRESPONSES) && defined(USE_NTLM2SESSION) /* We don't support NTLM2 if we don't have USE_NTRESPONSES */ if(ntlm->flags & NTLMFLAG_NEGOTIATE_NTLM_KEY) { unsigned char ntbuffer[0x18]; unsigned char tmp[0x18]; unsigned char md5sum[MD5_DIGEST_LENGTH]; unsigned char entropy[8]; /* Need to create 8 bytes random data */ result = Curl_rand(data, entropy, 8); if(result) return result; /* 8 bytes random data as challenge in lmresp */ memcpy(lmresp, entropy, 8); /* Pad with zeros */ memset(lmresp + 8, 0, 0x10); /* Fill tmp with challenge(nonce?) + entropy */ memcpy(tmp, &ntlm->nonce[0], 8); memcpy(tmp + 8, entropy, 8); result = Curl_ssl_md5sum(tmp, 16, md5sum, MD5_DIGEST_LENGTH); if(!result) /* We shall only use the first 8 bytes of md5sum, but the des code in Curl_ntlm_core_lm_resp only encrypt the first 8 bytes */ result = Curl_ntlm_core_mk_nt_hash(data, passwdp, ntbuffer); if(result) return result; Curl_ntlm_core_lm_resp(ntbuffer, md5sum, ntresp); /* End of NTLM2 Session code */ /* NTLM v2 session security is a misnomer because it is not NTLM v2. It is NTLM v1 using the extended session security that is also in NTLM v2 */ } else #endif { #ifdef USE_NTRESPONSES unsigned char ntbuffer[0x18]; #endif unsigned char lmbuffer[0x18]; #ifdef USE_NTRESPONSES result = Curl_ntlm_core_mk_nt_hash(data, passwdp, ntbuffer); if(result) return result; Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], ntresp); #endif result = Curl_ntlm_core_mk_lm_hash(data, passwdp, lmbuffer); if(result) return result; Curl_ntlm_core_lm_resp(lmbuffer, &ntlm->nonce[0], lmresp); /* A safer but less compatible alternative is: * Curl_ntlm_core_lm_resp(ntbuffer, &ntlm->nonce[0], lmresp); * See https://davenport.sourceforge.io/ntlm.html#ntlmVersion2 */ } if(unicode) { domlen = domlen * 2; userlen = userlen * 2; hostlen = hostlen * 2; } lmrespoff = 64; /* size of the message header */ #ifdef USE_NTRESPONSES ntrespoff = lmrespoff + 0x18; domoff = ntrespoff + ntresplen; #else domoff = lmrespoff + 0x18; #endif useroff = domoff + domlen; hostoff = useroff + userlen; /* Create the big type-3 message binary blob */ size = msnprintf((char *)ntlmbuf, NTLM_BUFSIZE, NTLMSSP_SIGNATURE "%c" "\x03%c%c%c" /* 32-bit type = 3 */ "%c%c" /* LanManager length */ "%c%c" /* LanManager allocated space */ "%c%c" /* LanManager offset */ "%c%c" /* 2 zeroes */ "%c%c" /* NT-response length */ "%c%c" /* NT-response allocated space */ "%c%c" /* NT-response offset */ "%c%c" /* 2 zeroes */ "%c%c" /* domain length */ "%c%c" /* domain allocated space */ "%c%c" /* domain name offset */ "%c%c" /* 2 zeroes */ "%c%c" /* user length */ "%c%c" /* user allocated space */ "%c%c" /* user offset */ "%c%c" /* 2 zeroes */ "%c%c" /* host length */ "%c%c" /* host allocated space */ "%c%c" /* host offset */ "%c%c" /* 2 zeroes */ "%c%c" /* session key length (unknown purpose) */ "%c%c" /* session key allocated space (unknown purpose) */ "%c%c" /* session key offset (unknown purpose) */ "%c%c" /* 2 zeroes */ "%c%c%c%c", /* flags */ /* domain string */ /* user string */ /* host string */ /* LanManager response */ /* NT response */ 0, /* zero termination */ 0, 0, 0, /* type-3 long, the 24 upper bits */ SHORTPAIR(0x18), /* LanManager response length, twice */ SHORTPAIR(0x18), SHORTPAIR(lmrespoff), 0x0, 0x0, #ifdef USE_NTRESPONSES SHORTPAIR(ntresplen), /* NT-response length, twice */ SHORTPAIR(ntresplen), SHORTPAIR(ntrespoff), 0x0, 0x0, #else 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, #endif SHORTPAIR(domlen), SHORTPAIR(domlen), SHORTPAIR(domoff), 0x0, 0x0, SHORTPAIR(userlen), SHORTPAIR(userlen), SHORTPAIR(useroff), 0x0, 0x0, SHORTPAIR(hostlen), SHORTPAIR(hostlen), SHORTPAIR(hostoff), 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, LONGQUARTET(ntlm->flags)); DEBUGASSERT(size == 64); DEBUGASSERT(size == (size_t)lmrespoff); /* We append the binary hashes */ if(size < (NTLM_BUFSIZE - 0x18)) { memcpy(&ntlmbuf[size], lmresp, 0x18); size += 0x18; } DEBUG_OUT({ fprintf(stderr, "**** TYPE3 header lmresp="); ntlm_print_hex(stderr, (char *)&ntlmbuf[lmrespoff], 0x18); }); #ifdef USE_NTRESPONSES /* ntresplen + size should not be risking an integer overflow here */ if(ntresplen + size > sizeof(ntlmbuf)) { failf(data, "incoming NTLM message too big"); return CURLE_OUT_OF_MEMORY; } DEBUGASSERT(size == (size_t)ntrespoff); memcpy(&ntlmbuf[size], ptr_ntresp, ntresplen); size += ntresplen; DEBUG_OUT({ fprintf(stderr, "\n ntresp="); ntlm_print_hex(stderr, (char *)&ntlmbuf[ntrespoff], ntresplen); }); free(ntlmv2resp);/* Free the dynamic buffer allocated for NTLMv2 */ #endif DEBUG_OUT({ fprintf(stderr, "\n flags=0x%02.2x%02.2x%02.2x%02.2x 0x%08.8x ", LONGQUARTET(ntlm->flags), ntlm->flags); ntlm_print_flags(stderr, ntlm->flags); fprintf(stderr, "\n****\n"); }); /* Make sure that the domain, user and host strings fit in the buffer before we copy them there. */ if(size + userlen + domlen + hostlen >= NTLM_BUFSIZE) { failf(data, "user + domain + host name too big"); return CURLE_OUT_OF_MEMORY; } DEBUGASSERT(size == domoff); if(unicode) unicodecpy(&ntlmbuf[size], domain, domlen / 2); else memcpy(&ntlmbuf[size], domain, domlen); size += domlen; DEBUGASSERT(size == useroff); if(unicode) unicodecpy(&ntlmbuf[size], user, userlen / 2); else memcpy(&ntlmbuf[size], user, userlen); size += userlen; DEBUGASSERT(size == hostoff); if(unicode) unicodecpy(&ntlmbuf[size], host, hostlen / 2); else memcpy(&ntlmbuf[size], host, hostlen); size += hostlen; /* Convert domain, user, and host to ASCII but leave the rest as-is */ result = Curl_convert_to_network(data, (char *)&ntlmbuf[domoff], size - domoff); if(result) return CURLE_CONV_FAILED; /* Return with binary blob encoded into base64 */ result = Curl_base64_encode(data, (char *)ntlmbuf, size, outptr, outlen); Curl_auth_cleanup_ntlm(ntlm); return result; } /* * Curl_auth_cleanup_ntlm() * * This is used to clean up the NTLM specific data. * * Parameters: * * ntlm [in/out] - The NTLM data struct being cleaned up. * */ void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) { /* Free the target info */ Curl_safefree(ntlm->target_info); /* Reset any variables */ ntlm->target_info_len = 0; } #endif /* USE_NTLM && !USE_WINDOWS_SSPI */
YifuLiu/AliOS-Things
components/curl/lib/vauth/ntlm.c
C
apache-2.0
28,139
#ifndef HEADER_VAUTH_NTLM_H #define HEADER_VAUTH_NTLM_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_NTLM /* NTLM buffer fixed size, large enough for long user + host + domain */ #define NTLM_BUFSIZE 1024 /* Stuff only required for curl_ntlm_msgs.c */ #ifdef BUILDING_CURL_NTLM_MSGS_C /* Flag bits definitions based on https://davenport.sourceforge.io/ntlm.html */ #define NTLMFLAG_NEGOTIATE_UNICODE (1<<0) /* Indicates that Unicode strings are supported for use in security buffer data. */ #define NTLMFLAG_NEGOTIATE_OEM (1<<1) /* Indicates that OEM strings are supported for use in security buffer data. */ #define NTLMFLAG_REQUEST_TARGET (1<<2) /* Requests that the server's authentication realm be included in the Type 2 message. */ /* unknown (1<<3) */ #define NTLMFLAG_NEGOTIATE_SIGN (1<<4) /* Specifies that authenticated communication between the client and server should carry a digital signature (message integrity). */ #define NTLMFLAG_NEGOTIATE_SEAL (1<<5) /* Specifies that authenticated communication between the client and server should be encrypted (message confidentiality). */ #define NTLMFLAG_NEGOTIATE_DATAGRAM_STYLE (1<<6) /* Indicates that datagram authentication is being used. */ #define NTLMFLAG_NEGOTIATE_LM_KEY (1<<7) /* Indicates that the LAN Manager session key should be used for signing and sealing authenticated communications. */ #define NTLMFLAG_NEGOTIATE_NETWARE (1<<8) /* unknown purpose */ #define NTLMFLAG_NEGOTIATE_NTLM_KEY (1<<9) /* Indicates that NTLM authentication is being used. */ /* unknown (1<<10) */ #define NTLMFLAG_NEGOTIATE_ANONYMOUS (1<<11) /* Sent by the client in the Type 3 message to indicate that an anonymous context has been established. This also affects the response fields. */ #define NTLMFLAG_NEGOTIATE_DOMAIN_SUPPLIED (1<<12) /* Sent by the client in the Type 1 message to indicate that a desired authentication realm is included in the message. */ #define NTLMFLAG_NEGOTIATE_WORKSTATION_SUPPLIED (1<<13) /* Sent by the client in the Type 1 message to indicate that the client workstation's name is included in the message. */ #define NTLMFLAG_NEGOTIATE_LOCAL_CALL (1<<14) /* Sent by the server to indicate that the server and client are on the same machine. Implies that the client may use a pre-established local security context rather than responding to the challenge. */ #define NTLMFLAG_NEGOTIATE_ALWAYS_SIGN (1<<15) /* Indicates that authenticated communication between the client and server should be signed with a "dummy" signature. */ #define NTLMFLAG_TARGET_TYPE_DOMAIN (1<<16) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a domain. */ #define NTLMFLAG_TARGET_TYPE_SERVER (1<<17) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a server. */ #define NTLMFLAG_TARGET_TYPE_SHARE (1<<18) /* Sent by the server in the Type 2 message to indicate that the target authentication realm is a share. Presumably, this is for share-level authentication. Usage is unclear. */ #define NTLMFLAG_NEGOTIATE_NTLM2_KEY (1<<19) /* Indicates that the NTLM2 signing and sealing scheme should be used for protecting authenticated communications. */ #define NTLMFLAG_REQUEST_INIT_RESPONSE (1<<20) /* unknown purpose */ #define NTLMFLAG_REQUEST_ACCEPT_RESPONSE (1<<21) /* unknown purpose */ #define NTLMFLAG_REQUEST_NONNT_SESSION_KEY (1<<22) /* unknown purpose */ #define NTLMFLAG_NEGOTIATE_TARGET_INFO (1<<23) /* Sent by the server in the Type 2 message to indicate that it is including a Target Information block in the message. */ /* unknown (1<24) */ /* unknown (1<25) */ /* unknown (1<26) */ /* unknown (1<27) */ /* unknown (1<28) */ #define NTLMFLAG_NEGOTIATE_128 (1<<29) /* Indicates that 128-bit encryption is supported. */ #define NTLMFLAG_NEGOTIATE_KEY_EXCHANGE (1<<30) /* Indicates that the client will provide an encrypted master key in the "Session Key" field of the Type 3 message. */ #define NTLMFLAG_NEGOTIATE_56 (1<<31) /* Indicates that 56-bit encryption is supported. */ #endif /* BUILDING_CURL_NTLM_MSGS_C */ #endif /* USE_NTLM */ #endif /* HEADER_VAUTH_NTLM_H */
YifuLiu/AliOS-Things
components/curl/lib/vauth/ntlm.h
C
apache-2.0
5,541
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_WINDOWS_SSPI) && defined(USE_NTLM) #include <curl/curl.h> #include "vauth/vauth.h" #include "urldata.h" #include "curl_base64.h" #include "curl_ntlm_core.h" #include "warnless.h" #include "curl_multibyte.h" #include "sendf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_ntlm_supported() * * This is used to evaluate if NTLM is supported. * * Parameters: None * * Returns TRUE if NTLM is supported by Windows SSPI. */ bool Curl_auth_is_ntlm_supported(void) { PSecPkgInfo SecurityPackage; SECURITY_STATUS status; /* Query the security package for NTLM */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), &SecurityPackage); return (status == SEC_E_OK ? TRUE : FALSE); } /* * Curl_auth_create_ntlm_type1_message() * * This is used to generate an already encoded NTLM type-1 message ready for * sending to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *host, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { PSecPkgInfo SecurityPackage; SecBuffer type_1_buf; SecBufferDesc type_1_desc; SECURITY_STATUS status; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ /* Clean up any former leftovers and initialise to defaults */ Curl_auth_cleanup_ntlm(ntlm); /* Query the security package for NTLM */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM), &SecurityPackage); if(status != SEC_E_OK) return CURLE_NOT_BUILT_IN; ntlm->token_max = SecurityPackage->cbMaxToken; /* Release the package buffer as it is not required anymore */ s_pSecFn->FreeContextBuffer(SecurityPackage); /* Allocate our output buffer */ ntlm->output_token = malloc(ntlm->token_max); if(!ntlm->output_token) return CURLE_OUT_OF_MEMORY; if(userp && *userp) { CURLcode result; /* Populate our identity structure */ result = Curl_create_sspi_identity(userp, passwdp, &ntlm->identity); if(result) return result; /* Allow proper cleanup of the identity structure */ ntlm->p_identity = &ntlm->identity; } else /* Use the current Windows user */ ntlm->p_identity = NULL; /* Allocate our credentials handle */ ntlm->credentials = calloc(1, sizeof(CredHandle)); if(!ntlm->credentials) return CURLE_OUT_OF_MEMORY; /* Acquire our credentials handle */ status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *) TEXT(SP_NAME_NTLM), SECPKG_CRED_OUTBOUND, NULL, ntlm->p_identity, NULL, NULL, ntlm->credentials, &expiry); if(status != SEC_E_OK) return CURLE_LOGIN_DENIED; /* Allocate our new context handle */ ntlm->context = calloc(1, sizeof(CtxtHandle)); if(!ntlm->context) return CURLE_OUT_OF_MEMORY; ntlm->spn = Curl_auth_build_spn(service, host, NULL); if(!ntlm->spn) return CURLE_OUT_OF_MEMORY; /* Setup the type-1 "output" security buffer */ type_1_desc.ulVersion = SECBUFFER_VERSION; type_1_desc.cBuffers = 1; type_1_desc.pBuffers = &type_1_buf; type_1_buf.BufferType = SECBUFFER_TOKEN; type_1_buf.pvBuffer = ntlm->output_token; type_1_buf.cbBuffer = curlx_uztoul(ntlm->token_max); /* Generate our type-1 message */ status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, NULL, ntlm->spn, 0, 0, SECURITY_NETWORK_DREP, NULL, 0, ntlm->context, &type_1_desc, &attrs, &expiry); if(status == SEC_I_COMPLETE_NEEDED || status == SEC_I_COMPLETE_AND_CONTINUE) s_pSecFn->CompleteAuthToken(ntlm->context, &type_1_desc); else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) return CURLE_RECV_ERROR; /* Base64 encode the response */ return Curl_base64_encode(data, (char *) ntlm->output_token, type_1_buf.cbBuffer, outptr, outlen); } /* * Curl_auth_decode_ntlm_type2_message() * * This is used to decode an already encoded NTLM type-2 message. * * Parameters: * * data [in] - The session handle. * type2msg [in] - The base64 encoded type-2 message. * ntlm [in/out] - The NTLM data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, const char *type2msg, struct ntlmdata *ntlm) { CURLcode result = CURLE_OK; unsigned char *type2 = NULL; size_t type2_len = 0; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) data; #endif /* Decode the base-64 encoded type-2 message */ if(strlen(type2msg) && *type2msg != '=') { result = Curl_base64_decode(type2msg, &type2, &type2_len); if(result) return result; } /* Ensure we have a valid type-2 message */ if(!type2) { infof(data, "NTLM handshake failure (empty type-2 message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Simply store the challenge for use later */ ntlm->input_token = type2; ntlm->input_token_len = type2_len; return result; } /* * Curl_auth_create_ntlm_type3_message() * Curl_auth_create_ntlm_type3_message() * * This is used to generate an already encoded NTLM type-3 message ready for * sending to the recipient. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * ntlm [in/out] - The NTLM data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; SecBuffer type_2_bufs[2]; SecBuffer type_3_buf; SecBufferDesc type_2_desc; SecBufferDesc type_3_desc; SECURITY_STATUS status; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ (void) passwdp; (void) userp; /* Setup the type-2 "input" security buffer */ type_2_desc.ulVersion = SECBUFFER_VERSION; type_2_desc.cBuffers = 1; type_2_desc.pBuffers = &type_2_bufs[0]; type_2_bufs[0].BufferType = SECBUFFER_TOKEN; type_2_bufs[0].pvBuffer = ntlm->input_token; type_2_bufs[0].cbBuffer = curlx_uztoul(ntlm->input_token_len); #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS /* ssl context comes from schannel. * When extended protection is used in IIS server, * we have to pass a second SecBuffer to the SecBufferDesc * otherwise IIS will not pass the authentication (401 response). * Minimum supported version is Windows 7. * https://docs.microsoft.com/en-us/security-updates * /SecurityAdvisories/2009/973811 */ if(ntlm->sslContext) { SEC_CHANNEL_BINDINGS channelBindings; SecPkgContext_Bindings pkgBindings; pkgBindings.Bindings = &channelBindings; status = s_pSecFn->QueryContextAttributes( ntlm->sslContext, SECPKG_ATTR_ENDPOINT_BINDINGS, &pkgBindings ); if(status == SEC_E_OK) { type_2_desc.cBuffers++; type_2_bufs[1].BufferType = SECBUFFER_CHANNEL_BINDINGS; type_2_bufs[1].cbBuffer = pkgBindings.BindingsLength; type_2_bufs[1].pvBuffer = pkgBindings.Bindings; } } #endif /* Setup the type-3 "output" security buffer */ type_3_desc.ulVersion = SECBUFFER_VERSION; type_3_desc.cBuffers = 1; type_3_desc.pBuffers = &type_3_buf; type_3_buf.BufferType = SECBUFFER_TOKEN; type_3_buf.pvBuffer = ntlm->output_token; type_3_buf.cbBuffer = curlx_uztoul(ntlm->token_max); /* Generate our type-3 message */ status = s_pSecFn->InitializeSecurityContext(ntlm->credentials, ntlm->context, ntlm->spn, 0, 0, SECURITY_NETWORK_DREP, &type_2_desc, 0, ntlm->context, &type_3_desc, &attrs, &expiry); if(status != SEC_E_OK) { infof(data, "NTLM handshake failure (type-3 message): Status=%x\n", status); return CURLE_RECV_ERROR; } /* Base64 encode the response */ result = Curl_base64_encode(data, (char *) ntlm->output_token, type_3_buf.cbBuffer, outptr, outlen); Curl_auth_cleanup_ntlm(ntlm); return result; } /* * Curl_auth_cleanup_ntlm() * * This is used to clean up the NTLM specific data. * * Parameters: * * ntlm [in/out] - The NTLM data struct being cleaned up. * */ void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm) { /* Free our security context */ if(ntlm->context) { s_pSecFn->DeleteSecurityContext(ntlm->context); free(ntlm->context); ntlm->context = NULL; } /* Free our credentials handle */ if(ntlm->credentials) { s_pSecFn->FreeCredentialsHandle(ntlm->credentials); free(ntlm->credentials); ntlm->credentials = NULL; } /* Free our identity */ Curl_sspi_free_identity(ntlm->p_identity); ntlm->p_identity = NULL; /* Free the input and output tokens */ Curl_safefree(ntlm->input_token); Curl_safefree(ntlm->output_token); /* Reset any variables */ ntlm->token_max = 0; Curl_safefree(ntlm->spn); } #endif /* USE_WINDOWS_SSPI && USE_NTLM */
YifuLiu/AliOS-Things
components/curl/lib/vauth/ntlm_sspi.c
C
apache-2.0
12,299
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC6749 OAuth 2.0 Authorization Framework * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_POP3) #include <curl/curl.h> #include "urldata.h" #include "vauth/vauth.h" #include "curl_base64.h" #include "warnless.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_create_oauth_bearer_message() * * This is used to generate an already encoded OAuth 2.0 message ready for * sending to the recipient. * * Parameters: * * data[in] - The session handle. * user[in] - The user name. * host[in] - The host name. * port[in] - The port(when not Port 80). * bearer[in] - The bearer token. * outptr[in / out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen[out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_easy *data, const char *user, const char *host, const long port, const char *bearer, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; char *oauth = NULL; /* Generate the message */ if(port == 0 || port == 80) oauth = aprintf("n,a=%s,\1host=%s\1auth=Bearer %s\1\1", user, host, bearer); else oauth = aprintf("n,a=%s,\1host=%s\1port=%ld\1auth=Bearer %s\1\1", user, host, port, bearer); if(!oauth) return CURLE_OUT_OF_MEMORY; /* Base64 encode the reply */ result = Curl_base64_encode(data, oauth, strlen(oauth), outptr, outlen); free(oauth); return result; } /* * Curl_auth_create_xoauth_bearer_message() * * This is used to generate an already encoded XOAuth 2.0 message ready for * sending to the recipient. * * Parameters: * * data[in] - The session handle. * user[in] - The user name. * bearer[in] - The bearer token. * outptr[in / out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen[out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_xoauth_bearer_message(struct Curl_easy *data, const char *user, const char *bearer, char **outptr, size_t *outlen) { CURLcode result = CURLE_OK; /* Generate the message */ char *xoauth = aprintf("user=%s\1auth=Bearer %s\1\1", user, bearer); if(!xoauth) return CURLE_OUT_OF_MEMORY; /* Base64 encode the reply */ result = Curl_base64_encode(data, xoauth, strlen(xoauth), outptr, outlen); free(xoauth); return result; } #endif /* disabled, no users */
YifuLiu/AliOS-Things
components/curl/lib/vauth/oauth2.c
C
apache-2.0
4,174
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC4178 Simple and Protected GSS-API Negotiation Mechanism * ***************************************************************************/ #include "curl_setup.h" #if defined(HAVE_GSSAPI) && defined(USE_SPNEGO) #include <curl/curl.h> #include "vauth/vauth.h" #include "urldata.h" #include "curl_base64.h" #include "curl_gssapi.h" #include "warnless.h" #include "curl_multibyte.h" #include "sendf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_spnego_supported() * * This is used to evaluate if SPNEGO (Negotiate) is supported. * * Parameters: None * * Returns TRUE if Negotiate supported by the GSS-API library. */ bool Curl_auth_is_spnego_supported(void) { return TRUE; } /* * Curl_auth_decode_spnego_message() * * This is used to decode an already encoded SPNEGO (Negotiate) challenge * message. * * Parameters: * * data [in] - The session handle. * userp [in] - The user name in the format User or Domain\User. * passwdp [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * chlg64 [in] - The optional base64 encoded challenge message. * nego [in/out] - The Negotiate data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, const char *user, const char *password, const char *service, const char *host, const char *chlg64, struct negotiatedata *nego) { CURLcode result = CURLE_OK; size_t chlglen = 0; unsigned char *chlg = NULL; OM_uint32 major_status; OM_uint32 minor_status; OM_uint32 unused_status; gss_buffer_desc spn_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; (void) user; (void) password; if(nego->context && nego->status == GSS_S_COMPLETE) { /* We finished successfully our part of authentication, but server * rejected it (since we're again here). Exit with an error since we * can't invent anything better */ Curl_auth_cleanup_spnego(nego); return CURLE_LOGIN_DENIED; } if(!nego->spn) { /* Generate our SPN */ char *spn = Curl_auth_build_spn(service, NULL, host); if(!spn) return CURLE_OUT_OF_MEMORY; /* Populate the SPN structure */ spn_token.value = spn; spn_token.length = strlen(spn); /* Import the SPN */ major_status = gss_import_name(&minor_status, &spn_token, GSS_C_NT_HOSTBASED_SERVICE, &nego->spn); if(GSS_ERROR(major_status)) { Curl_gss_log_error(data, "gss_import_name() failed: ", major_status, minor_status); free(spn); return CURLE_OUT_OF_MEMORY; } free(spn); } if(chlg64 && *chlg64) { /* Decode the base-64 encoded challenge message */ if(*chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "SPNEGO handshake failure (empty challenge message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Setup the challenge "input" security buffer */ input_token.value = chlg; input_token.length = chlglen; } /* Generate our challenge-response message */ major_status = Curl_gss_init_sec_context(data, &minor_status, &nego->context, nego->spn, &Curl_spnego_mech_oid, GSS_C_NO_CHANNEL_BINDINGS, &input_token, &output_token, TRUE, NULL); /* Free the decoded challenge as it is not required anymore */ Curl_safefree(input_token.value); nego->status = major_status; if(GSS_ERROR(major_status)) { if(output_token.value) gss_release_buffer(&unused_status, &output_token); Curl_gss_log_error(data, "gss_init_sec_context() failed: ", major_status, minor_status); return CURLE_LOGIN_DENIED; } if(!output_token.value || !output_token.length) { if(output_token.value) gss_release_buffer(&unused_status, &output_token); return CURLE_OUT_OF_MEMORY; } /* Free previous token */ if(nego->output_token.length && nego->output_token.value) gss_release_buffer(&unused_status, &nego->output_token); nego->output_token = output_token; return CURLE_OK; } /* * Curl_auth_create_spnego_message() * * This is used to generate an already encoded SPNEGO (Negotiate) response * message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * nego [in/out] - The Negotiate data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, struct negotiatedata *nego, char **outptr, size_t *outlen) { CURLcode result; OM_uint32 minor_status; /* Base64 encode the already generated response */ result = Curl_base64_encode(data, nego->output_token.value, nego->output_token.length, outptr, outlen); if(result) { gss_release_buffer(&minor_status, &nego->output_token); nego->output_token.value = NULL; nego->output_token.length = 0; return result; } if(!*outptr || !*outlen) { gss_release_buffer(&minor_status, &nego->output_token); nego->output_token.value = NULL; nego->output_token.length = 0; return CURLE_REMOTE_ACCESS_DENIED; } return CURLE_OK; } /* * Curl_auth_cleanup_spnego() * * This is used to clean up the SPNEGO (Negotiate) specific data. * * Parameters: * * nego [in/out] - The Negotiate data struct being cleaned up. * */ void Curl_auth_cleanup_spnego(struct negotiatedata *nego) { OM_uint32 minor_status; /* Free our security context */ if(nego->context != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&minor_status, &nego->context, GSS_C_NO_BUFFER); nego->context = GSS_C_NO_CONTEXT; } /* Free the output token */ if(nego->output_token.value) { gss_release_buffer(&minor_status, &nego->output_token); nego->output_token.value = NULL; nego->output_token.length = 0; } /* Free the SPN */ if(nego->spn != GSS_C_NO_NAME) { gss_release_name(&minor_status, &nego->spn); nego->spn = GSS_C_NO_NAME; } /* Reset any variables */ nego->status = 0; nego->noauthpersist = FALSE; nego->havenoauthpersist = FALSE; nego->havenegdata = FALSE; nego->havemultiplerequests = FALSE; } #endif /* HAVE_GSSAPI && USE_SPNEGO */
YifuLiu/AliOS-Things
components/curl/lib/vauth/spnego_gssapi.c
C
apache-2.0
8,557
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC4178 Simple and Protected GSS-API Negotiation Mechanism * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_WINDOWS_SSPI) && defined(USE_SPNEGO) #include <curl/curl.h> #include "vauth/vauth.h" #include "urldata.h" #include "curl_base64.h" #include "warnless.h" #include "curl_multibyte.h" #include "sendf.h" #include "strerror.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_is_spnego_supported() * * This is used to evaluate if SPNEGO (Negotiate) is supported. * * Parameters: None * * Returns TRUE if Negotiate is supported by Windows SSPI. */ bool Curl_auth_is_spnego_supported(void) { PSecPkgInfo SecurityPackage; SECURITY_STATUS status; /* Query the security package for Negotiate */ status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NEGOTIATE), &SecurityPackage); return (status == SEC_E_OK ? TRUE : FALSE); } /* * Curl_auth_decode_spnego_message() * * This is used to decode an already encoded SPNEGO (Negotiate) challenge * message. * * Parameters: * * data [in] - The session handle. * user [in] - The user name in the format User or Domain\User. * password [in] - The user's password. * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * chlg64 [in] - The optional base64 encoded challenge message. * nego [in/out] - The Negotiate data struct being used and modified. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, const char *user, const char *password, const char *service, const char *host, const char *chlg64, struct negotiatedata *nego) { CURLcode result = CURLE_OK; size_t chlglen = 0; unsigned char *chlg = NULL; PSecPkgInfo SecurityPackage; SecBuffer chlg_buf[2]; SecBuffer resp_buf; SecBufferDesc chlg_desc; SecBufferDesc resp_desc; unsigned long attrs; TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */ #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) data; #endif if(nego->context && nego->status == SEC_E_OK) { /* We finished successfully our part of authentication, but server * rejected it (since we're again here). Exit with an error since we * can't invent anything better */ Curl_auth_cleanup_spnego(nego); return CURLE_LOGIN_DENIED; } if(!nego->spn) { /* Generate our SPN */ nego->spn = Curl_auth_build_spn(service, host, NULL); if(!nego->spn) return CURLE_OUT_OF_MEMORY; } if(!nego->output_token) { /* Query the security package for Negotiate */ nego->status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NEGOTIATE), &SecurityPackage); if(nego->status != SEC_E_OK) return CURLE_NOT_BUILT_IN; nego->token_max = SecurityPackage->cbMaxToken; /* Release the package buffer as it is not required anymore */ s_pSecFn->FreeContextBuffer(SecurityPackage); /* Allocate our output buffer */ nego->output_token = malloc(nego->token_max); if(!nego->output_token) return CURLE_OUT_OF_MEMORY; } if(!nego->credentials) { /* Do we have credentials to use or are we using single sign-on? */ if(user && *user) { /* Populate our identity structure */ result = Curl_create_sspi_identity(user, password, &nego->identity); if(result) return result; /* Allow proper cleanup of the identity structure */ nego->p_identity = &nego->identity; } else /* Use the current Windows user */ nego->p_identity = NULL; /* Allocate our credentials handle */ nego->credentials = calloc(1, sizeof(CredHandle)); if(!nego->credentials) return CURLE_OUT_OF_MEMORY; /* Acquire our credentials handle */ nego->status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)TEXT(SP_NAME_NEGOTIATE), SECPKG_CRED_OUTBOUND, NULL, nego->p_identity, NULL, NULL, nego->credentials, &expiry); if(nego->status != SEC_E_OK) return CURLE_LOGIN_DENIED; /* Allocate our new context handle */ nego->context = calloc(1, sizeof(CtxtHandle)); if(!nego->context) return CURLE_OUT_OF_MEMORY; } if(chlg64 && *chlg64) { /* Decode the base-64 encoded challenge message */ if(*chlg64 != '=') { result = Curl_base64_decode(chlg64, &chlg, &chlglen); if(result) return result; } /* Ensure we have a valid challenge message */ if(!chlg) { infof(data, "SPNEGO handshake failure (empty challenge message)\n"); return CURLE_BAD_CONTENT_ENCODING; } /* Setup the challenge "input" security buffer */ chlg_desc.ulVersion = SECBUFFER_VERSION; chlg_desc.cBuffers = 1; chlg_desc.pBuffers = &chlg_buf[0]; chlg_buf[0].BufferType = SECBUFFER_TOKEN; chlg_buf[0].pvBuffer = chlg; chlg_buf[0].cbBuffer = curlx_uztoul(chlglen); #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS /* ssl context comes from Schannel. * When extended protection is used in IIS server, * we have to pass a second SecBuffer to the SecBufferDesc * otherwise IIS will not pass the authentication (401 response). * Minimum supported version is Windows 7. * https://docs.microsoft.com/en-us/security-updates * /SecurityAdvisories/2009/973811 */ if(nego->sslContext) { SEC_CHANNEL_BINDINGS channelBindings; SecPkgContext_Bindings pkgBindings; pkgBindings.Bindings = &channelBindings; nego->status = s_pSecFn->QueryContextAttributes( nego->sslContext, SECPKG_ATTR_ENDPOINT_BINDINGS, &pkgBindings ); if(nego->status == SEC_E_OK) { chlg_desc.cBuffers++; chlg_buf[1].BufferType = SECBUFFER_CHANNEL_BINDINGS; chlg_buf[1].cbBuffer = pkgBindings.BindingsLength; chlg_buf[1].pvBuffer = pkgBindings.Bindings; } } #endif } /* Setup the response "output" security buffer */ resp_desc.ulVersion = SECBUFFER_VERSION; resp_desc.cBuffers = 1; resp_desc.pBuffers = &resp_buf; resp_buf.BufferType = SECBUFFER_TOKEN; resp_buf.pvBuffer = nego->output_token; resp_buf.cbBuffer = curlx_uztoul(nego->token_max); /* Generate our challenge-response message */ nego->status = s_pSecFn->InitializeSecurityContext(nego->credentials, chlg ? nego->context : NULL, nego->spn, ISC_REQ_CONFIDENTIALITY, 0, SECURITY_NATIVE_DREP, chlg ? &chlg_desc : NULL, 0, nego->context, &resp_desc, &attrs, &expiry); /* Free the decoded challenge as it is not required anymore */ free(chlg); if(GSS_ERROR(nego->status)) { char buffer[STRERROR_LEN]; failf(data, "InitializeSecurityContext failed: %s", Curl_sspi_strerror(nego->status, buffer, sizeof(buffer))); return CURLE_OUT_OF_MEMORY; } if(nego->status == SEC_I_COMPLETE_NEEDED || nego->status == SEC_I_COMPLETE_AND_CONTINUE) { nego->status = s_pSecFn->CompleteAuthToken(nego->context, &resp_desc); if(GSS_ERROR(nego->status)) { return CURLE_RECV_ERROR; } } nego->output_token_length = resp_buf.cbBuffer; return result; } /* * Curl_auth_create_spnego_message() * * This is used to generate an already encoded SPNEGO (Negotiate) response * message ready for sending to the recipient. * * Parameters: * * data [in] - The session handle. * nego [in/out] - The Negotiate data struct being used and modified. * outptr [in/out] - The address where a pointer to newly allocated memory * holding the result will be stored upon completion. * outlen [out] - The length of the output message. * * Returns CURLE_OK on success. */ CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, struct negotiatedata *nego, char **outptr, size_t *outlen) { CURLcode result; /* Base64 encode the already generated response */ result = Curl_base64_encode(data, (const char *) nego->output_token, nego->output_token_length, outptr, outlen); if(result) return result; if(!*outptr || !*outlen) { free(*outptr); return CURLE_REMOTE_ACCESS_DENIED; } return CURLE_OK; } /* * Curl_auth_cleanup_spnego() * * This is used to clean up the SPNEGO (Negotiate) specific data. * * Parameters: * * nego [in/out] - The Negotiate data struct being cleaned up. * */ void Curl_auth_cleanup_spnego(struct negotiatedata *nego) { /* Free our security context */ if(nego->context) { s_pSecFn->DeleteSecurityContext(nego->context); free(nego->context); nego->context = NULL; } /* Free our credentials handle */ if(nego->credentials) { s_pSecFn->FreeCredentialsHandle(nego->credentials); free(nego->credentials); nego->credentials = NULL; } /* Free our identity */ Curl_sspi_free_identity(nego->p_identity); nego->p_identity = NULL; /* Free the SPN and output token */ Curl_safefree(nego->spn); Curl_safefree(nego->output_token); /* Reset any variables */ nego->status = 0; nego->token_max = 0; nego->noauthpersist = FALSE; nego->havenoauthpersist = FALSE; nego->havenegdata = FALSE; nego->havemultiplerequests = FALSE; } #endif /* USE_WINDOWS_SSPI && USE_SPNEGO */
YifuLiu/AliOS-Things
components/curl/lib/vauth/spnego_sspi.c
C
apache-2.0
11,523
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014 - 2019, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "vauth.h" #include "curl_multibyte.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* * Curl_auth_build_spn() * * This is used to build a SPN string in the following formats: * * service/host@realm (Not currently used) * service/host (Not used by GSS-API) * service@realm (Not used by Windows SSPI) * * Parameters: * * service [in] - The service type such as http, smtp, pop or imap. * host [in] - The host name. * realm [in] - The realm. * * Returns a pointer to the newly allocated SPN. */ #if !defined(USE_WINDOWS_SSPI) char *Curl_auth_build_spn(const char *service, const char *host, const char *realm) { char *spn = NULL; /* Generate our SPN */ if(host && realm) spn = aprintf("%s/%s@%s", service, host, realm); else if(host) spn = aprintf("%s/%s", service, host); else if(realm) spn = aprintf("%s@%s", service, realm); /* Return our newly allocated SPN */ return spn; } #else TCHAR *Curl_auth_build_spn(const char *service, const char *host, const char *realm) { char *utf8_spn = NULL; TCHAR *tchar_spn = NULL; (void) realm; /* Note: We could use DsMakeSPN() or DsClientMakeSpnForTargetServer() rather than doing this ourselves but the first is only available in Windows XP and Windows Server 2003 and the latter is only available in Windows 2000 but not Windows95/98/ME or Windows NT4.0 unless the Active Directory Client Extensions are installed. As such it is far simpler for us to formulate the SPN instead. */ /* Generate our UTF8 based SPN */ utf8_spn = aprintf("%s/%s", service, host); if(!utf8_spn) { return NULL; } /* Allocate our TCHAR based SPN */ tchar_spn = Curl_convert_UTF8_to_tchar(utf8_spn); if(!tchar_spn) { free(utf8_spn); return NULL; } /* Release the UTF8 variant when operating with Unicode */ Curl_unicodefree(utf8_spn); /* Return our newly allocated SPN */ return tchar_spn; } #endif /* USE_WINDOWS_SSPI */ /* * Curl_auth_user_contains_domain() * * This is used to test if the specified user contains a Windows domain name as * follows: * * Domain\User (Down-level Logon Name) * Domain/User (curl Down-level format - for compatibility with existing code) * User@Domain (User Principal Name) * * Note: The user name may be empty when using a GSS-API library or Windows * SSPI as the user and domain are either obtained from the credentials cache * when using GSS-API or via the currently logged in user's credentials when * using Windows SSPI. * * Parameters: * * user [in] - The user name. * * Returns TRUE on success; otherwise FALSE. */ bool Curl_auth_user_contains_domain(const char *user) { bool valid = FALSE; if(user && *user) { /* Check we have a domain name or UPN present */ char *p = strpbrk(user, "\\/@"); valid = (p != NULL && p > user && p < user + strlen(user) - 1 ? TRUE : FALSE); } #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) else /* User and domain are obtained from the GSS-API credentials cache or the currently logged in user from Windows */ valid = TRUE; #endif return valid; }
YifuLiu/AliOS-Things
components/curl/lib/vauth/vauth.c
C
apache-2.0
4,414
#ifndef HEADER_CURL_VAUTH_H #define HEADER_CURL_VAUTH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014 - 2019, Steve Holme, <steve_holme@hotmail.com>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <curl/curl.h> struct Curl_easy; #if !defined(CURL_DISABLE_CRYPTO_AUTH) struct digestdata; #endif #if defined(USE_NTLM) struct ntlmdata; #endif #if defined(USE_KERBEROS5) struct kerberos5data; #endif #if (defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)) && defined(USE_SPNEGO) struct negotiatedata; #endif #if defined(USE_WINDOWS_SSPI) #define GSS_ERROR(status) (status & 0x80000000) #endif /* This is used to build a SPN string */ #if !defined(USE_WINDOWS_SSPI) char *Curl_auth_build_spn(const char *service, const char *host, const char *realm); #else TCHAR *Curl_auth_build_spn(const char *service, const char *host, const char *realm); #endif /* This is used to test if the user contains a Windows domain name */ bool Curl_auth_user_contains_domain(const char *user); /* This is used to generate a base64 encoded PLAIN cleartext message */ CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, const char *authzid, const char *authcid, const char *passwd, char **outptr, size_t *outlen); /* This is used to generate a base64 encoded LOGIN cleartext message */ CURLcode Curl_auth_create_login_message(struct Curl_easy *data, const char *valuep, char **outptr, size_t *outlen); /* This is used to generate a base64 encoded EXTERNAL cleartext message */ CURLcode Curl_auth_create_external_message(struct Curl_easy *data, const char *user, char **outptr, size_t *outlen); #if !defined(CURL_DISABLE_CRYPTO_AUTH) /* This is used to decode a CRAM-MD5 challenge message */ CURLcode Curl_auth_decode_cram_md5_message(const char *chlg64, char **outptr, size_t *outlen); /* This is used to generate a CRAM-MD5 response message */ CURLcode Curl_auth_create_cram_md5_message(struct Curl_easy *data, const char *chlg, const char *userp, const char *passwdp, char **outptr, size_t *outlen); /* This is used to evaluate if DIGEST is supported */ bool Curl_auth_is_digest_supported(void); /* This is used to generate a base64 encoded DIGEST-MD5 response message */ CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data, const char *chlg64, const char *userp, const char *passwdp, const char *service, char **outptr, size_t *outlen); /* This is used to decode a HTTP DIGEST challenge message */ CURLcode Curl_auth_decode_digest_http_message(const char *chlg, struct digestdata *digest); /* This is used to generate a HTTP DIGEST response message */ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data, const char *userp, const char *passwdp, const unsigned char *request, const unsigned char *uri, struct digestdata *digest, char **outptr, size_t *outlen); /* This is used to clean up the digest specific data */ void Curl_auth_digest_cleanup(struct digestdata *digest); #endif /* !CURL_DISABLE_CRYPTO_AUTH */ #if defined(USE_NTLM) /* This is used to evaluate if NTLM is supported */ bool Curl_auth_is_ntlm_supported(void); /* This is used to generate a base64 encoded NTLM type-1 message */ CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *host, struct ntlmdata *ntlm, char **outptr, size_t *outlen); /* This is used to decode a base64 encoded NTLM type-2 message */ CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data, const char *type2msg, struct ntlmdata *ntlm); /* This is used to generate a base64 encoded NTLM type-3 message */ CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data, const char *userp, const char *passwdp, struct ntlmdata *ntlm, char **outptr, size_t *outlen); /* This is used to clean up the NTLM specific data */ void Curl_auth_cleanup_ntlm(struct ntlmdata *ntlm); #endif /* USE_NTLM */ /* This is used to generate a base64 encoded OAuth 2.0 message */ CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_easy *data, const char *user, const char *host, const long port, const char *bearer, char **outptr, size_t *outlen); /* This is used to generate a base64 encoded XOAuth 2.0 message */ CURLcode Curl_auth_create_xoauth_bearer_message(struct Curl_easy *data, const char *user, const char *bearer, char **outptr, size_t *outlen); #if defined(USE_KERBEROS5) /* This is used to evaluate if GSSAPI (Kerberos V5) is supported */ bool Curl_auth_is_gssapi_supported(void); /* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token message */ CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data, const char *userp, const char *passwdp, const char *service, const char *host, const bool mutual, const char *chlg64, struct kerberos5data *krb5, char **outptr, size_t *outlen); /* This is used to generate a base64 encoded GSSAPI (Kerberos V5) security token message */ CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data, const char *input, struct kerberos5data *krb5, char **outptr, size_t *outlen); /* This is used to clean up the GSSAPI specific data */ void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5); #endif /* USE_KERBEROS5 */ #if defined(USE_SPNEGO) /* This is used to evaluate if SPNEGO (Negotiate) is supported */ bool Curl_auth_is_spnego_supported(void); /* This is used to decode a base64 encoded SPNEGO (Negotiate) challenge message */ CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data, const char *user, const char *passwood, const char *service, const char *host, const char *chlg64, struct negotiatedata *nego); /* This is used to generate a base64 encoded SPNEGO (Negotiate) response message */ CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data, struct negotiatedata *nego, char **outptr, size_t *outlen); /* This is used to clean up the SPNEGO specifiec data */ void Curl_auth_cleanup_spnego(struct negotiatedata *nego); #endif /* USE_SPNEGO */ #endif /* HEADER_CURL_VAUTH_H */
YifuLiu/AliOS-Things
components/curl/lib/vauth/vauth.h
C
apache-2.0
9,903
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "vtls/vtls.h" #include "http2.h" #include "ssh.h" #include "curl_printf.h" #ifdef USE_ARES # if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ (defined(WIN32) || defined(__SYMBIAN32__)) # define CARES_STATICLIB # endif # include <ares.h> #endif #ifdef USE_LIBIDN2 #include <idn2.h> #endif #ifdef USE_LIBPSL #include <libpsl.h> #endif #if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS) #include <iconv.h> #endif #ifdef USE_LIBRTMP #include <librtmp/rtmp.h> #endif #ifdef USE_LIBSSH2 #include <libssh2.h> #endif #ifdef HAVE_LIBSSH2_VERSION /* get it run-time if possible */ #define CURL_LIBSSH2_VERSION libssh2_version(0) #else /* use build-time if run-time not possible */ #define CURL_LIBSSH2_VERSION LIBSSH2_VERSION #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #ifdef __SYMBIAN32__ /* zlib pollutes the namespace with this definition */ #undef WIN32 #endif #endif #ifdef HAVE_BROTLI #include <brotli/decode.h> #endif void Curl_version_init(void); /* For thread safety purposes this function is called by global_init so that the static data in both version functions is initialized. */ void Curl_version_init(void) { curl_version(); curl_version_info(CURLVERSION_NOW); } #ifdef HAVE_BROTLI static size_t brotli_version(char *buf, size_t bufsz) { uint32_t brotli_version = BrotliDecoderVersion(); unsigned int major = brotli_version >> 24; unsigned int minor = (brotli_version & 0x00FFFFFF) >> 12; unsigned int patch = brotli_version & 0x00000FFF; return msnprintf(buf, bufsz, "%u.%u.%u", major, minor, patch); } #endif char *curl_version(void) { static bool initialized; static char version[200]; char *ptr = version; size_t len; size_t left = sizeof(version); if(initialized) return version; strcpy(ptr, LIBCURL_NAME "/" LIBCURL_VERSION); len = strlen(ptr); left -= len; ptr += len; if(left > 1) { len = Curl_ssl_version(ptr + 1, left - 1); if(len > 0) { *ptr = ' '; left -= ++len; ptr += len; } } #ifdef HAVE_LIBZ len = msnprintf(ptr, left, " zlib/%s", zlibVersion()); left -= len; ptr += len; #endif #ifdef HAVE_BROTLI len = msnprintf(ptr, left, "%s", " brotli/"); left -= len; ptr += len; len = brotli_version(ptr, left); left -= len; ptr += len; #endif #ifdef USE_ARES /* this function is only present in c-ares, not in the original ares */ len = msnprintf(ptr, left, " c-ares/%s", ares_version(NULL)); left -= len; ptr += len; #endif #ifdef USE_LIBIDN2 if(idn2_check_version(IDN2_VERSION)) { len = msnprintf(ptr, left, " libidn2/%s", idn2_check_version(NULL)); left -= len; ptr += len; } #endif #ifdef USE_LIBPSL len = msnprintf(ptr, left, " libpsl/%s", psl_get_version()); left -= len; ptr += len; #endif #ifdef USE_WIN32_IDN len = msnprintf(ptr, left, " WinIDN"); left -= len; ptr += len; #endif #if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS) #ifdef _LIBICONV_VERSION len = msnprintf(ptr, left, " iconv/%d.%d", _LIBICONV_VERSION >> 8, _LIBICONV_VERSION & 255); #else /* version unknown */ len = msnprintf(ptr, left, " iconv"); #endif /* _LIBICONV_VERSION */ left -= len; ptr += len; #endif #ifdef USE_LIBSSH2 len = msnprintf(ptr, left, " libssh2/%s", CURL_LIBSSH2_VERSION); left -= len; ptr += len; #endif #ifdef USE_LIBSSH len = msnprintf(ptr, left, " libssh/%s", CURL_LIBSSH_VERSION); left -= len; ptr += len; #endif #ifdef USE_NGHTTP2 len = Curl_http2_ver(ptr, left); left -= len; ptr += len; #endif #ifdef USE_LIBRTMP { char suff[2]; if(RTMP_LIB_VERSION & 0xff) { suff[0] = (RTMP_LIB_VERSION & 0xff) + 'a' - 1; suff[1] = '\0'; } else suff[0] = '\0'; msnprintf(ptr, left, " librtmp/%d.%d%s", RTMP_LIB_VERSION >> 16, (RTMP_LIB_VERSION >> 8) & 0xff, suff); /* If another lib version is added below this one, this code would also have to do: len = what msnprintf() returned left -= len; ptr += len; */ } #endif /* Silent scan-build even if librtmp is not enabled. */ (void) left; (void) ptr; initialized = true; return version; } /* data for curl_version_info Keep the list sorted alphabetically. It is also written so that each protocol line has its own #if line to make things easier on the eye. */ static const char * const protocols[] = { #ifndef CURL_DISABLE_DICT "dict", #endif #ifndef CURL_DISABLE_FILE "file", #endif #ifndef CURL_DISABLE_FTP "ftp", #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) "ftps", #endif #ifndef CURL_DISABLE_GOPHER "gopher", #endif #ifndef CURL_DISABLE_HTTP "http", #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) "https", #endif #ifndef CURL_DISABLE_IMAP "imap", #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP) "imaps", #endif #ifndef CURL_DISABLE_LDAP "ldap", #if !defined(CURL_DISABLE_LDAPS) && \ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) "ldaps", #endif #endif #ifndef CURL_DISABLE_POP3 "pop3", #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_POP3) "pop3s", #endif #ifdef USE_LIBRTMP "rtmp", #endif #ifndef CURL_DISABLE_RTSP "rtsp", #endif #if defined(USE_SSH) "scp", "sftp", #endif #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \ (CURL_SIZEOF_CURL_OFF_T > 4) && \ (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO)) "smb", # ifdef USE_SSL "smbs", # endif #endif #ifndef CURL_DISABLE_SMTP "smtp", #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP) "smtps", #endif #ifndef CURL_DISABLE_TELNET "telnet", #endif #ifndef CURL_DISABLE_TFTP "tftp", #endif NULL }; static curl_version_info_data version_info = { CURLVERSION_NOW, LIBCURL_VERSION, LIBCURL_VERSION_NUM, OS, /* as found by configure or set by hand at build-time */ 0 /* features is 0 by default */ #ifdef ENABLE_IPV6 | CURL_VERSION_IPV6 #endif #ifdef USE_SSL | CURL_VERSION_SSL #endif #ifdef USE_NTLM | CURL_VERSION_NTLM #endif #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \ defined(NTLM_WB_ENABLED) | CURL_VERSION_NTLM_WB #endif #ifdef USE_SPNEGO | CURL_VERSION_SPNEGO #endif #ifdef USE_KERBEROS5 | CURL_VERSION_KERBEROS5 #endif #ifdef HAVE_GSSAPI | CURL_VERSION_GSSAPI #endif #ifdef USE_WINDOWS_SSPI | CURL_VERSION_SSPI #endif #ifdef HAVE_LIBZ | CURL_VERSION_LIBZ #endif #ifdef DEBUGBUILD | CURL_VERSION_DEBUG #endif #ifdef CURLDEBUG | CURL_VERSION_CURLDEBUG #endif #ifdef CURLRES_ASYNCH | CURL_VERSION_ASYNCHDNS #endif #if (CURL_SIZEOF_CURL_OFF_T > 4) && \ ( (SIZEOF_OFF_T > 4) || defined(USE_WIN32_LARGE_FILES) ) | CURL_VERSION_LARGEFILE #endif #if defined(CURL_DOES_CONVERSIONS) | CURL_VERSION_CONV #endif #if defined(USE_TLS_SRP) | CURL_VERSION_TLSAUTH_SRP #endif #if defined(USE_NGHTTP2) | CURL_VERSION_HTTP2 #endif #if defined(USE_UNIX_SOCKETS) | CURL_VERSION_UNIX_SOCKETS #endif #if defined(USE_LIBPSL) | CURL_VERSION_PSL #endif #if defined(CURL_WITH_MULTI_SSL) | CURL_VERSION_MULTI_SSL #endif #if defined(HAVE_BROTLI) | CURL_VERSION_BROTLI #endif #if defined(USE_ALTSVC) | CURL_VERSION_ALTSVC #endif , NULL, /* ssl_version */ 0, /* ssl_version_num, this is kept at zero */ NULL, /* zlib_version */ protocols, NULL, /* c-ares version */ 0, /* c-ares version numerical */ NULL, /* libidn version */ 0, /* iconv version */ NULL, /* ssh lib version */ 0, /* brotli_ver_num */ NULL, /* brotli version */ }; curl_version_info_data *curl_version_info(CURLversion stamp) { static bool initialized; #if defined(USE_SSH) static char ssh_buffer[80]; #endif #ifdef USE_SSL #ifdef CURL_WITH_MULTI_SSL static char ssl_buffer[200]; #else static char ssl_buffer[80]; #endif #endif #ifdef HAVE_BROTLI static char brotli_buffer[80]; #endif if(initialized) return &version_info; #ifdef USE_SSL Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer)); version_info.ssl_version = ssl_buffer; if(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY) version_info.features |= CURL_VERSION_HTTPS_PROXY; else version_info.features &= ~CURL_VERSION_HTTPS_PROXY; #endif #ifdef HAVE_LIBZ version_info.libz_version = zlibVersion(); /* libz left NULL if non-existing */ #endif #ifdef USE_ARES { int aresnum; version_info.ares = ares_version(&aresnum); version_info.ares_num = aresnum; } #endif #ifdef USE_LIBIDN2 /* This returns a version string if we use the given version or later, otherwise it returns NULL */ version_info.libidn = idn2_check_version(IDN2_VERSION); if(version_info.libidn) version_info.features |= CURL_VERSION_IDN; #elif defined(USE_WIN32_IDN) version_info.features |= CURL_VERSION_IDN; #endif #if defined(HAVE_ICONV) && defined(CURL_DOES_CONVERSIONS) #ifdef _LIBICONV_VERSION version_info.iconv_ver_num = _LIBICONV_VERSION; #else /* version unknown */ version_info.iconv_ver_num = -1; #endif /* _LIBICONV_VERSION */ #endif #if defined(USE_LIBSSH2) msnprintf(ssh_buffer, sizeof(ssh_buffer), "libssh2/%s", LIBSSH2_VERSION); version_info.libssh_version = ssh_buffer; #elif defined(USE_LIBSSH) msnprintf(ssh_buffer, sizeof(ssh_buffer), "libssh/%s", CURL_LIBSSH_VERSION); version_info.libssh_version = ssh_buffer; #endif #ifdef HAVE_BROTLI version_info.brotli_ver_num = BrotliDecoderVersion(); brotli_version(brotli_buffer, sizeof(brotli_buffer)); version_info.brotli_version = brotli_buffer; #endif (void)stamp; /* avoid compiler warnings, we don't use this */ initialized = true; return &version_info; }
YifuLiu/AliOS-Things
components/curl/lib/version.c
C
apache-2.0
10,730
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all CyaSSL-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. * */ #include "curl_setup.h" #ifdef USE_CYASSL #define WOLFSSL_OPTIONS_IGNORE_SYS /* CyaSSL's version.h, which should contain only the version, should come before all other CyaSSL includes and be immediately followed by build config aka options.h. https://curl.haxx.se/mail/lib-2015-04/0069.html */ #include <cyassl/version.h> #if defined(HAVE_CYASSL_OPTIONS_H) && (LIBCYASSL_VERSION_HEX > 0x03004008) #if defined(CYASSL_API) || defined(WOLFSSL_API) /* Safety measure. If either is defined some API include was already included and that's a problem since options.h hasn't been included yet. */ #error "CyaSSL API was included before the CyaSSL build options." #endif #include <cyassl/options.h> #endif /* To determine what functions are available we rely on one or both of: - the user's options.h generated by CyaSSL/wolfSSL - the symbols detected by curl's configure Since they are markedly different from one another, and one or the other may not be available, we do some checking below to bring things in sync. */ /* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */ #ifndef HAVE_ALPN #ifdef HAVE_WOLFSSL_USEALPN #define HAVE_ALPN #endif #endif /* WOLFSSL_ALLOW_SSLV3 is wolfSSL's build time symbol for enabling SSLv3 in options.h, but is only seen in >= 3.6.6 since that's when they started disabling SSLv3 by default. */ #ifndef WOLFSSL_ALLOW_SSLV3 #if (LIBCYASSL_VERSION_HEX < 0x03006006) || \ defined(HAVE_WOLFSSLV3_CLIENT_METHOD) #define WOLFSSL_ALLOW_SSLV3 #endif #endif #include <limits.h> #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "strcase.h" #include "x509asn1.h" #include "curl_printf.h" #include "multiif.h" #include <cyassl/openssl/ssl.h> #include <cyassl/ssl.h> #ifdef HAVE_CYASSL_ERROR_SSL_H #include <cyassl/error-ssl.h> #else #include <cyassl/error.h> #endif #include <cyassl/ctaocrypt/random.h> #include <cyassl/ctaocrypt/sha256.h> #include "cyassl.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" #if LIBCYASSL_VERSION_HEX < 0x02007002 /* < 2.7.2 */ #define CYASSL_MAX_ERROR_SZ 80 #endif /* KEEP_PEER_CERT is a product of the presence of build time symbol OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is in wolfSSL's settings.h, and the latter two are build time symbols in options.h. */ #ifndef KEEP_PEER_CERT #if defined(HAVE_CYASSL_GET_PEER_CERTIFICATE) || \ defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \ (defined(OPENSSL_EXTRA) && !defined(NO_CERTS)) #define KEEP_PEER_CERT #endif #endif struct ssl_backend_data { SSL_CTX* ctx; SSL* handle; }; #define BACKEND connssl->backend static Curl_recv cyassl_recv; static Curl_send cyassl_send; static int do_file_type(const char *type) { if(!type || !type[0]) return SSL_FILETYPE_PEM; if(strcasecompare(type, "PEM")) return SSL_FILETYPE_PEM; if(strcasecompare(type, "DER")) return SSL_FILETYPE_ASN1; return -1; } /* * This function loads all the client/CA certificates and CRLs. Setup the TLS * layer and do all necessary magic. */ static CURLcode cyassl_connect_step1(struct connectdata *conn, int sockindex) { char *ciphers; struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; SSL_METHOD* req_method = NULL; curl_socket_t sockfd = conn->sock[sockindex]; #ifdef HAVE_SNI bool sni = FALSE; #define use_sni(x) sni = (x) #else #define use_sni(x) Curl_nop_stmt #endif if(connssl->state == ssl_connection_complete) return CURLE_OK; if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) { failf(data, "CyaSSL does not support to set maximum SSL/TLS version"); return CURLE_SSL_CONNECT_ERROR; } /* check to see if we've been told to use an explicit SSL/TLS version */ switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: #if LIBCYASSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */ /* minimum protocol version is set later after the CTX object is created */ req_method = SSLv23_client_method(); #else infof(data, "CyaSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, " "TLS 1.0 is used exclusively\n"); req_method = TLSv1_client_method(); #endif use_sni(TRUE); break; case CURL_SSLVERSION_TLSv1_0: #ifdef WOLFSSL_ALLOW_TLSV10 req_method = TLSv1_client_method(); use_sni(TRUE); #else failf(data, "CyaSSL does not support TLS 1.0"); return CURLE_NOT_BUILT_IN; #endif break; case CURL_SSLVERSION_TLSv1_1: req_method = TLSv1_1_client_method(); use_sni(TRUE); break; case CURL_SSLVERSION_TLSv1_2: req_method = TLSv1_2_client_method(); use_sni(TRUE); break; case CURL_SSLVERSION_TLSv1_3: #ifdef WOLFSSL_TLS13 req_method = wolfTLSv1_3_client_method(); use_sni(TRUE); break; #else failf(data, "CyaSSL: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; #endif case CURL_SSLVERSION_SSLv3: #ifdef WOLFSSL_ALLOW_SSLV3 req_method = SSLv3_client_method(); use_sni(FALSE); #else failf(data, "CyaSSL does not support SSLv3"); return CURLE_NOT_BUILT_IN; #endif break; case CURL_SSLVERSION_SSLv2: failf(data, "CyaSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } if(!req_method) { failf(data, "SSL: couldn't create a method!"); return CURLE_OUT_OF_MEMORY; } if(BACKEND->ctx) SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = SSL_CTX_new(req_method); if(!BACKEND->ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: #if LIBCYASSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */ /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is whatever minimum version of TLS was built in and at least TLS 1.0. For later library versions that could change (eg TLS 1.0 built in but defaults to TLS 1.1) so we have this short circuit evaluation to find the minimum supported TLS version. We use wolfSSL_CTX_SetMinVersion and not CyaSSL_SetMinVersion because only the former will work before the user's CTX callback is called. */ if((wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1) != 1) && (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_1) != 1) && (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_2) != 1) #ifdef WOLFSSL_TLS13 && (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_3) != 1) #endif ) { failf(data, "SSL: couldn't set the minimum protocol version"); return CURLE_SSL_CONNECT_ERROR; } #endif break; } ciphers = SSL_CONN_CONFIG(cipher_list); if(ciphers) { if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) { failf(data, "failed setting cipher list: %s", ciphers); return CURLE_SSL_CIPHER; } infof(data, "Cipher selection: %s\n", ciphers); } #ifndef NO_FILESYSTEM /* load trusted cacert */ if(SSL_CONN_CONFIG(CAfile)) { if(1 != SSL_CTX_load_verify_locations(BACKEND->ctx, SSL_CONN_CONFIG(CAfile), SSL_CONN_CONFIG(CApath))) { if(SSL_CONN_CONFIG(verifypeer)) { /* Fail if we insist on successfully verifying the server. */ failf(data, "error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s", SSL_CONN_CONFIG(CAfile)? SSL_CONN_CONFIG(CAfile): "none", SSL_CONN_CONFIG(CApath)? SSL_CONN_CONFIG(CApath) : "none"); return CURLE_SSL_CACERT_BADFILE; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", SSL_CONN_CONFIG(CAfile) ? SSL_CONN_CONFIG(CAfile): "none", SSL_CONN_CONFIG(CApath) ? SSL_CONN_CONFIG(CApath): "none"); } /* Load the client certificate, and private key */ if(SSL_SET_OPTION(cert) && SSL_SET_OPTION(key)) { int file_type = do_file_type(SSL_SET_OPTION(cert_type)); if(SSL_CTX_use_certificate_file(BACKEND->ctx, SSL_SET_OPTION(cert), file_type) != 1) { failf(data, "unable to use client certificate (no key or wrong pass" " phrase?)"); return CURLE_SSL_CONNECT_ERROR; } file_type = do_file_type(SSL_SET_OPTION(key_type)); if(SSL_CTX_use_PrivateKey_file(BACKEND->ctx, SSL_SET_OPTION(key), file_type) != 1) { failf(data, "unable to set private key"); return CURLE_SSL_CONNECT_ERROR; } } #endif /* !NO_FILESYSTEM */ /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ SSL_CTX_set_verify(BACKEND->ctx, SSL_CONN_CONFIG(verifypeer)?SSL_VERIFY_PEER: SSL_VERIFY_NONE, NULL); #ifdef HAVE_SNI if(sni) { struct in_addr addr4; #ifdef ENABLE_IPV6 struct in6_addr addr6; #endif const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; size_t hostname_len = strlen(hostname); if((hostname_len < USHRT_MAX) && (0 == Curl_inet_pton(AF_INET, hostname, &addr4)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) && #endif (CyaSSL_CTX_UseSNI(BACKEND->ctx, CYASSL_SNI_HOST_NAME, hostname, (unsigned short)hostname_len) != 1)) { infof(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); } } #endif /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { CURLcode result = CURLE_OK; result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx, data->set.ssl.fsslctxp); if(result) { failf(data, "error signaled by ssl ctx callback"); return result; } } #ifdef NO_FILESYSTEM else if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "SSL: Certificates couldn't be loaded because CyaSSL was built" " with \"no filesystem\". Either disable peer verification" " (insecure) or if you are building an application with libcurl you" " can load certificates via CURLOPT_SSL_CTX_FUNCTION."); return CURLE_SSL_CONNECT_ERROR; } #endif /* Let's make an SSL structure */ if(BACKEND->handle) SSL_free(BACKEND->handle); BACKEND->handle = SSL_new(BACKEND->ctx); if(!BACKEND->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } #ifdef HAVE_ALPN if(conn->bits.tls_enable_alpn) { char protocols[128]; *protocols = '\0'; /* wolfSSL's ALPN protocol name list format is a comma separated string of protocols in descending order of preference, eg: "h2,http/1.1" */ #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { strcpy(protocols + strlen(protocols), NGHTTP2_PROTO_VERSION_ID ","); infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1); infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); if(wolfSSL_UseALPN(BACKEND->handle, protocols, (unsigned)strlen(protocols), WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) { failf(data, "SSL: failed setting ALPN protocols"); return CURLE_SSL_CONNECT_ERROR; } } #endif /* HAVE_ALPN */ /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *ssl_sessionid = NULL; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) { /* we got a session id, use it! */ if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) { char error_buffer[CYASSL_MAX_ERROR_SZ]; Curl_ssl_sessionid_unlock(conn); failf(data, "SSL: SSL_set_session failed: %s", ERR_error_string(SSL_get_error(BACKEND->handle, 0), error_buffer)); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } Curl_ssl_sessionid_unlock(conn); } /* pass the raw socket into the SSL layer */ if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) { failf(data, "SSL: SSL_set_fd failed"); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode cyassl_connect_step2(struct connectdata *conn, int sockindex) { int ret = -1; struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const char * const dispname = SSL_IS_PROXY() ? conn->http_proxy.host.dispname : conn->host.dispname; const char * const pinnedpubkey = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; conn->recv[sockindex] = cyassl_recv; conn->send[sockindex] = cyassl_send; /* Enable RFC2818 checks */ if(SSL_CONN_CONFIG(verifyhost)) { ret = CyaSSL_check_domain_name(BACKEND->handle, hostname); if(ret == SSL_FAILURE) return CURLE_OUT_OF_MEMORY; } ret = SSL_connect(BACKEND->handle); if(ret != 1) { char error_buffer[CYASSL_MAX_ERROR_SZ]; int detail = SSL_get_error(BACKEND->handle, ret); if(SSL_ERROR_WANT_READ == detail) { connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; } else if(SSL_ERROR_WANT_WRITE == detail) { connssl->connecting_state = ssl_connect_2_writing; return CURLE_OK; } /* There is no easy way to override only the CN matching. * This will enable the override of both mismatching SubjectAltNames * as also mismatching CN fields */ else if(DOMAIN_NAME_MISMATCH == detail) { #if 1 failf(data, "\tsubject alt name(s) or common name do not match \"%s\"\n", dispname); return CURLE_PEER_FAILED_VERIFICATION; #else /* When the CyaSSL_check_domain_name() is used and you desire to continue * on a DOMAIN_NAME_MISMATCH, i.e. 'conn->ssl_config.verifyhost == 0', * CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA error. The only * way to do this is currently to switch the CyaSSL_check_domain_name() * in and out based on the 'conn->ssl_config.verifyhost' value. */ if(SSL_CONN_CONFIG(verifyhost)) { failf(data, "\tsubject alt name(s) or common name do not match \"%s\"\n", dispname); return CURLE_PEER_FAILED_VERIFICATION; } else { infof(data, "\tsubject alt name(s) and/or common name do not match \"%s\"\n", dispname); return CURLE_OK; } #endif } #if LIBCYASSL_VERSION_HEX >= 0x02007000 /* 2.7.0 */ else if(ASN_NO_SIGNER_E == detail) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "\tCA signer not available for verification\n"); return CURLE_SSL_CACERT_BADFILE; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "CA signer not available for verification, " "continuing anyway\n"); } } #endif else { failf(data, "SSL_connect failed with error %d: %s", detail, ERR_error_string(detail, error_buffer)); return CURLE_SSL_CONNECT_ERROR; } } if(pinnedpubkey) { #ifdef KEEP_PEER_CERT X509 *x509; const char *x509_der; int x509_der_len; curl_X509certificate x509_parsed; curl_asn1Element *pubkey; CURLcode result; x509 = SSL_get_peer_certificate(BACKEND->handle); if(!x509) { failf(data, "SSL: failed retrieving server certificate"); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } x509_der = (const char *)CyaSSL_X509_get_der(x509, &x509_der_len); if(!x509_der) { failf(data, "SSL: failed retrieving ASN.1 server certificate"); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } memset(&x509_parsed, 0, sizeof(x509_parsed)); if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) return CURLE_SSL_PINNEDPUBKEYNOTMATCH; pubkey = &x509_parsed.subjectPublicKeyInfo; if(!pubkey->header || pubkey->end <= pubkey->header) { failf(data, "SSL: failed retrieving public key from server certificate"); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } result = Curl_pin_peer_pubkey(data, pinnedpubkey, (const unsigned char *)pubkey->header, (size_t)(pubkey->end - pubkey->header)); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; } #else failf(data, "Library lacks pinning support built-in"); return CURLE_NOT_BUILT_IN; #endif } #ifdef HAVE_ALPN if(conn->bits.tls_enable_alpn) { int rc; char *protocol = NULL; unsigned short protocol_len = 0; rc = wolfSSL_ALPN_GetProtocol(BACKEND->handle, &protocol, &protocol_len); if(rc == SSL_SUCCESS) { infof(data, "ALPN, server accepted to use %.*s\n", protocol_len, protocol); if(protocol_len == ALPN_HTTP_1_1_LENGTH && !memcmp(protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) conn->negnpn = CURL_HTTP_VERSION_1_1; #ifdef USE_NGHTTP2 else if(data->set.httpversion >= CURL_HTTP_VERSION_2 && protocol_len == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(protocol, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN)) conn->negnpn = CURL_HTTP_VERSION_2; #endif else infof(data, "ALPN, unrecognized protocol %.*s\n", protocol_len, protocol); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } else if(rc == SSL_ALPN_NOT_FOUND) infof(data, "ALPN, server did not agree to a protocol\n"); else { failf(data, "ALPN, failure getting protocol, error %d", rc); return CURLE_SSL_CONNECT_ERROR; } } #endif /* HAVE_ALPN */ connssl->connecting_state = ssl_connect_3; #if (LIBCYASSL_VERSION_HEX >= 0x03009010) infof(data, "SSL connection using %s / %s\n", wolfSSL_get_version(BACKEND->handle), wolfSSL_get_cipher_name(BACKEND->handle)); #else infof(data, "SSL connected\n"); #endif return CURLE_OK; } static CURLcode cyassl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); if(SSL_SET_OPTION(primary.sessionid)) { bool incache; SSL_SESSION *our_ssl_sessionid; void *old_ssl_sessionid = NULL; our_ssl_sessionid = SSL_get_session(BACKEND->handle); Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex)); if(incache) { if(old_ssl_sessionid != our_ssl_sessionid) { infof(data, "old SSL session ID is stale, removing\n"); Curl_ssl_delsessionid(conn, old_ssl_sessionid); incache = FALSE; } } if(!incache) { result = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0 /* unknown size */, sockindex); if(result) { Curl_ssl_sessionid_unlock(conn); failf(data, "failed to store ssl session"); return result; } } Curl_ssl_sessionid_unlock(conn); } connssl->connecting_state = ssl_connect_done; return result; } static ssize_t cyassl_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; char error_buffer[CYASSL_MAX_ERROR_SZ]; int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; int rc = SSL_write(BACKEND->handle, mem, memlen); if(rc < 0) { int err = SSL_get_error(BACKEND->handle, rc); switch(err) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* there's data pending, re-invoke SSL_write() */ *curlcode = CURLE_AGAIN; return -1; default: failf(conn->data, "SSL write: %s, errno %d", ERR_error_string(err, error_buffer), SOCKERRNO); *curlcode = CURLE_SEND_ERROR; return -1; } } return rc; } static void Curl_cyassl_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(BACKEND->handle) { (void)SSL_shutdown(BACKEND->handle); SSL_free(BACKEND->handle); BACKEND->handle = NULL; } if(BACKEND->ctx) { SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = NULL; } } static ssize_t cyassl_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; char error_buffer[CYASSL_MAX_ERROR_SZ]; int buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; int nread = SSL_read(BACKEND->handle, buf, buffsize); if(nread < 0) { int err = SSL_get_error(BACKEND->handle, nread); switch(err) { case SSL_ERROR_ZERO_RETURN: /* no more data */ break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* there's data pending, re-invoke SSL_read() */ *curlcode = CURLE_AGAIN; return -1; default: failf(conn->data, "SSL read: %s, errno %d", ERR_error_string(err, error_buffer), SOCKERRNO); *curlcode = CURLE_RECV_ERROR; return -1; } } return nread; } static void Curl_cyassl_session_free(void *ptr) { (void)ptr; /* CyaSSL reuses sessions on own, no free */ } static size_t Curl_cyassl_version(char *buffer, size_t size) { #if LIBCYASSL_VERSION_HEX >= 0x03006000 return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version()); #elif defined(WOLFSSL_VERSION) return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION); #elif defined(CYASSL_VERSION) return msnprintf(buffer, size, "CyaSSL/%s", CYASSL_VERSION); #else return msnprintf(buffer, size, "CyaSSL/%s", "<1.8.8"); #endif } static int Curl_cyassl_init(void) { return (CyaSSL_Init() == SSL_SUCCESS); } static void Curl_cyassl_cleanup(void) { CyaSSL_Cleanup(); } static bool Curl_cyassl_data_pending(const struct connectdata* conn, int connindex) { const struct ssl_connect_data *connssl = &conn->ssl[connindex]; if(BACKEND->handle) /* SSL is in use */ return (0 != SSL_pending(BACKEND->handle)) ? TRUE : FALSE; else return FALSE; } /* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */ static int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(BACKEND->handle) { SSL_free(BACKEND->handle); BACKEND->handle = NULL; } return retval; } static CURLcode cyassl_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; time_t timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = cyassl_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if * this connection is part of a multi handle and this loop would * execute again. This permits the owner of a multi handle to * abort a connection attempt before step2 has completed while * ensuring that a client using select() or epoll() will always * have a valid fdset to wait on. */ result = cyassl_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = cyassl_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = cyassl_recv; conn->send[sockindex] = cyassl_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_cyassl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return cyassl_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_cyassl_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = cyassl_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static CURLcode Curl_cyassl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { RNG rng; (void)data; if(InitRng(&rng)) return CURLE_FAILED_INIT; if(length > UINT_MAX) return CURLE_FAILED_INIT; if(RNG_GenerateBlock(&rng, entropy, (unsigned)length)) return CURLE_FAILED_INIT; if(FreeRng(&rng)) return CURLE_FAILED_INIT; return CURLE_OK; } static CURLcode Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum /* output */, size_t unused) { Sha256 SHA256pw; (void)unused; InitSha256(&SHA256pw); Sha256Update(&SHA256pw, tmp, (word32)tmplen); Sha256Final(&SHA256pw, sha256sum); return CURLE_OK; } static void *Curl_cyassl_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->handle; } const struct Curl_ssl Curl_ssl_cyassl = { { CURLSSLBACKEND_WOLFSSL, "WolfSSL" }, /* info */ #ifdef KEEP_PEER_CERT SSLSUPP_PINNEDPUBKEY | #endif SSLSUPP_SSL_CTX, sizeof(struct ssl_backend_data), Curl_cyassl_init, /* init */ Curl_cyassl_cleanup, /* cleanup */ Curl_cyassl_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_cyassl_shutdown, /* shutdown */ Curl_cyassl_data_pending, /* data_pending */ Curl_cyassl_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_cyassl_connect, /* connect */ Curl_cyassl_connect_nonblocking, /* connect_nonblocking */ Curl_cyassl_get_internals, /* get_internals */ Curl_cyassl_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_cyassl_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ Curl_cyassl_sha256sum /* sha256sum */ }; #endif
YifuLiu/AliOS-Things
components/curl/lib/vtls/cyassl.c
C
apache-2.0
32,131
#ifndef HEADER_CURL_CYASSL_H #define HEADER_CURL_CYASSL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_CYASSL extern const struct Curl_ssl Curl_ssl_cyassl; #endif /* USE_CYASSL */ #endif /* HEADER_CURL_CYASSL_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/cyassl.h
C
apache-2.0
1,233
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_GSKIT #include <gskssl.h> #include <qsoasync.h> /* Some symbols are undefined/unsupported on OS400 versions < V7R1. */ #ifndef GSK_SSL_EXTN_SERVERNAME_REQUEST #define GSK_SSL_EXTN_SERVERNAME_REQUEST 230 #endif #ifndef GSK_TLSV10_CIPHER_SPECS #define GSK_TLSV10_CIPHER_SPECS 236 #endif #ifndef GSK_TLSV11_CIPHER_SPECS #define GSK_TLSV11_CIPHER_SPECS 237 #endif #ifndef GSK_TLSV12_CIPHER_SPECS #define GSK_TLSV12_CIPHER_SPECS 238 #endif #ifndef GSK_PROTOCOL_TLSV11 #define GSK_PROTOCOL_TLSV11 437 #endif #ifndef GSK_PROTOCOL_TLSV12 #define GSK_PROTOCOL_TLSV12 438 #endif #ifndef GSK_FALSE #define GSK_FALSE 0 #endif #ifndef GSK_TRUE #define GSK_TRUE 1 #endif #include <limits.h> #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "gskit.h" #include "vtls.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "strcase.h" #include "x509asn1.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* Directions. */ #define SOS_READ 0x01 #define SOS_WRITE 0x02 /* SSL version flags. */ #define CURL_GSKPROTO_SSLV2 0 #define CURL_GSKPROTO_SSLV2_MASK (1 << CURL_GSKPROTO_SSLV2) #define CURL_GSKPROTO_SSLV3 1 #define CURL_GSKPROTO_SSLV3_MASK (1 << CURL_GSKPROTO_SSLV3) #define CURL_GSKPROTO_TLSV10 2 #define CURL_GSKPROTO_TLSV10_MASK (1 << CURL_GSKPROTO_TLSV10) #define CURL_GSKPROTO_TLSV11 3 #define CURL_GSKPROTO_TLSV11_MASK (1 << CURL_GSKPROTO_TLSV11) #define CURL_GSKPROTO_TLSV12 4 #define CURL_GSKPROTO_TLSV12_MASK (1 << CURL_GSKPROTO_TLSV12) #define CURL_GSKPROTO_LAST 5 struct ssl_backend_data { gsk_handle handle; int iocport; int localfd; int remotefd; }; #define BACKEND connssl->backend /* Supported ciphers. */ typedef struct { const char *name; /* Cipher name. */ const char *gsktoken; /* Corresponding token for GSKit String. */ unsigned int versions; /* SSL version flags. */ } gskit_cipher; static const gskit_cipher ciphertable[] = { { "null-md5", "01", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "null-sha", "02", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "exp-rc4-md5", "03", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK }, { "rc4-md5", "04", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "rc4-sha", "05", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "exp-rc2-cbc-md5", "06", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK }, { "exp-des-cbc-sha", "09", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK }, { "des-cbc3-sha", "0A", CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "aes128-sha", "2F", CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "aes256-sha", "35", CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK }, { "null-sha256", "3B", CURL_GSKPROTO_TLSV12_MASK }, { "aes128-sha256", "3C", CURL_GSKPROTO_TLSV12_MASK }, { "aes256-sha256", "3D", CURL_GSKPROTO_TLSV12_MASK }, { "aes128-gcm-sha256", "9C", CURL_GSKPROTO_TLSV12_MASK }, { "aes256-gcm-sha384", "9D", CURL_GSKPROTO_TLSV12_MASK }, { "rc4-md5", "1", CURL_GSKPROTO_SSLV2_MASK }, { "exp-rc4-md5", "2", CURL_GSKPROTO_SSLV2_MASK }, { "rc2-md5", "3", CURL_GSKPROTO_SSLV2_MASK }, { "exp-rc2-md5", "4", CURL_GSKPROTO_SSLV2_MASK }, { "des-cbc-md5", "6", CURL_GSKPROTO_SSLV2_MASK }, { "des-cbc3-md5", "7", CURL_GSKPROTO_SSLV2_MASK }, { (const char *) NULL, (const char *) NULL, 0 } }; static bool is_separator(char c) { /* Return whether character is a cipher list separator. */ switch(c) { case ' ': case '\t': case ':': case ',': case ';': return true; } return false; } static CURLcode gskit_status(struct Curl_easy *data, int rc, const char *procname, CURLcode defcode) { /* Process GSKit status and map it to a CURLcode. */ switch(rc) { case GSK_OK: case GSK_OS400_ASYNCHRONOUS_SOC_INIT: return CURLE_OK; case GSK_KEYRING_OPEN_ERROR: case GSK_OS400_ERROR_NO_ACCESS: return CURLE_SSL_CACERT_BADFILE; case GSK_INSUFFICIENT_STORAGE: return CURLE_OUT_OF_MEMORY; case GSK_ERROR_BAD_V2_CIPHER: case GSK_ERROR_BAD_V3_CIPHER: case GSK_ERROR_NO_CIPHERS: return CURLE_SSL_CIPHER; case GSK_OS400_ERROR_NOT_TRUSTED_ROOT: case GSK_ERROR_CERT_VALIDATION: return CURLE_PEER_FAILED_VERIFICATION; case GSK_OS400_ERROR_TIMED_OUT: return CURLE_OPERATION_TIMEDOUT; case GSK_WOULD_BLOCK: return CURLE_AGAIN; case GSK_OS400_ERROR_NOT_REGISTERED: break; case GSK_ERROR_IO: switch(errno) { case ENOMEM: return CURLE_OUT_OF_MEMORY; default: failf(data, "%s I/O error: %s", procname, strerror(errno)); break; } break; default: failf(data, "%s: %s", procname, gsk_strerror(rc)); break; } return defcode; } static CURLcode set_enum(struct Curl_easy *data, gsk_handle h, GSK_ENUM_ID id, GSK_ENUM_VALUE value, bool unsupported_ok) { int rc = gsk_attribute_set_enum(h, id, value); switch(rc) { case GSK_OK: return CURLE_OK; case GSK_ERROR_IO: failf(data, "gsk_attribute_set_enum() I/O error: %s", strerror(errno)); break; case GSK_ATTRIBUTE_INVALID_ID: if(unsupported_ok) return CURLE_UNSUPPORTED_PROTOCOL; default: failf(data, "gsk_attribute_set_enum(): %s", gsk_strerror(rc)); break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_buffer(struct Curl_easy *data, gsk_handle h, GSK_BUF_ID id, const char *buffer, bool unsupported_ok) { int rc = gsk_attribute_set_buffer(h, id, buffer, 0); switch(rc) { case GSK_OK: return CURLE_OK; case GSK_ERROR_IO: failf(data, "gsk_attribute_set_buffer() I/O error: %s", strerror(errno)); break; case GSK_ATTRIBUTE_INVALID_ID: if(unsupported_ok) return CURLE_UNSUPPORTED_PROTOCOL; default: failf(data, "gsk_attribute_set_buffer(): %s", gsk_strerror(rc)); break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_numeric(struct Curl_easy *data, gsk_handle h, GSK_NUM_ID id, int value) { int rc = gsk_attribute_set_numeric_value(h, id, value); switch(rc) { case GSK_OK: return CURLE_OK; case GSK_ERROR_IO: failf(data, "gsk_attribute_set_numeric_value() I/O error: %s", strerror(errno)); break; default: failf(data, "gsk_attribute_set_numeric_value(): %s", gsk_strerror(rc)); break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_callback(struct Curl_easy *data, gsk_handle h, GSK_CALLBACK_ID id, void *info) { int rc = gsk_attribute_set_callback(h, id, info); switch(rc) { case GSK_OK: return CURLE_OK; case GSK_ERROR_IO: failf(data, "gsk_attribute_set_callback() I/O error: %s", strerror(errno)); break; default: failf(data, "gsk_attribute_set_callback(): %s", gsk_strerror(rc)); break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_ciphers(struct connectdata *conn, gsk_handle h, unsigned int *protoflags) { struct Curl_easy *data = conn->data; const char *cipherlist = SSL_CONN_CONFIG(cipher_list); const char *clp; const gskit_cipher *ctp; int i; int l; bool unsupported; CURLcode result; struct { char *buf; char *ptr; } ciphers[CURL_GSKPROTO_LAST]; /* Compile cipher list into GSKit-compatible cipher lists. */ if(!cipherlist) return CURLE_OK; while(is_separator(*cipherlist)) /* Skip initial separators. */ cipherlist++; if(!*cipherlist) return CURLE_OK; /* We allocate GSKit buffers of the same size as the input string: since GSKit tokens are always shorter than their cipher names, allocated buffers will always be large enough to accommodate the result. */ l = strlen(cipherlist) + 1; memset((char *) ciphers, 0, sizeof(ciphers)); for(i = 0; i < CURL_GSKPROTO_LAST; i++) { ciphers[i].buf = malloc(l); if(!ciphers[i].buf) { while(i--) free(ciphers[i].buf); return CURLE_OUT_OF_MEMORY; } ciphers[i].ptr = ciphers[i].buf; *ciphers[i].ptr = '\0'; } /* Process each cipher in input string. */ unsupported = FALSE; result = CURLE_OK; for(;;) { for(clp = cipherlist; *cipherlist && !is_separator(*cipherlist);) cipherlist++; l = cipherlist - clp; if(!l) break; /* Search the cipher in our table. */ for(ctp = ciphertable; ctp->name; ctp++) if(strncasecompare(ctp->name, clp, l) && !ctp->name[l]) break; if(!ctp->name) { failf(data, "Unknown cipher %.*s", l, clp); result = CURLE_SSL_CIPHER; } else { unsupported |= !(ctp->versions & (CURL_GSKPROTO_SSLV2_MASK | CURL_GSKPROTO_SSLV3_MASK | CURL_GSKPROTO_TLSV10_MASK)); for(i = 0; i < CURL_GSKPROTO_LAST; i++) { if(ctp->versions & (1 << i)) { strcpy(ciphers[i].ptr, ctp->gsktoken); ciphers[i].ptr += strlen(ctp->gsktoken); } } } /* Advance to next cipher name or end of string. */ while(is_separator(*cipherlist)) cipherlist++; } /* Disable protocols with empty cipher lists. */ for(i = 0; i < CURL_GSKPROTO_LAST; i++) { if(!(*protoflags & (1 << i)) || !ciphers[i].buf[0]) { *protoflags &= ~(1 << i); ciphers[i].buf[0] = '\0'; } } /* Try to set-up TLSv1.1 and TLSv2.1 ciphers. */ if(*protoflags & CURL_GSKPROTO_TLSV11_MASK) { result = set_buffer(data, h, GSK_TLSV11_CIPHER_SPECS, ciphers[CURL_GSKPROTO_TLSV11].buf, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) { result = CURLE_OK; if(unsupported) { failf(data, "TLSv1.1-only ciphers are not yet supported"); result = CURLE_SSL_CIPHER; } } } if(!result && (*protoflags & CURL_GSKPROTO_TLSV12_MASK)) { result = set_buffer(data, h, GSK_TLSV12_CIPHER_SPECS, ciphers[CURL_GSKPROTO_TLSV12].buf, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) { result = CURLE_OK; if(unsupported) { failf(data, "TLSv1.2-only ciphers are not yet supported"); result = CURLE_SSL_CIPHER; } } } /* Try to set-up TLSv1.0 ciphers. If not successful, concatenate them to the SSLv3 ciphers. OS/400 prior to version 7.1 will understand it. */ if(!result && (*protoflags & CURL_GSKPROTO_TLSV10_MASK)) { result = set_buffer(data, h, GSK_TLSV10_CIPHER_SPECS, ciphers[CURL_GSKPROTO_TLSV10].buf, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) { result = CURLE_OK; strcpy(ciphers[CURL_GSKPROTO_SSLV3].ptr, ciphers[CURL_GSKPROTO_TLSV10].ptr); } } /* Set-up other ciphers. */ if(!result && (*protoflags & CURL_GSKPROTO_SSLV3_MASK)) result = set_buffer(data, h, GSK_V3_CIPHER_SPECS, ciphers[CURL_GSKPROTO_SSLV3].buf, FALSE); if(!result && (*protoflags & CURL_GSKPROTO_SSLV2_MASK)) result = set_buffer(data, h, GSK_V2_CIPHER_SPECS, ciphers[CURL_GSKPROTO_SSLV2].buf, FALSE); /* Clean-up. */ for(i = 0; i < CURL_GSKPROTO_LAST; i++) free(ciphers[i].buf); return result; } static int Curl_gskit_init(void) { /* No initialisation needed. */ return 1; } static void Curl_gskit_cleanup(void) { /* Nothing to do. */ } static CURLcode init_environment(struct Curl_easy *data, gsk_handle *envir, const char *appid, const char *file, const char *label, const char *password) { int rc; CURLcode result; gsk_handle h; /* Creates the GSKit environment. */ rc = gsk_environment_open(&h); switch(rc) { case GSK_OK: break; case GSK_INSUFFICIENT_STORAGE: return CURLE_OUT_OF_MEMORY; default: failf(data, "gsk_environment_open(): %s", gsk_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } result = set_enum(data, h, GSK_SESSION_TYPE, GSK_CLIENT_SESSION, FALSE); if(!result && appid) result = set_buffer(data, h, GSK_OS400_APPLICATION_ID, appid, FALSE); if(!result && file) result = set_buffer(data, h, GSK_KEYRING_FILE, file, FALSE); if(!result && label) result = set_buffer(data, h, GSK_KEYRING_LABEL, label, FALSE); if(!result && password) result = set_buffer(data, h, GSK_KEYRING_PW, password, FALSE); if(!result) { /* Locate CAs, Client certificate and key according to our settings. Note: this call may be blocking for some tenths of seconds. */ result = gskit_status(data, gsk_environment_init(h), "gsk_environment_init()", CURLE_SSL_CERTPROBLEM); if(!result) { *envir = h; return result; } } /* Error: rollback. */ gsk_environment_close(&h); return result; } static void cancel_async_handshake(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; Qso_OverlappedIO_t cstat; if(QsoCancelOperation(conn->sock[sockindex], 0) > 0) QsoWaitForIOCompletion(BACKEND->iocport, &cstat, (struct timeval *) NULL); } static void close_async_handshake(struct ssl_connect_data *connssl) { QsoDestroyIOCompletionPort(BACKEND->iocport); BACKEND->iocport = -1; } /* SSL over SSL * Problems: * 1) GSKit can only perform SSL on an AF_INET or AF_INET6 stream socket. To * pipe an SSL stream into another, it is therefore needed to have a pair * of such communicating sockets and handle the pipelining explicitly. * 2) OS/400 socketpair() is only implemented for domain AF_UNIX, thus cannot * be used to produce the pipeline. * The solution is to simulate socketpair() for AF_INET with low-level API * listen(), bind() and connect(). */ static int inetsocketpair(int sv[2]) { int lfd; /* Listening socket. */ int sfd; /* Server socket. */ int cfd; /* Client socket. */ int len; struct sockaddr_in addr1; struct sockaddr_in addr2; /* Create listening socket on a local dynamic port. */ lfd = socket(AF_INET, SOCK_STREAM, 0); if(lfd < 0) return -1; memset((char *) &addr1, 0, sizeof(addr1)); addr1.sin_family = AF_INET; addr1.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr1.sin_port = 0; if(bind(lfd, (struct sockaddr *) &addr1, sizeof(addr1)) || listen(lfd, 2) < 0) { close(lfd); return -1; } /* Get the allocated port. */ len = sizeof(addr1); if(getsockname(lfd, (struct sockaddr *) &addr1, &len) < 0) { close(lfd); return -1; } /* Create the client socket. */ cfd = socket(AF_INET, SOCK_STREAM, 0); if(cfd < 0) { close(lfd); return -1; } /* Request unblocking connection to the listening socket. */ curlx_nonblock(cfd, TRUE); if(connect(cfd, (struct sockaddr *) &addr1, sizeof(addr1)) < 0 && errno != EINPROGRESS) { close(lfd); close(cfd); return -1; } /* Get the client dynamic port for intrusion check below. */ len = sizeof(addr2); if(getsockname(cfd, (struct sockaddr *) &addr2, &len) < 0) { close(lfd); close(cfd); return -1; } /* Accept the incoming connection and get the server socket. */ curlx_nonblock(lfd, TRUE); for(;;) { len = sizeof(addr1); sfd = accept(lfd, (struct sockaddr *) &addr1, &len); if(sfd < 0) { close(lfd); close(cfd); return -1; } /* Check for possible intrusion from an external process. */ if(addr1.sin_addr.s_addr == addr2.sin_addr.s_addr && addr1.sin_port == addr2.sin_port) break; /* Intrusion: reject incoming connection. */ close(sfd); } /* Done, return sockets and succeed. */ close(lfd); curlx_nonblock(cfd, FALSE); sv[0] = cfd; sv[1] = sfd; return 0; } static int pipe_ssloverssl(struct connectdata *conn, int sockindex, int directions) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct ssl_connect_data *connproxyssl = &conn->proxy_ssl[sockindex]; fd_set fds_read; fd_set fds_write; int n; int m; int i; int ret = 0; struct timeval tv = {0, 0}; char buf[CURL_MAX_WRITE_SIZE]; if(!connssl->use || !connproxyssl->use) return 0; /* No SSL over SSL: OK. */ FD_ZERO(&fds_read); FD_ZERO(&fds_write); n = -1; if(directions & SOS_READ) { FD_SET(BACKEND->remotefd, &fds_write); n = BACKEND->remotefd; } if(directions & SOS_WRITE) { FD_SET(BACKEND->remotefd, &fds_read); n = BACKEND->remotefd; FD_SET(conn->sock[sockindex], &fds_write); if(n < conn->sock[sockindex]) n = conn->sock[sockindex]; } i = select(n + 1, &fds_read, &fds_write, NULL, &tv); if(i < 0) return -1; /* Select error. */ if(FD_ISSET(BACKEND->remotefd, &fds_write)) { /* Try getting data from HTTPS proxy and pipe it upstream. */ n = 0; i = gsk_secure_soc_read(connproxyssl->backend->handle, buf, sizeof(buf), &n); switch(i) { case GSK_OK: if(n) { i = write(BACKEND->remotefd, buf, n); if(i < 0) return -1; ret = 1; } break; case GSK_OS400_ERROR_TIMED_OUT: case GSK_WOULD_BLOCK: break; default: return -1; } } if(FD_ISSET(BACKEND->remotefd, &fds_read) && FD_ISSET(conn->sock[sockindex], &fds_write)) { /* Pipe data to HTTPS proxy. */ n = read(BACKEND->remotefd, buf, sizeof(buf)); if(n < 0) return -1; if(n) { i = gsk_secure_soc_write(connproxyssl->backend->handle, buf, n, &m); if(i != GSK_OK || n != m) return -1; ret = 1; } } return ret; /* OK */ } static void close_one(struct ssl_connect_data *connssl, struct connectdata *conn, int sockindex) { if(BACKEND->handle) { gskit_status(conn->data, gsk_secure_soc_close(&BACKEND->handle), "gsk_secure_soc_close()", 0); /* Last chance to drain output. */ while(pipe_ssloverssl(conn, sockindex, SOS_WRITE) > 0) ; BACKEND->handle = (gsk_handle) NULL; if(BACKEND->localfd >= 0) { close(BACKEND->localfd); BACKEND->localfd = -1; } if(BACKEND->remotefd >= 0) { close(BACKEND->remotefd); BACKEND->remotefd = -1; } } if(BACKEND->iocport >= 0) close_async_handshake(connssl); } static ssize_t gskit_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; CURLcode cc = CURLE_SEND_ERROR; int written; if(pipe_ssloverssl(conn, sockindex, SOS_WRITE) >= 0) { cc = gskit_status(data, gsk_secure_soc_write(BACKEND->handle, (char *) mem, (int) len, &written), "gsk_secure_soc_write()", CURLE_SEND_ERROR); if(cc == CURLE_OK) if(pipe_ssloverssl(conn, sockindex, SOS_WRITE) < 0) cc = CURLE_SEND_ERROR; } if(cc != CURLE_OK) { *curlcode = cc; written = -1; } return (ssize_t) written; /* number of bytes */ } static ssize_t gskit_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; struct Curl_easy *data = conn->data; int nread; CURLcode cc = CURLE_RECV_ERROR; if(pipe_ssloverssl(conn, num, SOS_READ) >= 0) { int buffsize = buffersize > (size_t) INT_MAX? INT_MAX: (int) buffersize; cc = gskit_status(data, gsk_secure_soc_read(BACKEND->handle, buf, buffsize, &nread), "gsk_secure_soc_read()", CURLE_RECV_ERROR); } switch(cc) { case CURLE_OK: break; case CURLE_OPERATION_TIMEDOUT: cc = CURLE_AGAIN; default: *curlcode = cc; nread = -1; break; } return (ssize_t) nread; } static CURLcode set_ssl_version_min_max(unsigned int *protoflags, struct connectdata *conn) { struct Curl_easy *data = conn->data; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); long i = ssl_version; switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: ssl_version_max = CURL_SSLVERSION_TLSv1_2; break; } for(; i <= (ssl_version_max >> 16); ++i) { switch(i) { case CURL_SSLVERSION_TLSv1_0: *protoflags |= CURL_GSKPROTO_TLSV10_MASK; break; case CURL_SSLVERSION_TLSv1_1: *protoflags |= CURL_GSKPROTO_TLSV11_MASK; break; case CURL_SSLVERSION_TLSv1_2: *protoflags |= CURL_GSKPROTO_TLSV11_MASK; break; case CURL_SSLVERSION_TLSv1_3: failf(data, "GSKit: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; } } return CURLE_OK; } static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gsk_handle envir; CURLcode result; int rc; const char * const keyringfile = SSL_CONN_CONFIG(CAfile); const char * const keyringpwd = SSL_SET_OPTION(key_passwd); const char * const keyringlabel = SSL_SET_OPTION(cert); const long int ssl_version = SSL_CONN_CONFIG(version); const bool verifypeer = SSL_CONN_CONFIG(verifypeer); const char * const hostname = SSL_IS_PROXY()? conn->http_proxy.host.name: conn->host.name; const char *sni; unsigned int protoflags = 0; Qso_OverlappedIO_t commarea; int sockpair[2]; static const int sobufsize = CURL_MAX_WRITE_SIZE; /* Create SSL environment, start (preferably asynchronous) handshake. */ BACKEND->handle = (gsk_handle) NULL; BACKEND->iocport = -1; BACKEND->localfd = -1; BACKEND->remotefd = -1; /* GSKit supports two ways of specifying an SSL context: either by * application identifier (that should have been defined at the system * level) or by keyring file, password and certificate label. * Local certificate name (CURLOPT_SSLCERT) is used to hold either the * application identifier of the certificate label. * Key password (CURLOPT_KEYPASSWD) holds the keyring password. * It is not possible to have different keyrings for the CAs and the * local certificate. We thus use the CA file (CURLOPT_CAINFO) to identify * the keyring file. * If no key password is given and the keyring is the system keyring, * application identifier mode is tried first, as recommended in IBM doc. */ envir = (gsk_handle) NULL; if(keyringlabel && *keyringlabel && !keyringpwd && !strcmp(keyringfile, CURL_CA_BUNDLE)) { /* Try application identifier mode. */ init_environment(data, &envir, keyringlabel, (const char *) NULL, (const char *) NULL, (const char *) NULL); } if(!envir) { /* Use keyring mode. */ result = init_environment(data, &envir, (const char *) NULL, keyringfile, keyringlabel, keyringpwd); if(result) return result; } /* Create secure session. */ result = gskit_status(data, gsk_secure_soc_open(envir, &BACKEND->handle), "gsk_secure_soc_open()", CURLE_SSL_CONNECT_ERROR); gsk_environment_close(&envir); if(result) return result; /* Establish a pipelining socket pair for SSL over SSL. */ if(conn->proxy_ssl[sockindex].use) { if(inetsocketpair(sockpair)) return CURLE_SSL_CONNECT_ERROR; BACKEND->localfd = sockpair[0]; BACKEND->remotefd = sockpair[1]; setsockopt(BACKEND->localfd, SOL_SOCKET, SO_RCVBUF, (void *) sobufsize, sizeof(sobufsize)); setsockopt(BACKEND->remotefd, SOL_SOCKET, SO_RCVBUF, (void *) sobufsize, sizeof(sobufsize)); setsockopt(BACKEND->localfd, SOL_SOCKET, SO_SNDBUF, (void *) sobufsize, sizeof(sobufsize)); setsockopt(BACKEND->remotefd, SOL_SOCKET, SO_SNDBUF, (void *) sobufsize, sizeof(sobufsize)); curlx_nonblock(BACKEND->localfd, TRUE); curlx_nonblock(BACKEND->remotefd, TRUE); } /* Determine which SSL/TLS version should be enabled. */ sni = hostname; switch(ssl_version) { case CURL_SSLVERSION_SSLv2: protoflags = CURL_GSKPROTO_SSLV2_MASK; sni = NULL; break; case CURL_SSLVERSION_SSLv3: protoflags = CURL_GSKPROTO_SSLV3_MASK; sni = NULL; break; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: protoflags = CURL_GSKPROTO_TLSV10_MASK | CURL_GSKPROTO_TLSV11_MASK | CURL_GSKPROTO_TLSV12_MASK; break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: result = set_ssl_version_min_max(&protoflags, conn); if(result != CURLE_OK) return result; break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } /* Process SNI. Ignore if not supported (on OS400 < V7R1). */ if(sni) { result = set_buffer(data, BACKEND->handle, GSK_SSL_EXTN_SERVERNAME_REQUEST, sni, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) result = CURLE_OK; } /* Set session parameters. */ if(!result) { /* Compute the handshake timeout. Since GSKit granularity is 1 second, we round up the required value. */ long timeout = Curl_timeleft(data, NULL, TRUE); if(timeout < 0) result = CURLE_OPERATION_TIMEDOUT; else result = set_numeric(data, BACKEND->handle, GSK_HANDSHAKE_TIMEOUT, (timeout + 999) / 1000); } if(!result) result = set_numeric(data, BACKEND->handle, GSK_OS400_READ_TIMEOUT, 1); if(!result) result = set_numeric(data, BACKEND->handle, GSK_FD, BACKEND->localfd >= 0? BACKEND->localfd: conn->sock[sockindex]); if(!result) result = set_ciphers(conn, BACKEND->handle, &protoflags); if(!protoflags) { failf(data, "No SSL protocol/cipher combination enabled"); result = CURLE_SSL_CIPHER; } if(!result) result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_SSLV2, (protoflags & CURL_GSKPROTO_SSLV2_MASK)? GSK_PROTOCOL_SSLV2_ON: GSK_PROTOCOL_SSLV2_OFF, FALSE); if(!result) result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_SSLV3, (protoflags & CURL_GSKPROTO_SSLV3_MASK)? GSK_PROTOCOL_SSLV3_ON: GSK_PROTOCOL_SSLV3_OFF, FALSE); if(!result) result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV1, (protoflags & CURL_GSKPROTO_TLSV10_MASK)? GSK_PROTOCOL_TLSV1_ON: GSK_PROTOCOL_TLSV1_OFF, FALSE); if(!result) { result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV11, (protoflags & CURL_GSKPROTO_TLSV11_MASK)? GSK_TRUE: GSK_FALSE, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) { result = CURLE_OK; if(protoflags == CURL_GSKPROTO_TLSV11_MASK) { failf(data, "TLS 1.1 not yet supported"); result = CURLE_SSL_CIPHER; } } } if(!result) { result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV12, (protoflags & CURL_GSKPROTO_TLSV12_MASK)? GSK_TRUE: GSK_FALSE, TRUE); if(result == CURLE_UNSUPPORTED_PROTOCOL) { result = CURLE_OK; if(protoflags == CURL_GSKPROTO_TLSV12_MASK) { failf(data, "TLS 1.2 not yet supported"); result = CURLE_SSL_CIPHER; } } } if(!result) result = set_enum(data, BACKEND->handle, GSK_SERVER_AUTH_TYPE, verifypeer? GSK_SERVER_AUTH_FULL: GSK_SERVER_AUTH_PASSTHRU, FALSE); if(!result) { /* Start handshake. Try asynchronous first. */ memset(&commarea, 0, sizeof(commarea)); BACKEND->iocport = QsoCreateIOCompletionPort(); if(BACKEND->iocport != -1) { result = gskit_status(data, gsk_secure_soc_startInit(BACKEND->handle, BACKEND->iocport, &commarea), "gsk_secure_soc_startInit()", CURLE_SSL_CONNECT_ERROR); if(!result) { connssl->connecting_state = ssl_connect_2; return CURLE_OK; } else close_async_handshake(connssl); } else if(errno != ENOBUFS) result = gskit_status(data, GSK_ERROR_IO, "QsoCreateIOCompletionPort()", 0); else if(conn->proxy_ssl[sockindex].use) { /* Cannot pipeline while handshaking synchronously. */ result = CURLE_SSL_CONNECT_ERROR; } else { /* No more completion port available. Use synchronous IO. */ result = gskit_status(data, gsk_secure_soc_init(BACKEND->handle), "gsk_secure_soc_init()", CURLE_SSL_CONNECT_ERROR); if(!result) { connssl->connecting_state = ssl_connect_3; return CURLE_OK; } } } /* Error: rollback. */ close_one(connssl, conn, sockindex); return result; } static CURLcode gskit_connect_step2(struct connectdata *conn, int sockindex, bool nonblocking) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; Qso_OverlappedIO_t cstat; struct timeval stmv; CURLcode result; /* Poll or wait for end of SSL asynchronous handshake. */ for(;;) { long timeout_ms = nonblocking? 0: Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) timeout_ms = 0; stmv.tv_sec = timeout_ms / 1000; stmv.tv_usec = (timeout_ms - stmv.tv_sec * 1000) * 1000; switch(QsoWaitForIOCompletion(BACKEND->iocport, &cstat, &stmv)) { case 1: /* Operation complete. */ break; case -1: /* An error occurred: handshake still in progress. */ if(errno == EINTR) { if(nonblocking) return CURLE_OK; continue; /* Retry. */ } if(errno != ETIME) { failf(data, "QsoWaitForIOCompletion() I/O error: %s", strerror(errno)); cancel_async_handshake(conn, sockindex); close_async_handshake(connssl); return CURLE_SSL_CONNECT_ERROR; } /* FALL INTO... */ case 0: /* Handshake in progress, timeout occurred. */ if(nonblocking) return CURLE_OK; cancel_async_handshake(conn, sockindex); close_async_handshake(connssl); return CURLE_OPERATION_TIMEDOUT; } break; } result = gskit_status(data, cstat.returnValue, "SSL handshake", CURLE_SSL_CONNECT_ERROR); if(!result) connssl->connecting_state = ssl_connect_3; close_async_handshake(connssl); return result; } static CURLcode gskit_connect_step3(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; const gsk_cert_data_elem *cdev; int cdec; const gsk_cert_data_elem *p; const char *cert = (const char *) NULL; const char *certend; const char *ptr; CURLcode result; /* SSL handshake done: gather certificate info and verify host. */ if(gskit_status(data, gsk_attribute_get_cert_info(BACKEND->handle, GSK_PARTNER_CERT_INFO, &cdev, &cdec), "gsk_attribute_get_cert_info()", CURLE_SSL_CONNECT_ERROR) == CURLE_OK) { int i; infof(data, "Server certificate:\n"); p = cdev; for(i = 0; i++ < cdec; p++) switch(p->cert_data_id) { case CERT_BODY_DER: cert = p->cert_data_p; certend = cert + cdev->cert_data_l; break; case CERT_DN_PRINTABLE: infof(data, "\t subject: %.*s\n", p->cert_data_l, p->cert_data_p); break; case CERT_ISSUER_DN_PRINTABLE: infof(data, "\t issuer: %.*s\n", p->cert_data_l, p->cert_data_p); break; case CERT_VALID_FROM: infof(data, "\t start date: %.*s\n", p->cert_data_l, p->cert_data_p); break; case CERT_VALID_TO: infof(data, "\t expire date: %.*s\n", p->cert_data_l, p->cert_data_p); break; } } /* Verify host. */ result = Curl_verifyhost(conn, cert, certend); if(result) return result; /* The only place GSKit can get the whole CA chain is a validation callback where no user data pointer is available. Therefore it's not possible to copy this chain into our structures for CAINFO. However the server certificate may be available, thus we can return info about it. */ if(data->set.ssl.certinfo) { result = Curl_ssl_init_certinfo(data, 1); if(result) return result; if(cert) { result = Curl_extract_certinfo(conn, 0, cert, certend); if(result) return result; } } /* Check pinned public key. */ ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; if(!result && ptr) { curl_X509certificate x509; curl_asn1Element *p; if(Curl_parseX509(&x509, cert, certend)) return CURLE_SSL_PINNEDPUBKEYNOTMATCH; p = &x509.subjectPublicKeyInfo; result = Curl_pin_peer_pubkey(data, ptr, p->header, p->end - p->header); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; } } connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static CURLcode gskit_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long timeout_ms; CURLcode result = CURLE_OK; *done = connssl->state == ssl_connection_complete; if(*done) return CURLE_OK; /* Step 1: create session, start handshake. */ if(connssl->connecting_state == ssl_connect_1) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); result = CURLE_OPERATION_TIMEDOUT; } else result = gskit_connect_step1(conn, sockindex); } /* Handle handshake pipelining. */ if(!result) if(pipe_ssloverssl(conn, sockindex, SOS_READ | SOS_WRITE) < 0) result = CURLE_SSL_CONNECT_ERROR; /* Step 2: check if handshake is over. */ if(!result && connssl->connecting_state == ssl_connect_2) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); result = CURLE_OPERATION_TIMEDOUT; } else result = gskit_connect_step2(conn, sockindex, nonblocking); } /* Handle handshake pipelining. */ if(!result) if(pipe_ssloverssl(conn, sockindex, SOS_READ | SOS_WRITE) < 0) result = CURLE_SSL_CONNECT_ERROR; /* Step 3: gather certificate info, verify host. */ if(!result && connssl->connecting_state == ssl_connect_3) result = gskit_connect_step3(conn, sockindex); if(result) close_one(connssl, conn, sockindex); else if(connssl->connecting_state == ssl_connect_done) { connssl->state = ssl_connection_complete; connssl->connecting_state = ssl_connect_1; conn->recv[sockindex] = gskit_recv; conn->send[sockindex] = gskit_send; *done = TRUE; } return result; } static CURLcode Curl_gskit_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { CURLcode result; result = gskit_connect_common(conn, sockindex, TRUE, done); if(*done || result) conn->ssl[sockindex].connecting_state = ssl_connect_1; return result; } static CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done; conn->ssl[sockindex].connecting_state = ssl_connect_1; result = gskit_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static void Curl_gskit_close(struct connectdata *conn, int sockindex) { close_one(&conn->ssl[sockindex], conn, sockindex); close_one(&conn->proxy_ssl[sockindex], conn, sockindex); } static int Curl_gskit_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; int what; int rc; char buf[120]; if(!BACKEND->handle) return 0; #ifndef CURL_DISABLE_FTP if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE) return 0; #endif close_one(connssl, conn, sockindex); rc = 0; what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT); for(;;) { ssize_t nread; if(what < 0) { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); rc = -1; break; } if(!what) { /* timeout */ failf(data, "SSL shutdown timeout"); break; } /* Something to read, let's do it and hope that it is the close notify alert from the server. No way to gsk_secure_soc_read() now, so use read(). */ nread = read(conn->sock[sockindex], buf, sizeof(buf)); if(nread < 0) { failf(data, "read: %s", strerror(errno)); rc = -1; } if(nread <= 0) break; what = SOCKET_READABLE(conn->sock[sockindex], 0); } return rc; } static size_t Curl_gskit_version(char *buffer, size_t size) { return msnprintf(buffer, size, "GSKit"); } static int Curl_gskit_check_cxn(struct connectdata *cxn) { struct ssl_connect_data *connssl = &cxn->ssl[FIRSTSOCKET]; int err; int errlen; /* The only thing that can be tested here is at the socket level. */ if(!BACKEND->handle) return 0; /* connection has been closed */ err = 0; errlen = sizeof(err); if(getsockopt(cxn->sock[FIRSTSOCKET], SOL_SOCKET, SO_ERROR, (unsigned char *) &err, &errlen) || errlen != sizeof(err) || err) return 0; /* connection has been closed */ return -1; /* connection status unknown */ } static void *Curl_gskit_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->handle; } const struct Curl_ssl Curl_ssl_gskit = { { CURLSSLBACKEND_GSKIT, "gskit" }, /* info */ SSLSUPP_CERTINFO | SSLSUPP_PINNEDPUBKEY, sizeof(struct ssl_backend_data), Curl_gskit_init, /* init */ Curl_gskit_cleanup, /* cleanup */ Curl_gskit_version, /* version */ Curl_gskit_check_cxn, /* check_cxn */ Curl_gskit_shutdown, /* shutdown */ Curl_none_data_pending, /* data_pending */ Curl_none_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_gskit_connect, /* connect */ Curl_gskit_connect_nonblocking, /* connect_nonblocking */ Curl_gskit_get_internals, /* get_internals */ Curl_gskit_close, /* close_one */ Curl_none_close_all, /* close_all */ /* No session handling for GSKit */ Curl_none_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ NULL /* sha256sum */ }; #endif /* USE_GSKIT */
YifuLiu/AliOS-Things
components/curl/lib/vtls/gskit.c
C
apache-2.0
42,031
#ifndef HEADER_CURL_GSKIT_H #define HEADER_CURL_GSKIT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* * This header should only be needed to get included by vtls.c and gskit.c */ #include "urldata.h" #ifdef USE_GSKIT extern const struct Curl_ssl Curl_ssl_gskit; #endif /* USE_GSKIT */ #endif /* HEADER_CURL_GSKIT_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/gskit.h
C
apache-2.0
1,333
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. * * Note: don't use the GnuTLS' *_t variable type names in this source code, * since they were not present in 1.0.X. */ #include "curl_setup.h" #ifdef USE_GNUTLS #include <gnutls/abstract.h> #include <gnutls/gnutls.h> #include <gnutls/x509.h> #ifdef USE_GNUTLS_NETTLE #include <gnutls/crypto.h> #include <nettle/md5.h> #include <nettle/sha2.h> #else #include <gcrypt.h> #endif #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "gtls.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "strcase.h" #include "warnless.h" #include "x509asn1.h" #include "multiif.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* Enable GnuTLS debugging by defining GTLSDEBUG */ /*#define GTLSDEBUG */ #ifdef GTLSDEBUG static void tls_log_func(int level, const char *str) { fprintf(stderr, "|<%d>| %s", level, str); } #endif static bool gtls_inited = FALSE; #if defined(GNUTLS_VERSION_NUMBER) # if (GNUTLS_VERSION_NUMBER >= 0x020c00) # undef gnutls_transport_set_lowat # define gnutls_transport_set_lowat(A,B) Curl_nop_stmt # define USE_GNUTLS_PRIORITY_SET_DIRECT 1 # endif # if (GNUTLS_VERSION_NUMBER >= 0x020c03) # define GNUTLS_MAPS_WINSOCK_ERRORS 1 # endif # if HAVE_GNUTLS_ALPN_SET_PROTOCOLS # define HAS_ALPN # endif # if HAVE_GNUTLS_OCSP_REQ_INIT # define HAS_OCSP # endif # if (GNUTLS_VERSION_NUMBER >= 0x030306) # define HAS_CAPATH # endif #endif #if (GNUTLS_VERSION_NUMBER >= 0x030603) #define HAS_TLS13 #endif #ifdef HAS_OCSP # include <gnutls/ocsp.h> #endif struct ssl_backend_data { gnutls_session_t session; gnutls_certificate_credentials_t cred; #ifdef USE_TLS_SRP gnutls_srp_client_credentials_t srp_client_cred; #endif }; #define BACKEND connssl->backend /* * Custom push and pull callback functions used by GNU TLS to read and write * to the socket. These functions are simple wrappers to send() and recv() * (although here using the sread/swrite macros as defined by * curl_setup_once.h). * We use custom functions rather than the GNU TLS defaults because it allows * us to get specific about the fourth "flags" argument, and to use arbitrary * private data with gnutls_transport_set_ptr if we wish. * * When these custom push and pull callbacks fail, GNU TLS checks its own * session-specific error variable, and when not set also its own global * errno variable, in order to take appropriate action. GNU TLS does not * require that the transport is actually a socket. This implies that for * Windows builds these callbacks should ideally set the session-specific * error variable using function gnutls_transport_set_errno or as a last * resort global errno variable using gnutls_transport_set_global_errno, * with a transport agnostic error value. This implies that some winsock * error translation must take place in these callbacks. * * Paragraph above applies to GNU TLS versions older than 2.12.3, since * this version GNU TLS does its own internal winsock error translation * using system_errno() function. */ #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS) # define gtls_EINTR 4 # define gtls_EIO 5 # define gtls_EAGAIN 11 static int gtls_mapped_sockerrno(void) { switch(SOCKERRNO) { case WSAEWOULDBLOCK: return gtls_EAGAIN; case WSAEINTR: return gtls_EINTR; default: break; } return gtls_EIO; } #endif static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len) { curl_socket_t sock = *(curl_socket_t *)s; ssize_t ret = swrite(sock, buf, len); #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS) if(ret < 0) gnutls_transport_set_global_errno(gtls_mapped_sockerrno()); #endif return ret; } static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len) { curl_socket_t sock = *(curl_socket_t *)s; ssize_t ret = sread(sock, buf, len); #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS) if(ret < 0) gnutls_transport_set_global_errno(gtls_mapped_sockerrno()); #endif return ret; } static ssize_t Curl_gtls_push_ssl(void *s, const void *buf, size_t len) { return gnutls_record_send((gnutls_session_t) s, buf, len); } static ssize_t Curl_gtls_pull_ssl(void *s, void *buf, size_t len) { return gnutls_record_recv((gnutls_session_t) s, buf, len); } /* Curl_gtls_init() * * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that * are not thread-safe and thus this function itself is not thread-safe and * must only be called from within curl_global_init() to keep the thread * situation under control! */ static int Curl_gtls_init(void) { int ret = 1; if(!gtls_inited) { ret = gnutls_global_init()?0:1; #ifdef GTLSDEBUG gnutls_global_set_log_function(tls_log_func); gnutls_global_set_log_level(2); #endif gtls_inited = TRUE; } return ret; } static void Curl_gtls_cleanup(void) { if(gtls_inited) { gnutls_global_deinit(); gtls_inited = FALSE; } } #ifndef CURL_DISABLE_VERBOSE_STRINGS static void showtime(struct Curl_easy *data, const char *text, time_t stamp) { struct tm buffer; const struct tm *tm = &buffer; char str[96]; CURLcode result = Curl_gmtime(stamp, &buffer); if(result) return; msnprintf(str, sizeof(str), "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT", text, Curl_wkday[tm->tm_wday?tm->tm_wday-1:6], tm->tm_mday, Curl_month[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); infof(data, "%s\n", str); } #endif static gnutls_datum_t load_file(const char *file) { FILE *f; gnutls_datum_t loaded_file = { NULL, 0 }; long filelen; void *ptr; f = fopen(file, "rb"); if(!f) return loaded_file; if(fseek(f, 0, SEEK_END) != 0 || (filelen = ftell(f)) < 0 || fseek(f, 0, SEEK_SET) != 0 || !(ptr = malloc((size_t)filelen))) goto out; if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) { free(ptr); goto out; } loaded_file.data = ptr; loaded_file.size = (unsigned int)filelen; out: fclose(f); return loaded_file; } static void unload_file(gnutls_datum_t data) { free(data.data); } /* this function does a SSL/TLS (re-)handshake */ static CURLcode handshake(struct connectdata *conn, int sockindex, bool duringconnect, bool nonblocking) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gnutls_session_t session = BACKEND->session; curl_socket_t sockfd = conn->sock[sockindex]; for(;;) { time_t timeout_ms; int rc; /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, duringconnect); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { int what; curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking?0: timeout_ms?timeout_ms:1000); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) return CURLE_OK; else if(timeout_ms) { /* timeout */ failf(data, "SSL connection timeout at %ld", (long)timeout_ms); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } rc = gnutls_handshake(session); if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { connssl->connecting_state = gnutls_record_get_direction(session)? ssl_connect_2_writing:ssl_connect_2_reading; continue; } else if((rc < 0) && !gnutls_error_is_fatal(rc)) { const char *strerr = NULL; if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) { int alert = gnutls_alert_get(session); strerr = gnutls_alert_get_name(alert); } if(strerr == NULL) strerr = gnutls_strerror(rc); infof(data, "gnutls_handshake() warning: %s\n", strerr); continue; } else if(rc < 0) { const char *strerr = NULL; if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) { int alert = gnutls_alert_get(session); strerr = gnutls_alert_get_name(alert); } if(strerr == NULL) strerr = gnutls_strerror(rc); failf(data, "gnutls_handshake() failed: %s", strerr); return CURLE_SSL_CONNECT_ERROR; } /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } } static gnutls_x509_crt_fmt_t do_file_type(const char *type) { if(!type || !type[0]) return GNUTLS_X509_FMT_PEM; if(strcasecompare(type, "PEM")) return GNUTLS_X509_FMT_PEM; if(strcasecompare(type, "DER")) return GNUTLS_X509_FMT_DER; return -1; } #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT static CURLcode set_ssl_version_min_max(int *list, size_t list_size, struct connectdata *conn) { struct Curl_easy *data = conn->data; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); long i = ssl_version; long protocol_priority_idx = 0; switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: #ifdef HAS_TLS13 ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3; #endif ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; break; } for(; i <= (ssl_version_max >> 16) && protocol_priority_idx < list_size; ++i) { switch(i) { case CURL_SSLVERSION_TLSv1_0: protocol_priority[protocol_priority_idx++] = GNUTLS_TLS1_0; break; case CURL_SSLVERSION_TLSv1_1: protocol_priority[protocol_priority_idx++] = GNUTLS_TLS1_1; break; case CURL_SSLVERSION_TLSv1_2: protocol_priority[protocol_priority_idx++] = GNUTLS_TLS1_2; break; case CURL_SSLVERSION_TLSv1_3: #ifdef HAS_TLS13 protocol_priority[protocol_priority_idx++] = GNUTLS_TLS1_3; break; #else failf(data, "GnuTLS: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; #endif } } return CURLE_OK; } #else #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509" /* If GnuTLS was compiled without support for SRP it will error out if SRP is requested in the priority string, so treat it specially */ #define GNUTLS_SRP "+SRP" static CURLcode set_ssl_version_min_max(const char **prioritylist, struct connectdata *conn) { struct Curl_easy *data = conn->data; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) { ssl_version_max = CURL_SSLVERSION_MAX_DEFAULT; } switch(ssl_version | ssl_version_max) { case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_0: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.0:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_1: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.0:+VERS-TLS1.1:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_2: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.0:+VERS-TLS1.1:+VERS-TLS1.2:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_1: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.1:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_2: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.1:+VERS-TLS1.2:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_2: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.2:" GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_TLSv1_3: #ifdef HAS_TLS13 *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.3:" GNUTLS_SRP; return CURLE_OK; #else failf(data, "GnuTLS: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; #endif case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_DEFAULT: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.0:+VERS-TLS1.1:+VERS-TLS1.2:" #ifdef HAS_TLS13 "+VERS-TLS1.3:" #endif GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_DEFAULT: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.1:+VERS-TLS1.2:" #ifdef HAS_TLS13 "+VERS-TLS1.3:" #endif GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_DEFAULT: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.2:" #ifdef HAS_TLS13 "+VERS-TLS1.3:" #endif GNUTLS_SRP; return CURLE_OK; case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_DEFAULT: *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:" "+VERS-TLS1.2:" #ifdef HAS_TLS13 "+VERS-TLS1.3:" #endif GNUTLS_SRP; return CURLE_OK; } failf(data, "GnuTLS: cannot set ssl protocol"); return CURLE_SSL_CONNECT_ERROR; } #endif static CURLcode gtls_connect_step1(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; unsigned int init_flags; gnutls_session_t session; int rc; bool sni = TRUE; /* default is SNI enabled */ void *transport_ptr = NULL; gnutls_push_func gnutls_transport_push = NULL; gnutls_pull_func gnutls_transport_pull = NULL; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT static const int cipher_priority[] = { /* These two ciphers were added to GnuTLS as late as ver. 3.0.1, but this code path is only ever used for ver. < 2.12.0. GNUTLS_CIPHER_AES_128_GCM, GNUTLS_CIPHER_AES_256_GCM, */ GNUTLS_CIPHER_AES_128_CBC, GNUTLS_CIPHER_AES_256_CBC, GNUTLS_CIPHER_CAMELLIA_128_CBC, GNUTLS_CIPHER_CAMELLIA_256_CBC, GNUTLS_CIPHER_3DES_CBC, }; static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 }; int protocol_priority[] = { 0, 0, 0, 0 }; #else const char *prioritylist; const char *err = NULL; #endif const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; if(connssl->state == ssl_connection_complete) /* to make us tolerant against being called more than once for the same connection */ return CURLE_OK; if(!gtls_inited) Curl_gtls_init(); if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) { failf(data, "GnuTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } else if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv3) sni = FALSE; /* SSLv3 has no SNI */ /* allocate a cred struct */ rc = gnutls_certificate_allocate_credentials(&BACKEND->cred); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } #ifdef USE_TLS_SRP if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) { infof(data, "Using TLS-SRP username: %s\n", SSL_SET_OPTION(username)); rc = gnutls_srp_allocate_client_credentials( &BACKEND->srp_client_cred); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_srp_allocate_client_cred() failed: %s", gnutls_strerror(rc)); return CURLE_OUT_OF_MEMORY; } rc = gnutls_srp_set_client_credentials(BACKEND->srp_client_cred, SSL_SET_OPTION(username), SSL_SET_OPTION(password)); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_srp_set_client_cred() failed: %s", gnutls_strerror(rc)); return CURLE_BAD_FUNCTION_ARGUMENT; } } #endif if(SSL_CONN_CONFIG(CAfile)) { /* set the trusted CA cert bundle file */ gnutls_certificate_set_verify_flags(BACKEND->cred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT); rc = gnutls_certificate_set_x509_trust_file(BACKEND->cred, SSL_CONN_CONFIG(CAfile), GNUTLS_X509_FMT_PEM); if(rc < 0) { infof(data, "error reading ca cert file %s (%s)\n", SSL_CONN_CONFIG(CAfile), gnutls_strerror(rc)); if(SSL_CONN_CONFIG(verifypeer)) return CURLE_SSL_CACERT_BADFILE; } else infof(data, "found %d certificates in %s\n", rc, SSL_CONN_CONFIG(CAfile)); } #ifdef HAS_CAPATH if(SSL_CONN_CONFIG(CApath)) { /* set the trusted CA cert directory */ rc = gnutls_certificate_set_x509_trust_dir(BACKEND->cred, SSL_CONN_CONFIG(CApath), GNUTLS_X509_FMT_PEM); if(rc < 0) { infof(data, "error reading ca cert file %s (%s)\n", SSL_CONN_CONFIG(CApath), gnutls_strerror(rc)); if(SSL_CONN_CONFIG(verifypeer)) return CURLE_SSL_CACERT_BADFILE; } else infof(data, "found %d certificates in %s\n", rc, SSL_CONN_CONFIG(CApath)); } #endif #ifdef CURL_CA_FALLBACK /* use system ca certificate store as fallback */ if(SSL_CONN_CONFIG(verifypeer) && !(SSL_CONN_CONFIG(CAfile) || SSL_CONN_CONFIG(CApath))) { gnutls_certificate_set_x509_system_trust(BACKEND->cred); } #endif if(SSL_SET_OPTION(CRLfile)) { /* set the CRL list file */ rc = gnutls_certificate_set_x509_crl_file(BACKEND->cred, SSL_SET_OPTION(CRLfile), GNUTLS_X509_FMT_PEM); if(rc < 0) { failf(data, "error reading crl file %s (%s)", SSL_SET_OPTION(CRLfile), gnutls_strerror(rc)); return CURLE_SSL_CRL_BADFILE; } else infof(data, "found %d CRL in %s\n", rc, SSL_SET_OPTION(CRLfile)); } /* Initialize TLS session as a client */ init_flags = GNUTLS_CLIENT; #if defined(GNUTLS_NO_TICKETS) /* Disable TLS session tickets */ init_flags |= GNUTLS_NO_TICKETS; #endif rc = gnutls_init(&BACKEND->session, init_flags); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_init() failed: %d", rc); return CURLE_SSL_CONNECT_ERROR; } /* convenient assign */ session = BACKEND->session; if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) && #endif sni && (gnutls_server_name_set(session, GNUTLS_NAME_DNS, hostname, strlen(hostname)) < 0)) infof(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); /* Use default priorities */ rc = gnutls_set_default_priority(session); if(rc != GNUTLS_E_SUCCESS) return CURLE_SSL_CONNECT_ERROR; #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT rc = gnutls_cipher_set_priority(session, cipher_priority); if(rc != GNUTLS_E_SUCCESS) return CURLE_SSL_CONNECT_ERROR; /* Sets the priority on the certificate types supported by gnutls. Priority is higher for types specified before others. After specifying the types you want, you must append a 0. */ rc = gnutls_certificate_type_set_priority(session, cert_type_priority); if(rc != GNUTLS_E_SUCCESS) return CURLE_SSL_CONNECT_ERROR; if(SSL_CONN_CONFIG(cipher_list) != NULL) { failf(data, "can't pass a custom cipher list to older GnuTLS" " versions"); return CURLE_SSL_CONNECT_ERROR; } switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_SSLv3: protocol_priority[0] = GNUTLS_SSL3; break; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: protocol_priority[0] = GNUTLS_TLS1_0; protocol_priority[1] = GNUTLS_TLS1_1; protocol_priority[2] = GNUTLS_TLS1_2; #ifdef HAS_TLS13 protocol_priority[3] = GNUTLS_TLS1_3; #endif break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(protocol_priority, sizeof(protocol_priority)/sizeof(protocol_priority[0]), conn); if(result != CURLE_OK) return result; break; } case CURL_SSLVERSION_SSLv2: failf(data, "GnuTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } rc = gnutls_protocol_set_priority(session, protocol_priority); if(rc != GNUTLS_E_SUCCESS) { failf(data, "Did you pass a valid GnuTLS cipher list?"); return CURLE_SSL_CONNECT_ERROR; } #else /* Ensure +SRP comes at the *end* of all relevant strings so that it can be * removed if a run-time error indicates that SRP is not supported by this * GnuTLS version */ switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_SSLv3: prioritylist = GNUTLS_CIPHERS ":-VERS-TLS-ALL:+VERS-SSL3.0"; break; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:" #ifdef HAS_TLS13 "+VERS-TLS1.3:" #endif GNUTLS_SRP; break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(&prioritylist, conn); if(result != CURLE_OK) return result; break; } case CURL_SSLVERSION_SSLv2: failf(data, "GnuTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } rc = gnutls_priority_set_direct(session, prioritylist, &err); if((rc == GNUTLS_E_INVALID_REQUEST) && err) { if(!strcmp(err, GNUTLS_SRP)) { /* This GnuTLS was probably compiled without support for SRP. * Note that fact and try again without it. */ int validprioritylen = curlx_uztosi(err - prioritylist); char *prioritycopy = strdup(prioritylist); if(!prioritycopy) return CURLE_OUT_OF_MEMORY; infof(data, "This GnuTLS does not support SRP\n"); if(validprioritylen) /* Remove the :+SRP */ prioritycopy[validprioritylen - 1] = 0; rc = gnutls_priority_set_direct(session, prioritycopy, &err); free(prioritycopy); } } if(rc != GNUTLS_E_SUCCESS) { failf(data, "Error %d setting GnuTLS cipher list starting with %s", rc, err); return CURLE_SSL_CONNECT_ERROR; } #endif #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { int cur = 0; gnutls_datum_t protocols[2]; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2 && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) { protocols[cur].data = (unsigned char *)NGHTTP2_PROTO_VERSION_ID; protocols[cur].size = NGHTTP2_PROTO_VERSION_ID_LEN; cur++; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif protocols[cur].data = (unsigned char *)ALPN_HTTP_1_1; protocols[cur].size = ALPN_HTTP_1_1_LENGTH; cur++; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); gnutls_alpn_set_protocols(session, protocols, cur, 0); } #endif if(SSL_SET_OPTION(cert)) { if(SSL_SET_OPTION(key_passwd)) { #if HAVE_GNUTLS_CERTIFICATE_SET_X509_KEY_FILE2 const unsigned int supported_key_encryption_algorithms = GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR | GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES | GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 | GNUTLS_PKCS_USE_PBES2_AES_256; rc = gnutls_certificate_set_x509_key_file2( BACKEND->cred, SSL_SET_OPTION(cert), SSL_SET_OPTION(key) ? SSL_SET_OPTION(key) : SSL_SET_OPTION(cert), do_file_type(SSL_SET_OPTION(cert_type)), SSL_SET_OPTION(key_passwd), supported_key_encryption_algorithms); if(rc != GNUTLS_E_SUCCESS) { failf(data, "error reading X.509 potentially-encrypted key file: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } #else failf(data, "gnutls lacks support for encrypted key files"); return CURLE_SSL_CONNECT_ERROR; #endif } else { if(gnutls_certificate_set_x509_key_file( BACKEND->cred, SSL_SET_OPTION(cert), SSL_SET_OPTION(key) ? SSL_SET_OPTION(key) : SSL_SET_OPTION(cert), do_file_type(SSL_SET_OPTION(cert_type)) ) != GNUTLS_E_SUCCESS) { failf(data, "error reading X.509 key or certificate file"); return CURLE_SSL_CONNECT_ERROR; } } } #ifdef USE_TLS_SRP /* put the credentials to the current session */ if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) { rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP, BACKEND->srp_client_cred); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } } else #endif { rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, BACKEND->cred); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } } if(conn->proxy_ssl[sockindex].use) { transport_ptr = conn->proxy_ssl[sockindex].backend->session; gnutls_transport_push = Curl_gtls_push_ssl; gnutls_transport_pull = Curl_gtls_pull_ssl; } else { /* file descriptor for the socket */ transport_ptr = &conn->sock[sockindex]; gnutls_transport_push = Curl_gtls_push; gnutls_transport_pull = Curl_gtls_pull; } /* set the connection handle */ gnutls_transport_set_ptr(session, transport_ptr); /* register callback functions to send and receive data. */ gnutls_transport_set_push_function(session, gnutls_transport_push); gnutls_transport_set_pull_function(session, gnutls_transport_pull); /* lowat must be set to zero when using custom push and pull functions. */ gnutls_transport_set_lowat(session, 0); #ifdef HAS_OCSP if(SSL_CONN_CONFIG(verifystatus)) { rc = gnutls_ocsp_status_request_enable_client(session, NULL, 0, NULL); if(rc != GNUTLS_E_SUCCESS) { failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc); return CURLE_SSL_CONNECT_ERROR; } } #endif /* This might be a reconnect, so we check for a session ID in the cache to speed up things */ if(SSL_SET_OPTION(primary.sessionid)) { void *ssl_sessionid; size_t ssl_idsize; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize, sockindex)) { /* we got a session id, use it! */ gnutls_session_set_data(session, ssl_sessionid, ssl_idsize); /* Informational message */ infof(data, "SSL re-using session ID\n"); } Curl_ssl_sessionid_unlock(conn); } return CURLE_OK; } static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, gnutls_x509_crt_t cert, const char *pinnedpubkey) { /* Scratch */ size_t len1 = 0, len2 = 0; unsigned char *buff1 = NULL; gnutls_pubkey_t key = NULL; /* Result is returned to caller */ CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; /* if a path wasn't specified, don't pin */ if(NULL == pinnedpubkey) return CURLE_OK; if(NULL == cert) return result; do { int ret; /* Begin Gyrations to get the public key */ gnutls_pubkey_init(&key); ret = gnutls_pubkey_import_x509(key, cert, 0); if(ret < 0) break; /* failed */ ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1); if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0) break; /* failed */ buff1 = malloc(len1); if(NULL == buff1) break; /* failed */ len2 = len1; ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2); if(ret < 0 || len1 != len2) break; /* failed */ /* End Gyrations */ /* The one good exit point */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); } while(0); if(NULL != key) gnutls_pubkey_deinit(key); Curl_safefree(buff1); return result; } static Curl_recv gtls_recv; static Curl_send gtls_send; static CURLcode gtls_connect_step3(struct connectdata *conn, int sockindex) { unsigned int cert_list_size; const gnutls_datum_t *chainp; unsigned int verify_status = 0; gnutls_x509_crt_t x509_cert, x509_issuer; gnutls_datum_t issuerp; char certbuf[256] = ""; /* big enough? */ size_t size; time_t certclock; const char *ptr; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; gnutls_session_t session = BACKEND->session; int rc; #ifdef HAS_ALPN gnutls_datum_t proto; #endif CURLcode result = CURLE_OK; #ifndef CURL_DISABLE_VERBOSE_STRINGS unsigned int algo; unsigned int bits; gnutls_protocol_t version = gnutls_protocol_get_version(session); #endif const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */ ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session), gnutls_cipher_get(session), gnutls_mac_get(session)); infof(data, "SSL connection using %s / %s\n", gnutls_protocol_get_name(version), ptr); /* This function will return the peer's raw certificate (chain) as sent by the peer. These certificates are in raw format (DER encoded for X.509). In case of a X.509 then a certificate list may be present. The first certificate in the list is the peer's certificate, following the issuer's certificate, then the issuer's issuer etc. */ chainp = gnutls_certificate_get_peers(session, &cert_list_size); if(!chainp) { if(SSL_CONN_CONFIG(verifypeer) || SSL_CONN_CONFIG(verifyhost) || SSL_SET_OPTION(issuercert)) { #ifdef USE_TLS_SRP if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP && SSL_SET_OPTION(username) != NULL && !SSL_CONN_CONFIG(verifypeer) && gnutls_cipher_get(session)) { /* no peer cert, but auth is ok if we have SRP user and cipher and no peer verify */ } else { #endif failf(data, "failed to get server cert"); return CURLE_PEER_FAILED_VERIFICATION; #ifdef USE_TLS_SRP } #endif } infof(data, "\t common name: WARNING couldn't obtain\n"); } if(data->set.ssl.certinfo && chainp) { unsigned int i; result = Curl_ssl_init_certinfo(data, cert_list_size); if(result) return result; for(i = 0; i < cert_list_size; i++) { const char *beg = (const char *) chainp[i].data; const char *end = beg + chainp[i].size; result = Curl_extract_certinfo(conn, i, beg, end); if(result) return result; } } if(SSL_CONN_CONFIG(verifypeer)) { /* This function will try to verify the peer's certificate and return its status (trusted, invalid etc.). The value of status should be one or more of the gnutls_certificate_status_t enumerated elements bitwise or'd. To avoid denial of service attacks some default upper limits regarding the certificate key size and chain size are set. To override them use gnutls_certificate_set_verify_limits(). */ rc = gnutls_certificate_verify_peers2(session, &verify_status); if(rc < 0) { failf(data, "server cert verify failed: %d", rc); return CURLE_SSL_CONNECT_ERROR; } /* verify_status is a bitmask of gnutls_certificate_status bits */ if(verify_status & GNUTLS_CERT_INVALID) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "server certificate verification failed. CAfile: %s " "CRLfile: %s", SSL_CONN_CONFIG(CAfile) ? SSL_CONN_CONFIG(CAfile): "none", SSL_SET_OPTION(CRLfile)?SSL_SET_OPTION(CRLfile):"none"); return CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\t server certificate verification FAILED\n"); } else infof(data, "\t server certificate verification OK\n"); } else infof(data, "\t server certificate verification SKIPPED\n"); #ifdef HAS_OCSP if(SSL_CONN_CONFIG(verifystatus)) { if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) { gnutls_datum_t status_request; gnutls_ocsp_resp_t ocsp_resp; gnutls_ocsp_cert_status_t status; gnutls_x509_crl_reason_t reason; rc = gnutls_ocsp_status_request_get(session, &status_request); infof(data, "\t server certificate status verification FAILED\n"); if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) { failf(data, "No OCSP response received"); return CURLE_SSL_INVALIDCERTSTATUS; } if(rc < 0) { failf(data, "Invalid OCSP response received"); return CURLE_SSL_INVALIDCERTSTATUS; } gnutls_ocsp_resp_init(&ocsp_resp); rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request); if(rc < 0) { failf(data, "Invalid OCSP response received"); return CURLE_SSL_INVALIDCERTSTATUS; } (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL, &status, NULL, NULL, NULL, &reason); switch(status) { case GNUTLS_OCSP_CERT_GOOD: break; case GNUTLS_OCSP_CERT_REVOKED: { const char *crl_reason; switch(reason) { default: case GNUTLS_X509_CRLREASON_UNSPECIFIED: crl_reason = "unspecified reason"; break; case GNUTLS_X509_CRLREASON_KEYCOMPROMISE: crl_reason = "private key compromised"; break; case GNUTLS_X509_CRLREASON_CACOMPROMISE: crl_reason = "CA compromised"; break; case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: crl_reason = "affiliation has changed"; break; case GNUTLS_X509_CRLREASON_SUPERSEDED: crl_reason = "certificate superseded"; break; case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: crl_reason = "operation has ceased"; break; case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: crl_reason = "certificate is on hold"; break; case GNUTLS_X509_CRLREASON_REMOVEFROMCRL: crl_reason = "will be removed from delta CRL"; break; case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: crl_reason = "privilege withdrawn"; break; case GNUTLS_X509_CRLREASON_AACOMPROMISE: crl_reason = "AA compromised"; break; } failf(data, "Server certificate was revoked: %s", crl_reason); break; } default: case GNUTLS_OCSP_CERT_UNKNOWN: failf(data, "Server certificate status is unknown"); break; } gnutls_ocsp_resp_deinit(ocsp_resp); return CURLE_SSL_INVALIDCERTSTATUS; } else infof(data, "\t server certificate status verification OK\n"); } else infof(data, "\t server certificate status verification SKIPPED\n"); #endif /* initialize an X.509 certificate structure. */ gnutls_x509_crt_init(&x509_cert); if(chainp) /* convert the given DER or PEM encoded Certificate to the native gnutls_x509_crt_t format */ gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER); if(SSL_SET_OPTION(issuercert)) { gnutls_x509_crt_init(&x509_issuer); issuerp = load_file(SSL_SET_OPTION(issuercert)); gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM); rc = gnutls_x509_crt_check_issuer(x509_cert, x509_issuer); gnutls_x509_crt_deinit(x509_issuer); unload_file(issuerp); if(rc <= 0) { failf(data, "server certificate issuer check failed (IssuerCert: %s)", SSL_SET_OPTION(issuercert)?SSL_SET_OPTION(issuercert):"none"); gnutls_x509_crt_deinit(x509_cert); return CURLE_SSL_ISSUER_ERROR; } infof(data, "\t server certificate issuer check OK (Issuer Cert: %s)\n", SSL_SET_OPTION(issuercert)?SSL_SET_OPTION(issuercert):"none"); } size = sizeof(certbuf); rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME, 0, /* the first and only one */ FALSE, certbuf, &size); if(rc) { infof(data, "error fetching CN from cert:%s\n", gnutls_strerror(rc)); } /* This function will check if the given certificate's subject matches the given hostname. This is a basic implementation of the matching described in RFC2818 (HTTPS), which takes into account wildcards, and the subject alternative name PKIX extension. Returns non zero on success, and zero on failure. */ rc = gnutls_x509_crt_check_hostname(x509_cert, hostname); #if GNUTLS_VERSION_NUMBER < 0x030306 /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP addresses. */ if(!rc) { #ifdef ENABLE_IPV6 #define use_addr in6_addr #else #define use_addr in_addr #endif unsigned char addrbuf[sizeof(struct use_addr)]; size_t addrlen = 0; if(Curl_inet_pton(AF_INET, hostname, addrbuf) > 0) addrlen = 4; #ifdef ENABLE_IPV6 else if(Curl_inet_pton(AF_INET6, hostname, addrbuf) > 0) addrlen = 16; #endif if(addrlen) { unsigned char certaddr[sizeof(struct use_addr)]; int i; for(i = 0; ; i++) { size_t certaddrlen = sizeof(certaddr); int ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr, &certaddrlen, NULL); /* If this happens, it wasn't an IP address. */ if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER) continue; if(ret < 0) break; if(ret != GNUTLS_SAN_IPADDRESS) continue; if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) { rc = 1; break; } } } } #endif if(!rc) { const char * const dispname = SSL_IS_PROXY() ? conn->http_proxy.host.dispname : conn->host.dispname; if(SSL_CONN_CONFIG(verifyhost)) { failf(data, "SSL: certificate subject name (%s) does not match " "target host name '%s'", certbuf, dispname); gnutls_x509_crt_deinit(x509_cert); return CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\t common name: %s (does not match '%s')\n", certbuf, dispname); } else infof(data, "\t common name: %s (matched)\n", certbuf); /* Check for time-based validity */ certclock = gnutls_x509_crt_get_expiration_time(x509_cert); if(certclock == (time_t)-1) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "server cert expiration date verify failed"); gnutls_x509_crt_deinit(x509_cert); return CURLE_SSL_CONNECT_ERROR; } else infof(data, "\t server certificate expiration date verify FAILED\n"); } else { if(certclock < time(NULL)) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "server certificate expiration date has passed."); gnutls_x509_crt_deinit(x509_cert); return CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\t server certificate expiration date FAILED\n"); } else infof(data, "\t server certificate expiration date OK\n"); } certclock = gnutls_x509_crt_get_activation_time(x509_cert); if(certclock == (time_t)-1) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "server cert activation date verify failed"); gnutls_x509_crt_deinit(x509_cert); return CURLE_SSL_CONNECT_ERROR; } else infof(data, "\t server certificate activation date verify FAILED\n"); } else { if(certclock > time(NULL)) { if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "server certificate not activated yet."); gnutls_x509_crt_deinit(x509_cert); return CURLE_PEER_FAILED_VERIFICATION; } else infof(data, "\t server certificate activation date FAILED\n"); } else infof(data, "\t server certificate activation date OK\n"); } ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; if(ptr) { result = pkp_pin_peer_pubkey(data, x509_cert, ptr); if(result != CURLE_OK) { failf(data, "SSL: public key does not match pinned public key!"); gnutls_x509_crt_deinit(x509_cert); return result; } } /* Show: - subject - start date - expire date - common name - issuer */ #ifndef CURL_DISABLE_VERBOSE_STRINGS /* public key algorithm's parameters */ algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits); infof(data, "\t certificate public key: %s\n", gnutls_pk_algorithm_get_name(algo)); /* version of the X.509 certificate. */ infof(data, "\t certificate version: #%d\n", gnutls_x509_crt_get_version(x509_cert)); size = sizeof(certbuf); gnutls_x509_crt_get_dn(x509_cert, certbuf, &size); infof(data, "\t subject: %s\n", certbuf); certclock = gnutls_x509_crt_get_activation_time(x509_cert); showtime(data, "start date", certclock); certclock = gnutls_x509_crt_get_expiration_time(x509_cert); showtime(data, "expire date", certclock); size = sizeof(certbuf); gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size); infof(data, "\t issuer: %s\n", certbuf); #endif gnutls_x509_crt_deinit(x509_cert); #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { rc = gnutls_alpn_get_selected_protocol(session, &proto); if(rc == 0) { infof(data, "ALPN, server accepted to use %.*s\n", proto.size, proto.data); #ifdef USE_NGHTTP2 if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data, NGHTTP2_PROTO_VERSION_ID_LEN)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(proto.size == ALPN_HTTP_1_1_LENGTH && !memcmp(ALPN_HTTP_1_1, proto.data, ALPN_HTTP_1_1_LENGTH)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } } else infof(data, "ALPN, server did not agree to a protocol\n"); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } #endif conn->ssl[sockindex].state = ssl_connection_complete; conn->recv[sockindex] = gtls_recv; conn->send[sockindex] = gtls_send; if(SSL_SET_OPTION(primary.sessionid)) { /* we always unconditionally get the session id here, as even if we already got it from the cache and asked to use it in the connection, it might've been rejected and then a new one is in use now and we need to detect that. */ void *connect_sessionid; size_t connect_idsize = 0; /* get the session ID data size */ gnutls_session_get_data(session, NULL, &connect_idsize); connect_sessionid = malloc(connect_idsize); /* get a buffer for it */ if(connect_sessionid) { bool incache; void *ssl_sessionid; /* extract session ID to the allocated buffer */ gnutls_session_get_data(session, connect_sessionid, &connect_idsize); Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)); if(incache) { /* there was one before in the cache, so instead of risking that the previous one was rejected, we just kill that and store the new */ Curl_ssl_delsessionid(conn, ssl_sessionid); } /* store this session id */ result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize, sockindex); Curl_ssl_sessionid_unlock(conn); if(result) { free(connect_sessionid); result = CURLE_OUT_OF_MEMORY; } } else result = CURLE_OUT_OF_MEMORY; } return result; } /* * This function is called after the TCP connect has completed. Setup the TLS * layer and do all necessary magic. */ /* We use connssl->connecting_state to keep track of the connection status; there are three states: 'ssl_connect_1' (not started yet or complete), 'ssl_connect_2_reading' (waiting for data from server), and 'ssl_connect_2_writing' (waiting to be able to write). */ static CURLcode gtls_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { int rc; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; /* Initiate the connection, if not already done */ if(ssl_connect_1 == connssl->connecting_state) { rc = gtls_connect_step1(conn, sockindex); if(rc) return rc; } rc = handshake(conn, sockindex, TRUE, nonblocking); if(rc) /* handshake() sets its own error message with failf() */ return rc; /* Finish connecting once the handshake is done */ if(ssl_connect_1 == connssl->connecting_state) { rc = gtls_connect_step3(conn, sockindex); if(rc) return rc; } *done = ssl_connect_1 == connssl->connecting_state; return CURLE_OK; } static CURLcode Curl_gtls_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return gtls_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_gtls_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = gtls_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static bool Curl_gtls_data_pending(const struct connectdata *conn, int connindex) { const struct ssl_connect_data *connssl = &conn->ssl[connindex]; bool res = FALSE; if(BACKEND->session && 0 != gnutls_record_check_pending(BACKEND->session)) res = TRUE; connssl = &conn->proxy_ssl[connindex]; if(BACKEND->session && 0 != gnutls_record_check_pending(BACKEND->session)) res = TRUE; return res; } static ssize_t gtls_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; ssize_t rc = gnutls_record_send(BACKEND->session, mem, len); if(rc < 0) { *curlcode = (rc == GNUTLS_E_AGAIN) ? CURLE_AGAIN : CURLE_SEND_ERROR; rc = -1; } return rc; } static void close_one(struct ssl_connect_data *connssl) { if(BACKEND->session) { gnutls_bye(BACKEND->session, GNUTLS_SHUT_RDWR); gnutls_deinit(BACKEND->session); BACKEND->session = NULL; } if(BACKEND->cred) { gnutls_certificate_free_credentials(BACKEND->cred); BACKEND->cred = NULL; } #ifdef USE_TLS_SRP if(BACKEND->srp_client_cred) { gnutls_srp_free_client_credentials(BACKEND->srp_client_cred); BACKEND->srp_client_cred = NULL; } #endif } static void Curl_gtls_close(struct connectdata *conn, int sockindex) { close_one(&conn->ssl[sockindex]); close_one(&conn->proxy_ssl[sockindex]); } /* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */ static int Curl_gtls_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; int retval = 0; struct Curl_easy *data = conn->data; #ifndef CURL_DISABLE_FTP /* This has only been tested on the proftpd server, and the mod_tls code sends a close notify alert without waiting for a close notify alert in response. Thus we wait for a close notify alert from the server, but we do not send one. Let's hope other servers do the same... */ if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) gnutls_bye(BACKEND->session, GNUTLS_SHUT_WR); #endif if(BACKEND->session) { ssize_t result; bool done = FALSE; char buf[120]; while(!done) { int what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT); if(what > 0) { /* Something to read, let's do it and hope that it is the close notify alert from the server */ result = gnutls_record_recv(BACKEND->session, buf, sizeof(buf)); switch(result) { case 0: /* This is the expected response. There was no data but only the close notify alert */ done = TRUE; break; case GNUTLS_E_AGAIN: case GNUTLS_E_INTERRUPTED: infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n"); break; default: retval = -1; done = TRUE; break; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); done = TRUE; } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; done = TRUE; } } gnutls_deinit(BACKEND->session); } gnutls_certificate_free_credentials(BACKEND->cred); #ifdef USE_TLS_SRP if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP && SSL_SET_OPTION(username) != NULL) gnutls_srp_free_client_credentials(BACKEND->srp_client_cred); #endif BACKEND->cred = NULL; BACKEND->session = NULL; return retval; } static ssize_t gtls_recv(struct connectdata *conn, /* connection data */ int num, /* socketindex */ char *buf, /* store read data here */ size_t buffersize, /* max amount to read */ CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; ssize_t ret; ret = gnutls_record_recv(BACKEND->session, buf, buffersize); if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) { *curlcode = CURLE_AGAIN; return -1; } if(ret == GNUTLS_E_REHANDSHAKE) { /* BLOCKING call, this is bad but a work-around for now. Fixing this "the proper way" takes a whole lot of work. */ CURLcode result = handshake(conn, num, FALSE, FALSE); if(result) /* handshake() writes error message on its own */ *curlcode = result; else *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */ return -1; } if(ret < 0) { failf(conn->data, "GnuTLS recv error (%d): %s", (int)ret, gnutls_strerror((int)ret)); *curlcode = CURLE_RECV_ERROR; return -1; } return ret; } static void Curl_gtls_session_free(void *ptr) { free(ptr); } static size_t Curl_gtls_version(char *buffer, size_t size) { return msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL)); } #ifndef USE_GNUTLS_NETTLE static int Curl_gtls_seed(struct Curl_easy *data) { /* we have the "SSL is seeded" boolean static to prevent multiple time-consuming seedings in vain */ static bool ssl_seeded = FALSE; /* Quickly add a bit of entropy */ gcry_fast_random_poll(); if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] || data->set.str[STRING_SSL_EGDSOCKET]) { ssl_seeded = TRUE; } return 0; } #endif /* data might be NULL! */ static CURLcode Curl_gtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { #if defined(USE_GNUTLS_NETTLE) int rc; (void)data; rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length); return rc?CURLE_FAILED_INIT:CURLE_OK; #elif defined(USE_GNUTLS) if(data) Curl_gtls_seed(data); /* Initiate the seed if not already done */ gcry_randomize(entropy, length, GCRY_STRONG_RANDOM); #endif return CURLE_OK; } static CURLcode Curl_gtls_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len) { #if defined(USE_GNUTLS_NETTLE) struct md5_ctx MD5pw; md5_init(&MD5pw); md5_update(&MD5pw, (unsigned int)tmplen, tmp); md5_digest(&MD5pw, (unsigned int)md5len, md5sum); #elif defined(USE_GNUTLS) gcry_md_hd_t MD5pw; gcry_md_open(&MD5pw, GCRY_MD_MD5, 0); gcry_md_write(MD5pw, tmp, tmplen); memcpy(md5sum, gcry_md_read(MD5pw, 0), md5len); gcry_md_close(MD5pw); #endif return CURLE_OK; } static CURLcode Curl_gtls_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum, /* output */ size_t sha256len) { #if defined(USE_GNUTLS_NETTLE) struct sha256_ctx SHA256pw; sha256_init(&SHA256pw); sha256_update(&SHA256pw, (unsigned int)tmplen, tmp); sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum); #elif defined(USE_GNUTLS) gcry_md_hd_t SHA256pw; gcry_md_open(&SHA256pw, GCRY_MD_SHA256, 0); gcry_md_write(SHA256pw, tmp, tmplen); memcpy(sha256sum, gcry_md_read(SHA256pw, 0), sha256len); gcry_md_close(SHA256pw); #endif return CURLE_OK; } static bool Curl_gtls_cert_status_request(void) { #ifdef HAS_OCSP return TRUE; #else return FALSE; #endif } static void *Curl_gtls_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->session; } const struct Curl_ssl Curl_ssl_gnutls = { { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */ SSLSUPP_CA_PATH | SSLSUPP_CERTINFO | SSLSUPP_PINNEDPUBKEY | SSLSUPP_HTTPS_PROXY, sizeof(struct ssl_backend_data), Curl_gtls_init, /* init */ Curl_gtls_cleanup, /* cleanup */ Curl_gtls_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_gtls_shutdown, /* shutdown */ Curl_gtls_data_pending, /* data_pending */ Curl_gtls_random, /* random */ Curl_gtls_cert_status_request, /* cert_status_request */ Curl_gtls_connect, /* connect */ Curl_gtls_connect_nonblocking, /* connect_nonblocking */ Curl_gtls_get_internals, /* get_internals */ Curl_gtls_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_gtls_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_gtls_md5sum, /* md5sum */ Curl_gtls_sha256sum /* sha256sum */ }; #endif /* USE_GNUTLS */
YifuLiu/AliOS-Things
components/curl/lib/vtls/gtls.c
C
apache-2.0
58,184
#ifndef HEADER_CURL_GTLS_H #define HEADER_CURL_GTLS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_GNUTLS #include "urldata.h" extern const struct Curl_ssl Curl_ssl_gnutls; #endif /* USE_GNUTLS */ #endif /* HEADER_CURL_GTLS_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/gtls.h
C
apache-2.0
1,250
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. * */ #include "curl_setup.h" #ifdef USE_MBEDTLS #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <mbedtls/version.h> #if MBEDTLS_VERSION_NUMBER >= 0x02040000 #include <mbedtls/net_sockets.h> #else #include <mbedtls/net.h> #endif #include <mbedtls/ssl.h> #include <mbedtls/certs.h> #include <mbedtls/x509.h> #include <mbedtls/error.h> #ifdef MBEDTLS_ENTROPY_C #include <mbedtls/entropy.h> #endif #include <mbedtls/ctr_drbg.h> #include <mbedtls/sha256.h> #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "mbedtls.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "multiif.h" #include "polarssl_threadlock.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" struct ssl_backend_data { mbedtls_ctr_drbg_context ctr_drbg; #ifdef MBEDTLS_ENTROPY_C mbedtls_entropy_context entropy; #endif mbedtls_ssl_context ssl; int server_fd; mbedtls_x509_crt cacert; mbedtls_x509_crt clicert; mbedtls_x509_crl crl; mbedtls_pk_context pk; mbedtls_ssl_config config; const char *protocols[3]; }; #define BACKEND connssl->backend /* apply threading? */ #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) #define THREADING_SUPPORT #endif #if defined(THREADING_SUPPORT) static mbedtls_entropy_context ts_entropy; static int entropy_init_initialized = 0; /* start of entropy_init_mutex() */ static void entropy_init_mutex(mbedtls_entropy_context *ctx) { /* lock 0 = entropy_init_mutex() */ Curl_polarsslthreadlock_lock_function(0); if(entropy_init_initialized == 0) { mbedtls_entropy_init(ctx); entropy_init_initialized = 1; } Curl_polarsslthreadlock_unlock_function(0); } /* end of entropy_init_mutex() */ /* start of entropy_func_mutex() */ static int entropy_func_mutex(void *data, unsigned char *output, size_t len) { int ret; /* lock 1 = entropy_func_mutex() */ Curl_polarsslthreadlock_lock_function(1); ret = mbedtls_entropy_func(data, output, len); Curl_polarsslthreadlock_unlock_function(1); return ret; } /* end of entropy_func_mutex() */ #endif /* THREADING_SUPPORT */ /* Define this to enable lots of debugging for mbedTLS */ #undef MBEDTLS_DEBUG #ifdef MBEDTLS_DEBUG static void mbed_debug(void *context, int level, const char *f_name, int line_nb, const char *line) { struct Curl_easy *data = NULL; if(!context) return; data = (struct Curl_easy *)context; infof(data, "%s", line); (void) level; } #else #endif /* ALPN for http2? */ #ifdef USE_NGHTTP2 # undef HAS_ALPN # ifdef MBEDTLS_SSL_ALPN # define HAS_ALPN # endif #endif /* * profile */ static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr = { /* Hashes from SHA-1 and above */ MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512), 0xFFFFFFF, /* Any PK alg */ 0xFFFFFFF, /* Any curve */ 1024, /* RSA min key len */ }; /* See https://tls.mbed.org/discussions/generic/ howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der */ #define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE) #define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES) #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) static Curl_recv mbed_recv; static Curl_send mbed_send; static CURLcode mbedtls_version_from_curl(int *mbedver, long version) { switch(version) { case CURL_SSLVERSION_TLSv1_0: *mbedver = MBEDTLS_SSL_MINOR_VERSION_1; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1: *mbedver = MBEDTLS_SSL_MINOR_VERSION_2; return CURLE_OK; case CURL_SSLVERSION_TLSv1_2: *mbedver = MBEDTLS_SSL_MINOR_VERSION_3; return CURLE_OK; case CURL_SSLVERSION_TLSv1_3: break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_ssl_version_min_max(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_1; int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_1; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); CURLcode result = CURLE_OK; switch(ssl_version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_version = CURL_SSLVERSION_TLSv1_0; break; } switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; break; } result = mbedtls_version_from_curl(&mbedtls_ver_min, ssl_version); if(result) { failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); return result; } result = mbedtls_version_from_curl(&mbedtls_ver_max, ssl_version_max >> 16); if(result) { failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); return result; } mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3, mbedtls_ver_min); mbedtls_ssl_conf_max_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3, mbedtls_ver_max); return result; } static CURLcode mbed_connect_step1(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile); #ifdef MBEDTLS_X509_CRT_PARSE_C #ifdef MBEDTLS_FS_IO const bool verifypeer = SSL_CONN_CONFIG(verifypeer); #endif #endif const char * const ssl_capath = SSL_CONN_CONFIG(CApath); char * const ssl_cert = SSL_SET_OPTION(cert); const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile); const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; int ret = -1; char errorbuf[128]; errorbuf[0] = 0; /* mbedTLS only supports SSLv3 and TLSv1 */ if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) { failf(data, "mbedTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } #ifdef THREADING_SUPPORT entropy_init_mutex(&ts_entropy); mbedtls_ctr_drbg_init(&BACKEND->ctr_drbg); #ifdef MBEDTLS_ENTROPY_C ret = mbedtls_ctr_drbg_seed(&BACKEND->ctr_drbg, entropy_func_mutex, &ts_entropy, NULL, 0); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #endif #else #ifdef MBEDTLS_ENTROPY_C mbedtls_entropy_init(&BACKEND->entropy); mbedtls_ctr_drbg_init(&BACKEND->ctr_drbg); ret = mbedtls_ctr_drbg_seed(&BACKEND->ctr_drbg, mbedtls_entropy_func, &BACKEND->entropy, NULL, 0); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #endif #endif /* THREADING_SUPPORT */ /* Load the trusted CA */ mbedtls_x509_crt_init(&BACKEND->cacert); if(ssl_cafile) { #ifdef MBEDTLS_X509_CRT_PARSE_C #ifdef MBEDTLS_FS_IO ret = mbedtls_x509_crt_parse_file(&BACKEND->cacert, ssl_cafile); if(ret<0) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s", ssl_cafile, -ret, errorbuf); if(verifypeer) return CURLE_SSL_CACERT_BADFILE; } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ } if(ssl_capath) { #ifdef MBEDTLS_X509_CRT_PARSE_C #ifdef MBEDTLS_FS_IO ret = mbedtls_x509_crt_parse_path(&BACKEND->cacert, ssl_capath); if(ret<0) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s", ssl_capath, -ret, errorbuf); if(verifypeer) return CURLE_SSL_CACERT_BADFILE; } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ } /* Load the client certificate */ mbedtls_x509_crt_init(&BACKEND->clicert); if(ssl_cert) { #ifdef MBEDTLS_X509_CRT_PARSE_C #ifdef MBEDTLS_FS_IO ret = mbedtls_x509_crt_parse_file(&BACKEND->clicert, ssl_cert); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s", ssl_cert, -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ } /* Load the client private key */ mbedtls_pk_init(&BACKEND->pk); if(SSL_SET_OPTION(key)) { #ifdef MBEDTLS_FS_IO ret = mbedtls_pk_parse_keyfile(&BACKEND->pk, SSL_SET_OPTION(key), SSL_SET_OPTION(key_passwd)); if(ret == 0 && !(mbedtls_pk_can_do(&BACKEND->pk, MBEDTLS_PK_RSA) || mbedtls_pk_can_do(&BACKEND->pk, MBEDTLS_PK_ECKEY))) ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s", SSL_SET_OPTION(key), -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } #endif /* MBEDTLS_FS_IO */ } /* Load the CRL */ mbedtls_x509_crl_init(&BACKEND->crl); if(ssl_crlfile) { #ifdef MBEDTLS_FS_IO ret = mbedtls_x509_crl_parse_file(&BACKEND->crl, ssl_crlfile); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s", ssl_crlfile, -ret, errorbuf); return CURLE_SSL_CRL_BADFILE; } #endif /* MBEDTLS_FS_IO */ } infof(data, "mbedTLS: Connecting to %s:%ld\n", hostname, port); mbedtls_ssl_config_init(&BACKEND->config); mbedtls_ssl_init(&BACKEND->ssl); if(mbedtls_ssl_setup(&BACKEND->ssl, &BACKEND->config)) { failf(data, "mbedTLS: ssl_init failed"); return CURLE_SSL_CONNECT_ERROR; } ret = mbedtls_ssl_config_defaults(&BACKEND->config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if(ret) { failf(data, "mbedTLS: ssl_config failed"); return CURLE_SSL_CONNECT_ERROR; } /* new profile with RSA min key len = 1024 ... */ mbedtls_ssl_conf_cert_profile(&BACKEND->config, &mbedtls_x509_crt_profile_fr); switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1); infof(data, "mbedTLS: Set min SSL version to TLS 1.0\n"); break; case CURL_SSLVERSION_SSLv3: mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0); mbedtls_ssl_conf_max_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0); infof(data, "mbedTLS: Set SSL version to SSLv3\n"); break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(conn, sockindex); if(result != CURLE_OK) return result; break; } default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } mbedtls_ssl_conf_authmode(&BACKEND->config, MBEDTLS_SSL_VERIFY_OPTIONAL); #ifdef MBEDTLS_ENTROPY_C mbedtls_ssl_conf_rng(&BACKEND->config, mbedtls_ctr_drbg_random, &BACKEND->ctr_drbg); #endif mbedtls_ssl_set_bio(&BACKEND->ssl, &conn->sock[sockindex], mbedtls_net_send, mbedtls_net_recv, NULL /* rev_timeout() */); mbedtls_ssl_conf_ciphersuites(&BACKEND->config, mbedtls_ssl_list_ciphersuites()); #if defined(MBEDTLS_SSL_RENEGOTIATION) mbedtls_ssl_conf_renegotiation(&BACKEND->config, MBEDTLS_SSL_RENEGOTIATION_ENABLED); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) mbedtls_ssl_conf_session_tickets(&BACKEND->config, MBEDTLS_SSL_SESSION_TICKETS_DISABLED); #endif /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *old_session = NULL; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) { ret = mbedtls_ssl_set_session(&BACKEND->ssl, old_session); if(ret) { Curl_ssl_sessionid_unlock(conn); failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } infof(data, "mbedTLS re-using session\n"); } Curl_ssl_sessionid_unlock(conn); } mbedtls_ssl_conf_ca_chain(&BACKEND->config, &BACKEND->cacert, &BACKEND->crl); if(SSL_SET_OPTION(key)) { mbedtls_ssl_conf_own_cert(&BACKEND->config, &BACKEND->clicert, &BACKEND->pk); } if(mbedtls_ssl_set_hostname(&BACKEND->ssl, hostname)) { /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name to set in the SNI extension. So even if curl connects to a host specified as an IP address, this function must be used. */ failf(data, "couldn't set hostname in mbedTLS"); return CURLE_SSL_CONNECT_ERROR; } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { const char **p = &BACKEND->protocols[0]; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) *p++ = NGHTTP2_PROTO_VERSION_ID; #endif *p++ = ALPN_HTTP_1_1; *p = NULL; /* this function doesn't clone the protocols array, which is why we need to keep it around */ if(mbedtls_ssl_conf_alpn_protocols(&BACKEND->config, &BACKEND->protocols[0])) { failf(data, "Failed setting ALPN protocols"); return CURLE_SSL_CONNECT_ERROR; } for(p = &BACKEND->protocols[0]; *p; ++p) infof(data, "ALPN, offering %s\n", *p); } #endif #ifdef MBEDTLS_DEBUG /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */ mbedtls_ssl_conf_dbg(&BACKEND->config, mbed_debug, data); /* - 0 No debug * - 1 Error * - 2 State change * - 3 Informational * - 4 Verbose */ mbedtls_debug_set_threshold(4); #endif /* give application a chance to interfere with mbedTLS set up. */ if(data->set.ssl.fsslctx) { ret = (*data->set.ssl.fsslctx)(data, &BACKEND->config, data->set.ssl.fsslctxp); if(ret) { failf(data, "error signaled by ssl ctx callback"); return ret; } } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode mbed_connect_step2(struct connectdata *conn, int sockindex) { int ret; struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; const mbedtls_x509_crt *peercert; const char * const pinnedpubkey = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; conn->recv[sockindex] = mbed_recv; conn->send[sockindex] = mbed_send; ret = mbedtls_ssl_handshake(&BACKEND->ssl); if(ret == MBEDTLS_ERR_SSL_WANT_READ) { connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; } else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) { connssl->connecting_state = ssl_connect_2_writing; return CURLE_OK; } else if(ret) { char errorbuf[128]; errorbuf[0] = 0; #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s", -ret, errorbuf); return CURLE_SSL_CONNECT_ERROR; } infof(data, "mbedTLS: Handshake complete, cipher is %s\n", mbedtls_ssl_get_ciphersuite(&BACKEND->ssl) ); ret = mbedtls_ssl_get_verify_result(&BACKEND->ssl); if(!SSL_CONN_CONFIG(verifyhost)) /* Ignore hostname errors if verifyhost is disabled */ ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH; if(ret && SSL_CONN_CONFIG(verifypeer)) { if(ret & MBEDTLS_X509_BADCERT_EXPIRED) failf(data, "Cert verify failed: BADCERT_EXPIRED"); else if(ret & MBEDTLS_X509_BADCERT_REVOKED) failf(data, "Cert verify failed: BADCERT_REVOKED"); else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) failf(data, "Cert verify failed: BADCERT_CN_MISMATCH"); else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED) failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED"); return CURLE_PEER_FAILED_VERIFICATION; } peercert = mbedtls_ssl_get_peer_cert(&BACKEND->ssl); if(peercert && data->set.verbose) { const size_t bufsize = 16384; char *buffer = malloc(bufsize); if(!buffer) return CURLE_OUT_OF_MEMORY; if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0) infof(data, "Dumping cert info:\n%s\n", buffer); else infof(data, "Unable to dump certificate information.\n"); free(buffer); } if(pinnedpubkey) { int size = 0; CURLcode result; mbedtls_x509_crt *p; unsigned char pubkey[PUB_DER_MAX_BYTES]; if(!peercert || !peercert->raw.p || !peercert->raw.len) { failf(data, "Failed due to missing peer certificate"); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } p = calloc(1, sizeof(*p)); if(!p) return CURLE_OUT_OF_MEMORY; mbedtls_x509_crt_init(p); /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der needs a non-const key, for now. https://github.com/ARMmbed/mbedtls/issues/396 */ if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { failf(data, "Failed copying peer certificate"); mbedtls_x509_crt_free(p); free(p); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } #ifdef MBEDTLS_PK_WRITE_C size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); if(size <= 0) { failf(data, "Failed copying public key from peer certificate"); mbedtls_x509_crt_free(p); free(p); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } #endif /* MBEDTLS_PK_WRITE_C */ /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, &pubkey[PUB_DER_MAX_BYTES - size], size); if(result) { mbedtls_x509_crt_free(p); free(p); return result; } mbedtls_x509_crt_free(p); free(p); } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { const char *next_protocol = mbedtls_ssl_get_alpn_protocol(&BACKEND->ssl); if(next_protocol) { infof(data, "ALPN, server accepted to use %s\n", next_protocol); #ifdef USE_NGHTTP2 if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN) && !next_protocol[NGHTTP2_PROTO_VERSION_ID_LEN]) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH) && !next_protocol[ALPN_HTTP_1_1_LENGTH]) { conn->negnpn = CURL_HTTP_VERSION_1_1; } } else { infof(data, "ALPN, server did not agree to a protocol\n"); } Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } #endif connssl->connecting_state = ssl_connect_3; infof(data, "SSL connected\n"); return CURLE_OK; } static CURLcode mbed_connect_step3(struct connectdata *conn, int sockindex) { CURLcode retcode = CURLE_OK; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); if(SSL_SET_OPTION(primary.sessionid)) { int ret; mbedtls_ssl_session *our_ssl_sessionid; void *old_ssl_sessionid = NULL; our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session)); if(!our_ssl_sessionid) return CURLE_OUT_OF_MEMORY; mbedtls_ssl_session_init(our_ssl_sessionid); ret = mbedtls_ssl_get_session(&BACKEND->ssl, our_ssl_sessionid); if(ret) { if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED) mbedtls_ssl_session_free(our_ssl_sessionid); free(our_ssl_sessionid); failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } /* If there's already a matching session in the cache, delete it */ Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex)) Curl_ssl_delsessionid(conn, old_ssl_sessionid); retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0, sockindex); Curl_ssl_sessionid_unlock(conn); if(retcode) { mbedtls_ssl_session_free(our_ssl_sessionid); free(our_ssl_sessionid); failf(data, "failed to store ssl session"); return retcode; } } connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static ssize_t mbed_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; int ret = -1; ret = mbedtls_ssl_write(&BACKEND->ssl, (unsigned char *)mem, len); if(ret < 0) { *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ? CURLE_AGAIN : CURLE_SEND_ERROR; ret = -1; } return ret; } static void Curl_mbedtls_close_all(struct Curl_easy *data) { (void)data; } static void Curl_mbedtls_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; mbedtls_pk_free(&BACKEND->pk); mbedtls_x509_crt_free(&BACKEND->clicert); mbedtls_x509_crt_free(&BACKEND->cacert); mbedtls_x509_crl_free(&BACKEND->crl); mbedtls_ssl_config_free(&BACKEND->config); mbedtls_ssl_free(&BACKEND->ssl); #ifdef MBEDTLS_ENTROPY_C mbedtls_ctr_drbg_free(&BACKEND->ctr_drbg); #ifndef THREADING_SUPPORT mbedtls_entropy_free(&BACKEND->entropy); #endif /* THREADING_SUPPORT */ #endif /* MBEDTLS_ENTROPY_C */ } static ssize_t mbed_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; int ret = -1; ssize_t len = -1; memset(buf, 0, buffersize); ret = mbedtls_ssl_read(&BACKEND->ssl, (unsigned char *)buf, buffersize); if(ret <= 0) { if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) return 0; *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_READ) ? CURLE_AGAIN : CURLE_RECV_ERROR; return -1; } len = ret; return len; } static void Curl_mbedtls_session_free(void *ptr) { mbedtls_ssl_session_free(ptr); free(ptr); } static size_t Curl_mbedtls_version(char *buffer, size_t size) { #ifdef MBEDTLS_VERSION_C /* if mbedtls_version_get_number() is available it is better */ unsigned int version = mbedtls_version_get_number(); return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24, (version>>16)&0xff, (version>>8)&0xff); #else return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING); #endif } static CURLcode Curl_mbedtls_random_alt(struct Curl_easy *prng, unsigned char *output, size_t output_len) { unsigned int rnglen = output_len; unsigned char rngoffset = 0; while (rnglen > 0) { *(output + rngoffset) = (uint8_t)rand(); rngoffset++; rnglen--; } return 0; } #if 0 static CURLcode Curl_mbedtls_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { #if defined(MBEDTLS_CTR_DRBG_C) int ret = -1; char errorbuf[128]; #ifdef MBEDTLS_ENTROPY_C mbedtls_entropy_context ctr_entropy; mbedtls_entropy_init(&ctr_entropy); #endif mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ctr_drbg_init(&ctr_drbg); errorbuf[0] = 0; #ifdef MBEDTLS_ENTROPY_C ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &ctr_entropy, NULL, 0); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Failed - mbedTLS: ctr_drbg_seed returned (-0x%04X) %s\n", -ret, errorbuf); } else #endif { ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } } mbedtls_ctr_drbg_free(&ctr_drbg); #ifdef MBEDTLS_ENTROPY_C mbedtls_entropy_free(&ctr_entropy); #endif return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT; #elif defined(MBEDTLS_HAVEGE_C) mbedtls_havege_state hs; mbedtls_havege_init(&hs); mbedtls_havege_random(&hs, entropy, length); mbedtls_havege_free(&hs); return CURLE_OK; #else return CURLE_NOT_BUILT_IN; #endif } #endif static CURLcode mbed_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode retcode; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } retcode = mbed_connect_step1(conn, sockindex); if(retcode) return retcode; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking ? 0 : timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if * this connection is part of a multi handle and this loop would * execute again. This permits the owner of a multi handle to * abort a connection attempt before step2 has completed while * ensuring that a client using select() or epoll() will always * have a valid fdset to wait on. */ retcode = mbed_connect_step2(conn, sockindex); if(retcode || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return retcode; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { retcode = mbed_connect_step3(conn, sockindex); if(retcode) return retcode; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = mbed_recv; conn->send[sockindex] = mbed_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return mbed_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex) { CURLcode retcode; bool done = FALSE; retcode = mbed_connect_common(conn, sockindex, FALSE, &done); if(retcode) return retcode; DEBUGASSERT(done); return CURLE_OK; } /* * return 0 error initializing SSL * return 1 SSL initialized successfully */ static int Curl_mbedtls_init(void) { return Curl_polarsslthreadlock_thread_setup(); } static void Curl_mbedtls_cleanup(void) { (void)Curl_polarsslthreadlock_thread_cleanup(); } static bool Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex) { const struct ssl_connect_data *connssl = &conn->ssl[sockindex]; return mbedtls_ssl_get_bytes_avail(&BACKEND->ssl) != 0; } static CURLcode Curl_mbedtls_sha256sum(const unsigned char *input, size_t inputlen, unsigned char *sha256sum, size_t sha256len UNUSED_PARAM) { (void)sha256len; #if MBEDTLS_VERSION_NUMBER < 0x02070000 mbedtls_sha256(input, inputlen, sha256sum, 0); #else /* returns 0 on success, otherwise failure */ if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0) return CURLE_BAD_FUNCTION_ARGUMENT; #endif return CURLE_OK; } static void *Curl_mbedtls_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return &BACKEND->ssl; } const struct Curl_ssl Curl_ssl_mbedtls = { { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */ SSLSUPP_CA_PATH | SSLSUPP_PINNEDPUBKEY | SSLSUPP_SSL_CTX, sizeof(struct ssl_backend_data), Curl_mbedtls_init, /* init */ Curl_mbedtls_cleanup, /* cleanup */ Curl_mbedtls_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_none_shutdown, /* shutdown */ Curl_mbedtls_data_pending, /* data_pending */ Curl_mbedtls_random_alt, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_mbedtls_connect, /* connect */ Curl_mbedtls_connect_nonblocking, /* connect_nonblocking */ Curl_mbedtls_get_internals, /* get_internals */ Curl_mbedtls_close, /* close_one */ Curl_mbedtls_close_all, /* close_all */ Curl_mbedtls_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ Curl_mbedtls_sha256sum /* sha256sum */ }; #endif /* USE_MBEDTLS */
YifuLiu/AliOS-Things
components/curl/lib/vtls/mbedtls.c
C
apache-2.0
34,271
#ifndef HEADER_CURL_MBEDTLS_H #define HEADER_CURL_MBEDTLS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_MBEDTLS extern const struct Curl_ssl Curl_ssl_mbedtls; #endif /* USE_MBEDTLS */ #endif /* HEADER_CURL_MBEDTLS_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/mbedtls.h
C
apache-2.0
1,298
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2017 - 2018, Yiming Jing, <jingyiming@baidu.com> * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all MesaLink-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. * */ /* * Based upon the CyaSSL implementation in cyassl.c and cyassl.h: * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * Thanks for code and inspiration! */ #include "curl_setup.h" #ifdef USE_MESALINK #include <mesalink/options.h> #include <mesalink/version.h> #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "strcase.h" #include "x509asn1.h" #include "curl_printf.h" #include "mesalink.h" #include <mesalink/openssl/ssl.h> #include <mesalink/openssl/err.h> /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" #define MESALINK_MAX_ERROR_SZ 80 struct ssl_backend_data { SSL_CTX *ctx; SSL *handle; }; #define BACKEND connssl->backend static Curl_recv mesalink_recv; static Curl_send mesalink_send; /* * This function loads all the client/CA certificates and CRLs. Setup the TLS * layer and do all necessary magic. */ static CURLcode mesalink_connect_step1(struct connectdata *conn, int sockindex) { char *ciphers; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; const bool verifypeer = SSL_CONN_CONFIG(verifypeer); const char *const ssl_cafile = SSL_CONN_CONFIG(CAfile); const char *const ssl_capath = SSL_CONN_CONFIG(CApath); struct in_addr addr4; #ifdef ENABLE_IPV6 struct in6_addr addr6; #endif const char *const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; size_t hostname_len = strlen(hostname); SSL_METHOD *req_method = NULL; curl_socket_t sockfd = conn->sock[sockindex]; if(connssl->state == ssl_connection_complete) return CURLE_OK; if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) { failf(data, "MesaLink does not support to set maximum SSL/TLS version"); return CURLE_SSL_CONNECT_ERROR; } switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_SSLv3: case CURL_SSLVERSION_TLSv1: case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: failf(data, "MesaLink does not support SSL 3.0, TLS 1.0, or TLS 1.1"); return CURLE_NOT_BUILT_IN; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1_2: req_method = TLSv1_2_client_method(); break; case CURL_SSLVERSION_TLSv1_3: req_method = TLSv1_3_client_method(); break; case CURL_SSLVERSION_SSLv2: failf(data, "MesaLink does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } if(!req_method) { failf(data, "SSL: couldn't create a method!"); return CURLE_OUT_OF_MEMORY; } if(BACKEND->ctx) SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = SSL_CTX_new(req_method); if(!BACKEND->ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } SSL_CTX_set_verify( BACKEND->ctx, verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); if(ssl_cafile || ssl_capath) { if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) { if(verifypeer) { failf(data, "error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s", ssl_cafile ? ssl_cafile : "none", ssl_capath ? ssl_capath : "none"); return CURLE_SSL_CACERT_BADFILE; } infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } else { infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", ssl_cafile ? ssl_cafile : "none", ssl_capath ? ssl_capath : "none"); } ciphers = SSL_CONN_CONFIG(cipher_list); if(ciphers) { #ifdef MESALINK_HAVE_CIPHER if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) { failf(data, "failed setting cipher list: %s", ciphers); return CURLE_SSL_CIPHER; } #endif infof(data, "Cipher selection: %s\n", ciphers); } if(BACKEND->handle) SSL_free(BACKEND->handle); BACKEND->handle = SSL_new(BACKEND->ctx); if(!BACKEND->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } if((hostname_len < USHRT_MAX) && (0 == Curl_inet_pton(AF_INET, hostname, &addr4)) #ifdef ENABLE_IPV6 && (0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) #endif ) { /* hostname is not a valid IP address */ if(SSL_set_tlsext_host_name(BACKEND->handle, hostname) != SSL_SUCCESS) { failf(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); return CURLE_SSL_CONNECT_ERROR; } } else { #ifdef CURLDEBUG /* Check if the hostname is 127.0.0.1 or [::1]; * otherwise reject because MesaLink always wants a valid DNS Name * specified in RFC 5280 Section 7.2 */ if(strncmp(hostname, "127.0.0.1", 9) == 0 #ifdef ENABLE_IPV6 || strncmp(hostname, "[::1]", 5) == 0 #endif ) { SSL_set_tlsext_host_name(BACKEND->handle, "localhost"); } else #endif { failf(data, "ERROR: MesaLink does not accept an IP address as a hostname\n"); return CURLE_SSL_CONNECT_ERROR; } } #ifdef MESALINK_HAVE_SESSION if(SSL_SET_OPTION(primary.sessionid)) { void *ssl_sessionid = NULL; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) { /* we got a session id, use it! */ if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) { Curl_ssl_sessionid_unlock(conn); failf( data, "SSL: SSL_set_session failed: %s", ERR_error_string(SSL_get_error(BACKEND->handle, 0), error_buffer)); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } Curl_ssl_sessionid_unlock(conn); } #endif /* MESALINK_HAVE_SESSION */ if(SSL_set_fd(BACKEND->handle, (int)sockfd) != SSL_SUCCESS) { failf(data, "SSL: SSL_set_fd failed"); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode mesalink_connect_step2(struct connectdata *conn, int sockindex) { int ret = -1; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; conn->recv[sockindex] = mesalink_recv; conn->send[sockindex] = mesalink_send; ret = SSL_connect(BACKEND->handle); if(ret != SSL_SUCCESS) { char error_buffer[MESALINK_MAX_ERROR_SZ]; int detail = SSL_get_error(BACKEND->handle, ret); if(SSL_ERROR_WANT_CONNECT == detail || SSL_ERROR_WANT_READ == detail) { connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; } else { failf(data, "SSL_connect failed with error %d: %s", detail, ERR_error_string_n(detail, error_buffer, sizeof(error_buffer))); ERR_print_errors_fp(stderr); if(detail && SSL_CONN_CONFIG(verifypeer)) { detail &= ~0xFF; if(detail == TLS_ERROR_WEBPKI_ERRORS) { failf(data, "Cert verify failed"); return CURLE_PEER_FAILED_VERIFICATION; } } return CURLE_SSL_CONNECT_ERROR; } } connssl->connecting_state = ssl_connect_3; infof(data, "SSL connection using %s / %s\n", SSL_get_version(BACKEND->handle), SSL_get_cipher_name(BACKEND->handle)); return CURLE_OK; } static CURLcode mesalink_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); #ifdef MESALINK_HAVE_SESSION if(SSL_SET_OPTION(primary.sessionid)) { bool incache; SSL_SESSION *our_ssl_sessionid; void *old_ssl_sessionid = NULL; our_ssl_sessionid = SSL_get_session(BACKEND->handle); Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex)); if(incache) { if(old_ssl_sessionid != our_ssl_sessionid) { infof(data, "old SSL session ID is stale, removing\n"); Curl_ssl_delsessionid(conn, old_ssl_sessionid); incache = FALSE; } } if(!incache) { result = Curl_ssl_addsessionid( conn, our_ssl_sessionid, 0 /* unknown size */, sockindex); if(result) { Curl_ssl_sessionid_unlock(conn); failf(data, "failed to store ssl session"); return result; } } Curl_ssl_sessionid_unlock(conn); } #endif /* MESALINK_HAVE_SESSION */ connssl->connecting_state = ssl_connect_done; return result; } static ssize_t mesalink_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; char error_buffer[MESALINK_MAX_ERROR_SZ]; int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; int rc = SSL_write(BACKEND->handle, mem, memlen); if(rc < 0) { int err = SSL_get_error(BACKEND->handle, rc); switch(err) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* there's data pending, re-invoke SSL_write() */ *curlcode = CURLE_AGAIN; return -1; default: failf(conn->data, "SSL write: %s, errno %d", ERR_error_string_n(err, error_buffer, sizeof(error_buffer)), SOCKERRNO); *curlcode = CURLE_SEND_ERROR; return -1; } } return rc; } static void Curl_mesalink_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(BACKEND->handle) { (void)SSL_shutdown(BACKEND->handle); SSL_free(BACKEND->handle); BACKEND->handle = NULL; } if(BACKEND->ctx) { SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = NULL; } } static ssize_t mesalink_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; char error_buffer[MESALINK_MAX_ERROR_SZ]; int buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; int nread = SSL_read(BACKEND->handle, buf, buffsize); if(nread <= 0) { int err = SSL_get_error(BACKEND->handle, nread); switch(err) { case SSL_ERROR_ZERO_RETURN: /* no more data */ case IO_ERROR_CONNECTION_ABORTED: break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* there's data pending, re-invoke SSL_read() */ *curlcode = CURLE_AGAIN; return -1; default: failf(conn->data, "SSL read: %s, errno %d", ERR_error_string_n(err, error_buffer, sizeof(error_buffer)), SOCKERRNO); *curlcode = CURLE_RECV_ERROR; return -1; } } return nread; } static size_t Curl_mesalink_version(char *buffer, size_t size) { return msnprintf(buffer, size, "MesaLink/%s", MESALINK_VERSION_STRING); } static int Curl_mesalink_init(void) { return (SSL_library_init() == SSL_SUCCESS); } /* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */ static int Curl_mesalink_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(BACKEND->handle) { SSL_free(BACKEND->handle); BACKEND->handle = NULL; } return retval; } static CURLcode mesalink_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; time_t timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = mesalink_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; what = Curl_socket_check( readfd, CURL_SOCKET_BAD, writefd, nonblocking ? 0 : timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if * this connection is part of a multi handle and this loop would * execute again. This permits the owner of a multi handle to * abort a connection attempt before step2 has completed while * ensuring that a client using select() or epoll() will always * have a valid fdset to wait on. */ result = mesalink_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) { return result; } } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = mesalink_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = mesalink_recv; conn->send[sockindex] = mesalink_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_mesalink_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return mesalink_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_mesalink_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = mesalink_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static void * Curl_mesalink_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->handle; } const struct Curl_ssl Curl_ssl_mesalink = { { CURLSSLBACKEND_MESALINK, "MesaLink" }, /* info */ SSLSUPP_SSL_CTX, sizeof(struct ssl_backend_data), Curl_mesalink_init, /* init */ Curl_none_cleanup, /* cleanup */ Curl_mesalink_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_mesalink_shutdown, /* shutdown */ Curl_none_data_pending, /* data_pending */ Curl_none_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_mesalink_connect, /* connect */ Curl_mesalink_connect_nonblocking, /* connect_nonblocking */ Curl_mesalink_get_internals, /* get_internals */ Curl_mesalink_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_none_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ NULL /* sha256sum */ }; #endif
YifuLiu/AliOS-Things
components/curl/lib/vtls/mesalink.c
C
apache-2.0
18,289
#ifndef HEADER_CURL_MESALINK_H #define HEADER_CURL_MESALINK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2017-2018, Yiming Jing, <jingyiming@baidu.com> * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_MESALINK extern const struct Curl_ssl Curl_ssl_mesalink; #endif /* USE_MESALINK */ #endif /* HEADER_CURL_MESALINK_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/mesalink.h
C
apache-2.0
1,309
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all NSS-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. */ #include "curl_setup.h" #ifdef USE_NSS #include "urldata.h" #include "sendf.h" #include "formdata.h" /* for the boundary function */ #include "url.h" /* for the ssl config check function */ #include "connect.h" #include "strcase.h" #include "select.h" #include "vtls.h" #include "llist.h" #include "multiif.h" #include "curl_printf.h" #include "nssg.h" #include <nspr.h> #include <nss.h> #include <ssl.h> #include <sslerr.h> #include <secerr.h> #include <secmod.h> #include <sslproto.h> #include <prtypes.h> #include <pk11pub.h> #include <prio.h> #include <secitem.h> #include <secport.h> #include <certdb.h> #include <base64.h> #include <cert.h> #include <prerror.h> #include <keyhi.h> /* for SECKEY_DestroyPublicKey() */ #include <private/pprio.h> /* for PR_ImportTCPSocket */ #define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH) #if NSSVERNUM >= 0x030f00 /* 3.15.0 */ #include <ocsp.h> #endif #include "strcase.h" #include "warnless.h" #include "x509asn1.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" #define SSL_DIR "/etc/pki/nssdb" /* enough to fit the string "PEM Token #[0|1]" */ #define SLOTSIZE 13 struct ssl_backend_data { PRFileDesc *handle; char *client_nickname; struct Curl_easy *data; struct curl_llist obj_list; PK11GenericObject *obj_clicert; }; #define BACKEND connssl->backend static PRLock *nss_initlock = NULL; static PRLock *nss_crllock = NULL; static PRLock *nss_findslot_lock = NULL; static PRLock *nss_trustload_lock = NULL; static struct curl_llist nss_crl_list; static NSSInitContext *nss_context = NULL; static volatile int initialized = 0; /* type used to wrap pointers as list nodes */ struct ptr_list_wrap { void *ptr; struct curl_llist_element node; }; typedef struct { const char *name; int num; } cipher_s; #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \ CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \ ptr->type = (_type); \ ptr->pValue = (_val); \ ptr->ulValueLen = (_len); \ } WHILE_FALSE #define CERT_NewTempCertificate __CERT_NewTempCertificate #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0]) static const cipher_s cipherlist[] = { /* SSL2 cipher suites */ {"rc4", SSL_EN_RC4_128_WITH_MD5}, {"rc4-md5", SSL_EN_RC4_128_WITH_MD5}, {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5}, {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5}, {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5}, {"des", SSL_EN_DES_64_CBC_WITH_MD5}, {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5}, /* SSL3/TLS cipher suites */ {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5}, {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA}, {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA}, {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA}, {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5}, {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5}, {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5}, {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA}, {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA}, {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA}, {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA}, {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA}, {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA}, /* TLS 1.0: Exportable 56-bit Cipher Suites. */ {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA}, {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA}, /* AES ciphers. */ {"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA}, {"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA}, {"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA}, {"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA}, {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA}, {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA}, /* ECC ciphers. */ {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA}, {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA}, {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA}, {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA}, {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA}, {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA}, {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA}, {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA}, {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA}, {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}, {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA}, {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA}, {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA}, {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA}, {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA}, {"ecdhe_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA}, {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA}, {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA}, {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA}, {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA}, {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA}, {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA}, {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA}, #ifdef TLS_RSA_WITH_NULL_SHA256 /* new HMAC-SHA256 cipher suites specified in RFC */ {"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256}, {"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256}, {"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256}, {"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256}, {"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256}, {"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256}, {"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256}, #endif #ifdef TLS_RSA_WITH_AES_128_GCM_SHA256 /* AES GCM cipher suites in RFC 5288 and RFC 5289 */ {"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256}, {"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256}, {"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256}, {"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, {"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256}, {"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, {"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256}, #endif #ifdef TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 /* cipher suites using SHA384 */ {"rsa_aes_256_gcm_sha_384", TLS_RSA_WITH_AES_256_GCM_SHA384}, {"dhe_rsa_aes_256_gcm_sha_384", TLS_DHE_RSA_WITH_AES_256_GCM_SHA384}, {"dhe_dss_aes_256_gcm_sha_384", TLS_DHE_DSS_WITH_AES_256_GCM_SHA384}, {"ecdhe_ecdsa_aes_256_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384}, {"ecdhe_rsa_aes_256_sha_384", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384}, {"ecdhe_ecdsa_aes_256_gcm_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384}, {"ecdhe_rsa_aes_256_gcm_sha_384", TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}, #endif #ifdef TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 /* chacha20-poly1305 cipher suites */ {"ecdhe_rsa_chacha20_poly1305_sha_256", TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, {"ecdhe_ecdsa_chacha20_poly1305_sha_256", TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256}, {"dhe_rsa_chacha20_poly1305_sha_256", TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, #endif }; #ifdef WIN32 static const char *pem_library = "nsspem.dll"; static const char *trust_library = "nssckbi.dll"; #else static const char *pem_library = "libnsspem.so"; static const char *trust_library = "libnssckbi.so"; #endif static SECMODModule *pem_module = NULL; static SECMODModule *trust_module = NULL; /* NSPR I/O layer we use to detect blocking direction during SSL handshake */ static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER; static PRIOMethods nspr_io_methods; static const char *nss_error_to_name(PRErrorCode code) { const char *name = PR_ErrorToName(code); if(name) return name; return "unknown error"; } static void nss_print_error_message(struct Curl_easy *data, PRUint32 err) { failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT)); } static char *nss_sslver_to_name(PRUint16 nssver) { switch(nssver) { case SSL_LIBRARY_VERSION_2: return strdup("SSLv2"); case SSL_LIBRARY_VERSION_3_0: return strdup("SSLv3"); case SSL_LIBRARY_VERSION_TLS_1_0: return strdup("TLSv1.0"); #ifdef SSL_LIBRARY_VERSION_TLS_1_1 case SSL_LIBRARY_VERSION_TLS_1_1: return strdup("TLSv1.1"); #endif #ifdef SSL_LIBRARY_VERSION_TLS_1_2 case SSL_LIBRARY_VERSION_TLS_1_2: return strdup("TLSv1.2"); #endif #ifdef SSL_LIBRARY_VERSION_TLS_1_3 case SSL_LIBRARY_VERSION_TLS_1_3: return strdup("TLSv1.3"); #endif default: return curl_maprintf("0x%04x", nssver); } } static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model, char *cipher_list) { unsigned int i; PRBool cipher_state[NUM_OF_CIPHERS]; PRBool found; char *cipher; /* use accessors to avoid dynamic linking issues after an update of NSS */ const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers(); const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers(); if(!implemented_ciphers) return SECFailure; /* First disable all ciphers. This uses a different max value in case * NSS adds more ciphers later we don't want them available by * accident */ for(i = 0; i < num_implemented_ciphers; i++) { SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE); } /* Set every entry in our list to false */ for(i = 0; i < NUM_OF_CIPHERS; i++) { cipher_state[i] = PR_FALSE; } cipher = cipher_list; while(cipher_list && (cipher_list[0])) { while((*cipher) && (ISSPACE(*cipher))) ++cipher; cipher_list = strchr(cipher, ','); if(cipher_list) { *cipher_list++ = '\0'; } found = PR_FALSE; for(i = 0; i<NUM_OF_CIPHERS; i++) { if(strcasecompare(cipher, cipherlist[i].name)) { cipher_state[i] = PR_TRUE; found = PR_TRUE; break; } } if(found == PR_FALSE) { failf(data, "Unknown cipher in list: %s", cipher); return SECFailure; } if(cipher_list) { cipher = cipher_list; } } /* Finally actually enable the selected ciphers */ for(i = 0; i<NUM_OF_CIPHERS; i++) { if(!cipher_state[i]) continue; if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) { failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name); return SECFailure; } } return SECSuccess; } /* * Return true if at least one cipher-suite is enabled. Used to determine * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers. */ static bool any_cipher_enabled(void) { unsigned int i; for(i = 0; i<NUM_OF_CIPHERS; i++) { PRInt32 policy = 0; SSL_CipherPolicyGet(cipherlist[i].num, &policy); if(policy) return TRUE; } return FALSE; } /* * Determine whether the nickname passed in is a filename that needs to * be loaded as a PEM or a regular NSS nickname. * * returns 1 for a file * returns 0 for not a file (NSS nickname) */ static int is_file(const char *filename) { struct_stat st; if(filename == NULL) return 0; if(stat(filename, &st) == 0) if(S_ISREG(st.st_mode) || S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode)) return 1; return 0; } /* Check if the given string is filename or nickname of a certificate. If the * given string is recognized as filename, return NULL. If the given string is * recognized as nickname, return a duplicated string. The returned string * should be later deallocated using free(). If the OOM failure occurs, we * return NULL, too. */ static char *dup_nickname(struct Curl_easy *data, const char *str) { const char *n; if(!is_file(str)) /* no such file exists, use the string as nickname */ return strdup(str); /* search the first slash; we require at least one slash in a file name */ n = strchr(str, '/'); if(!n) { infof(data, "warning: certificate file name \"%s\" handled as nickname; " "please use \"./%s\" to force file name\n", str, str); return strdup(str); } /* we'll use the PEM reader to read the certificate from file */ return NULL; } /* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition * in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN. For more * details, go to <https://bugzilla.mozilla.org/1297397>. */ static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name) { PK11SlotInfo *slot; PR_Lock(nss_findslot_lock); slot = PK11_FindSlotByName(slot_name); PR_Unlock(nss_findslot_lock); return slot; } /* wrap 'ptr' as list node and tail-insert into 'list' */ static CURLcode insert_wrapped_ptr(struct curl_llist *list, void *ptr) { struct ptr_list_wrap *wrap = malloc(sizeof(*wrap)); if(!wrap) return CURLE_OUT_OF_MEMORY; wrap->ptr = ptr; Curl_llist_insert_next(list, list->tail, wrap, &wrap->node); return CURLE_OK; } /* Call PK11_CreateGenericObject() with the given obj_class and filename. If * the call succeeds, append the object handle to the list of objects so that * the object can be destroyed in Curl_nss_close(). */ static CURLcode nss_create_object(struct ssl_connect_data *connssl, CK_OBJECT_CLASS obj_class, const char *filename, bool cacert) { PK11SlotInfo *slot; PK11GenericObject *obj; CK_BBOOL cktrue = CK_TRUE; CK_BBOOL ckfalse = CK_FALSE; CK_ATTRIBUTE attrs[/* max count of attributes */ 4]; int attr_cnt = 0; CURLcode result = (cacert) ? CURLE_SSL_CACERT_BADFILE : CURLE_SSL_CERTPROBLEM; const int slot_id = (cacert) ? 0 : 1; char *slot_name = aprintf("PEM Token #%d", slot_id); if(!slot_name) return CURLE_OUT_OF_MEMORY; slot = nss_find_slot_by_name(slot_name); free(slot_name); if(!slot) return result; PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class)); PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL)); PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename, (CK_ULONG)strlen(filename) + 1); if(CKO_CERTIFICATE == obj_class) { CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse); PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval)); } /* PK11_CreateManagedGenericObject() was introduced in NSS 3.34 because * PK11_DestroyGenericObject() does not release resources allocated by * PK11_CreateGenericObject() early enough. */ obj = #ifdef HAVE_PK11_CREATEMANAGEDGENERICOBJECT PK11_CreateManagedGenericObject #else PK11_CreateGenericObject #endif (slot, attrs, attr_cnt, PR_FALSE); PK11_FreeSlot(slot); if(!obj) return result; if(insert_wrapped_ptr(&BACKEND->obj_list, obj) != CURLE_OK) { PK11_DestroyGenericObject(obj); return CURLE_OUT_OF_MEMORY; } if(!cacert && CKO_CERTIFICATE == obj_class) /* store reference to a client certificate */ BACKEND->obj_clicert = obj; return CURLE_OK; } /* Destroy the NSS object whose handle is given by ptr. This function is * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy * NSS objects in Curl_nss_close() */ static void nss_destroy_object(void *user, void *ptr) { struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr; PK11GenericObject *obj = (PK11GenericObject *) wrap->ptr; (void) user; PK11_DestroyGenericObject(obj); free(wrap); } /* same as nss_destroy_object() but for CRL items */ static void nss_destroy_crl_item(void *user, void *ptr) { struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr; SECItem *crl_der = (SECItem *) wrap->ptr; (void) user; SECITEM_FreeItem(crl_der, PR_TRUE); free(wrap); } static CURLcode nss_load_cert(struct ssl_connect_data *ssl, const char *filename, PRBool cacert) { CURLcode result = (cacert) ? CURLE_SSL_CACERT_BADFILE : CURLE_SSL_CERTPROBLEM; /* libnsspem.so leaks memory if the requested file does not exist. For more * details, go to <https://bugzilla.redhat.com/734760>. */ if(is_file(filename)) result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert); if(!result && !cacert) { /* we have successfully loaded a client certificate */ CERTCertificate *cert; char *nickname = NULL; char *n = strrchr(filename, '/'); if(n) n++; /* The following undocumented magic helps to avoid a SIGSEGV on call * of PK11_ReadRawAttribute() from SelectClientCert() when using an * immature version of libnsspem.so. For more details, go to * <https://bugzilla.redhat.com/733685>. */ nickname = aprintf("PEM Token #1:%s", n); if(nickname) { cert = PK11_FindCertFromNickname(nickname, NULL); if(cert) CERT_DestroyCertificate(cert); free(nickname); } } return result; } /* add given CRL to cache if it is not already there */ static CURLcode nss_cache_crl(SECItem *crl_der) { CERTCertDBHandle *db = CERT_GetDefaultCertDB(); CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0); if(crl) { /* CRL already cached */ SEC_DestroyCrl(crl); SECITEM_FreeItem(crl_der, PR_TRUE); return CURLE_OK; } /* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */ PR_Lock(nss_crllock); /* store the CRL item so that we can free it in Curl_nss_cleanup() */ if(insert_wrapped_ptr(&nss_crl_list, crl_der) != CURLE_OK) { SECITEM_FreeItem(crl_der, PR_TRUE); PR_Unlock(nss_crllock); return CURLE_OUT_OF_MEMORY; } if(SECSuccess != CERT_CacheCRL(db, crl_der)) { /* unable to cache CRL */ PR_Unlock(nss_crllock); return CURLE_SSL_CRL_BADFILE; } /* we need to clear session cache, so that the CRL could take effect */ SSL_ClearSessionCache(); PR_Unlock(nss_crllock); return CURLE_OK; } static CURLcode nss_load_crl(const char *crlfilename) { PRFileDesc *infile; PRFileInfo info; SECItem filedata = { 0, NULL, 0 }; SECItem *crl_der = NULL; char *body; infile = PR_Open(crlfilename, PR_RDONLY, 0); if(!infile) return CURLE_SSL_CRL_BADFILE; if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info)) goto fail; if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1)) goto fail; if(info.size != PR_Read(infile, filedata.data, info.size)) goto fail; crl_der = SECITEM_AllocItem(NULL, NULL, 0U); if(!crl_der) goto fail; /* place a trailing zero right after the visible data */ body = (char *)filedata.data; body[--filedata.len] = '\0'; body = strstr(body, "-----BEGIN"); if(body) { /* assume ASCII */ char *trailer; char *begin = PORT_Strchr(body, '\n'); if(!begin) begin = PORT_Strchr(body, '\r'); if(!begin) goto fail; trailer = strstr(++begin, "-----END"); if(!trailer) goto fail; /* retrieve DER from ASCII */ *trailer = '\0'; if(ATOB_ConvertAsciiToItem(crl_der, begin)) goto fail; SECITEM_FreeItem(&filedata, PR_FALSE); } else /* assume DER */ *crl_der = filedata; PR_Close(infile); return nss_cache_crl(crl_der); fail: PR_Close(infile); SECITEM_FreeItem(crl_der, PR_TRUE); SECITEM_FreeItem(&filedata, PR_FALSE); return CURLE_SSL_CRL_BADFILE; } static CURLcode nss_load_key(struct connectdata *conn, int sockindex, char *key_file) { PK11SlotInfo *slot, *tmp; SECStatus status; CURLcode result; struct ssl_connect_data *ssl = conn->ssl; struct Curl_easy *data = conn->data; (void)sockindex; /* unused */ result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE); if(result) { PR_SetError(SEC_ERROR_BAD_KEY, 0); return result; } slot = nss_find_slot_by_name("PEM Token #1"); if(!slot) return CURLE_SSL_CERTPROBLEM; /* This will force the token to be seen as re-inserted */ tmp = SECMOD_WaitForAnyTokenEvent(pem_module, 0, 0); if(tmp) PK11_FreeSlot(tmp); PK11_IsPresent(slot); status = PK11_Authenticate(slot, PR_TRUE, SSL_SET_OPTION(key_passwd)); PK11_FreeSlot(slot); return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM; } static int display_error(struct connectdata *conn, PRInt32 err, const char *filename) { switch(err) { case SEC_ERROR_BAD_PASSWORD: failf(conn->data, "Unable to load client key: Incorrect password"); return 1; case SEC_ERROR_UNKNOWN_CERT: failf(conn->data, "Unable to load certificate %s", filename); return 1; default: break; } return 0; /* The caller will print a generic error */ } static CURLcode cert_stuff(struct connectdata *conn, int sockindex, char *cert_file, char *key_file) { struct Curl_easy *data = conn->data; CURLcode result; if(cert_file) { result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE); if(result) { const PRErrorCode err = PR_GetError(); if(!display_error(conn, err, cert_file)) { const char *err_name = nss_error_to_name(err); failf(data, "unable to load client cert: %d (%s)", err, err_name); } return result; } } if(key_file || (is_file(cert_file))) { if(key_file) result = nss_load_key(conn, sockindex, key_file); else /* In case the cert file also has the key */ result = nss_load_key(conn, sockindex, cert_file); if(result) { const PRErrorCode err = PR_GetError(); if(!display_error(conn, err, key_file)) { const char *err_name = nss_error_to_name(err); failf(data, "unable to load client key: %d (%s)", err, err_name); } return result; } } return CURLE_OK; } static char *nss_get_password(PK11SlotInfo *slot, PRBool retry, void *arg) { (void)slot; /* unused */ if(retry || NULL == arg) return NULL; else return (char *)PORT_Strdup((char *)arg); } /* bypass the default SSL_AuthCertificate() hook in case we do not want to * verify peer */ static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig, PRBool isServer) { struct connectdata *conn = (struct connectdata *)arg; #ifdef SSL_ENABLE_OCSP_STAPLING if(SSL_CONN_CONFIG(verifystatus)) { SECStatus cacheResult; const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd); if(!csa) { failf(conn->data, "Invalid OCSP response"); return SECFailure; } if(csa->len == 0) { failf(conn->data, "No OCSP response received"); return SECFailure; } cacheResult = CERT_CacheOCSPResponseFromSideChannel( CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd), PR_Now(), &csa->items[0], arg ); if(cacheResult != SECSuccess) { failf(conn->data, "Invalid OCSP response"); return cacheResult; } } #endif if(!SSL_CONN_CONFIG(verifypeer)) { infof(conn->data, "skipping SSL peer certificate verification\n"); return SECSuccess; } return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer); } /** * Inform the application that the handshake is complete. */ static void HandshakeCallback(PRFileDesc *sock, void *arg) { struct connectdata *conn = (struct connectdata*) arg; unsigned int buflenmax = 50; unsigned char buf[50]; unsigned int buflen; SSLNextProtoState state; if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) { return; } if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) { switch(state) { #if NSSVERNUM >= 0x031a00 /* 3.26.0 */ /* used by NSS internally to implement 0-RTT */ case SSL_NEXT_PROTO_EARLY_VALUE: /* fall through! */ #endif case SSL_NEXT_PROTO_NO_SUPPORT: case SSL_NEXT_PROTO_NO_OVERLAP: infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n"); return; #ifdef SSL_ENABLE_ALPN case SSL_NEXT_PROTO_SELECTED: infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf); break; #endif case SSL_NEXT_PROTO_NEGOTIATED: infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf); break; } #ifdef USE_NGHTTP2 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(buflen == ALPN_HTTP_1_1_LENGTH && !memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } } #if NSSVERNUM >= 0x030f04 /* 3.15.4 */ static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data, PRBool *canFalseStart) { struct connectdata *conn = client_data; struct Curl_easy *data = conn->data; SSLChannelInfo channelInfo; SSLCipherSuiteInfo cipherInfo; SECStatus rv; PRBool negotiatedExtension; *canFalseStart = PR_FALSE; if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess) return SECFailure; if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo, sizeof(cipherInfo)) != SECSuccess) return SECFailure; /* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for * TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310 */ if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2) goto end; /* Only allow ECDHE key exchange algorithm. * See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */ if(cipherInfo.keaType != ssl_kea_ecdh) goto end; /* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC * mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt * design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */ if(cipherInfo.symCipher != ssl_calg_aes_gcm) goto end; /* Enforce ALPN or NPN to do False Start, as an indicator of server * compatibility. */ rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn, &negotiatedExtension); if(rv != SECSuccess || !negotiatedExtension) { rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn, &negotiatedExtension); } if(rv != SECSuccess || !negotiatedExtension) goto end; *canFalseStart = PR_TRUE; infof(data, "Trying TLS False Start\n"); end: return SECSuccess; } #endif static void display_cert_info(struct Curl_easy *data, CERTCertificate *cert) { char *subject, *issuer, *common_name; PRExplodedTime printableTime; char timeString[256]; PRTime notBefore, notAfter; subject = CERT_NameToAscii(&cert->subject); issuer = CERT_NameToAscii(&cert->issuer); common_name = CERT_GetCommonName(&cert->subject); infof(data, "\tsubject: %s\n", subject); CERT_GetCertTimes(cert, &notBefore, &notAfter); PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime); PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime); infof(data, "\tstart date: %s\n", timeString); PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime); PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime); infof(data, "\texpire date: %s\n", timeString); infof(data, "\tcommon name: %s\n", common_name); infof(data, "\tissuer: %s\n", issuer); PR_Free(subject); PR_Free(issuer); PR_Free(common_name); } static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock) { CURLcode result = CURLE_OK; SSLChannelInfo channel; SSLCipherSuiteInfo suite; CERTCertificate *cert; CERTCertificate *cert2; CERTCertificate *cert3; PRTime now; int i; if(SSL_GetChannelInfo(sock, &channel, sizeof(channel)) == SECSuccess && channel.length == sizeof(channel) && channel.cipherSuite) { if(SSL_GetCipherSuiteInfo(channel.cipherSuite, &suite, sizeof(suite)) == SECSuccess) { infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName); } } cert = SSL_PeerCertificate(sock); if(cert) { infof(conn->data, "Server certificate:\n"); if(!conn->data->set.ssl.certinfo) { display_cert_info(conn->data, cert); CERT_DestroyCertificate(cert); } else { /* Count certificates in chain. */ now = PR_Now(); i = 1; if(!cert->isRoot) { cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA); while(cert2) { i++; if(cert2->isRoot) { CERT_DestroyCertificate(cert2); break; } cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA); CERT_DestroyCertificate(cert2); cert2 = cert3; } } result = Curl_ssl_init_certinfo(conn->data, i); if(!result) { for(i = 0; cert; cert = cert2) { result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data, (char *)cert->derCert.data + cert->derCert.len); if(result) break; if(cert->isRoot) { CERT_DestroyCertificate(cert); break; } cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA); CERT_DestroyCertificate(cert); } } } } return result; } static SECStatus BadCertHandler(void *arg, PRFileDesc *sock) { struct connectdata *conn = (struct connectdata *)arg; struct Curl_easy *data = conn->data; PRErrorCode err = PR_GetError(); CERTCertificate *cert; /* remember the cert verification result */ if(SSL_IS_PROXY()) data->set.proxy_ssl.certverifyresult = err; else data->set.ssl.certverifyresult = err; if(err == SSL_ERROR_BAD_CERT_DOMAIN && !SSL_CONN_CONFIG(verifyhost)) /* we are asked not to verify the host name */ return SECSuccess; /* print only info about the cert, the error is printed off the callback */ cert = SSL_PeerCertificate(sock); if(cert) { infof(data, "Server certificate:\n"); display_cert_info(data, cert); CERT_DestroyCertificate(cert); } return SECFailure; } /** * * Check that the Peer certificate's issuer certificate matches the one found * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the * issuer check, so we provide comments that mimic the OpenSSL * X509_check_issued function (in x509v3/v3_purp.c) */ static SECStatus check_issuer_cert(PRFileDesc *sock, char *issuer_nickname) { CERTCertificate *cert, *cert_issuer, *issuer; SECStatus res = SECSuccess; void *proto_win = NULL; cert = SSL_PeerCertificate(sock); cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner); proto_win = SSL_RevealPinArg(sock); issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win); if((!cert_issuer) || (!issuer)) res = SECFailure; else if(SECITEM_CompareItem(&cert_issuer->derCert, &issuer->derCert) != SECEqual) res = SECFailure; CERT_DestroyCertificate(cert); CERT_DestroyCertificate(issuer); CERT_DestroyCertificate(cert_issuer); return res; } static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl, const char *pinnedpubkey) { CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; struct Curl_easy *data = BACKEND->data; CERTCertificate *cert; if(!pinnedpubkey) /* no pinned public key specified */ return CURLE_OK; /* get peer certificate */ cert = SSL_PeerCertificate(BACKEND->handle); if(cert) { /* extract public key from peer certificate */ SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert); if(pubkey) { /* encode the public key as DER */ SECItem *cert_der = PK11_DEREncodePublicKey(pubkey); if(cert_der) { /* compare the public key with the pinned public key */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data, cert_der->len); SECITEM_FreeItem(cert_der, PR_TRUE); } SECKEY_DestroyPublicKey(pubkey); } CERT_DestroyCertificate(cert); } /* report the resulting status */ switch(result) { case CURLE_OK: infof(data, "pinned public key verified successfully!\n"); break; case CURLE_SSL_PINNEDPUBKEYNOTMATCH: failf(data, "failed to verify pinned public key"); break; default: /* OOM, etc. */ break; } return result; } /** * * Callback to pick the SSL client certificate. */ static SECStatus SelectClientCert(void *arg, PRFileDesc *sock, struct CERTDistNamesStr *caNames, struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey) { struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg; struct Curl_easy *data = BACKEND->data; const char *nickname = BACKEND->client_nickname; static const char pem_slotname[] = "PEM Token #1"; if(BACKEND->obj_clicert) { /* use the cert/key provided by PEM reader */ SECItem cert_der = { 0, NULL, 0 }; void *proto_win = SSL_RevealPinArg(sock); struct CERTCertificateStr *cert; struct SECKEYPrivateKeyStr *key; PK11SlotInfo *slot = nss_find_slot_by_name(pem_slotname); if(NULL == slot) { failf(data, "NSS: PK11 slot not found: %s", pem_slotname); return SECFailure; } if(PK11_ReadRawAttribute(PK11_TypeGeneric, BACKEND->obj_clicert, CKA_VALUE, &cert_der) != SECSuccess) { failf(data, "NSS: CKA_VALUE not found in PK11 generic object"); PK11_FreeSlot(slot); return SECFailure; } cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win); SECITEM_FreeItem(&cert_der, PR_FALSE); if(NULL == cert) { failf(data, "NSS: client certificate from file not found"); PK11_FreeSlot(slot); return SECFailure; } key = PK11_FindPrivateKeyFromCert(slot, cert, NULL); PK11_FreeSlot(slot); if(NULL == key) { failf(data, "NSS: private key from file not found"); CERT_DestroyCertificate(cert); return SECFailure; } infof(data, "NSS: client certificate from file\n"); display_cert_info(data, cert); *pRetCert = cert; *pRetKey = key; return SECSuccess; } /* use the default NSS hook */ if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames, pRetCert, pRetKey) || NULL == *pRetCert) { if(NULL == nickname) failf(data, "NSS: client certificate not found (nickname not " "specified)"); else failf(data, "NSS: client certificate not found: %s", nickname); return SECFailure; } /* get certificate nickname if any */ nickname = (*pRetCert)->nickname; if(NULL == nickname) nickname = "[unknown]"; if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) { failf(data, "NSS: refusing previously loaded certificate from file: %s", nickname); return SECFailure; } if(NULL == *pRetKey) { failf(data, "NSS: private key not found for certificate: %s", nickname); return SECFailure; } infof(data, "NSS: using client certificate: %s\n", nickname); display_cert_info(data, *pRetCert); return SECSuccess; } /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */ static void nss_update_connecting_state(ssl_connect_state state, void *secret) { struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret; if(PR_GetError() != PR_WOULD_BLOCK_ERROR) /* an unrelated error is passing by */ return; switch(connssl->connecting_state) { case ssl_connect_2: case ssl_connect_2_reading: case ssl_connect_2_writing: break; default: /* we are not called from an SSL handshake */ return; } /* update the state accordingly */ connssl->connecting_state = state; } /* recv() wrapper we use to detect blocking direction during SSL handshake */ static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags, PRIntervalTime timeout) { const PRRecvFN recv_fn = fd->lower->methods->recv; const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout); if(rv < 0) /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */ nss_update_connecting_state(ssl_connect_2_reading, fd->secret); return rv; } /* send() wrapper we use to detect blocking direction during SSL handshake */ static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, PRIntervalTime timeout) { const PRSendFN send_fn = fd->lower->methods->send; const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout); if(rv < 0) /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */ nss_update_connecting_state(ssl_connect_2_writing, fd->secret); return rv; } /* close() wrapper to avoid assertion failure due to fd->secret != NULL */ static PRStatus nspr_io_close(PRFileDesc *fd) { const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close; fd->secret = NULL; return close_fn(fd); } /* load a PKCS #11 module */ static CURLcode nss_load_module(SECMODModule **pmod, const char *library, const char *name) { char *config_string; SECMODModule *module = *pmod; if(module) /* already loaded */ return CURLE_OK; config_string = aprintf("library=%s name=%s", library, name); if(!config_string) return CURLE_OUT_OF_MEMORY; module = SECMOD_LoadUserModule(config_string, NULL, PR_FALSE); free(config_string); if(module && module->loaded) { /* loaded successfully */ *pmod = module; return CURLE_OK; } if(module) SECMOD_DestroyModule(module); return CURLE_FAILED_INIT; } /* unload a PKCS #11 module */ static void nss_unload_module(SECMODModule **pmod) { SECMODModule *module = *pmod; if(!module) /* not loaded */ return; if(SECMOD_UnloadUserModule(module) != SECSuccess) /* unload failed */ return; SECMOD_DestroyModule(module); *pmod = NULL; } /* data might be NULL */ static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir) { NSSInitParameters initparams; PRErrorCode err; const char *err_name; if(nss_context != NULL) return CURLE_OK; memset((void *) &initparams, '\0', sizeof(initparams)); initparams.length = sizeof(initparams); if(cert_dir) { char *certpath = aprintf("sql:%s", cert_dir); if(!certpath) return CURLE_OUT_OF_MEMORY; infof(data, "Initializing NSS with certpath: %s\n", certpath); nss_context = NSS_InitContext(certpath, "", "", "", &initparams, NSS_INIT_READONLY | NSS_INIT_PK11RELOAD); free(certpath); if(nss_context != NULL) return CURLE_OK; err = PR_GetError(); err_name = nss_error_to_name(err); infof(data, "Unable to initialize NSS database: %d (%s)\n", err, err_name); } infof(data, "Initializing NSS with certpath: none\n"); nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD); if(nss_context != NULL) return CURLE_OK; err = PR_GetError(); err_name = nss_error_to_name(err); failf(data, "Unable to initialize NSS: %d (%s)", err, err_name); return CURLE_SSL_CACERT_BADFILE; } /* data might be NULL */ static CURLcode nss_init(struct Curl_easy *data) { char *cert_dir; struct_stat st; CURLcode result; if(initialized) return CURLE_OK; /* list of all CRL items we need to destroy in Curl_nss_cleanup() */ Curl_llist_init(&nss_crl_list, nss_destroy_crl_item); /* First we check if $SSL_DIR points to a valid dir */ cert_dir = getenv("SSL_DIR"); if(cert_dir) { if((stat(cert_dir, &st) != 0) || (!S_ISDIR(st.st_mode))) { cert_dir = NULL; } } /* Now we check if the default location is a valid dir */ if(!cert_dir) { if((stat(SSL_DIR, &st) == 0) && (S_ISDIR(st.st_mode))) { cert_dir = (char *)SSL_DIR; } } if(nspr_io_identity == PR_INVALID_IO_LAYER) { /* allocate an identity for our own NSPR I/O layer */ nspr_io_identity = PR_GetUniqueIdentity("libcurl"); if(nspr_io_identity == PR_INVALID_IO_LAYER) return CURLE_OUT_OF_MEMORY; /* the default methods just call down to the lower I/O layer */ memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof(nspr_io_methods)); /* override certain methods in the table by our wrappers */ nspr_io_methods.recv = nspr_io_recv; nspr_io_methods.send = nspr_io_send; nspr_io_methods.close = nspr_io_close; } result = nss_init_core(data, cert_dir); if(result) return result; if(!any_cipher_enabled()) NSS_SetDomesticPolicy(); initialized = 1; return CURLE_OK; } /** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */ static int Curl_nss_init(void) { /* curl_global_init() is not thread-safe so this test is ok */ if(nss_initlock == NULL) { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256); nss_initlock = PR_NewLock(); nss_crllock = PR_NewLock(); nss_findslot_lock = PR_NewLock(); nss_trustload_lock = PR_NewLock(); } /* We will actually initialize NSS later */ return 1; } /* data might be NULL */ CURLcode Curl_nss_force_init(struct Curl_easy *data) { CURLcode result; if(!nss_initlock) { if(data) failf(data, "unable to initialize NSS, curl_global_init() should have " "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL"); return CURLE_FAILED_INIT; } PR_Lock(nss_initlock); result = nss_init(data); PR_Unlock(nss_initlock); return result; } /* Global cleanup */ static void Curl_nss_cleanup(void) { /* This function isn't required to be threadsafe and this is only done * as a safety feature. */ PR_Lock(nss_initlock); if(initialized) { /* Free references to client certificates held in the SSL session cache. * Omitting this hampers destruction of the security module owning * the certificates. */ SSL_ClearSessionCache(); nss_unload_module(&pem_module); nss_unload_module(&trust_module); NSS_ShutdownContext(nss_context); nss_context = NULL; } /* destroy all CRL items */ Curl_llist_destroy(&nss_crl_list, NULL); PR_Unlock(nss_initlock); PR_DestroyLock(nss_initlock); PR_DestroyLock(nss_crllock); PR_DestroyLock(nss_findslot_lock); PR_DestroyLock(nss_trustload_lock); nss_initlock = NULL; initialized = 0; } /* * This function uses SSL_peek to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ static int Curl_nss_check_cxn(struct connectdata *conn) { struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET]; int rc; char buf; rc = PR_Recv(BACKEND->handle, (void *)&buf, 1, PR_MSG_PEEK, PR_SecondsToInterval(1)); if(rc > 0) return 1; /* connection still in place */ if(rc == 0) return 0; /* connection has been closed */ return -1; /* connection status unknown */ } static void nss_close(struct ssl_connect_data *connssl) { /* before the cleanup, check whether we are using a client certificate */ const bool client_cert = (BACKEND->client_nickname != NULL) || (BACKEND->obj_clicert != NULL); free(BACKEND->client_nickname); BACKEND->client_nickname = NULL; /* destroy all NSS objects in order to avoid failure of NSS shutdown */ Curl_llist_destroy(&BACKEND->obj_list, NULL); BACKEND->obj_clicert = NULL; if(BACKEND->handle) { if(client_cert) /* A server might require different authentication based on the * particular path being requested by the client. To support this * scenario, we must ensure that a connection will never reuse the * authentication data from a previous connection. */ SSL_InvalidateSession(BACKEND->handle); PR_Close(BACKEND->handle); BACKEND->handle = NULL; } } /* * This function is called when an SSL connection is closed. */ static void Curl_nss_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct ssl_connect_data *connssl_proxy = &conn->proxy_ssl[sockindex]; if(BACKEND->handle || connssl_proxy->backend->handle) { /* NSS closes the socket we previously handed to it, so we must mark it as closed to avoid double close */ fake_sclose(conn->sock[sockindex]); conn->sock[sockindex] = CURL_SOCKET_BAD; } if(BACKEND->handle) /* nss_close(connssl) will transitively close also connssl_proxy->backend->handle if both are used. Clear it to avoid a double close leading to crash. */ connssl_proxy->backend->handle = NULL; nss_close(connssl); nss_close(connssl_proxy); } /* return true if NSS can provide error code (and possibly msg) for the error */ static bool is_nss_error(CURLcode err) { switch(err) { case CURLE_PEER_FAILED_VERIFICATION: case CURLE_SSL_CERTPROBLEM: case CURLE_SSL_CONNECT_ERROR: case CURLE_SSL_ISSUER_ERROR: return true; default: return false; } } /* return true if the given error code is related to a client certificate */ static bool is_cc_error(PRInt32 err) { switch(err) { case SSL_ERROR_BAD_CERT_ALERT: case SSL_ERROR_EXPIRED_CERT_ALERT: case SSL_ERROR_REVOKED_CERT_ALERT: return true; default: return false; } } static Curl_recv nss_recv; static Curl_send nss_send; static CURLcode nss_load_ca_certificates(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; const char *cafile = SSL_CONN_CONFIG(CAfile); const char *capath = SSL_CONN_CONFIG(CApath); bool use_trust_module; CURLcode result = CURLE_OK; /* treat empty string as unset */ if(cafile && !cafile[0]) cafile = NULL; if(capath && !capath[0]) capath = NULL; infof(data, " CAfile: %s\n CApath: %s\n", cafile ? cafile : "none", capath ? capath : "none"); /* load libnssckbi.so if no other trust roots were specified */ use_trust_module = !cafile && !capath; PR_Lock(nss_trustload_lock); if(use_trust_module && !trust_module) { /* libnssckbi.so needed but not yet loaded --> load it! */ result = nss_load_module(&trust_module, trust_library, "trust"); infof(data, "%s %s\n", (result) ? "failed to load" : "loaded", trust_library); if(result == CURLE_FAILED_INIT) /* If libnssckbi.so is not available (or fails to load), one can still use CA certificates stored in NSS database. Ignore the failure. */ result = CURLE_OK; } else if(!use_trust_module && trust_module) { /* libnssckbi.so not needed but already loaded --> unload it! */ infof(data, "unloading %s\n", trust_library); nss_unload_module(&trust_module); } PR_Unlock(nss_trustload_lock); if(cafile) result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE); if(result) return result; if(capath) { struct_stat st; if(stat(capath, &st) == -1) return CURLE_SSL_CACERT_BADFILE; if(S_ISDIR(st.st_mode)) { PRDirEntry *entry; PRDir *dir = PR_OpenDir(capath); if(!dir) return CURLE_SSL_CACERT_BADFILE; while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) { char *fullpath = aprintf("%s/%s", capath, entry->name); if(!fullpath) { PR_CloseDir(dir); return CURLE_OUT_OF_MEMORY; } if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE)) /* This is purposefully tolerant of errors so non-PEM files can * be in the same directory */ infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath); free(fullpath); } PR_CloseDir(dir); } else infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath); } return CURLE_OK; } static CURLcode nss_sslver_from_curl(PRUint16 *nssver, long version) { switch(version) { case CURL_SSLVERSION_SSLv2: *nssver = SSL_LIBRARY_VERSION_2; return CURLE_OK; case CURL_SSLVERSION_SSLv3: *nssver = SSL_LIBRARY_VERSION_3_0; return CURLE_OK; case CURL_SSLVERSION_TLSv1_0: *nssver = SSL_LIBRARY_VERSION_TLS_1_0; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1: #ifdef SSL_LIBRARY_VERSION_TLS_1_1 *nssver = SSL_LIBRARY_VERSION_TLS_1_1; return CURLE_OK; #else return CURLE_SSL_CONNECT_ERROR; #endif case CURL_SSLVERSION_TLSv1_2: #ifdef SSL_LIBRARY_VERSION_TLS_1_2 *nssver = SSL_LIBRARY_VERSION_TLS_1_2; return CURLE_OK; #else return CURLE_SSL_CONNECT_ERROR; #endif case CURL_SSLVERSION_TLSv1_3: #ifdef SSL_LIBRARY_VERSION_TLS_1_3 *nssver = SSL_LIBRARY_VERSION_TLS_1_3; return CURLE_OK; #else return CURLE_SSL_CONNECT_ERROR; #endif default: return CURLE_SSL_CONNECT_ERROR; } } static CURLcode nss_init_sslver(SSLVersionRange *sslver, struct Curl_easy *data, struct connectdata *conn) { CURLcode result; const long min = SSL_CONN_CONFIG(version); const long max = SSL_CONN_CONFIG(version_max); /* map CURL_SSLVERSION_DEFAULT to NSS default */ if(min == CURL_SSLVERSION_DEFAULT || max == CURL_SSLVERSION_MAX_DEFAULT) { /* map CURL_SSLVERSION_DEFAULT to NSS default */ if(SSL_VersionRangeGetDefault(ssl_variant_stream, sslver) != SECSuccess) return CURLE_SSL_CONNECT_ERROR; /* ... but make sure we use at least TLSv1.0 according to libcurl API */ if(sslver->min < SSL_LIBRARY_VERSION_TLS_1_0) sslver->min = SSL_LIBRARY_VERSION_TLS_1_0; } switch(min) { case CURL_SSLVERSION_TLSv1: case CURL_SSLVERSION_DEFAULT: break; default: result = nss_sslver_from_curl(&sslver->min, min); if(result) { failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); return result; } } switch(max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: break; default: result = nss_sslver_from_curl(&sslver->max, max >> 16); if(result) { failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); return result; } } return CURLE_OK; } static CURLcode nss_fail_connect(struct ssl_connect_data *connssl, struct Curl_easy *data, CURLcode curlerr) { PRErrorCode err = 0; if(is_nss_error(curlerr)) { /* read NSPR error code */ err = PR_GetError(); if(is_cc_error(err)) curlerr = CURLE_SSL_CERTPROBLEM; /* print the error number and error string */ infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err)); /* print a human-readable message describing the error if available */ nss_print_error_message(data, err); } /* cleanup on connection failure */ Curl_llist_destroy(&BACKEND->obj_list, NULL); return curlerr; } /* Switch the SSL socket into blocking or non-blocking mode. */ static CURLcode nss_set_blocking(struct ssl_connect_data *connssl, struct Curl_easy *data, bool blocking) { static PRSocketOptionData sock_opt; sock_opt.option = PR_SockOpt_Nonblocking; sock_opt.value.non_blocking = !blocking; if(PR_SetSocketOption(BACKEND->handle, &sock_opt) != PR_SUCCESS) return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR); return CURLE_OK; } static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex) { PRFileDesc *model = NULL; PRFileDesc *nspr_io = NULL; PRFileDesc *nspr_io_stub = NULL; PRBool ssl_no_cache; PRBool ssl_cbc_random_iv; struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CURLcode result; bool second_layer = FALSE; SSLVersionRange sslver_supported; SSLVersionRange sslver = { SSL_LIBRARY_VERSION_TLS_1_0, /* min */ #ifdef SSL_LIBRARY_VERSION_TLS_1_3 SSL_LIBRARY_VERSION_TLS_1_3 /* max */ #elif defined SSL_LIBRARY_VERSION_TLS_1_2 SSL_LIBRARY_VERSION_TLS_1_2 #elif defined SSL_LIBRARY_VERSION_TLS_1_1 SSL_LIBRARY_VERSION_TLS_1_1 #else SSL_LIBRARY_VERSION_TLS_1_0 #endif }; BACKEND->data = data; /* list of all NSS objects we need to destroy in Curl_nss_close() */ Curl_llist_init(&BACKEND->obj_list, nss_destroy_object); PR_Lock(nss_initlock); result = nss_init(conn->data); if(result) { PR_Unlock(nss_initlock); goto error; } PK11_SetPasswordFunc(nss_get_password); result = nss_load_module(&pem_module, pem_library, "PEM"); PR_Unlock(nss_initlock); if(result == CURLE_FAILED_INIT) infof(data, "WARNING: failed to load NSS PEM library %s. Using " "OpenSSL PEM certificates will not work.\n", pem_library); else if(result) goto error; result = CURLE_SSL_CONNECT_ERROR; model = PR_NewTCPSocket(); if(!model) goto error; model = SSL_ImportFD(NULL, model); if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess) goto error; if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess) goto error; if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess) goto error; /* do not use SSL cache if disabled or we are not going to verify peer */ ssl_no_cache = (SSL_SET_OPTION(primary.sessionid) && SSL_CONN_CONFIG(verifypeer)) ? PR_FALSE : PR_TRUE; if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess) goto error; /* enable/disable the requested SSL version(s) */ if(nss_init_sslver(&sslver, data, conn) != CURLE_OK) goto error; if(SSL_VersionRangeGetSupported(ssl_variant_stream, &sslver_supported) != SECSuccess) goto error; if(sslver_supported.max < sslver.max && sslver_supported.max >= sslver.min) { char *sslver_req_str, *sslver_supp_str; sslver_req_str = nss_sslver_to_name(sslver.max); sslver_supp_str = nss_sslver_to_name(sslver_supported.max); if(sslver_req_str && sslver_supp_str) infof(data, "Falling back from %s to max supported SSL version (%s)\n", sslver_req_str, sslver_supp_str); free(sslver_req_str); free(sslver_supp_str); sslver.max = sslver_supported.max; } if(SSL_VersionRangeSet(model, &sslver) != SECSuccess) goto error; ssl_cbc_random_iv = !SSL_SET_OPTION(enable_beast); #ifdef SSL_CBC_RANDOM_IV /* unless the user explicitly asks to allow the protocol vulnerability, we use the work-around */ if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess) infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n", ssl_cbc_random_iv); #else if(ssl_cbc_random_iv) infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n"); #endif if(SSL_CONN_CONFIG(cipher_list)) { if(set_ciphers(data, model, SSL_CONN_CONFIG(cipher_list)) != SECSuccess) { result = CURLE_SSL_CIPHER; goto error; } } if(!SSL_CONN_CONFIG(verifypeer) && SSL_CONN_CONFIG(verifyhost)) infof(data, "warning: ignoring value of ssl.verifyhost\n"); /* bypass the default SSL_AuthCertificate() hook in case we do not want to * verify peer */ if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess) goto error; /* not checked yet */ if(SSL_IS_PROXY()) data->set.proxy_ssl.certverifyresult = 0; else data->set.ssl.certverifyresult = 0; if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess) goto error; if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess) goto error; { const CURLcode rv = nss_load_ca_certificates(conn, sockindex); if((rv == CURLE_SSL_CACERT_BADFILE) && !SSL_CONN_CONFIG(verifypeer)) /* not a fatal error because we are not going to verify the peer */ infof(data, "warning: CA certificates failed to load\n"); else if(rv) { result = rv; goto error; } } if(SSL_SET_OPTION(CRLfile)) { const CURLcode rv = nss_load_crl(SSL_SET_OPTION(CRLfile)); if(rv) { result = rv; goto error; } infof(data, " CRLfile: %s\n", SSL_SET_OPTION(CRLfile)); } if(SSL_SET_OPTION(cert)) { char *nickname = dup_nickname(data, SSL_SET_OPTION(cert)); if(nickname) { /* we are not going to use libnsspem.so to read the client cert */ BACKEND->obj_clicert = NULL; } else { CURLcode rv = cert_stuff(conn, sockindex, SSL_SET_OPTION(cert), SSL_SET_OPTION(key)); if(rv) { /* failf() is already done in cert_stuff() */ result = rv; goto error; } } /* store the nickname for SelectClientCert() called during handshake */ BACKEND->client_nickname = nickname; } else BACKEND->client_nickname = NULL; if(SSL_GetClientAuthDataHook(model, SelectClientCert, (void *)connssl) != SECSuccess) { result = CURLE_SSL_CERTPROBLEM; goto error; } if(conn->proxy_ssl[sockindex].use) { DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state); DEBUGASSERT(conn->proxy_ssl[sockindex].backend->handle != NULL); nspr_io = conn->proxy_ssl[sockindex].backend->handle; second_layer = TRUE; } else { /* wrap OS file descriptor by NSPR's file descriptor abstraction */ nspr_io = PR_ImportTCPSocket(sockfd); if(!nspr_io) goto error; } /* create our own NSPR I/O layer */ nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods); if(!nspr_io_stub) { if(!second_layer) PR_Close(nspr_io); goto error; } /* make the per-connection data accessible from NSPR I/O callbacks */ nspr_io_stub->secret = (void *)connssl; /* push our new layer to the NSPR I/O stack */ if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) { if(!second_layer) PR_Close(nspr_io); PR_Close(nspr_io_stub); goto error; } /* import our model socket onto the current I/O stack */ BACKEND->handle = SSL_ImportFD(model, nspr_io); if(!BACKEND->handle) { if(!second_layer) PR_Close(nspr_io); goto error; } PR_Close(model); /* We don't need this any more */ model = NULL; /* This is the password associated with the cert that we're using */ if(SSL_SET_OPTION(key_passwd)) { SSL_SetPKCS11PinArg(BACKEND->handle, SSL_SET_OPTION(key_passwd)); } #ifdef SSL_ENABLE_OCSP_STAPLING if(SSL_CONN_CONFIG(verifystatus)) { if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE) != SECSuccess) goto error; } #endif #ifdef SSL_ENABLE_NPN if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn ? PR_TRUE : PR_FALSE) != SECSuccess) goto error; #endif #ifdef SSL_ENABLE_ALPN if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn ? PR_TRUE : PR_FALSE) != SECSuccess) goto error; #endif #if NSSVERNUM >= 0x030f04 /* 3.15.4 */ if(data->set.ssl.falsestart) { if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_FALSE_START, PR_TRUE) != SECSuccess) goto error; if(SSL_SetCanFalseStartCallback(BACKEND->handle, CanFalseStartCallback, conn) != SECSuccess) goto error; } #endif #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN) if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) { int cur = 0; unsigned char protocols[128]; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2 && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN; memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN); cur += NGHTTP2_PROTO_VERSION_ID_LEN; } #endif protocols[cur++] = ALPN_HTTP_1_1_LENGTH; memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH); cur += ALPN_HTTP_1_1_LENGTH; if(SSL_SetNextProtoNego(BACKEND->handle, protocols, cur) != SECSuccess) goto error; } #endif /* Force handshake on next I/O */ if(SSL_ResetHandshake(BACKEND->handle, /* asServer */ PR_FALSE) != SECSuccess) goto error; /* propagate hostname to the TLS layer */ if(SSL_SetURL(BACKEND->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name) != SECSuccess) goto error; /* prevent NSS from re-using the session for a different hostname */ if(SSL_SetSockPeerID(BACKEND->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name) != SECSuccess) goto error; return CURLE_OK; error: if(model) PR_Close(model); return nss_fail_connect(connssl, data, result); } static CURLcode nss_do_connect(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; CURLcode result = CURLE_SSL_CONNECT_ERROR; PRUint32 timeout; long * const certverifyresult = SSL_IS_PROXY() ? &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult; const char * const pinnedpubkey = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; /* check timeout situation */ const time_t time_left = Curl_timeleft(data, NULL, TRUE); if(time_left < 0) { failf(data, "timed out before SSL handshake"); result = CURLE_OPERATION_TIMEDOUT; goto error; } /* Force the handshake now */ timeout = PR_MillisecondsToInterval((PRUint32) time_left); if(SSL_ForceHandshakeWithTimeout(BACKEND->handle, timeout) != SECSuccess) { if(PR_GetError() == PR_WOULD_BLOCK_ERROR) /* blocking direction is updated by nss_update_connecting_state() */ return CURLE_AGAIN; else if(*certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN) result = CURLE_PEER_FAILED_VERIFICATION; else if(*certverifyresult != 0) result = CURLE_PEER_FAILED_VERIFICATION; goto error; } result = display_conn_info(conn, BACKEND->handle); if(result) goto error; if(SSL_SET_OPTION(issuercert)) { SECStatus ret = SECFailure; char *nickname = dup_nickname(data, SSL_SET_OPTION(issuercert)); if(nickname) { /* we support only nicknames in case of issuercert for now */ ret = check_issuer_cert(BACKEND->handle, nickname); free(nickname); } if(SECFailure == ret) { infof(data, "SSL certificate issuer check failed\n"); result = CURLE_SSL_ISSUER_ERROR; goto error; } else { infof(data, "SSL certificate issuer check ok\n"); } } result = cmp_peer_pubkey(connssl, pinnedpubkey); if(result) /* status already printed */ goto error; return CURLE_OK; error: return nss_fail_connect(connssl, data, result); } static CURLcode nss_connect_common(struct connectdata *conn, int sockindex, bool *done) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; const bool blocking = (done == NULL); CURLcode result; if(connssl->state == ssl_connection_complete) { if(!blocking) *done = TRUE; return CURLE_OK; } if(connssl->connecting_state == ssl_connect_1) { result = nss_setup_connect(conn, sockindex); if(result) /* we do not expect CURLE_AGAIN from nss_setup_connect() */ return result; connssl->connecting_state = ssl_connect_2; } /* enable/disable blocking mode before handshake */ result = nss_set_blocking(connssl, data, blocking); if(result) return result; result = nss_do_connect(conn, sockindex); switch(result) { case CURLE_OK: break; case CURLE_AGAIN: if(!blocking) /* CURLE_AGAIN in non-blocking mode is not an error */ return CURLE_OK; /* FALLTHROUGH */ default: return result; } if(blocking) { /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */ result = nss_set_blocking(connssl, data, /* blocking */ FALSE); if(result) return result; } else /* signal completed SSL handshake */ *done = TRUE; connssl->state = ssl_connection_complete; conn->recv[sockindex] = nss_recv; conn->send[sockindex] = nss_send; /* ssl_connect_done is never used outside, go back to the initial state */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex) { return nss_connect_common(conn, sockindex, /* blocking */ NULL); } static CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return nss_connect_common(conn, sockindex, done); } static ssize_t nss_send(struct connectdata *conn, /* connection data */ int sockindex, /* socketindex */ const void *mem, /* send this data */ size_t len, /* amount to write */ CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; ssize_t rc; /* The SelectClientCert() hook uses this for infof() and failf() but the handle stored in nss_setup_connect() could have already been freed. */ BACKEND->data = conn->data; rc = PR_Send(BACKEND->handle, mem, (int)len, 0, PR_INTERVAL_NO_WAIT); if(rc < 0) { PRInt32 err = PR_GetError(); if(err == PR_WOULD_BLOCK_ERROR) *curlcode = CURLE_AGAIN; else { /* print the error number and error string */ const char *err_name = nss_error_to_name(err); infof(conn->data, "SSL write: error %d (%s)\n", err, err_name); /* print a human-readable message describing the error if available */ nss_print_error_message(conn->data, err); *curlcode = (is_cc_error(err)) ? CURLE_SSL_CERTPROBLEM : CURLE_SEND_ERROR; } return -1; } return rc; /* number of bytes */ } static ssize_t nss_recv(struct connectdata *conn, /* connection data */ int sockindex, /* socketindex */ char *buf, /* store read data here */ size_t buffersize, /* max amount to read */ CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; ssize_t nread; /* The SelectClientCert() hook uses this for infof() and failf() but the handle stored in nss_setup_connect() could have already been freed. */ BACKEND->data = conn->data; nread = PR_Recv(BACKEND->handle, buf, (int)buffersize, 0, PR_INTERVAL_NO_WAIT); if(nread < 0) { /* failed SSL read */ PRInt32 err = PR_GetError(); if(err == PR_WOULD_BLOCK_ERROR) *curlcode = CURLE_AGAIN; else { /* print the error number and error string */ const char *err_name = nss_error_to_name(err); infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name); /* print a human-readable message describing the error if available */ nss_print_error_message(conn->data, err); *curlcode = (is_cc_error(err)) ? CURLE_SSL_CERTPROBLEM : CURLE_RECV_ERROR; } return -1; } return nread; } static size_t Curl_nss_version(char *buffer, size_t size) { return msnprintf(buffer, size, "NSS/%s", NSS_VERSION); } /* data might be NULL */ static int Curl_nss_seed(struct Curl_easy *data) { /* make sure that NSS is initialized */ return !!Curl_nss_force_init(data); } /* data might be NULL */ static CURLcode Curl_nss_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { Curl_nss_seed(data); /* Initiate the seed if not already done */ if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length))) /* signal a failure */ return CURLE_FAILED_INIT; return CURLE_OK; } static CURLcode Curl_nss_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len) { PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5); unsigned int MD5out; PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen)); PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len)); PK11_DestroyContext(MD5pw, PR_TRUE); return CURLE_OK; } static CURLcode Curl_nss_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum, /* output */ size_t sha256len) { PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256); unsigned int SHA256out; PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen)); PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len)); PK11_DestroyContext(SHA256pw, PR_TRUE); return CURLE_OK; } static bool Curl_nss_cert_status_request(void) { #ifdef SSL_ENABLE_OCSP_STAPLING return TRUE; #else return FALSE; #endif } static bool Curl_nss_false_start(void) { #if NSSVERNUM >= 0x030f04 /* 3.15.4 */ return TRUE; #else return FALSE; #endif } static void *Curl_nss_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->handle; } const struct Curl_ssl Curl_ssl_nss = { { CURLSSLBACKEND_NSS, "nss" }, /* info */ SSLSUPP_CA_PATH | SSLSUPP_CERTINFO | SSLSUPP_PINNEDPUBKEY | SSLSUPP_HTTPS_PROXY, sizeof(struct ssl_backend_data), Curl_nss_init, /* init */ Curl_nss_cleanup, /* cleanup */ Curl_nss_version, /* version */ Curl_nss_check_cxn, /* check_cxn */ /* NSS has no shutdown function provided and thus always fail */ Curl_none_shutdown, /* shutdown */ Curl_none_data_pending, /* data_pending */ Curl_nss_random, /* random */ Curl_nss_cert_status_request, /* cert_status_request */ Curl_nss_connect, /* connect */ Curl_nss_connect_nonblocking, /* connect_nonblocking */ Curl_nss_get_internals, /* get_internals */ Curl_nss_close, /* close_one */ Curl_none_close_all, /* close_all */ /* NSS has its own session ID cache */ Curl_none_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_nss_false_start, /* false_start */ Curl_nss_md5sum, /* md5sum */ Curl_nss_sha256sum /* sha256sum */ }; #endif /* USE_NSS */
YifuLiu/AliOS-Things
components/curl/lib/vtls/nss.c
C
apache-2.0
73,816
#ifndef HEADER_CURL_NSSG_H #define HEADER_CURL_NSSG_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_NSS /* * This header should only be needed to get included by vtls.c and nss.c */ #include "urldata.h" /* initialize NSS library if not already */ CURLcode Curl_nss_force_init(struct Curl_easy *data); extern const struct Curl_ssl Curl_ssl_nss; #endif /* USE_NSS */ #endif /* HEADER_CURL_NSSG_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/nssg.h
C
apache-2.0
1,419
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. */ /* * The original SSLeay-using code for curl was written by Linas Vepstas and * Sampo Kellomaki 1998. */ #include "curl_setup.h" #ifdef USE_OPENSSL #include <limits.h> #include "urldata.h" #include "sendf.h" #include "formdata.h" /* for the boundary function */ #include "url.h" /* for the ssl config check function */ #include "inet_pton.h" #include "openssl.h" #include "connect.h" #include "slist.h" #include "select.h" #include "vtls.h" #include "strcase.h" #include "hostcheck.h" #include "multiif.h" #include "curl_printf.h" #include <openssl/ssl.h> #include <openssl/rand.h> #include <openssl/x509v3.h> #ifndef OPENSSL_NO_DSA #include <openssl/dsa.h> #endif #include <openssl/dh.h> #include <openssl/err.h> #include <openssl/md5.h> #include <openssl/conf.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/pkcs12.h> #ifdef USE_AMISSL #include "amigaos.h" #endif #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP) #include <openssl/ocsp.h> #endif #if (OPENSSL_VERSION_NUMBER >= 0x0090700fL) && /* 0.9.7 or later */ \ !defined(OPENSSL_NO_ENGINE) #define USE_OPENSSL_ENGINE #include <openssl/engine.h> #endif #include "warnless.h" #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */ /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS renegotiations when built with BoringSSL. Renegotiating is non-compliant with HTTP/2 and "an extremely dangerous protocol feature". Beware. #define ALLOW_RENEG 1 */ #ifndef OPENSSL_VERSION_NUMBER #error "OPENSSL_VERSION_NUMBER not defined" #endif #ifdef USE_OPENSSL_ENGINE #include <openssl/ui.h> #endif #if OPENSSL_VERSION_NUMBER >= 0x00909000L #define SSL_METHOD_QUAL const #else #define SSL_METHOD_QUAL #endif #if (OPENSSL_VERSION_NUMBER >= 0x10000000L) #define HAVE_ERR_REMOVE_THREAD_STATE 1 #endif #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \ OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */ #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */ #define OPENSSL_NO_SSL2 #endif #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \ !(defined(LIBRESSL_VERSION_NUMBER) && \ LIBRESSL_VERSION_NUMBER < 0x20700000L) #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */ #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */ #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */ #define CONST_EXTS const #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1 /* funny typecast define due to difference in API */ #ifdef LIBRESSL_VERSION_NUMBER #define ARG2_X509_signature_print (X509_ALGOR *) #else #define ARG2_X509_signature_print #endif #else /* For OpenSSL before 1.1.0 */ #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x) #define X509_get0_notBefore(x) X509_get_notBefore(x) #define X509_get0_notAfter(x) X509_get_notAfter(x) #define CONST_EXTS /* nope */ #ifndef LIBRESSL_VERSION_NUMBER #define OpenSSL_version_num() SSLeay() #endif #endif #ifdef LIBRESSL_VERSION_NUMBER #define OpenSSL_version_num() LIBRESSL_VERSION_NUMBER #endif #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \ !(defined(LIBRESSL_VERSION_NUMBER) && \ LIBRESSL_VERSION_NUMBER < 0x20700000L) #define HAVE_X509_GET0_SIGNATURE 1 #endif #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \ OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \ !defined(OPENSSL_NO_COMP) #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1 #endif #if (OPENSSL_VERSION_NUMBER < 0x0090808fL) /* not present in older OpenSSL */ #define OPENSSL_load_builtin_modules(x) #endif /* * Whether SSL_CTX_set_keylog_callback is available. * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287 * BoringSSL: supported since d28f59c27bac (committed 2015-11-19) * LibreSSL: unsupported in at least 2.7.2 (explicitly check for it since it * lies and pretends to be OpenSSL 2.0.0). */ #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \ !defined(LIBRESSL_VERSION_NUMBER)) || \ defined(OPENSSL_IS_BORINGSSL) #define HAVE_KEYLOG_CALLBACK #endif /* Whether SSL_CTX_set_ciphersuites is available. * OpenSSL: supported since 1.1.1 (commit a53b5be6a05) * BoringSSL: no * LibreSSL: no */ #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L) && \ !defined(LIBRESSL_VERSION_NUMBER) && \ !defined(OPENSSL_IS_BORINGSSL)) #define HAVE_SSL_CTX_SET_CIPHERSUITES #define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH #endif #if defined(LIBRESSL_VERSION_NUMBER) #define OSSL_PACKAGE "LibreSSL" #elif defined(OPENSSL_IS_BORINGSSL) #define OSSL_PACKAGE "BoringSSL" #else #define OSSL_PACKAGE "OpenSSL" #endif #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* up2date versions of OpenSSL maintain the default reasonably secure without * breaking compatibility, so it is better not to override the default by curl */ #define DEFAULT_CIPHER_SELECTION NULL #else /* ... but it is not the case with old versions of OpenSSL */ #define DEFAULT_CIPHER_SELECTION \ "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH" #endif #define ENABLE_SSLKEYLOGFILE #ifdef ENABLE_SSLKEYLOGFILE typedef struct ssl_tap_state { int master_key_length; unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char client_random[SSL3_RANDOM_SIZE]; } ssl_tap_state_t; #endif /* ENABLE_SSLKEYLOGFILE */ struct ssl_backend_data { /* these ones requires specific SSL-types */ SSL_CTX* ctx; SSL* handle; X509* server_cert; #ifdef ENABLE_SSLKEYLOGFILE /* tap_state holds the last seen master key if we're logging them */ ssl_tap_state_t tap_state; #endif }; #define BACKEND connssl->backend /* * Number of bytes to read from the random number seed file. This must be * a finite value (because some entropy "files" like /dev/urandom have * an infinite length), but must be large enough to provide enough * entropy to properly seed OpenSSL's PRNG. */ #define RAND_LOAD_LENGTH 1024 #ifdef ENABLE_SSLKEYLOGFILE /* The fp for the open SSLKEYLOGFILE, or NULL if not open */ static FILE *keylog_file_fp; #ifdef HAVE_KEYLOG_CALLBACK static void ossl_keylog_callback(const SSL *ssl, const char *line) { (void)ssl; /* Using fputs here instead of fprintf since libcurl's fprintf replacement may not be thread-safe. */ if(keylog_file_fp && line && *line) { char stackbuf[256]; char *buf; size_t linelen = strlen(line); if(linelen <= sizeof(stackbuf) - 2) buf = stackbuf; else { buf = malloc(linelen + 2); if(!buf) return; } memcpy(buf, line, linelen); buf[linelen] = '\n'; buf[linelen + 1] = '\0'; fputs(buf, keylog_file_fp); if(buf != stackbuf) free(buf); } } #else #define KEYLOG_PREFIX "CLIENT_RANDOM " #define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1) /* * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL * being used doesn't have native support for doing that. */ static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state) { const char *hex = "0123456789ABCDEF"; int pos, i; char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 + 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1]; const SSL_SESSION *session = SSL_get_session(ssl); unsigned char client_random[SSL3_RANDOM_SIZE]; unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; int master_key_length = 0; if(!session || !keylog_file_fp) return; #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ !(defined(LIBRESSL_VERSION_NUMBER) && \ LIBRESSL_VERSION_NUMBER < 0x20700000L) /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that * we have a valid SSL context if we have a non-NULL session. */ SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE); master_key_length = (int) SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH); #else if(ssl->s3 && session->master_key_length > 0) { master_key_length = session->master_key_length; memcpy(master_key, session->master_key, session->master_key_length); memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE); } #endif if(master_key_length <= 0) return; /* Skip writing keys if there is no key or it did not change. */ if(state->master_key_length == master_key_length && !memcmp(state->master_key, master_key, master_key_length) && !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) { return; } state->master_key_length = master_key_length; memcpy(state->master_key, master_key, master_key_length); memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE); memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN); pos = KEYLOG_PREFIX_LEN; /* Client Random for SSLv3/TLS */ for(i = 0; i < SSL3_RANDOM_SIZE; i++) { line[pos++] = hex[client_random[i] >> 4]; line[pos++] = hex[client_random[i] & 0xF]; } line[pos++] = ' '; /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */ for(i = 0; i < master_key_length; i++) { line[pos++] = hex[master_key[i] >> 4]; line[pos++] = hex[master_key[i] & 0xF]; } line[pos++] = '\n'; line[pos] = '\0'; /* Using fputs here instead of fprintf since libcurl's fprintf replacement may not be thread-safe. */ fputs(line, keylog_file_fp); } #endif /* !HAVE_KEYLOG_CALLBACK */ #endif /* ENABLE_SSLKEYLOGFILE */ static const char *SSL_ERROR_to_str(int err) { switch(err) { case SSL_ERROR_NONE: return "SSL_ERROR_NONE"; case SSL_ERROR_SSL: return "SSL_ERROR_SSL"; case SSL_ERROR_WANT_READ: return "SSL_ERROR_WANT_READ"; case SSL_ERROR_WANT_WRITE: return "SSL_ERROR_WANT_WRITE"; case SSL_ERROR_WANT_X509_LOOKUP: return "SSL_ERROR_WANT_X509_LOOKUP"; case SSL_ERROR_SYSCALL: return "SSL_ERROR_SYSCALL"; case SSL_ERROR_ZERO_RETURN: return "SSL_ERROR_ZERO_RETURN"; case SSL_ERROR_WANT_CONNECT: return "SSL_ERROR_WANT_CONNECT"; case SSL_ERROR_WANT_ACCEPT: return "SSL_ERROR_WANT_ACCEPT"; #if defined(SSL_ERROR_WANT_ASYNC) case SSL_ERROR_WANT_ASYNC: return "SSL_ERROR_WANT_ASYNC"; #endif #if defined(SSL_ERROR_WANT_ASYNC_JOB) case SSL_ERROR_WANT_ASYNC_JOB: return "SSL_ERROR_WANT_ASYNC_JOB"; #endif #if defined(SSL_ERROR_WANT_EARLY) case SSL_ERROR_WANT_EARLY: return "SSL_ERROR_WANT_EARLY"; #endif default: return "SSL_ERROR unknown"; } } /* Return error string for last OpenSSL error */ static char *ossl_strerror(unsigned long error, char *buf, size_t size) { ERR_error_string_n(error, buf, size); return buf; } /* Return an extra data index for the connection data. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data(). */ static int ossl_get_ssl_conn_index(void) { static int ssl_ex_data_conn_index = -1; if(ssl_ex_data_conn_index < 0) { ssl_ex_data_conn_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); } return ssl_ex_data_conn_index; } /* Return an extra data index for the sockindex. * This index can be used with SSL_get_ex_data() and SSL_set_ex_data(). */ static int ossl_get_ssl_sockindex_index(void) { static int ssl_ex_data_sockindex_index = -1; if(ssl_ex_data_sockindex_index < 0) { ssl_ex_data_sockindex_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); } return ssl_ex_data_sockindex_index; } static int passwd_callback(char *buf, int num, int encrypting, void *global_passwd) { DEBUGASSERT(0 == encrypting); if(!encrypting) { int klen = curlx_uztosi(strlen((char *)global_passwd)); if(num > klen) { memcpy(buf, global_passwd, klen + 1); return klen; } } return 0; } /* * rand_enough() returns TRUE if we have seeded the random engine properly. */ static bool rand_enough(void) { return (0 != RAND_status()) ? TRUE : FALSE; } static CURLcode Curl_ossl_seed(struct Curl_easy *data) { /* we have the "SSL is seeded" boolean static to prevent multiple time-consuming seedings in vain */ static bool ssl_seeded = FALSE; char fname[256]; if(ssl_seeded) return CURLE_OK; if(rand_enough()) { /* OpenSSL 1.1.0+ will return here */ ssl_seeded = TRUE; return CURLE_OK; } #ifndef RANDOM_FILE /* if RANDOM_FILE isn't defined, we only perform this if an option tells us to! */ if(data->set.str[STRING_SSL_RANDOM_FILE]) #define RANDOM_FILE "" /* doesn't matter won't be used */ #endif { /* let the option override the define */ RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]? data->set.str[STRING_SSL_RANDOM_FILE]: RANDOM_FILE), RAND_LOAD_LENGTH); if(rand_enough()) return CURLE_OK; } #if defined(HAVE_RAND_EGD) /* only available in OpenSSL 0.9.5 and later */ /* EGD_SOCKET is set at configure time or not at all */ #ifndef EGD_SOCKET /* If we don't have the define set, we only do this if the egd-option is set */ if(data->set.str[STRING_SSL_EGDSOCKET]) #define EGD_SOCKET "" /* doesn't matter won't be used */ #endif { /* If there's an option and a define, the option overrides the define */ int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]? data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET); if(-1 != ret) { if(rand_enough()) return CURLE_OK; } } #endif /* fallback to a custom seeding of the PRNG using a hash based on a current time */ do { unsigned char randb[64]; size_t len = sizeof(randb); size_t i, i_max; for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) { struct curltime tv = Curl_now(); Curl_wait_ms(1); tv.tv_sec *= i + 1; tv.tv_usec *= (unsigned int)i + 2; tv.tv_sec ^= ((Curl_now().tv_sec + Curl_now().tv_usec) * (i + 3)) << 8; tv.tv_usec ^= (unsigned int) ((Curl_now().tv_sec + Curl_now().tv_usec) * (i + 4)) << 16; memcpy(&randb[i * sizeof(struct curltime)], &tv, sizeof(struct curltime)); } RAND_add(randb, (int)len, (double)len/2); } while(!rand_enough()); /* generates a default path for the random seed file */ fname[0] = 0; /* blank it first */ RAND_file_name(fname, sizeof(fname)); if(fname[0]) { /* we got a file name to try */ RAND_load_file(fname, RAND_LOAD_LENGTH); if(rand_enough()) return CURLE_OK; } infof(data, "libcurl is now using a weak random seed!\n"); return (rand_enough() ? CURLE_OK : CURLE_SSL_CONNECT_ERROR /* confusing error code */); } #ifndef SSL_FILETYPE_ENGINE #define SSL_FILETYPE_ENGINE 42 #endif #ifndef SSL_FILETYPE_PKCS12 #define SSL_FILETYPE_PKCS12 43 #endif static int do_file_type(const char *type) { if(!type || !type[0]) return SSL_FILETYPE_PEM; if(strcasecompare(type, "PEM")) return SSL_FILETYPE_PEM; if(strcasecompare(type, "DER")) return SSL_FILETYPE_ASN1; if(strcasecompare(type, "ENG")) return SSL_FILETYPE_ENGINE; if(strcasecompare(type, "P12")) return SSL_FILETYPE_PKCS12; return -1; } #ifdef USE_OPENSSL_ENGINE /* * Supply default password to the engine user interface conversation. * The password is passed by OpenSSL engine from ENGINE_load_private_key() * last argument to the ui and can be obtained by UI_get0_user_data(ui) here. */ static int ssl_ui_reader(UI *ui, UI_STRING *uis) { const char *password; switch(UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: password = (const char *)UI_get0_user_data(ui); if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { UI_set_result(ui, uis, password); return 1; } default: break; } return (UI_method_get_reader(UI_OpenSSL()))(ui, uis); } /* * Suppress interactive request for a default password if available. */ static int ssl_ui_writer(UI *ui, UI_STRING *uis) { switch(UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: if(UI_get0_user_data(ui) && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { return 1; } default: break; } return (UI_method_get_writer(UI_OpenSSL()))(ui, uis); } /* * Check if a given string is a PKCS#11 URI */ static bool is_pkcs11_uri(const char *string) { return (string && strncasecompare(string, "pkcs11:", 7)); } #endif static CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine); static int cert_stuff(struct connectdata *conn, SSL_CTX* ctx, char *cert_file, const char *cert_type, char *key_file, const char *key_type, char *key_passwd) { struct Curl_easy *data = conn->data; char error_buffer[256]; bool check_privkey = TRUE; int file_type = do_file_type(cert_type); if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) { SSL *ssl; X509 *x509; int cert_done = 0; if(key_passwd) { /* set the password in the callback userdata */ SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd); /* Set passwd callback: */ SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); } switch(file_type) { case SSL_FILETYPE_PEM: /* SSL_CTX_use_certificate_chain_file() only works on PEM files */ if(SSL_CTX_use_certificate_chain_file(ctx, cert_file) != 1) { failf(data, "could not load PEM client certificate, " OSSL_PACKAGE " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); return 0; } break; case SSL_FILETYPE_ASN1: /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but we use the case above for PEM so this can only be performed with ASN1 files. */ if(SSL_CTX_use_certificate_file(ctx, cert_file, file_type) != 1) { failf(data, "could not load ASN1 client certificate, " OSSL_PACKAGE " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); return 0; } break; case SSL_FILETYPE_ENGINE: #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME) { /* Implicitly use pkcs11 engine if none was provided and the * cert_file is a PKCS#11 URI */ if(!data->state.engine) { if(is_pkcs11_uri(cert_file)) { if(Curl_ossl_set_engine(data, "pkcs11") != CURLE_OK) { return 0; } } } if(data->state.engine) { const char *cmd_name = "LOAD_CERT_CTRL"; struct { const char *cert_id; X509 *cert; } params; params.cert_id = cert_file; params.cert = NULL; /* Does the engine supports LOAD_CERT_CTRL ? */ if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME, 0, (void *)cmd_name, NULL)) { failf(data, "ssl engine does not support loading certificates"); return 0; } /* Load the certificate from the engine */ if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name, 0, &params, NULL, 1)) { failf(data, "ssl engine cannot load client cert with id" " '%s' [%s]", cert_file, ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); return 0; } if(!params.cert) { failf(data, "ssl engine didn't initialized the certificate " "properly."); return 0; } if(SSL_CTX_use_certificate(ctx, params.cert) != 1) { failf(data, "unable to set client certificate"); X509_free(params.cert); return 0; } X509_free(params.cert); /* we don't need the handle any more... */ } else { failf(data, "crypto engine not set, can't load certificate"); return 0; } } break; #else failf(data, "file type ENG for certificate not implemented"); return 0; #endif case SSL_FILETYPE_PKCS12: { BIO *fp = NULL; PKCS12 *p12 = NULL; EVP_PKEY *pri; STACK_OF(X509) *ca = NULL; fp = BIO_new(BIO_s_file()); if(fp == NULL) { failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); return 0; } if(BIO_read_filename(fp, cert_file) <= 0) { failf(data, "could not open PKCS12 file '%s'", cert_file); BIO_free(fp); return 0; } p12 = d2i_PKCS12_bio(fp, NULL); BIO_free(fp); if(!p12) { failf(data, "error reading PKCS12 file '%s'", cert_file); return 0; } PKCS12_PBE_add(); if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) { failf(data, "could not parse PKCS12 file, check password, " OSSL_PACKAGE " error %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); PKCS12_free(p12); return 0; } PKCS12_free(p12); if(SSL_CTX_use_certificate(ctx, x509) != 1) { failf(data, "could not load PKCS12 client certificate, " OSSL_PACKAGE " error %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); goto fail; } if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) { failf(data, "unable to use private key from PKCS12 file '%s'", cert_file); goto fail; } if(!SSL_CTX_check_private_key (ctx)) { failf(data, "private key from PKCS12 file '%s' " "does not match certificate in same file", cert_file); goto fail; } /* Set Certificate Verification chain */ if(ca) { while(sk_X509_num(ca)) { /* * Note that sk_X509_pop() is used below to make sure the cert is * removed from the stack properly before getting passed to * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously * we used sk_X509_value() instead, but then we'd clean it in the * subsequent sk_X509_pop_free() call. */ X509 *x = sk_X509_pop(ca); if(!SSL_CTX_add_client_CA(ctx, x)) { X509_free(x); failf(data, "cannot add certificate to client CA list"); goto fail; } if(!SSL_CTX_add_extra_chain_cert(ctx, x)) { X509_free(x); failf(data, "cannot add certificate to certificate chain"); goto fail; } } } cert_done = 1; fail: EVP_PKEY_free(pri); X509_free(x509); #ifdef USE_AMISSL sk_X509_pop_free(ca, Curl_amiga_X509_free); #else sk_X509_pop_free(ca, X509_free); #endif if(!cert_done) return 0; /* failure! */ break; } default: failf(data, "not supported file type '%s' for certificate", cert_type); return 0; } if(!key_file) key_file = cert_file; else file_type = do_file_type(key_type); switch(file_type) { case SSL_FILETYPE_PEM: if(cert_done) break; /* FALLTHROUGH */ case SSL_FILETYPE_ASN1: if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) { failf(data, "unable to set private key file: '%s' type %s", key_file, key_type?key_type:"PEM"); return 0; } break; case SSL_FILETYPE_ENGINE: #ifdef USE_OPENSSL_ENGINE { /* XXXX still needs some work */ EVP_PKEY *priv_key = NULL; /* Implicitly use pkcs11 engine if none was provided and the * key_file is a PKCS#11 URI */ if(!data->state.engine) { if(is_pkcs11_uri(key_file)) { if(Curl_ossl_set_engine(data, "pkcs11") != CURLE_OK) { return 0; } } } if(data->state.engine) { UI_METHOD *ui_method = UI_create_method((char *)"curl user interface"); if(!ui_method) { failf(data, "unable do create " OSSL_PACKAGE " user-interface method"); return 0; } UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); UI_method_set_reader(ui_method, ssl_ui_reader); UI_method_set_writer(ui_method, ssl_ui_writer); /* the typecast below was added to please mingw32 */ priv_key = (EVP_PKEY *) ENGINE_load_private_key(data->state.engine, key_file, ui_method, key_passwd); UI_destroy_method(ui_method); if(!priv_key) { failf(data, "failed to load private key from crypto engine"); return 0; } if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { failf(data, "unable to set private key"); EVP_PKEY_free(priv_key); return 0; } EVP_PKEY_free(priv_key); /* we don't need the handle any more... */ } else { failf(data, "crypto engine not set, can't load private key"); return 0; } } break; #else failf(data, "file type ENG for private key not supported"); return 0; #endif case SSL_FILETYPE_PKCS12: if(!cert_done) { failf(data, "file type P12 for private key not supported"); return 0; } break; default: failf(data, "not supported file type for private key"); return 0; } ssl = SSL_new(ctx); if(!ssl) { failf(data, "unable to create an SSL structure"); return 0; } x509 = SSL_get_certificate(ssl); /* This version was provided by Evan Jordan and is supposed to not leak memory as the previous version: */ if(x509) { EVP_PKEY *pktmp = X509_get_pubkey(x509); EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl)); EVP_PKEY_free(pktmp); } #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL) { /* If RSA is used, don't check the private key if its flags indicate * it doesn't support it. */ EVP_PKEY *priv_key = SSL_get_privatekey(ssl); int pktype; #ifdef HAVE_OPAQUE_EVP_PKEY pktype = EVP_PKEY_id(priv_key); #else pktype = priv_key->type; #endif if(pktype == EVP_PKEY_RSA) { RSA *rsa = EVP_PKEY_get1_RSA(priv_key); if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK) check_privkey = FALSE; RSA_free(rsa); /* Decrement reference count */ } } #endif SSL_free(ssl); /* If we are using DSA, we can copy the parameters from * the private key */ if(check_privkey == TRUE) { /* Now we know that a key and cert have been set against * the SSL context */ if(!SSL_CTX_check_private_key(ctx)) { failf(data, "Private key does not match the certificate public key"); return 0; } } } return 1; } /* returns non-zero on failure */ static int x509_name_oneline(X509_NAME *a, char *buf, size_t size) { #if 0 return X509_NAME_oneline(a, buf, size); #else BIO *bio_out = BIO_new(BIO_s_mem()); BUF_MEM *biomem; int rc; if(!bio_out) return 1; /* alloc failed! */ rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC); BIO_get_mem_ptr(bio_out, &biomem); if((size_t)biomem->length < size) size = biomem->length; else size--; /* don't overwrite the buffer end */ memcpy(buf, biomem->data, size); buf[size] = 0; BIO_free(bio_out); return !rc; #endif } /** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */ static int Curl_ossl_init(void) { #ifdef ENABLE_SSLKEYLOGFILE char *keylog_file_name; #endif OPENSSL_load_builtin_modules(); #ifdef USE_OPENSSL_ENGINE ENGINE_load_builtin_engines(); #endif /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately that function makes an exit() call on wrongly formatted config files which makes it hard to use in some situations. OPENSSL_config() itself calls CONF_modules_load_file() and we use that instead and we ignore its return code! */ /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and 0.9.8e */ #ifndef CONF_MFLAGS_DEFAULT_SECTION #define CONF_MFLAGS_DEFAULT_SECTION 0x0 #endif #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG CONF_modules_load_file(NULL, NULL, CONF_MFLAGS_DEFAULT_SECTION| CONF_MFLAGS_IGNORE_MISSING_FILE); #endif #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ !defined(LIBRESSL_VERSION_NUMBER) /* OpenSSL 1.1.0+ takes care of initialization itself */ #else /* Lets get nice error messages */ SSL_load_error_strings(); /* Init the global ciphers and digests */ if(!SSLeay_add_ssl_algorithms()) return 0; OpenSSL_add_all_algorithms(); #endif #ifdef ENABLE_SSLKEYLOGFILE if(!keylog_file_fp) { keylog_file_name = curl_getenv("SSLKEYLOGFILE"); if(keylog_file_name) { keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT); if(keylog_file_fp) { #ifdef WIN32 if(setvbuf(keylog_file_fp, NULL, _IONBF, 0)) #else if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096)) #endif { fclose(keylog_file_fp); keylog_file_fp = NULL; } } Curl_safefree(keylog_file_name); } } #endif /* Initialize the extra data indexes */ if(ossl_get_ssl_conn_index() < 0 || ossl_get_ssl_sockindex_index() < 0) return 0; return 1; } /* Global cleanup */ static void Curl_ossl_cleanup(void) { #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ !defined(LIBRESSL_VERSION_NUMBER) /* OpenSSL 1.1 deprecates all these cleanup functions and turns them into no-ops in OpenSSL 1.0 compatibility mode */ #else /* Free ciphers and digests lists */ EVP_cleanup(); #ifdef USE_OPENSSL_ENGINE /* Free engine list */ ENGINE_cleanup(); #endif /* Free OpenSSL error strings */ ERR_free_strings(); /* Free thread local error state, destroying hash upon zero refcount */ #ifdef HAVE_ERR_REMOVE_THREAD_STATE ERR_remove_thread_state(NULL); #else ERR_remove_state(0); #endif /* Free all memory allocated by all configuration modules */ CONF_modules_free(); #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS SSL_COMP_free_compression_methods(); #endif #endif #ifdef ENABLE_SSLKEYLOGFILE if(keylog_file_fp) { fclose(keylog_file_fp); keylog_file_fp = NULL; } #endif } /* * This function is used to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ static int Curl_ossl_check_cxn(struct connectdata *conn) { /* SSL_peek takes data out of the raw recv buffer without peeking so we use recv MSG_PEEK instead. Bug #795 */ #ifdef MSG_PEEK char buf; ssize_t nread; nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf, (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK); if(nread == 0) return 0; /* connection has been closed */ if(nread == 1) return 1; /* connection still in place */ else if(nread == -1) { int err = SOCKERRNO; if(err == EINPROGRESS || #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK) err == EAGAIN || #endif err == EWOULDBLOCK) return 1; /* connection still in place */ if(err == ECONNRESET || #ifdef ECONNABORTED err == ECONNABORTED || #endif #ifdef ENETDOWN err == ENETDOWN || #endif #ifdef ENETRESET err == ENETRESET || #endif #ifdef ESHUTDOWN err == ESHUTDOWN || #endif #ifdef ETIMEDOUT err == ETIMEDOUT || #endif err == ENOTCONN) return 0; /* connection has been closed */ } #endif return -1; /* connection status unknown */ } /* Selects an OpenSSL crypto engine */ static CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine) { #ifdef USE_OPENSSL_ENGINE ENGINE *e; #if OPENSSL_VERSION_NUMBER >= 0x00909000L e = ENGINE_by_id(engine); #else /* avoid memory leak */ for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { const char *e_id = ENGINE_get_id(e); if(!strcmp(engine, e_id)) break; } #endif if(!e) { failf(data, "SSL Engine '%s' not found", engine); return CURLE_SSL_ENGINE_NOTFOUND; } if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } if(!ENGINE_init(e)) { char buf[256]; ENGINE_free(e); failf(data, "Failed to initialise SSL Engine '%s':\n%s", engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf))); return CURLE_SSL_ENGINE_INITFAILED; } data->state.engine = e; return CURLE_OK; #else (void)engine; failf(data, "SSL Engine not supported"); return CURLE_SSL_ENGINE_NOTFOUND; #endif } /* Sets engine as default for all SSL operations */ static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data) { #ifdef USE_OPENSSL_ENGINE if(data->state.engine) { if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { infof(data, "set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine)); } else { failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine)); return CURLE_SSL_ENGINE_SETFAILED; } } #else (void) data; #endif return CURLE_OK; } /* Return list of OpenSSL crypto engine names. */ static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data) { struct curl_slist *list = NULL; #ifdef USE_OPENSSL_ENGINE struct curl_slist *beg; ENGINE *e; for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { beg = curl_slist_append(list, ENGINE_get_id(e)); if(!beg) { curl_slist_free_all(list); return NULL; } list = beg; } #endif (void) data; return list; } static void ossl_close(struct ssl_connect_data *connssl) { if(BACKEND->handle) { (void)SSL_shutdown(BACKEND->handle); SSL_set_connect_state(BACKEND->handle); SSL_free(BACKEND->handle); BACKEND->handle = NULL; } if(BACKEND->ctx) { SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = NULL; } } /* * This function is called when an SSL connection is closed. */ static void Curl_ossl_close(struct connectdata *conn, int sockindex) { ossl_close(&conn->ssl[sockindex]); ossl_close(&conn->proxy_ssl[sockindex]); } /* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */ static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; char buf[256]; /* We will use this for the OpenSSL error buffer, so it has to be at least 256 bytes long. */ unsigned long sslerror; ssize_t nread; int buffsize; int err; bool done = FALSE; #ifndef CURL_DISABLE_FTP /* This has only been tested on the proftpd server, and the mod_tls code sends a close notify alert without waiting for a close notify alert in response. Thus we wait for a close notify alert from the server, but we do not send one. Let's hope other servers do the same... */ if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE) (void)SSL_shutdown(BACKEND->handle); #endif if(BACKEND->handle) { buffsize = (int)sizeof(buf); while(!done) { int what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT); if(what > 0) { ERR_clear_error(); /* Something to read, let's do it and hope that it is the close notify alert from the server */ nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize); err = SSL_get_error(BACKEND->handle, (int)nread); switch(err) { case SSL_ERROR_NONE: /* this is not an error */ case SSL_ERROR_ZERO_RETURN: /* no more data */ /* This is the expected response. There was no data but only the close notify alert */ done = TRUE; break; case SSL_ERROR_WANT_READ: /* there's data pending, re-invoke SSL_read() */ infof(data, "SSL_ERROR_WANT_READ\n"); break; case SSL_ERROR_WANT_WRITE: /* SSL wants a write. Really odd. Let's bail out. */ infof(data, "SSL_ERROR_WANT_WRITE\n"); done = TRUE; break; default: /* openssl/ssl.h says "look at error stack/return value/errno" */ sslerror = ERR_get_error(); failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d", (sslerror ? ossl_strerror(sslerror, buf, sizeof(buf)) : SSL_ERROR_to_str(err)), SOCKERRNO); done = TRUE; break; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); done = TRUE; } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; done = TRUE; } } /* while()-loop for the select() */ if(data->set.verbose) { #ifdef HAVE_SSL_GET_SHUTDOWN switch(SSL_get_shutdown(BACKEND->handle)) { case SSL_SENT_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n"); break; case SSL_RECEIVED_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n"); break; case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|" "SSL_RECEIVED__SHUTDOWN\n"); break; } #endif } SSL_free(BACKEND->handle); BACKEND->handle = NULL; } return retval; } static void Curl_ossl_session_free(void *ptr) { /* free the ID */ SSL_SESSION_free(ptr); } /* * This function is called when the 'data' struct is going away. Close * down everything and free all resources! */ static void Curl_ossl_close_all(struct Curl_easy *data) { #ifdef USE_OPENSSL_ENGINE if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } #else (void)data; #endif #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \ defined(HAVE_ERR_REMOVE_THREAD_STATE) /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread so we need to clean it here in case the thread will be killed. All OpenSSL code should extract the error in association with the error so clearing this queue here should be harmless at worst. */ ERR_remove_thread_state(NULL); #endif } /* ====================================================== */ /* * Match subjectAltName against the host name. This requires a conversion * in CURL_DOES_CONVERSIONS builds. */ static bool subj_alt_hostcheck(struct Curl_easy *data, const char *match_pattern, const char *hostname, const char *dispname) #ifdef CURL_DOES_CONVERSIONS { bool res = FALSE; /* Curl_cert_hostcheck uses host encoding, but we get ASCII from OpenSSl. */ char *match_pattern2 = strdup(match_pattern); if(match_pattern2) { if(Curl_convert_from_network(data, match_pattern2, strlen(match_pattern2)) == CURLE_OK) { if(Curl_cert_hostcheck(match_pattern2, hostname)) { res = TRUE; infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"\n", dispname, match_pattern2); } } free(match_pattern2); } else { failf(data, "SSL: out of memory when allocating temporary for subjectAltName"); } return res; } #else { #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)dispname; (void)data; #endif if(Curl_cert_hostcheck(match_pattern, hostname)) { infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"\n", dispname, match_pattern); return TRUE; } return FALSE; } #endif /* Quote from RFC2818 section 3.1 "Server Identity" If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead. Matching is performed using the matching rules specified by [RFC2459]. If more than one identity of a given type is present in the certificate (e.g., more than one dNSName name, a match in any one of the set is considered acceptable.) Names may contain the wildcard character * which is considered to match any single domain name component or component fragment. E.g., *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com but not bar.com. In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI. */ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) { bool matched = FALSE; int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */ size_t addrlen = 0; struct Curl_easy *data = conn->data; STACK_OF(GENERAL_NAME) *altnames; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif CURLcode result = CURLE_OK; bool dNSName = FALSE; /* if a dNSName field exists in the cert */ bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */ const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const char * const dispname = SSL_IS_PROXY() ? conn->http_proxy.host.dispname : conn->host.dispname; #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, hostname, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in6_addr); } else #endif if(Curl_inet_pton(AF_INET, hostname, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in_addr); } /* get a "list" of alternative names */ altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL); if(altnames) { int numalts; int i; bool dnsmatched = FALSE; bool ipmatched = FALSE; /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */ numalts = sk_GENERAL_NAME_num(altnames); /* loop through all alternatives - until a dnsmatch */ for(i = 0; (i < numalts) && !dnsmatched; i++) { /* get a handle to alternative name number i */ const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); if(check->type == GEN_DNS) dNSName = TRUE; else if(check->type == GEN_IPADD) iPAddress = TRUE; /* only check alternatives of the same type the target is */ if(check->type == target) { /* get data and length */ const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5); size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5); switch(target) { case GEN_DNS: /* name/pattern comparison */ /* The OpenSSL man page explicitly says: "In general it cannot be assumed that the data returned by ASN1_STRING_data() is null terminated or does not contain embedded nulls." But also that "The actual format of the data will depend on the actual string type itself: for example for and IA5String the data will be ASCII" Gisle researched the OpenSSL sources: "I checked the 0.9.6 and 0.9.8 sources before my patch and it always 0-terminates an IA5String." */ if((altlen == strlen(altptr)) && /* if this isn't true, there was an embedded zero in the name string and we cannot match it. */ subj_alt_hostcheck(data, altptr, hostname, dispname)) { dnsmatched = TRUE; } break; case GEN_IPADD: /* IP address comparison */ /* compare alternative IP address if the data chunk is the same size our server IP address is */ if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { ipmatched = TRUE; infof(data, " subjectAltName: host \"%s\" matched cert's IP address!\n", dispname); } break; } } } GENERAL_NAMES_free(altnames); if(dnsmatched || ipmatched) matched = TRUE; } if(matched) /* an alternative name matched */ ; else if(dNSName || iPAddress) { infof(data, " subjectAltName does not match %s\n", dispname); failf(data, "SSL: no alternative certificate subject name matches " "target host name '%s'", dispname); result = CURLE_PEER_FAILED_VERIFICATION; } else { /* we have to look to the last occurrence of a commonName in the distinguished one to get the most significant one. */ int j, i = -1; /* The following is done because of a bug in 0.9.6b */ unsigned char *nulstr = (unsigned char *)""; unsigned char *peer_CN = nulstr; X509_NAME *name = X509_get_subject_name(server_cert); if(name) while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) i = j; /* we have the name entry and we will now convert this to a string that we can use for comparison. Doing this we support BMPstring, UTF8 etc. */ if(i >= 0) { ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input is already UTF-8 encoded. We check for this case and copy the raw string manually to avoid the problem. This code can be made conditional in the future when OpenSSL has been fixed. Work-around brought by Alexis S. L. Carvalho. */ if(tmp) { if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { j = ASN1_STRING_length(tmp); if(j >= 0) { peer_CN = OPENSSL_malloc(j + 1); if(peer_CN) { memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j); peer_CN[j] = '\0'; } } } else /* not a UTF8 name */ j = ASN1_STRING_to_UTF8(&peer_CN, tmp); if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) { /* there was a terminating zero before the end of string, this cannot match and we return failure! */ failf(data, "SSL: illegal cert name field"); result = CURLE_PEER_FAILED_VERIFICATION; } } } if(peer_CN == nulstr) peer_CN = NULL; else { /* convert peer_CN from UTF8 */ CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN, strlen((char *)peer_CN)); /* Curl_convert_from_utf8 calls failf if unsuccessful */ if(rc) { OPENSSL_free(peer_CN); return rc; } } if(result) /* error already detected, pass through */ ; else if(!peer_CN) { failf(data, "SSL: unable to obtain common name from peer certificate"); result = CURLE_PEER_FAILED_VERIFICATION; } else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) { failf(data, "SSL: certificate subject name '%s' does not match " "target host name '%s'", peer_CN, dispname); result = CURLE_PEER_FAILED_VERIFICATION; } else { infof(data, " common name: %s (matched)\n", peer_CN); } if(peer_CN) OPENSSL_free(peer_CN); } return result; } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) static CURLcode verifystatus(struct connectdata *conn, struct ssl_connect_data *connssl) { int i, ocsp_status; unsigned char *status; const unsigned char *p; CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; OCSP_RESPONSE *rsp = NULL; OCSP_BASICRESP *br = NULL; X509_STORE *st = NULL; STACK_OF(X509) *ch = NULL; long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &status); if(!status) { failf(data, "No OCSP response received"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } p = status; rsp = d2i_OCSP_RESPONSE(NULL, &p, len); if(!rsp) { failf(data, "Invalid OCSP response"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } ocsp_status = OCSP_response_status(rsp); if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { failf(data, "Invalid OCSP response status: %s (%d)", OCSP_response_status_str(ocsp_status), ocsp_status); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } br = OCSP_response_get1_basic(rsp); if(!br) { failf(data, "Invalid OCSP response"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } ch = SSL_get_peer_cert_chain(BACKEND->handle); st = SSL_CTX_get_cert_store(BACKEND->ctx); #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \ (defined(LIBRESSL_VERSION_NUMBER) && \ LIBRESSL_VERSION_NUMBER <= 0x2040200fL)) /* The authorized responder cert in the OCSP response MUST be signed by the peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert, no problem, but if it's an intermediate cert OpenSSL has a bug where it expects this issuer to be present in the chain embedded in the OCSP response. So we add it if necessary. */ /* First make sure the peer cert chain includes both a peer and an issuer, and the OCSP response contains a responder cert. */ if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) { X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1); /* Find issuer of responder cert and add it to the OCSP response chain */ for(i = 0; i < sk_X509_num(ch); i++) { X509 *issuer = sk_X509_value(ch, i); if(X509_check_issued(issuer, responder) == X509_V_OK) { if(!OCSP_basic_add1_cert(br, issuer)) { failf(data, "Could not add issuer cert to OCSP response"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } } } } #endif if(OCSP_basic_verify(br, ch, st, 0) <= 0) { failf(data, "OCSP response verification failed"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } for(i = 0; i < OCSP_resp_count(br); i++) { int cert_status, crl_reason; OCSP_SINGLERESP *single = NULL; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; single = OCSP_resp_get0(br, i); if(!single) continue; cert_status = OCSP_single_get0_status(single, &crl_reason, &rev, &thisupd, &nextupd); if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { failf(data, "OCSP response has expired"); result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } infof(data, "SSL certificate status: %s (%d)\n", OCSP_cert_status_str(cert_status), cert_status); switch(cert_status) { case V_OCSP_CERTSTATUS_GOOD: break; case V_OCSP_CERTSTATUS_REVOKED: result = CURLE_SSL_INVALIDCERTSTATUS; failf(data, "SSL certificate revocation reason: %s (%d)", OCSP_crl_reason_str(crl_reason), crl_reason); goto end; case V_OCSP_CERTSTATUS_UNKNOWN: result = CURLE_SSL_INVALIDCERTSTATUS; goto end; } } end: if(br) OCSP_BASICRESP_free(br); OCSP_RESPONSE_free(rsp); return result; } #endif #endif /* USE_OPENSSL */ /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions and thus this cannot be done there. */ #ifdef SSL_CTRL_SET_MSG_CALLBACK static const char *ssl_msg_type(int ssl_ver, int msg) { #ifdef SSL2_VERSION_MAJOR if(ssl_ver == SSL2_VERSION_MAJOR) { switch(msg) { case SSL2_MT_ERROR: return "Error"; case SSL2_MT_CLIENT_HELLO: return "Client hello"; case SSL2_MT_CLIENT_MASTER_KEY: return "Client key"; case SSL2_MT_CLIENT_FINISHED: return "Client finished"; case SSL2_MT_SERVER_HELLO: return "Server hello"; case SSL2_MT_SERVER_VERIFY: return "Server verify"; case SSL2_MT_SERVER_FINISHED: return "Server finished"; case SSL2_MT_REQUEST_CERTIFICATE: return "Request CERT"; case SSL2_MT_CLIENT_CERTIFICATE: return "Client CERT"; } } else #endif if(ssl_ver == SSL3_VERSION_MAJOR) { switch(msg) { case SSL3_MT_HELLO_REQUEST: return "Hello request"; case SSL3_MT_CLIENT_HELLO: return "Client hello"; case SSL3_MT_SERVER_HELLO: return "Server hello"; #ifdef SSL3_MT_NEWSESSION_TICKET case SSL3_MT_NEWSESSION_TICKET: return "Newsession Ticket"; #endif case SSL3_MT_CERTIFICATE: return "Certificate"; case SSL3_MT_SERVER_KEY_EXCHANGE: return "Server key exchange"; case SSL3_MT_CLIENT_KEY_EXCHANGE: return "Client key exchange"; case SSL3_MT_CERTIFICATE_REQUEST: return "Request CERT"; case SSL3_MT_SERVER_DONE: return "Server finished"; case SSL3_MT_CERTIFICATE_VERIFY: return "CERT verify"; case SSL3_MT_FINISHED: return "Finished"; #ifdef SSL3_MT_CERTIFICATE_STATUS case SSL3_MT_CERTIFICATE_STATUS: return "Certificate Status"; #endif #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS case SSL3_MT_ENCRYPTED_EXTENSIONS: return "Encrypted Extensions"; #endif #ifdef SSL3_MT_END_OF_EARLY_DATA case SSL3_MT_END_OF_EARLY_DATA: return "End of early data"; #endif #ifdef SSL3_MT_KEY_UPDATE case SSL3_MT_KEY_UPDATE: return "Key update"; #endif #ifdef SSL3_MT_NEXT_PROTO case SSL3_MT_NEXT_PROTO: return "Next protocol"; #endif #ifdef SSL3_MT_MESSAGE_HASH case SSL3_MT_MESSAGE_HASH: return "Message hash"; #endif } } return "Unknown"; } static const char *tls_rt_type(int type) { switch(type) { #ifdef SSL3_RT_HEADER case SSL3_RT_HEADER: return "TLS header"; #endif case SSL3_RT_CHANGE_CIPHER_SPEC: return "TLS change cipher"; case SSL3_RT_ALERT: return "TLS alert"; case SSL3_RT_HANDSHAKE: return "TLS handshake"; case SSL3_RT_APPLICATION_DATA: return "TLS app data"; default: return "TLS Unknown"; } } /* * Our callback from the SSL/TLS layers. */ static void ssl_tls_trace(int direction, int ssl_ver, int content_type, const void *buf, size_t len, SSL *ssl, void *userp) { struct Curl_easy *data; char unknown[32]; const char *verstr = NULL; struct connectdata *conn = userp; if(!conn || !conn->data || !conn->data->set.fdebug || (direction != 0 && direction != 1)) return; data = conn->data; switch(ssl_ver) { #ifdef SSL2_VERSION /* removed in recent versions */ case SSL2_VERSION: verstr = "SSLv2"; break; #endif #ifdef SSL3_VERSION case SSL3_VERSION: verstr = "SSLv3"; break; #endif case TLS1_VERSION: verstr = "TLSv1.0"; break; #ifdef TLS1_1_VERSION case TLS1_1_VERSION: verstr = "TLSv1.1"; break; #endif #ifdef TLS1_2_VERSION case TLS1_2_VERSION: verstr = "TLSv1.2"; break; #endif #ifdef TLS1_3_VERSION case TLS1_3_VERSION: verstr = "TLSv1.3"; break; #endif case 0: break; default: msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver); verstr = unknown; break; } /* Log progress for interesting records only (like Handshake or Alert), skip * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0). * For TLS 1.3, skip notification of the decrypted inner Content Type. */ if(ssl_ver #ifdef SSL3_RT_INNER_CONTENT_TYPE && content_type != SSL3_RT_INNER_CONTENT_TYPE #endif ) { const char *msg_name, *tls_rt_name; char ssl_buf[1024]; int msg_type, txt_len; /* the info given when the version is zero is not that useful for us */ ssl_ver >>= 8; /* check the upper 8 bits only below */ /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL * always pass-up content-type as 0. But the interesting message-type * is at 'buf[0]'. */ if(ssl_ver == SSL3_VERSION_MAJOR && content_type) tls_rt_name = tls_rt_type(content_type); else tls_rt_name = ""; if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) { msg_type = *(char *)buf; msg_name = "Change cipher spec"; } else if(content_type == SSL3_RT_ALERT) { msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1]; msg_name = SSL_alert_desc_string_long(msg_type); } else { msg_type = *(char *)buf; msg_name = ssl_msg_type(ssl_ver, msg_type); } txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n", verstr, direction?"OUT":"IN", tls_rt_name, msg_name, msg_type); if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) { Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len); } } Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT : CURLINFO_SSL_DATA_IN, (char *)buf, len); (void) ssl; } #endif #ifdef USE_OPENSSL /* ====================================================== */ #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME # define use_sni(x) sni = (x) #else # define use_sni(x) Curl_nop_stmt #endif /* Check for OpenSSL 1.0.2 which has ALPN support. */ #undef HAS_ALPN #if OPENSSL_VERSION_NUMBER >= 0x10002000L \ && !defined(OPENSSL_NO_TLSEXT) # define HAS_ALPN 1 #endif /* Check for OpenSSL 1.0.1 which has NPN support. */ #undef HAS_NPN #if OPENSSL_VERSION_NUMBER >= 0x10001000L \ && !defined(OPENSSL_NO_TLSEXT) \ && !defined(OPENSSL_NO_NEXTPROTONEG) # define HAS_NPN 1 #endif #ifdef HAS_NPN /* * in is a list of length prefixed strings. this function has to select * the protocol we want to use from the list and write its string into out. */ static int select_next_protocol(unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, const char *key, unsigned int keylen) { unsigned int i; for(i = 0; i + keylen <= inlen; i += in[i] + 1) { if(memcmp(&in[i + 1], key, keylen) == 0) { *out = (unsigned char *) &in[i + 1]; *outlen = in[i]; return 0; } } return -1; } static int select_next_proto_cb(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { struct connectdata *conn = (struct connectdata*) arg; (void)ssl; #ifdef USE_NGHTTP2 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 && !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN)) { infof(conn->data, "NPN, negotiated HTTP2 (%s)\n", NGHTTP2_PROTO_VERSION_ID); conn->negnpn = CURL_HTTP_VERSION_2; return SSL_TLSEXT_ERR_OK; } #endif if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) { infof(conn->data, "NPN, negotiated HTTP1.1\n"); conn->negnpn = CURL_HTTP_VERSION_1_1; return SSL_TLSEXT_ERR_OK; } infof(conn->data, "NPN, no overlap, use HTTP1.1\n"); *out = (unsigned char *)ALPN_HTTP_1_1; *outlen = ALPN_HTTP_1_1_LENGTH; conn->negnpn = CURL_HTTP_VERSION_1_1; return SSL_TLSEXT_ERR_OK; } #endif /* HAS_NPN */ #ifndef CURL_DISABLE_VERBOSE_STRINGS static const char * get_ssl_version_txt(SSL *ssl) { if(!ssl) return ""; switch(SSL_version(ssl)) { #ifdef TLS1_3_VERSION case TLS1_3_VERSION: return "TLSv1.3"; #endif #if OPENSSL_VERSION_NUMBER >= 0x1000100FL case TLS1_2_VERSION: return "TLSv1.2"; case TLS1_1_VERSION: return "TLSv1.1"; #endif case TLS1_VERSION: return "TLSv1.0"; case SSL3_VERSION: return "SSLv3"; case SSL2_VERSION: return "SSLv2"; } return "unknown"; } #endif static CURLcode set_ssl_version_min_max(long *ctx_options, struct connectdata *conn, int sockindex) { #if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION) /* convoluted #if condition just to avoid compiler warnings on unused variable */ struct Curl_easy *data = conn->data; #endif long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); switch(ssl_version) { case CURL_SSLVERSION_TLSv1_3: #ifdef TLS1_3_VERSION { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION); *ctx_options |= SSL_OP_NO_TLSv1_2; } #else (void)sockindex; (void)ctx_options; failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); return CURLE_NOT_BUILT_IN; #endif /* FALLTHROUGH */ case CURL_SSLVERSION_TLSv1_2: #if OPENSSL_VERSION_NUMBER >= 0x1000100FL *ctx_options |= SSL_OP_NO_TLSv1_1; #else failf(data, OSSL_PACKAGE " was built without TLS 1.2 support"); return CURLE_NOT_BUILT_IN; #endif /* FALLTHROUGH */ case CURL_SSLVERSION_TLSv1_1: #if OPENSSL_VERSION_NUMBER >= 0x1000100FL *ctx_options |= SSL_OP_NO_TLSv1; #else failf(data, OSSL_PACKAGE " was built without TLS 1.1 support"); return CURLE_NOT_BUILT_IN; #endif /* FALLTHROUGH */ case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1: break; } switch(ssl_version_max) { case CURL_SSLVERSION_MAX_TLSv1_0: #if OPENSSL_VERSION_NUMBER >= 0x1000100FL *ctx_options |= SSL_OP_NO_TLSv1_1; #endif /* FALLTHROUGH */ case CURL_SSLVERSION_MAX_TLSv1_1: #if OPENSSL_VERSION_NUMBER >= 0x1000100FL *ctx_options |= SSL_OP_NO_TLSv1_2; #endif /* FALLTHROUGH */ case CURL_SSLVERSION_MAX_TLSv1_2: #ifdef TLS1_3_VERSION *ctx_options |= SSL_OP_NO_TLSv1_3; #endif break; case CURL_SSLVERSION_MAX_TLSv1_3: #ifdef TLS1_3_VERSION break; #else failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); return CURLE_NOT_BUILT_IN; #endif } return CURLE_OK; } /* The "new session" callback must return zero if the session can be removed * or non-zero if the session has been put into the session cache. */ static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) { int res = 0; struct connectdata *conn; struct Curl_easy *data; int sockindex; curl_socket_t *sockindex_ptr; int connectdata_idx = ossl_get_ssl_conn_index(); int sockindex_idx = ossl_get_ssl_sockindex_index(); if(connectdata_idx < 0 || sockindex_idx < 0) return 0; conn = (struct connectdata*) SSL_get_ex_data(ssl, connectdata_idx); if(!conn) return 0; data = conn->data; /* The sockindex has been stored as a pointer to an array element */ sockindex_ptr = (curl_socket_t*) SSL_get_ex_data(ssl, sockindex_idx); sockindex = (int)(sockindex_ptr - conn->sock); if(SSL_SET_OPTION(primary.sessionid)) { bool incache; void *old_ssl_sessionid = NULL; Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex)); if(incache) { if(old_ssl_sessionid != ssl_sessionid) { infof(data, "old SSL session ID is stale, removing\n"); Curl_ssl_delsessionid(conn, old_ssl_sessionid); incache = FALSE; } } if(!incache) { if(!Curl_ssl_addsessionid(conn, ssl_sessionid, 0 /* unknown size */, sockindex)) { /* the session has been put into the session cache */ res = 1; } else failf(data, "failed to store ssl session"); } Curl_ssl_sessionid_unlock(conn); } return res; } static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; char *ciphers; struct Curl_easy *data = conn->data; SSL_METHOD_QUAL SSL_METHOD *req_method = NULL; X509_LOOKUP *lookup = NULL; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long ctx_options = 0; #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME bool sni; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif #endif long * const certverifyresult = SSL_IS_PROXY() ? &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult; const long int ssl_version = SSL_CONN_CONFIG(version); #ifdef USE_TLS_SRP const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype); #endif char * const ssl_cert = SSL_SET_OPTION(cert); const char * const ssl_cert_type = SSL_SET_OPTION(cert_type); const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile); const char * const ssl_capath = SSL_CONN_CONFIG(CApath); const bool verifypeer = SSL_CONN_CONFIG(verifypeer); const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile); char error_buffer[256]; DEBUGASSERT(ssl_connect_1 == connssl->connecting_state); /* Make funny stuff to get random input */ result = Curl_ossl_seed(data); if(result) return result; *certverifyresult = !X509_V_OK; /* check to see if we've been told to use an explicit SSL/TLS version */ switch(ssl_version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: /* it will be handled later with the context options */ #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) req_method = TLS_client_method(); #else req_method = SSLv23_client_method(); #endif use_sni(TRUE); break; case CURL_SSLVERSION_SSLv2: #ifdef OPENSSL_NO_SSL2 failf(data, OSSL_PACKAGE " was built without SSLv2 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP if(ssl_authtype == CURL_TLSAUTH_SRP) return CURLE_SSL_CONNECT_ERROR; #endif req_method = SSLv2_client_method(); use_sni(FALSE); break; #endif case CURL_SSLVERSION_SSLv3: #ifdef OPENSSL_NO_SSL3_METHOD failf(data, OSSL_PACKAGE " was built without SSLv3 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP if(ssl_authtype == CURL_TLSAUTH_SRP) return CURLE_SSL_CONNECT_ERROR; #endif req_method = SSLv3_client_method(); use_sni(FALSE); break; #endif default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } if(BACKEND->ctx) SSL_CTX_free(BACKEND->ctx); BACKEND->ctx = SSL_CTX_new(req_method); if(!BACKEND->ctx) { failf(data, "SSL: couldn't create a context: %s", ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer))); return CURLE_OUT_OF_MEMORY; } #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS); #endif #ifdef SSL_CTRL_SET_MSG_CALLBACK if(data->set.fdebug && data->set.verbose) { /* the SSL trace callback is only used for verbose logging */ SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace); SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn); } #endif /* OpenSSL contains code to work-around lots of bugs and flaws in various SSL-implementations. SSL_CTX_set_options() is used to enabled those work-arounds. The man page for this option states that SSL_OP_ALL enables all the work-arounds and that "It is usually safe to use SSL_OP_ALL to enable the bug workaround options if compatibility with somewhat broken implementations is desired." The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to disable "rfc4507bis session ticket support". rfc4507bis was later turned into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077 The enabled extension concerns the session management. I wonder how often libcurl stops a connection and then resumes a TLS session. also, sending the session data is some overhead. .I suggest that you just use your proposed patch (which explicitly disables TICKET). If someone writes an application with libcurl and openssl who wants to enable the feature, one can do this in the SSL callback. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper interoperability with web server Netscape Enterprise Server 2.0.1 which was released back in 1996. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate CVE-2010-4180 when using previous OpenSSL versions we no longer enable this option regardless of OpenSSL version and SSL_OP_ALL definition. OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around despite the fact that SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set. */ ctx_options = SSL_OP_ALL; #ifdef SSL_OP_NO_TICKET ctx_options |= SSL_OP_NO_TICKET; #endif #ifdef SSL_OP_NO_COMPRESSION ctx_options |= SSL_OP_NO_COMPRESSION; #endif #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG /* mitigate CVE-2010-4180 */ ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; #endif #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS /* unless the user explicitly ask to allow the protocol vulnerability we use the work-around */ if(!SSL_SET_OPTION(enable_beast)) ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; #endif switch(ssl_version) { case CURL_SSLVERSION_SSLv3: ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_TLSv1; #if OPENSSL_VERSION_NUMBER >= 0x1000100FL ctx_options |= SSL_OP_NO_TLSv1_1; ctx_options |= SSL_OP_NO_TLSv1_2; #ifdef TLS1_3_VERSION ctx_options |= SSL_OP_NO_TLSv1_3; #endif #endif break; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: /* asking for any TLS version as the minimum, means no SSL versions allowed */ ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; result = set_ssl_version_min_max(&ctx_options, conn, sockindex); if(result != CURLE_OK) return result; break; case CURL_SSLVERSION_SSLv2: ctx_options |= SSL_OP_NO_SSLv3; ctx_options |= SSL_OP_NO_TLSv1; #if OPENSSL_VERSION_NUMBER >= 0x1000100FL ctx_options |= SSL_OP_NO_TLSv1_1; ctx_options |= SSL_OP_NO_TLSv1_2; #ifdef TLS1_3_VERSION ctx_options |= SSL_OP_NO_TLSv1_3; #endif #endif break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } SSL_CTX_set_options(BACKEND->ctx, ctx_options); #ifdef HAS_NPN if(conn->bits.tls_enable_npn) SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn); #endif #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { int cur = 0; unsigned char protocols[128]; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2 && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN; memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN); cur += NGHTTP2_PROTO_VERSION_ID_LEN; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif protocols[cur++] = ALPN_HTTP_1_1_LENGTH; memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH); cur += ALPN_HTTP_1_1_LENGTH; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); /* expects length prefixed preference ordered list of protocols in wire * format */ SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur); } #endif if(ssl_cert || ssl_cert_type) { if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type, SSL_SET_OPTION(key), SSL_SET_OPTION(key_type), SSL_SET_OPTION(key_passwd))) { /* failf() is already done in cert_stuff() */ return CURLE_SSL_CERTPROBLEM; } } ciphers = SSL_CONN_CONFIG(cipher_list); if(!ciphers) ciphers = (char *)DEFAULT_CIPHER_SELECTION; if(ciphers) { if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) { failf(data, "failed setting cipher list: %s", ciphers); return CURLE_SSL_CIPHER; } infof(data, "Cipher selection: %s\n", ciphers); } #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES { char *ciphers13 = SSL_CONN_CONFIG(cipher_list13); if(ciphers13) { if(!SSL_CTX_set_ciphersuites(BACKEND->ctx, ciphers13)) { failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13); return CURLE_SSL_CIPHER; } infof(data, "TLS 1.3 cipher selection: %s\n", ciphers13); } } #endif #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH /* OpenSSL 1.1.1 requires clients to opt-in for PHA */ SSL_CTX_set_post_handshake_auth(BACKEND->ctx, 1); #endif #ifdef USE_TLS_SRP if(ssl_authtype == CURL_TLSAUTH_SRP) { char * const ssl_username = SSL_SET_OPTION(username); infof(data, "Using TLS-SRP username: %s\n", ssl_username); if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) { failf(data, "Unable to set SRP user name"); return CURLE_BAD_FUNCTION_ARGUMENT; } if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) { failf(data, "failed setting SRP password"); return CURLE_BAD_FUNCTION_ARGUMENT; } if(!SSL_CONN_CONFIG(cipher_list)) { infof(data, "Setting cipher list SRP\n"); if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) { failf(data, "failed setting SRP cipher list"); return CURLE_SSL_CIPHER; } } } #endif if(ssl_cafile || ssl_capath) { /* tell SSL where to find CA certificates that are used to verify the servers certificate. */ if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) { if(verifypeer) { /* Fail if we insist on successfully verifying the server. */ failf(data, "error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s", ssl_cafile ? ssl_cafile : "none", ssl_capath ? ssl_capath : "none"); return CURLE_SSL_CACERT_BADFILE; } /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", ssl_cafile ? ssl_cafile : "none", ssl_capath ? ssl_capath : "none"); } #ifdef CURL_CA_FALLBACK else if(verifypeer) { /* verifying the peer without any CA certificates won't work so use openssl's built in default as fallback */ SSL_CTX_set_default_verify_paths(BACKEND->ctx); } #endif if(ssl_crlfile) { /* tell SSL where to find CRL file that is used to check certificate * revocation */ lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx), X509_LOOKUP_file()); if(!lookup || (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) { failf(data, "error loading CRL file: %s", ssl_crlfile); return CURLE_SSL_CRL_BADFILE; } /* Everything is fine. */ infof(data, "successfully load CRL file:\n"); X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx), X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL); infof(data, " CRLfile: %s\n", ssl_crlfile); } /* Try building a chain using issuers in the trusted store first to avoid problems with server-sent legacy intermediates. Newer versions of OpenSSL do alternate chain checking by default which gives us the same fix without as much of a performance hit (slight), so we prefer that if available. https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest */ #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS) if(verifypeer) { X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx), X509_V_FLAG_TRUSTED_FIRST); } #endif /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ SSL_CTX_set_verify(BACKEND->ctx, verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */ #if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK) if(keylog_file_fp) { SSL_CTX_set_keylog_callback(BACKEND->ctx, ossl_keylog_callback); } #endif /* Enable the session cache because it's a prerequisite for the "new session" * callback. Use the "external storage" mode to avoid that OpenSSL creates * an internal session cache. */ SSL_CTX_set_session_cache_mode(BACKEND->ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL); SSL_CTX_sess_set_new_cb(BACKEND->ctx, ossl_new_session_cb); /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx, data->set.ssl.fsslctxp); if(result) { failf(data, "error signaled by ssl ctx callback"); return result; } } /* Lets make an SSL structure */ if(BACKEND->handle) SSL_free(BACKEND->handle); BACKEND->handle = SSL_new(BACKEND->ctx); if(!BACKEND->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) if(SSL_CONN_CONFIG(verifystatus)) SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp); #endif #if defined(OPENSSL_IS_BORINGSSL) && defined(ALLOW_RENEG) SSL_set_renegotiate_mode(BACKEND->handle, ssl_renegotiate_freely); #endif SSL_set_connect_state(BACKEND->handle); BACKEND->server_cert = 0x0; #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) && #endif sni && !SSL_set_tlsext_host_name(BACKEND->handle, hostname)) infof(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); #endif /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *ssl_sessionid = NULL; int connectdata_idx = ossl_get_ssl_conn_index(); int sockindex_idx = ossl_get_ssl_sockindex_index(); if(connectdata_idx >= 0 && sockindex_idx >= 0) { /* Store the data needed for the "new session" callback. * The sockindex is stored as a pointer to an array element. */ SSL_set_ex_data(BACKEND->handle, connectdata_idx, conn); SSL_set_ex_data(BACKEND->handle, sockindex_idx, conn->sock + sockindex); } Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) { /* we got a session id, use it! */ if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) { Curl_ssl_sessionid_unlock(conn); failf(data, "SSL: SSL_set_session failed: %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } Curl_ssl_sessionid_unlock(conn); } if(conn->proxy_ssl[sockindex].use) { BIO *const bio = BIO_new(BIO_f_ssl()); SSL *handle = conn->proxy_ssl[sockindex].backend->handle; DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state); DEBUGASSERT(handle != NULL); DEBUGASSERT(bio != NULL); BIO_set_ssl(bio, handle, FALSE); SSL_set_bio(BACKEND->handle, bio, bio); } else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) { /* pass the raw socket into the SSL layers */ failf(data, "SSL: SSL_set_fd failed: %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer))); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; int err; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long * const certverifyresult = SSL_IS_PROXY() ? &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult; DEBUGASSERT(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state); ERR_clear_error(); err = SSL_connect(BACKEND->handle); /* If keylogging is enabled but the keylog callback is not supported then log secrets here, immediately after SSL_connect by using tap_ssl_key. */ #if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK) tap_ssl_key(BACKEND->handle, &BACKEND->tap_state); #endif /* 1 is fine 0 is "not successful but was shut down controlled" <0 is "handshake was not successful, because a fatal error occurred" */ if(1 != err) { int detail = SSL_get_error(BACKEND->handle, err); if(SSL_ERROR_WANT_READ == detail) { connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; } if(SSL_ERROR_WANT_WRITE == detail) { connssl->connecting_state = ssl_connect_2_writing; return CURLE_OK; } #ifdef SSL_ERROR_WANT_ASYNC if(SSL_ERROR_WANT_ASYNC == detail) { connssl->connecting_state = ssl_connect_2; return CURLE_OK; } #endif else { /* untreated error */ unsigned long errdetail; char error_buffer[256]=""; CURLcode result; long lerr; int lib; int reason; /* the connection failed, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_2; /* Get the earliest error code from the thread's error queue and removes the entry. */ errdetail = ERR_get_error(); /* Extract which lib and reason */ lib = ERR_GET_LIB(errdetail); reason = ERR_GET_REASON(errdetail); if((lib == ERR_LIB_SSL) && (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) { result = CURLE_PEER_FAILED_VERIFICATION; lerr = SSL_get_verify_result(BACKEND->handle); if(lerr != X509_V_OK) { *certverifyresult = lerr; msnprintf(error_buffer, sizeof(error_buffer), "SSL certificate problem: %s", X509_verify_cert_error_string(lerr)); } else /* strcpy() is fine here as long as the string fits within error_buffer */ strcpy(error_buffer, "SSL certificate verification failed"); } else { result = CURLE_SSL_CONNECT_ERROR; ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)); } /* detail is already set to the SSL error above */ /* If we e.g. use SSLv2 request-method and the server doesn't like us * (RST connection etc.), OpenSSL gives no explanation whatsoever and * the SO_ERROR is also lost. */ if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) { const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ", SSL_ERROR_to_str(detail), hostname, port); return result; } /* Could be a CERT problem */ failf(data, "%s", error_buffer); return result; } } else { /* we have been connected fine, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_3; /* Informational message */ infof(data, "SSL connection using %s / %s\n", get_ssl_version_txt(BACKEND->handle), SSL_get_cipher(BACKEND->handle)); #ifdef HAS_ALPN /* Sets data and len to negotiated protocol, len is 0 if no protocol was * negotiated */ if(conn->bits.tls_enable_alpn) { const unsigned char *neg_protocol; unsigned int len; SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len); if(len != 0) { infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol); #ifdef USE_NGHTTP2 if(len == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(len == ALPN_HTTP_1_1_LENGTH && !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } } else infof(data, "ALPN, server did not agree to a protocol\n"); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } #endif return CURLE_OK; } } static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len) { int i, ilen; ilen = (int)len; if(ilen < 0) return 1; /* buffer too big */ i = i2t_ASN1_OBJECT(buf, ilen, a); if(i >= ilen) return 1; /* buffer too small */ return 0; } #define push_certinfo(_label, _num) \ do { \ long info_len = BIO_get_mem_data(mem, &ptr); \ Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \ if(1 != BIO_reset(mem)) \ break; \ } WHILE_FALSE static void pubkey_show(struct Curl_easy *data, BIO *mem, int num, const char *type, const char *name, #ifdef HAVE_OPAQUE_RSA_DSA_DH const #endif BIGNUM *bn) { char *ptr; char namebuf[32]; msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); if(bn) BN_print(mem, bn); push_certinfo(namebuf, num); } #ifdef HAVE_OPAQUE_RSA_DSA_DH #define print_pubkey_BN(_type, _name, _num) \ pubkey_show(data, mem, _num, #_type, #_name, _name) #else #define print_pubkey_BN(_type, _name, _num) \ do { \ if(_type->_name) { \ pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \ } \ } WHILE_FALSE #endif static int X509V3_ext(struct Curl_easy *data, int certnum, CONST_EXTS STACK_OF(X509_EXTENSION) *exts) { int i; size_t j; if((int)sk_X509_EXTENSION_num(exts) <= 0) /* no extensions, bail out */ return 1; for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); BUF_MEM *biomem; char buf[512]; char *ptr = buf; char namebuf[128]; BIO *bio_out = BIO_new(BIO_s_mem()); if(!bio_out) return 1; obj = X509_EXTENSION_get_object(ext); asn1_object_dump(obj, namebuf, sizeof(namebuf)); if(!X509V3_EXT_print(bio_out, ext, 0, 0)) ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext)); BIO_get_mem_ptr(bio_out, &biomem); for(j = 0; j < (size_t)biomem->length; j++) { const char *sep = ""; if(biomem->data[j] == '\n') { sep = ", "; j++; /* skip the newline */ }; while((j<(size_t)biomem->length) && (biomem->data[j] == ' ')) j++; if(j<(size_t)biomem->length) ptr += msnprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep, biomem->data[j]); } Curl_ssl_push_certinfo(data, certnum, namebuf, buf); BIO_free(bio_out); } return 0; /* all is fine */ } static CURLcode get_cert_chain(struct connectdata *conn, struct ssl_connect_data *connssl) { CURLcode result; STACK_OF(X509) *sk; int i; struct Curl_easy *data = conn->data; int numcerts; BIO *mem; sk = SSL_get_peer_cert_chain(BACKEND->handle); if(!sk) { return CURLE_OUT_OF_MEMORY; } numcerts = sk_X509_num(sk); result = Curl_ssl_init_certinfo(data, numcerts); if(result) { return result; } mem = BIO_new(BIO_s_mem()); for(i = 0; i < numcerts; i++) { ASN1_INTEGER *num; X509 *x = sk_X509_value(sk, i); EVP_PKEY *pubkey = NULL; int j; char *ptr; const ASN1_BIT_STRING *psig = NULL; X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); push_certinfo("Subject", i); X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); push_certinfo("Issuer", i); BIO_printf(mem, "%lx", X509_get_version(x)); push_certinfo("Version", i); num = X509_get_serialNumber(x); if(num->type == V_ASN1_NEG_INTEGER) BIO_puts(mem, "-"); for(j = 0; j < num->length; j++) BIO_printf(mem, "%02x", num->data[j]); push_certinfo("Serial Number", i); #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS) { const X509_ALGOR *palg = NULL; ASN1_STRING *a = ASN1_STRING_new(); if(a) { X509_get0_signature(&psig, &palg, x); X509_signature_print(mem, ARG2_X509_signature_print palg, a); ASN1_STRING_free(a); if(palg) { i2a_ASN1_OBJECT(mem, palg->algorithm); push_certinfo("Public Key Algorithm", i); } } X509V3_ext(data, i, X509_get0_extensions(x)); } #else { /* before OpenSSL 1.0.2 */ X509_CINF *cinf = x->cert_info; i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); push_certinfo("Signature Algorithm", i); i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); push_certinfo("Public Key Algorithm", i); X509V3_ext(data, i, cinf->extensions); psig = x->signature; } #endif ASN1_TIME_print(mem, X509_get0_notBefore(x)); push_certinfo("Start date", i); ASN1_TIME_print(mem, X509_get0_notAfter(x)); push_certinfo("Expire date", i); pubkey = X509_get_pubkey(x); if(!pubkey) infof(data, " Unable to load public key\n"); else { int pktype; #ifdef HAVE_OPAQUE_EVP_PKEY pktype = EVP_PKEY_id(pubkey); #else pktype = pubkey->type; #endif switch(pktype) { case EVP_PKEY_RSA: { RSA *rsa; #ifdef HAVE_OPAQUE_EVP_PKEY rsa = EVP_PKEY_get0_RSA(pubkey); #else rsa = pubkey->pkey.rsa; #endif #ifdef HAVE_OPAQUE_RSA_DSA_DH { const BIGNUM *n; const BIGNUM *e; RSA_get0_key(rsa, &n, &e, NULL); BN_print(mem, n); push_certinfo("RSA Public Key", i); print_pubkey_BN(rsa, n, i); print_pubkey_BN(rsa, e, i); } #else BIO_printf(mem, "%d", BN_num_bits(rsa->n)); push_certinfo("RSA Public Key", i); print_pubkey_BN(rsa, n, i); print_pubkey_BN(rsa, e, i); #endif break; } case EVP_PKEY_DSA: { #ifndef OPENSSL_NO_DSA DSA *dsa; #ifdef HAVE_OPAQUE_EVP_PKEY dsa = EVP_PKEY_get0_DSA(pubkey); #else dsa = pubkey->pkey.dsa; #endif #ifdef HAVE_OPAQUE_RSA_DSA_DH { const BIGNUM *p; const BIGNUM *q; const BIGNUM *g; const BIGNUM *pub_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, NULL); print_pubkey_BN(dsa, p, i); print_pubkey_BN(dsa, q, i); print_pubkey_BN(dsa, g, i); print_pubkey_BN(dsa, pub_key, i); } #else print_pubkey_BN(dsa, p, i); print_pubkey_BN(dsa, q, i); print_pubkey_BN(dsa, g, i); print_pubkey_BN(dsa, pub_key, i); #endif #endif /* !OPENSSL_NO_DSA */ break; } case EVP_PKEY_DH: { DH *dh; #ifdef HAVE_OPAQUE_EVP_PKEY dh = EVP_PKEY_get0_DH(pubkey); #else dh = pubkey->pkey.dh; #endif #ifdef HAVE_OPAQUE_RSA_DSA_DH { const BIGNUM *p; const BIGNUM *q; const BIGNUM *g; const BIGNUM *pub_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, NULL); print_pubkey_BN(dh, p, i); print_pubkey_BN(dh, q, i); print_pubkey_BN(dh, g, i); print_pubkey_BN(dh, pub_key, i); } #else print_pubkey_BN(dh, p, i); print_pubkey_BN(dh, g, i); print_pubkey_BN(dh, pub_key, i); #endif break; } } EVP_PKEY_free(pubkey); } if(psig) { for(j = 0; j < psig->length; j++) BIO_printf(mem, "%02x:", psig->data[j]); push_certinfo("Signature", i); } PEM_write_bio_X509(mem, x); push_certinfo("Cert", i); } BIO_free(mem); return CURLE_OK; } /* * Heavily modified from: * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL */ static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert, const char *pinnedpubkey) { /* Scratch */ int len1 = 0, len2 = 0; unsigned char *buff1 = NULL, *temp = NULL; /* Result is returned to caller */ CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; /* if a path wasn't specified, don't pin */ if(!pinnedpubkey) return CURLE_OK; if(!cert) return result; do { /* Begin Gyrations to get the subjectPublicKeyInfo */ /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */ /* https://groups.google.com/group/mailing.openssl.users/browse_thread /thread/d61858dae102c6c7 */ len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); if(len1 < 1) break; /* failed */ /* https://www.openssl.org/docs/crypto/buffer.html */ buff1 = temp = malloc(len1); if(!buff1) break; /* failed */ /* https://www.openssl.org/docs/crypto/d2i_X509.html */ len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp); /* * These checks are verifying we got back the same values as when we * sized the buffer. It's pretty weak since they should always be the * same. But it gives us something to test. */ if((len1 != len2) || !temp || ((temp - buff1) != len1)) break; /* failed */ /* End Gyrations */ /* The one good exit point */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); } while(0); /* https://www.openssl.org/docs/crypto/buffer.html */ if(buff1) free(buff1); return result; } /* * Get the server cert, verify it and show it etc, only call failf() if the * 'strict' argument is TRUE as otherwise all this is for informational * purposes only! * * We check certificates to authenticate the server; otherwise we risk * man-in-the-middle attack. */ static CURLcode servercert(struct connectdata *conn, struct ssl_connect_data *connssl, bool strict) { CURLcode result = CURLE_OK; int rc; long lerr; struct Curl_easy *data = conn->data; X509 *issuer; BIO *fp = NULL; char error_buffer[256]=""; char buffer[2048]; const char *ptr; long * const certverifyresult = SSL_IS_PROXY() ? &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult; BIO *mem = BIO_new(BIO_s_mem()); if(data->set.ssl.certinfo) /* we've been asked to gather certificate info! */ (void)get_cert_chain(conn, connssl); BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle); if(!BACKEND->server_cert) { BIO_free(mem); if(!strict) return CURLE_OK; failf(data, "SSL: couldn't get peer certificate!"); return CURLE_PEER_FAILED_VERIFICATION; } infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server"); rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert), buffer, sizeof(buffer)); infof(data, " subject: %s\n", rc?"[NONE]":buffer); #ifndef CURL_DISABLE_VERBOSE_STRINGS { long len; ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert)); len = BIO_get_mem_data(mem, (char **) &ptr); infof(data, " start date: %.*s\n", len, ptr); (void)BIO_reset(mem); ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert)); len = BIO_get_mem_data(mem, (char **) &ptr); infof(data, " expire date: %.*s\n", len, ptr); (void)BIO_reset(mem); } #endif BIO_free(mem); if(SSL_CONN_CONFIG(verifyhost)) { result = verifyhost(conn, BACKEND->server_cert); if(result) { X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return result; } } rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert), buffer, sizeof(buffer)); if(rc) { if(strict) failf(data, "SSL: couldn't get X509-issuer name!"); result = CURLE_PEER_FAILED_VERIFICATION; } else { infof(data, " issuer: %s\n", buffer); /* We could do all sorts of certificate verification stuff here before deallocating the certificate. */ /* e.g. match issuer name with provided issuer certificate */ if(SSL_SET_OPTION(issuercert)) { fp = BIO_new(BIO_s_file()); if(fp == NULL) { failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s", ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)) ); X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return CURLE_OUT_OF_MEMORY; } if(BIO_read_filename(fp, SSL_SET_OPTION(issuercert)) <= 0) { if(strict) failf(data, "SSL: Unable to open issuer cert (%s)", SSL_SET_OPTION(issuercert)); BIO_free(fp); X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return CURLE_SSL_ISSUER_ERROR; } issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL); if(!issuer) { if(strict) failf(data, "SSL: Unable to read issuer cert (%s)", SSL_SET_OPTION(issuercert)); BIO_free(fp); X509_free(issuer); X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return CURLE_SSL_ISSUER_ERROR; } if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) { if(strict) failf(data, "SSL: Certificate issuer check failed (%s)", SSL_SET_OPTION(issuercert)); BIO_free(fp); X509_free(issuer); X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return CURLE_SSL_ISSUER_ERROR; } infof(data, " SSL certificate issuer check ok (%s)\n", SSL_SET_OPTION(issuercert)); BIO_free(fp); X509_free(issuer); } lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle); if(*certverifyresult != X509_V_OK) { if(SSL_CONN_CONFIG(verifypeer)) { /* We probably never reach this, because SSL_connect() will fail and we return earlier if verifypeer is set? */ if(strict) failf(data, "SSL certificate verify result: %s (%ld)", X509_verify_cert_error_string(lerr), lerr); result = CURLE_PEER_FAILED_VERIFICATION; } else infof(data, " SSL certificate verify result: %s (%ld)," " continuing anyway.\n", X509_verify_cert_error_string(lerr), lerr); } else infof(data, " SSL certificate verify ok.\n"); } #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) if(SSL_CONN_CONFIG(verifystatus)) { result = verifystatus(conn, connssl); if(result) { X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; return result; } } #endif if(!strict) /* when not strict, we don't bother about the verify cert problems */ result = CURLE_OK; ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; if(!result && ptr) { result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr); if(result) failf(data, "SSL: public key does not match pinned public key!"); } X509_free(BACKEND->server_cert); BACKEND->server_cert = NULL; connssl->connecting_state = ssl_connect_done; return result; } static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); /* * We check certificates to authenticate the server; otherwise we risk * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to * verify the peer ignore faults and failures from the server cert * operations. */ result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) || SSL_CONN_CONFIG(verifyhost))); if(!result) connssl->connecting_state = ssl_connect_done; return result; } static Curl_recv ossl_recv; static Curl_send ossl_send; static CURLcode ossl_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; time_t timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = ossl_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if this * connection is done nonblocking and this loop would execute again. This * permits the owner of a multi handle to abort a connection attempt * before step2 has completed while ensuring that a client using select() * or epoll() will always have a valid fdset to wait on. */ result = ossl_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = ossl_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = ossl_recv; conn->send[sockindex] = ossl_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return ossl_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = ossl_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex) { const struct ssl_connect_data *connssl = &conn->ssl[connindex]; const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex]; if(connssl->backend->handle && SSL_pending(connssl->backend->handle)) return TRUE; if(proxyssl->backend->handle && SSL_pending(proxyssl->backend->handle)) return TRUE; return FALSE; } static size_t Curl_ossl_version(char *buffer, size_t size); static ssize_t ossl_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { /* SSL_write() is said to return 'int' while write() and send() returns 'size_t' */ int err; char error_buffer[256]; unsigned long sslerror; int memlen; int rc; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; ERR_clear_error(); memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; rc = SSL_write(BACKEND->handle, mem, memlen); if(rc <= 0) { err = SSL_get_error(BACKEND->handle, rc); switch(err) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* The operation did not complete; the same TLS/SSL I/O function should be called again later. This is basically an EWOULDBLOCK equivalent. */ *curlcode = CURLE_AGAIN; return -1; case SSL_ERROR_SYSCALL: failf(conn->data, "SSL_write() returned SYSCALL, errno = %d", SOCKERRNO); *curlcode = CURLE_SEND_ERROR; return -1; case SSL_ERROR_SSL: /* A failure in the SSL library occurred, usually a protocol error. The OpenSSL error queue contains more information on the error. */ sslerror = ERR_get_error(); if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL && ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET && conn->ssl[sockindex].state == ssl_connection_complete && conn->proxy_ssl[sockindex].state == ssl_connection_complete) { char ver[120]; Curl_ossl_version(ver, 120); failf(conn->data, "Error: %s does not support double SSL tunneling.", ver); } else failf(conn->data, "SSL_write() error: %s", ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); *curlcode = CURLE_SEND_ERROR; return -1; } /* a true error */ failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d", SSL_ERROR_to_str(err), SOCKERRNO); *curlcode = CURLE_SEND_ERROR; return -1; } *curlcode = CURLE_OK; return (ssize_t)rc; /* number of bytes */ } static ssize_t ossl_recv(struct connectdata *conn, /* connection data */ int num, /* socketindex */ char *buf, /* store read data here */ size_t buffersize, /* max amount to read */ CURLcode *curlcode) { char error_buffer[256]; unsigned long sslerror; ssize_t nread; int buffsize; struct ssl_connect_data *connssl = &conn->ssl[num]; ERR_clear_error(); buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize); if(nread <= 0) { /* failed SSL_read */ int err = SSL_get_error(BACKEND->handle, (int)nread); switch(err) { case SSL_ERROR_NONE: /* this is not an error */ break; case SSL_ERROR_ZERO_RETURN: /* no more data */ /* close_notify alert */ connclose(conn, "TLS close_notify"); break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: /* there's data pending, re-invoke SSL_read() */ *curlcode = CURLE_AGAIN; return -1; default: /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return value/errno" */ /* https://www.openssl.org/docs/crypto/ERR_get_error.html */ sslerror = ERR_get_error(); if((nread < 0) || sslerror) { /* If the return code was negative or there actually is an error in the queue */ failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d", (sslerror ? ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)) : SSL_ERROR_to_str(err)), SOCKERRNO); *curlcode = CURLE_RECV_ERROR; return -1; } } } return nread; } static size_t Curl_ossl_version(char *buffer, size_t size) { #ifdef OPENSSL_IS_BORINGSSL return msnprintf(buffer, size, OSSL_PACKAGE); #elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING) return msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING)); #else /* not BoringSSL and not using OpenSSL_version */ char sub[3]; unsigned long ssleay_value; sub[2]='\0'; sub[1]='\0'; ssleay_value = OpenSSL_version_num(); if(ssleay_value < 0x906000) { ssleay_value = SSLEAY_VERSION_NUMBER; sub[0]='\0'; } else { if(ssleay_value&0xff0) { int minor_ver = (ssleay_value >> 4) & 0xff; if(minor_ver > 26) { /* handle extended version introduced for 0.9.8za */ sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); sub[0] = 'z'; } else { sub[0] = (char) (minor_ver + 'a' - 1); } } else sub[0]='\0'; } return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s" #ifdef OPENSSL_FIPS "-fips" #endif , OSSL_PACKAGE, (ssleay_value>>28)&0xf, (ssleay_value>>20)&0xff, (ssleay_value>>12)&0xff, sub); #endif /* OPENSSL_IS_BORINGSSL */ } /* can be called with data == NULL */ static CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { int rc; if(data) { if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */ return CURLE_FAILED_INIT; /* couldn't seed for some reason */ } else { if(!rand_enough()) return CURLE_FAILED_INIT; } /* RAND_bytes() returns 1 on success, 0 otherwise. */ rc = RAND_bytes(entropy, curlx_uztosi(length)); return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT); } static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum /* output */, size_t unused) { EVP_MD_CTX *mdctx; unsigned int len = 0; (void) unused; mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, EVP_md5(), NULL); EVP_DigestUpdate(mdctx, tmp, tmplen); EVP_DigestFinal_ex(mdctx, md5sum, &len); EVP_MD_CTX_destroy(mdctx); return CURLE_OK; } #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) static CURLcode Curl_ossl_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum /* output */, size_t unused) { EVP_MD_CTX *mdctx; unsigned int len = 0; (void) unused; mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL); EVP_DigestUpdate(mdctx, tmp, tmplen); EVP_DigestFinal_ex(mdctx, sha256sum, &len); EVP_MD_CTX_destroy(mdctx); return CURLE_OK; } #endif static bool Curl_ossl_cert_status_request(void) { #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) return TRUE; #else return FALSE; #endif } static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl, CURLINFO info) { /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */ return info == CURLINFO_TLS_SESSION ? (void *)BACKEND->ctx : (void *)BACKEND->handle; } const struct Curl_ssl Curl_ssl_openssl = { { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */ SSLSUPP_CA_PATH | SSLSUPP_CERTINFO | SSLSUPP_PINNEDPUBKEY | SSLSUPP_SSL_CTX | #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES SSLSUPP_TLS13_CIPHERSUITES | #endif SSLSUPP_HTTPS_PROXY, sizeof(struct ssl_backend_data), Curl_ossl_init, /* init */ Curl_ossl_cleanup, /* cleanup */ Curl_ossl_version, /* version */ Curl_ossl_check_cxn, /* check_cxn */ Curl_ossl_shutdown, /* shutdown */ Curl_ossl_data_pending, /* data_pending */ Curl_ossl_random, /* random */ Curl_ossl_cert_status_request, /* cert_status_request */ Curl_ossl_connect, /* connect */ Curl_ossl_connect_nonblocking, /* connect_nonblocking */ Curl_ossl_get_internals, /* get_internals */ Curl_ossl_close, /* close_one */ Curl_ossl_close_all, /* close_all */ Curl_ossl_session_free, /* session_free */ Curl_ossl_set_engine, /* set_engine */ Curl_ossl_set_engine_default, /* set_engine_default */ Curl_ossl_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_ossl_md5sum, /* md5sum */ #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) Curl_ossl_sha256sum /* sha256sum */ #else NULL /* sha256sum */ #endif }; #endif /* USE_OPENSSL */
YifuLiu/AliOS-Things
components/curl/lib/vtls/openssl.c
C
apache-2.0
118,612
#ifndef HEADER_CURL_SSLUSE_H #define HEADER_CURL_SSLUSE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_OPENSSL /* * This header should only be needed to get included by vtls.c and openssl.c */ #include "urldata.h" extern const struct Curl_ssl Curl_ssl_openssl; #endif /* USE_OPENSSL */ #endif /* HEADER_CURL_SSLUSE_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/openssl.h
C
apache-2.0
1,343
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all PolarSSL-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. * */ #include "curl_setup.h" #ifdef USE_POLARSSL #include <polarssl/net.h> #include <polarssl/ssl.h> #include <polarssl/certs.h> #include <polarssl/x509.h> #include <polarssl/version.h> #include <polarssl/sha256.h> #if POLARSSL_VERSION_NUMBER < 0x01030000 #error too old PolarSSL #endif #include <polarssl/error.h> #include <polarssl/entropy.h> #include <polarssl/ctr_drbg.h> #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "polarssl.h" #include "vtls.h" #include "parsedate.h" #include "connect.h" /* for the connect timeout */ #include "select.h" #include "strcase.h" #include "polarssl_threadlock.h" #include "multiif.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* See https://tls.mbed.org/discussions/generic/ howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der */ #define RSA_PUB_DER_MAX_BYTES (38 + 2 * POLARSSL_MPI_MAX_SIZE) #define ECP_PUB_DER_MAX_BYTES (30 + 2 * POLARSSL_ECP_MAX_BYTES) #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \ RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES) struct ssl_backend_data { ctr_drbg_context ctr_drbg; entropy_context entropy; ssl_context ssl; int server_fd; x509_crt cacert; x509_crt clicert; x509_crl crl; rsa_context rsa; }; #define BACKEND connssl->backend /* apply threading? */ #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) #define THREADING_SUPPORT #endif #ifndef POLARSSL_ERROR_C #define error_strerror(x,y,z) #endif /* POLARSSL_ERROR_C */ #if defined(THREADING_SUPPORT) static entropy_context entropy; static int entropy_init_initialized = 0; /* start of entropy_init_mutex() */ static void entropy_init_mutex(entropy_context *ctx) { /* lock 0 = entropy_init_mutex() */ Curl_polarsslthreadlock_lock_function(0); if(entropy_init_initialized == 0) { entropy_init(ctx); entropy_init_initialized = 1; } Curl_polarsslthreadlock_unlock_function(0); } /* end of entropy_init_mutex() */ /* start of entropy_func_mutex() */ static int entropy_func_mutex(void *data, unsigned char *output, size_t len) { int ret; /* lock 1 = entropy_func_mutex() */ Curl_polarsslthreadlock_lock_function(1); ret = entropy_func(data, output, len); Curl_polarsslthreadlock_unlock_function(1); return ret; } /* end of entropy_func_mutex() */ #endif /* THREADING_SUPPORT */ /* Define this to enable lots of debugging for PolarSSL */ #undef POLARSSL_DEBUG #ifdef POLARSSL_DEBUG static void polarssl_debug(void *context, int level, const char *line) { struct Curl_easy *data = NULL; if(!context) return; data = (struct Curl_easy *)context; infof(data, "%s", line); (void) level; } #else #endif /* ALPN for http2? */ #ifdef POLARSSL_SSL_ALPN # define HAS_ALPN #endif static Curl_recv polarssl_recv; static Curl_send polarssl_send; static CURLcode polarssl_version_from_curl(int *polarver, long ssl_version) { switch(ssl_version) { case CURL_SSLVERSION_TLSv1_0: *polarver = SSL_MINOR_VERSION_1; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1: *polarver = SSL_MINOR_VERSION_2; return CURLE_OK; case CURL_SSLVERSION_TLSv1_2: *polarver = SSL_MINOR_VERSION_3; return CURLE_OK; case CURL_SSLVERSION_TLSv1_3: break; } return CURLE_SSL_CONNECT_ERROR; } static CURLcode set_ssl_version_min_max(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); int ssl_min_ver = SSL_MINOR_VERSION_1; int ssl_max_ver = SSL_MINOR_VERSION_1; CURLcode result = CURLE_OK; switch(ssl_version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_version = CURL_SSLVERSION_TLSv1_0; break; } switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; break; } result = polarssl_version_from_curl(&ssl_min_ver, ssl_version); if(result) { failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); return result; } result = polarssl_version_from_curl(&ssl_max_ver, ssl_version_max >> 16); if(result) { failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); return result; } ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_min_ver); ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_max_ver); return result; } static CURLcode polarssl_connect_step1(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; const char *capath = SSL_CONN_CONFIG(CApath); const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; int ret = -1; char errorbuf[128]; errorbuf[0] = 0; /* PolarSSL only supports SSLv3 and TLSv1 */ if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) { failf(data, "PolarSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } #ifdef THREADING_SUPPORT entropy_init_mutex(&entropy); if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func_mutex, &entropy, NULL, 0)) != 0) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #else entropy_init(&BACKEND->entropy); if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func, &BACKEND->entropy, NULL, 0)) != 0) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n", -ret, errorbuf); } #endif /* THREADING_SUPPORT */ /* Load the trusted CA */ memset(&BACKEND->cacert, 0, sizeof(x509_crt)); if(SSL_CONN_CONFIG(CAfile)) { ret = x509_crt_parse_file(&BACKEND->cacert, SSL_CONN_CONFIG(CAfile)); if(ret<0) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s", SSL_CONN_CONFIG(CAfile), -ret, errorbuf); if(SSL_CONN_CONFIG(verifypeer)) return CURLE_SSL_CACERT_BADFILE; } } if(capath) { ret = x509_crt_parse_path(&BACKEND->cacert, capath); if(ret<0) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s", capath, -ret, errorbuf); if(SSL_CONN_CONFIG(verifypeer)) return CURLE_SSL_CACERT_BADFILE; } } /* Load the client certificate */ memset(&BACKEND->clicert, 0, sizeof(x509_crt)); if(SSL_SET_OPTION(cert)) { ret = x509_crt_parse_file(&BACKEND->clicert, SSL_SET_OPTION(cert)); if(ret) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s", SSL_SET_OPTION(cert), -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the client private key */ if(SSL_SET_OPTION(key)) { pk_context pk; pk_init(&pk); ret = pk_parse_keyfile(&pk, SSL_SET_OPTION(key), SSL_SET_OPTION(key_passwd)); if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA)) ret = POLARSSL_ERR_PK_TYPE_MISMATCH; if(ret == 0) rsa_copy(&BACKEND->rsa, pk_rsa(pk)); else rsa_free(&BACKEND->rsa); pk_free(&pk); if(ret) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s", SSL_SET_OPTION(key), -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the CRL */ memset(&BACKEND->crl, 0, sizeof(x509_crl)); if(SSL_SET_OPTION(CRLfile)) { ret = x509_crl_parse_file(&BACKEND->crl, SSL_SET_OPTION(CRLfile)); if(ret) { error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s", SSL_SET_OPTION(CRLfile), -ret, errorbuf); return CURLE_SSL_CRL_BADFILE; } } infof(data, "PolarSSL: Connecting to %s:%d\n", hostname, port); if(ssl_init(&BACKEND->ssl)) { failf(data, "PolarSSL: ssl_init failed"); return CURLE_SSL_CONNECT_ERROR; } switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1); break; case CURL_SSLVERSION_SSLv3: ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_0); infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n"); break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(conn, sockindex); if(result != CURLE_OK) return result; break; } default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } ssl_set_endpoint(&BACKEND->ssl, SSL_IS_CLIENT); ssl_set_authmode(&BACKEND->ssl, SSL_VERIFY_OPTIONAL); ssl_set_rng(&BACKEND->ssl, ctr_drbg_random, &BACKEND->ctr_drbg); ssl_set_bio(&BACKEND->ssl, net_recv, &conn->sock[sockindex], net_send, &conn->sock[sockindex]); ssl_set_ciphersuites(&BACKEND->ssl, ssl_list_ciphersuites()); /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *old_session = NULL; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) { ret = ssl_set_session(&BACKEND->ssl, old_session); if(ret) { Curl_ssl_sessionid_unlock(conn); failf(data, "ssl_set_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } infof(data, "PolarSSL re-using session\n"); } Curl_ssl_sessionid_unlock(conn); } ssl_set_ca_chain(&BACKEND->ssl, &BACKEND->cacert, &BACKEND->crl, hostname); ssl_set_own_cert_rsa(&BACKEND->ssl, &BACKEND->clicert, &BACKEND->rsa); if(ssl_set_hostname(&BACKEND->ssl, hostname)) { /* ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name to set in the SNI extension. So even if curl connects to a host specified as an IP address, this function must be used. */ failf(data, "couldn't set hostname in PolarSSL"); return CURLE_SSL_CONNECT_ERROR; } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { static const char *protocols[3]; int cur = 0; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = NGHTTP2_PROTO_VERSION_ID; infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif protocols[cur++] = ALPN_HTTP_1_1; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); protocols[cur] = NULL; ssl_set_alpn_protocols(&BACKEND->ssl, protocols); } #endif #ifdef POLARSSL_DEBUG ssl_set_dbg(&BACKEND->ssl, polarssl_debug, data); #endif connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode polarssl_connect_step2(struct connectdata *conn, int sockindex) { int ret; struct Curl_easy *data = conn->data; struct ssl_connect_data* connssl = &conn->ssl[sockindex]; char buffer[1024]; const char * const pinnedpubkey = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; char errorbuf[128]; errorbuf[0] = 0; conn->recv[sockindex] = polarssl_recv; conn->send[sockindex] = polarssl_send; ret = ssl_handshake(&BACKEND->ssl); switch(ret) { case 0: break; case POLARSSL_ERR_NET_WANT_READ: connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; case POLARSSL_ERR_NET_WANT_WRITE: connssl->connecting_state = ssl_connect_2_writing; return CURLE_OK; default: error_strerror(ret, errorbuf, sizeof(errorbuf)); failf(data, "ssl_handshake returned - PolarSSL: (-0x%04X) %s", -ret, errorbuf); return CURLE_SSL_CONNECT_ERROR; } infof(data, "PolarSSL: Handshake complete, cipher is %s\n", ssl_get_ciphersuite(&BACKEND->ssl) ); ret = ssl_get_verify_result(&BACKEND->ssl); if(ret && SSL_CONN_CONFIG(verifypeer)) { if(ret & BADCERT_EXPIRED) failf(data, "Cert verify failed: BADCERT_EXPIRED"); if(ret & BADCERT_REVOKED) { failf(data, "Cert verify failed: BADCERT_REVOKED"); return CURLE_PEER_FAILED_VERIFICATION; } if(ret & BADCERT_CN_MISMATCH) failf(data, "Cert verify failed: BADCERT_CN_MISMATCH"); if(ret & BADCERT_NOT_TRUSTED) failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED"); return CURLE_PEER_FAILED_VERIFICATION; } if(ssl_get_peer_cert(&(BACKEND->ssl))) { /* If the session was resumed, there will be no peer certs */ memset(buffer, 0, sizeof(buffer)); if(x509_crt_info(buffer, sizeof(buffer), (char *)"* ", ssl_get_peer_cert(&(BACKEND->ssl))) != -1) infof(data, "Dumping cert info:\n%s\n", buffer); } /* adapted from mbedtls.c */ if(pinnedpubkey) { int size; CURLcode result; x509_crt *p; unsigned char pubkey[PUB_DER_MAX_BYTES]; const x509_crt *peercert; peercert = ssl_get_peer_cert(&BACKEND->ssl); if(!peercert || !peercert->raw.p || !peercert->raw.len) { failf(data, "Failed due to missing peer certificate"); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } p = calloc(1, sizeof(*p)); if(!p) return CURLE_OUT_OF_MEMORY; x509_crt_init(p); /* Make a copy of our const peercert because pk_write_pubkey_der needs a non-const key, for now. https://github.com/ARMmbed/mbedtls/issues/396 */ if(x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) { failf(data, "Failed copying peer certificate"); x509_crt_free(p); free(p); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } size = pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES); if(size <= 0) { failf(data, "Failed copying public key from peer certificate"); x509_crt_free(p); free(p); return CURLE_SSL_PINNEDPUBKEYNOTMATCH; } /* pk_write_pubkey_der writes data at the end of the buffer. */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, &pubkey[PUB_DER_MAX_BYTES - size], size); if(result) { x509_crt_free(p); free(p); return result; } x509_crt_free(p); free(p); } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { const char *next_protocol = ssl_get_alpn_protocol(&BACKEND->ssl); if(next_protocol != NULL) { infof(data, "ALPN, server accepted to use %s\n", next_protocol); #ifdef USE_NGHTTP2 if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID, NGHTTP2_PROTO_VERSION_ID_LEN)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } } else infof(data, "ALPN, server did not agree to a protocol\n"); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } #endif connssl->connecting_state = ssl_connect_3; infof(data, "SSL connected\n"); return CURLE_OK; } static CURLcode polarssl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode retcode = CURLE_OK; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); if(SSL_SET_OPTION(primary.sessionid)) { int ret; ssl_session *our_ssl_sessionid; void *old_ssl_sessionid = NULL; our_ssl_sessionid = calloc(1, sizeof(ssl_session)); if(!our_ssl_sessionid) return CURLE_OUT_OF_MEMORY; ret = ssl_get_session(&BACKEND->ssl, our_ssl_sessionid); if(ret) { failf(data, "ssl_get_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } /* If there's already a matching session in the cache, delete it */ Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex)) Curl_ssl_delsessionid(conn, old_ssl_sessionid); retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0, sockindex); Curl_ssl_sessionid_unlock(conn); if(retcode) { free(our_ssl_sessionid); failf(data, "failed to store ssl session"); return retcode; } } connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static ssize_t polarssl_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; int ret = -1; ret = ssl_write(&BACKEND->ssl, (unsigned char *)mem, len); if(ret < 0) { *curlcode = (ret == POLARSSL_ERR_NET_WANT_WRITE) ? CURLE_AGAIN : CURLE_SEND_ERROR; ret = -1; } return ret; } static void Curl_polarssl_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; rsa_free(&BACKEND->rsa); x509_crt_free(&BACKEND->clicert); x509_crt_free(&BACKEND->cacert); x509_crl_free(&BACKEND->crl); ssl_free(&BACKEND->ssl); } static ssize_t polarssl_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { struct ssl_connect_data *connssl = &conn->ssl[num]; int ret = -1; ssize_t len = -1; memset(buf, 0, buffersize); ret = ssl_read(&BACKEND->ssl, (unsigned char *)buf, buffersize); if(ret <= 0) { if(ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY) return 0; *curlcode = (ret == POLARSSL_ERR_NET_WANT_READ) ? CURLE_AGAIN : CURLE_RECV_ERROR; return -1; } len = ret; return len; } static void Curl_polarssl_session_free(void *ptr) { ssl_session_free(ptr); free(ptr); } /* 1.3.10 was the first rebranded version. All new releases (in 1.3 branch and higher) will be mbed TLS branded.. */ static size_t Curl_polarssl_version(char *buffer, size_t size) { unsigned int version = version_get_number(); return msnprintf(buffer, size, "%s/%d.%d.%d", version >= 0x01030A00?"mbedTLS":"PolarSSL", version>>24, (version>>16)&0xff, (version>>8)&0xff); } static CURLcode polarssl_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = polarssl_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if * this connection is part of a multi handle and this loop would * execute again. This permits the owner of a multi handle to * abort a connection attempt before step2 has completed while * ensuring that a client using select() or epoll() will always * have a valid fdset to wait on. */ result = polarssl_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = polarssl_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = polarssl_recv; conn->send[sockindex] = polarssl_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_polarssl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return polarssl_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_polarssl_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = polarssl_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } /* * return 0 error initializing SSL * return 1 SSL initialized successfully */ static int Curl_polarssl_init(void) { return Curl_polarsslthreadlock_thread_setup(); } static void Curl_polarssl_cleanup(void) { (void)Curl_polarsslthreadlock_thread_cleanup(); } static bool Curl_polarssl_data_pending(const struct connectdata *conn, int sockindex) { const struct ssl_connect_data *connssl = &conn->ssl[sockindex]; return ssl_get_bytes_avail(&BACKEND->ssl) != 0; } static CURLcode Curl_polarssl_sha256sum(const unsigned char *input, size_t inputlen, unsigned char *sha256sum, size_t sha256len UNUSED_PARAM) { (void)sha256len; sha256(input, inputlen, sha256sum, 0); return CURLE_OK; } static void *Curl_polarssl_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return &BACKEND->ssl; } const struct Curl_ssl Curl_ssl_polarssl = { { CURLSSLBACKEND_POLARSSL, "polarssl" }, /* info */ SSLSUPP_CA_PATH | SSLSUPP_PINNEDPUBKEY, sizeof(struct ssl_backend_data), Curl_polarssl_init, /* init */ Curl_polarssl_cleanup, /* cleanup */ Curl_polarssl_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_none_shutdown, /* shutdown */ Curl_polarssl_data_pending, /* data_pending */ /* This might cause libcurl to use a weeker random! */ Curl_none_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_polarssl_connect, /* connect */ Curl_polarssl_connect_nonblocking, /* connect_nonblocking */ Curl_polarssl_get_internals, /* get_internals */ Curl_polarssl_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_polarssl_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ Curl_polarssl_sha256sum /* sha256sum */ }; #endif /* USE_POLARSSL */
YifuLiu/AliOS-Things
components/curl/lib/vtls/polarssl.c
C
apache-2.0
27,221
#ifndef HEADER_CURL_POLARSSL_H #define HEADER_CURL_POLARSSL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_POLARSSL extern const struct Curl_ssl Curl_ssl_polarssl; #endif /* USE_POLARSSL */ #endif /* HEADER_CURL_POLARSSL_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/polarssl.h
C
apache-2.0
1,304
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2013-2017, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if (defined(USE_POLARSSL) || defined(USE_MBEDTLS)) && \ ((defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ (defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H))) #if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) # include <pthread.h> # define POLARSSL_MUTEX_T pthread_mutex_t #elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) # include <process.h> # define POLARSSL_MUTEX_T HANDLE #endif #include "polarssl_threadlock.h" #include "curl_printf.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* number of thread locks */ #define NUMT 2 /* This array will store all of the mutexes available to PolarSSL. */ static POLARSSL_MUTEX_T *mutex_buf = NULL; int Curl_polarsslthreadlock_thread_setup(void) { int i; mutex_buf = calloc(NUMT * sizeof(POLARSSL_MUTEX_T), 1); if(!mutex_buf) return 0; /* error, no number of threads defined */ for(i = 0; i < NUMT; i++) { int ret; #if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) ret = pthread_mutex_init(&mutex_buf[i], NULL); if(ret) return 0; /* pthread_mutex_init failed */ #elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) mutex_buf[i] = CreateMutex(0, FALSE, 0); if(mutex_buf[i] == 0) return 0; /* CreateMutex failed */ #endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ } return 1; /* OK */ } int Curl_polarsslthreadlock_thread_cleanup(void) { int i; if(!mutex_buf) return 0; /* error, no threads locks defined */ for(i = 0; i < NUMT; i++) { int ret; #if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) ret = pthread_mutex_destroy(&mutex_buf[i]); if(ret) return 0; /* pthread_mutex_destroy failed */ #elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) ret = CloseHandle(mutex_buf[i]); if(!ret) return 0; /* CloseHandle failed */ #endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ } free(mutex_buf); mutex_buf = NULL; return 1; /* OK */ } int Curl_polarsslthreadlock_lock_function(int n) { if(n < NUMT) { int ret; #if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) ret = pthread_mutex_lock(&mutex_buf[n]); if(ret) { DEBUGF(fprintf(stderr, "Error: polarsslthreadlock_lock_function failed\n")); return 0; /* pthread_mutex_lock failed */ } #elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) ret = (WaitForSingleObject(mutex_buf[n], INFINITE) == WAIT_FAILED?1:0); if(ret) { DEBUGF(fprintf(stderr, "Error: polarsslthreadlock_lock_function failed\n")); return 0; /* pthread_mutex_lock failed */ } #endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ } return 1; /* OK */ } int Curl_polarsslthreadlock_unlock_function(int n) { if(n < NUMT) { int ret; #if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H) ret = pthread_mutex_unlock(&mutex_buf[n]); if(ret) { DEBUGF(fprintf(stderr, "Error: polarsslthreadlock_unlock_function failed\n")); return 0; /* pthread_mutex_unlock failed */ } #elif defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H) ret = ReleaseMutex(mutex_buf[n]); if(!ret) { DEBUGF(fprintf(stderr, "Error: polarsslthreadlock_unlock_function failed\n")); return 0; /* pthread_mutex_lock failed */ } #endif /* USE_THREADS_POSIX && HAVE_PTHREAD_H */ } return 1; /* OK */ } #endif /* USE_POLARSSL || USE_MBEDTLS */
YifuLiu/AliOS-Things
components/curl/lib/vtls/polarssl_threadlock.c
C
apache-2.0
4,640
#ifndef HEADER_CURL_POLARSSL_THREADLOCK_H #define HEADER_CURL_POLARSSL_THREADLOCK_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2013-2015, Daniel Stenberg, <daniel@haxx.se>, et al. * Copyright (C) 2010, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if (defined USE_POLARSSL) || (defined USE_MBEDTLS) #if (defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \ (defined(USE_THREADS_WIN32) && defined(HAVE_PROCESS_H)) int Curl_polarsslthreadlock_thread_setup(void); int Curl_polarsslthreadlock_thread_cleanup(void); int Curl_polarsslthreadlock_lock_function(int n); int Curl_polarsslthreadlock_unlock_function(int n); #else #define Curl_polarsslthreadlock_thread_setup() 1 #define Curl_polarsslthreadlock_thread_cleanup() 1 #define Curl_polarsslthreadlock_lock_function(x) 1 #define Curl_polarsslthreadlock_unlock_function(x) 1 #endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ #endif /* USE_POLARSSL */ #endif /* HEADER_CURL_POLARSSL_THREADLOCK_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/polarssl_threadlock.h
C
apache-2.0
1,911
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2016, Marc Hoersken, <info@marc-hoersken.de> * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com> * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all Schannel-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. */ /* * Based upon the PolarSSL implementation in polarssl.c and polarssl.h: * Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com> * * Based upon the CyaSSL implementation in cyassl.c and cyassl.h: * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * Thanks for code and inspiration! */ #include "curl_setup.h" #ifdef USE_SCHANNEL #define EXPOSE_SCHANNEL_INTERNAL_STRUCTS #ifndef USE_WINDOWS_SSPI # error "Can't compile SCHANNEL support without SSPI." #endif #include "schannel.h" #include "vtls.h" #include "sendf.h" #include "connect.h" /* for the connect timeout */ #include "strerror.h" #include "select.h" /* for the socket readyness */ #include "inet_pton.h" /* for IP addr SNI check */ #include "curl_multibyte.h" #include "warnless.h" #include "x509asn1.h" #include "curl_printf.h" #include "multiif.h" #include "system_win32.h" /* The last #include file should be: */ #include "curl_memory.h" #include "memdebug.h" /* ALPN requires version 8.1 of the Windows SDK, which was shipped with Visual Studio 2013, aka _MSC_VER 1800: https://technet.microsoft.com/en-us/library/hh831771%28v=ws.11%29.aspx */ #if defined(_MSC_VER) && (_MSC_VER >= 1800) && !defined(_USING_V110_SDK71_) # define HAS_ALPN 1 #endif #ifndef UNISP_NAME_A #define UNISP_NAME_A "Microsoft Unified Security Protocol Provider" #endif #ifndef UNISP_NAME_W #define UNISP_NAME_W L"Microsoft Unified Security Protocol Provider" #endif #ifndef UNISP_NAME #ifdef UNICODE #define UNISP_NAME UNISP_NAME_W #else #define UNISP_NAME UNISP_NAME_A #endif #endif #if defined(CryptStringToBinary) && defined(CRYPT_STRING_HEX) #define HAS_CLIENT_CERT_PATH #endif #ifdef HAS_CLIENT_CERT_PATH #ifdef UNICODE #define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_W #else #define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_A #endif #endif #ifndef SP_PROT_SSL2_CLIENT #define SP_PROT_SSL2_CLIENT 0x00000008 #endif #ifndef SP_PROT_SSL3_CLIENT #define SP_PROT_SSL3_CLIENT 0x00000008 #endif #ifndef SP_PROT_TLS1_CLIENT #define SP_PROT_TLS1_CLIENT 0x00000080 #endif #ifndef SP_PROT_TLS1_0_CLIENT #define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT #endif #ifndef SP_PROT_TLS1_1_CLIENT #define SP_PROT_TLS1_1_CLIENT 0x00000200 #endif #ifndef SP_PROT_TLS1_2_CLIENT #define SP_PROT_TLS1_2_CLIENT 0x00000800 #endif #ifndef SECBUFFER_ALERT #define SECBUFFER_ALERT 17 #endif /* Both schannel buffer sizes must be > 0 */ #define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096 #define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024 #define CERT_THUMBPRINT_STR_LEN 40 #define CERT_THUMBPRINT_DATA_LEN 20 /* Uncomment to force verbose output * #define infof(x, y, ...) printf(y, __VA_ARGS__) * #define failf(x, y, ...) printf(y, __VA_ARGS__) */ #ifndef CALG_SHA_256 # define CALG_SHA_256 0x0000800c #endif #define BACKEND connssl->backend static Curl_recv schannel_recv; static Curl_send schannel_send; static CURLcode pkp_pin_peer_pubkey(struct connectdata *conn, int sockindex, const char *pinnedpubkey); static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType, void *BufDataPtr, unsigned long BufByteSize) { buffer->cbBuffer = BufByteSize; buffer->BufferType = BufType; buffer->pvBuffer = BufDataPtr; } static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr, unsigned long NumArrElem) { desc->ulVersion = SECBUFFER_VERSION; desc->pBuffers = BufArr; desc->cBuffers = NumArrElem; } static CURLcode set_ssl_version_min_max(SCHANNEL_CRED *schannel_cred, struct connectdata *conn) { struct Curl_easy *data = conn->data; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); long i = ssl_version; switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2; break; } for(; i <= (ssl_version_max >> 16); ++i) { switch(i) { case CURL_SSLVERSION_TLSv1_0: schannel_cred->grbitEnabledProtocols |= SP_PROT_TLS1_0_CLIENT; break; case CURL_SSLVERSION_TLSv1_1: schannel_cred->grbitEnabledProtocols |= SP_PROT_TLS1_1_CLIENT; break; case CURL_SSLVERSION_TLSv1_2: schannel_cred->grbitEnabledProtocols |= SP_PROT_TLS1_2_CLIENT; break; case CURL_SSLVERSION_TLSv1_3: failf(data, "schannel: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; } } return CURLE_OK; } /*longest is 26, buffer is slightly bigger*/ #define LONGEST_ALG_ID 32 #define CIPHEROPTION(X) \ if(strcmp(#X, tmp) == 0) \ return X static int get_alg_id_by_name(char *name) { char tmp[LONGEST_ALG_ID] = { 0 }; char *nameEnd = strchr(name, ':'); size_t n = nameEnd ? min((size_t)(nameEnd - name), LONGEST_ALG_ID - 1) : \ min(strlen(name), LONGEST_ALG_ID - 1); strncpy(tmp, name, n); tmp[n] = 0; CIPHEROPTION(CALG_MD2); CIPHEROPTION(CALG_MD4); CIPHEROPTION(CALG_MD5); CIPHEROPTION(CALG_SHA); CIPHEROPTION(CALG_SHA1); CIPHEROPTION(CALG_MAC); CIPHEROPTION(CALG_RSA_SIGN); CIPHEROPTION(CALG_DSS_SIGN); /*ifdefs for the options that are defined conditionally in wincrypt.h*/ #ifdef CALG_NO_SIGN CIPHEROPTION(CALG_NO_SIGN); #endif CIPHEROPTION(CALG_RSA_KEYX); CIPHEROPTION(CALG_DES); #ifdef CALG_3DES_112 CIPHEROPTION(CALG_3DES_112); #endif CIPHEROPTION(CALG_3DES); CIPHEROPTION(CALG_DESX); CIPHEROPTION(CALG_RC2); CIPHEROPTION(CALG_RC4); CIPHEROPTION(CALG_SEAL); #ifdef CALG_DH_SF CIPHEROPTION(CALG_DH_SF); #endif CIPHEROPTION(CALG_DH_EPHEM); #ifdef CALG_AGREEDKEY_ANY CIPHEROPTION(CALG_AGREEDKEY_ANY); #endif #ifdef CALG_HUGHES_MD5 CIPHEROPTION(CALG_HUGHES_MD5); #endif CIPHEROPTION(CALG_SKIPJACK); #ifdef CALG_TEK CIPHEROPTION(CALG_TEK); #endif CIPHEROPTION(CALG_CYLINK_MEK); CIPHEROPTION(CALG_SSL3_SHAMD5); #ifdef CALG_SSL3_MASTER CIPHEROPTION(CALG_SSL3_MASTER); #endif #ifdef CALG_SCHANNEL_MASTER_HASH CIPHEROPTION(CALG_SCHANNEL_MASTER_HASH); #endif #ifdef CALG_SCHANNEL_MAC_KEY CIPHEROPTION(CALG_SCHANNEL_MAC_KEY); #endif #ifdef CALG_SCHANNEL_ENC_KEY CIPHEROPTION(CALG_SCHANNEL_ENC_KEY); #endif #ifdef CALG_PCT1_MASTER CIPHEROPTION(CALG_PCT1_MASTER); #endif #ifdef CALG_SSL2_MASTER CIPHEROPTION(CALG_SSL2_MASTER); #endif #ifdef CALG_TLS1_MASTER CIPHEROPTION(CALG_TLS1_MASTER); #endif #ifdef CALG_RC5 CIPHEROPTION(CALG_RC5); #endif #ifdef CALG_HMAC CIPHEROPTION(CALG_HMAC); #endif #if !defined(__W32API_MAJOR_VERSION) || \ !defined(__W32API_MINOR_VERSION) || \ defined(__MINGW64_VERSION_MAJOR) || \ (__W32API_MAJOR_VERSION > 5) || \ ((__W32API_MAJOR_VERSION == 5) && (__W32API_MINOR_VERSION > 0)) /* CALG_TLS1PRF has a syntax error in MinGW's w32api up to version 5.0, see https://osdn.net/projects/mingw/ticket/38391 */ CIPHEROPTION(CALG_TLS1PRF); #endif #ifdef CALG_HASH_REPLACE_OWF CIPHEROPTION(CALG_HASH_REPLACE_OWF); #endif #ifdef CALG_AES_128 CIPHEROPTION(CALG_AES_128); #endif #ifdef CALG_AES_192 CIPHEROPTION(CALG_AES_192); #endif #ifdef CALG_AES_256 CIPHEROPTION(CALG_AES_256); #endif #ifdef CALG_AES CIPHEROPTION(CALG_AES); #endif #ifdef CALG_SHA_256 CIPHEROPTION(CALG_SHA_256); #endif #ifdef CALG_SHA_384 CIPHEROPTION(CALG_SHA_384); #endif #ifdef CALG_SHA_512 CIPHEROPTION(CALG_SHA_512); #endif #ifdef CALG_ECDH CIPHEROPTION(CALG_ECDH); #endif #ifdef CALG_ECMQV CIPHEROPTION(CALG_ECMQV); #endif #ifdef CALG_ECDSA CIPHEROPTION(CALG_ECDSA); #endif #ifdef CALG_ECDH_EPHEM CIPHEROPTION(CALG_ECDH_EPHEM); #endif return 0; } static CURLcode set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers) { char *startCur = ciphers; int algCount = 0; static ALG_ID algIds[45]; /*There are 45 listed in the MS headers*/ while(startCur && (0 != *startCur) && (algCount < 45)) { long alg = strtol(startCur, 0, 0); if(!alg) alg = get_alg_id_by_name(startCur); if(alg) algIds[algCount++] = alg; else return CURLE_SSL_CIPHER; startCur = strchr(startCur, ':'); if(startCur) startCur++; } schannel_cred->palgSupportedAlgs = algIds; schannel_cred->cSupportedAlgs = algCount; return CURLE_OK; } #ifdef HAS_CLIENT_CERT_PATH static CURLcode get_cert_location(TCHAR *path, DWORD *store_name, TCHAR **store_path, TCHAR **thumbprint) { TCHAR *sep; TCHAR *store_path_start; size_t store_name_len; sep = _tcschr(path, TEXT('\\')); if(sep == NULL) return CURLE_SSL_CERTPROBLEM; store_name_len = sep - path; if(_tcsnccmp(path, TEXT("CurrentUser"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_CURRENT_USER; else if(_tcsnccmp(path, TEXT("LocalMachine"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE; else if(_tcsnccmp(path, TEXT("CurrentService"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE; else if(_tcsnccmp(path, TEXT("Services"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_SERVICES; else if(_tcsnccmp(path, TEXT("Users"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_USERS; else if(_tcsnccmp(path, TEXT("CurrentUserGroupPolicy"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY; else if(_tcsnccmp(path, TEXT("LocalMachineGroupPolicy"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY; else if(_tcsnccmp(path, TEXT("LocalMachineEnterprise"), store_name_len) == 0) *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE; else return CURLE_SSL_CERTPROBLEM; store_path_start = sep + 1; sep = _tcschr(store_path_start, TEXT('\\')); if(sep == NULL) return CURLE_SSL_CERTPROBLEM; *sep = TEXT('\0'); *store_path = _tcsdup(store_path_start); *sep = TEXT('\\'); if(*store_path == NULL) return CURLE_OUT_OF_MEMORY; *thumbprint = sep + 1; if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN) return CURLE_SSL_CERTPROBLEM; return CURLE_OK; } #endif static CURLcode schannel_connect_step1(struct connectdata *conn, int sockindex) { ssize_t written = -1; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; SecBuffer outbuf; SecBufferDesc outbuf_desc; SecBuffer inbuf; SecBufferDesc inbuf_desc; #ifdef HAS_ALPN unsigned char alpn_buffer[128]; #endif SCHANNEL_CRED schannel_cred; PCCERT_CONTEXT client_certs[1] = { NULL }; SECURITY_STATUS sspi_status = SEC_E_OK; struct curl_schannel_cred *old_cred = NULL; struct in_addr addr; #ifdef ENABLE_IPV6 struct in6_addr addr6; #endif TCHAR *host_name; CURLcode result; char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n", hostname, conn->remote_port)); if(Curl_verify_windows_version(5, 1, PLATFORM_WINNT, VERSION_LESS_THAN_EQUAL)) { /* Schannel in Windows XP (OS version 5.1) uses legacy handshakes and algorithms that may not be supported by all servers. */ infof(data, "schannel: Windows version is old and may not be able to " "connect to some servers due to lack of SNI, algorithms, etc.\n"); } #ifdef HAS_ALPN /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above. Also it doesn't seem to be supported for Wine, see curl bug #983. */ BACKEND->use_alpn = conn->bits.tls_enable_alpn && !GetProcAddress(GetModuleHandleA("ntdll"), "wine_get_version") && Curl_verify_windows_version(6, 3, PLATFORM_WINNT, VERSION_GREATER_THAN_EQUAL); #else BACKEND->use_alpn = false; #endif #ifdef _WIN32_WCE #ifdef HAS_MANUAL_VERIFY_API /* certificate validation on CE doesn't seem to work right; we'll * do it following a more manual process. */ BACKEND->use_manual_cred_validation = true; #else #error "compiler too old to support requisite manual cert verify for Win CE" #endif #else #ifdef HAS_MANUAL_VERIFY_API if(SSL_CONN_CONFIG(CAfile)) { if(Curl_verify_windows_version(6, 1, PLATFORM_WINNT, VERSION_GREATER_THAN_EQUAL)) { BACKEND->use_manual_cred_validation = true; } else { failf(data, "schannel: this version of Windows is too old to support " "certificate verification via CA bundle file."); return CURLE_SSL_CACERT_BADFILE; } } else BACKEND->use_manual_cred_validation = false; #else if(SSL_CONN_CONFIG(CAfile)) { failf(data, "schannel: CA cert support not built in"); return CURLE_NOT_BUILT_IN; } #endif #endif BACKEND->cred = NULL; /* check for an existing re-usable credential handle */ if(SSL_SET_OPTION(primary.sessionid)) { Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL, sockindex)) { BACKEND->cred = old_cred; DEBUGF(infof(data, "schannel: re-using existing credential handle\n")); /* increment the reference counter of the credential/session handle */ BACKEND->cred->refcount++; DEBUGF(infof(data, "schannel: incremented credential handle refcount = %d\n", BACKEND->cred->refcount)); } Curl_ssl_sessionid_unlock(conn); } if(!BACKEND->cred) { /* setup Schannel API options */ memset(&schannel_cred, 0, sizeof(schannel_cred)); schannel_cred.dwVersion = SCHANNEL_CRED_VERSION; if(conn->ssl_config.verifypeer) { #ifdef HAS_MANUAL_VERIFY_API if(BACKEND->use_manual_cred_validation) schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION; else #endif schannel_cred.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION; if(data->set.ssl.no_revoke) { schannel_cred.dwFlags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK | SCH_CRED_IGNORE_REVOCATION_OFFLINE; DEBUGF(infof(data, "schannel: disabled server certificate revocation " "checks\n")); } else { schannel_cred.dwFlags |= SCH_CRED_REVOCATION_CHECK_CHAIN; DEBUGF(infof(data, "schannel: checking server certificate revocation\n")); } } else { schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_IGNORE_NO_REVOCATION_CHECK | SCH_CRED_IGNORE_REVOCATION_OFFLINE; DEBUGF(infof(data, "schannel: disabled server cert revocation checks\n")); } if(!conn->ssl_config.verifyhost) { schannel_cred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK; DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from " "comparing the supplied target name with the subject " "names in server certificates.\n")); } switch(conn->ssl_config.version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT; break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { result = set_ssl_version_min_max(&schannel_cred, conn); if(result != CURLE_OK) return result; break; } case CURL_SSLVERSION_SSLv3: schannel_cred.grbitEnabledProtocols = SP_PROT_SSL3_CLIENT; break; case CURL_SSLVERSION_SSLv2: schannel_cred.grbitEnabledProtocols = SP_PROT_SSL2_CLIENT; break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } if(SSL_CONN_CONFIG(cipher_list)) { result = set_ssl_ciphers(&schannel_cred, SSL_CONN_CONFIG(cipher_list)); if(CURLE_OK != result) { failf(data, "Unable to set ciphers to passed via SSL_CONN_CONFIG"); return result; } } #ifdef HAS_CLIENT_CERT_PATH /* client certificate */ if(data->set.ssl.cert) { DWORD cert_store_name; TCHAR *cert_store_path; TCHAR *cert_thumbprint_str; CRYPT_HASH_BLOB cert_thumbprint; BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN]; HCERTSTORE cert_store; TCHAR *cert_path = Curl_convert_UTF8_to_tchar(data->set.ssl.cert); if(!cert_path) return CURLE_OUT_OF_MEMORY; result = get_cert_location(cert_path, &cert_store_name, &cert_store_path, &cert_thumbprint_str); if(result != CURLE_OK) { failf(data, "schannel: Failed to get certificate location for %s", cert_path); Curl_unicodefree(cert_path); return result; } cert_store = CertOpenStore(CURL_CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV)NULL, CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name, cert_store_path); if(!cert_store) { failf(data, "schannel: Failed to open cert store %x %s, " "last error is %x", cert_store_name, cert_store_path, GetLastError()); free(cert_store_path); Curl_unicodefree(cert_path); return CURLE_SSL_CERTPROBLEM; } free(cert_store_path); cert_thumbprint.pbData = cert_thumbprint_data; cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN; if(!CryptStringToBinary(cert_thumbprint_str, CERT_THUMBPRINT_STR_LEN, CRYPT_STRING_HEX, cert_thumbprint_data, &cert_thumbprint.cbData, NULL, NULL)) { Curl_unicodefree(cert_path); return CURLE_SSL_CERTPROBLEM; } client_certs[0] = CertFindCertificateInStore( cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_HASH, &cert_thumbprint, NULL); Curl_unicodefree(cert_path); if(client_certs[0]) { schannel_cred.cCreds = 1; schannel_cred.paCred = client_certs; } else { /* CRYPT_E_NOT_FOUND / E_INVALIDARG */ return CURLE_SSL_CERTPROBLEM; } CertCloseStore(cert_store, 0); } #else if(data->set.ssl.cert) { failf(data, "schannel: client cert support not built in"); return CURLE_NOT_BUILT_IN; } #endif /* allocate memory for the re-usable credential handle */ BACKEND->cred = (struct curl_schannel_cred *) calloc(1, sizeof(struct curl_schannel_cred)); if(!BACKEND->cred) { failf(data, "schannel: unable to allocate memory"); if(client_certs[0]) CertFreeCertificateContext(client_certs[0]); return CURLE_OUT_OF_MEMORY; } BACKEND->cred->refcount = 1; /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx */ sspi_status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL, &schannel_cred, NULL, NULL, &BACKEND->cred->cred_handle, &BACKEND->cred->time_stamp); if(client_certs[0]) CertFreeCertificateContext(client_certs[0]); if(sspi_status != SEC_E_OK) { char buffer[STRERROR_LEN]; failf(data, "schannel: AcquireCredentialsHandle failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); Curl_safefree(BACKEND->cred); switch(sspi_status) { case SEC_E_INSUFFICIENT_MEMORY: return CURLE_OUT_OF_MEMORY; case SEC_E_NO_CREDENTIALS: case SEC_E_SECPKG_NOT_FOUND: case SEC_E_NOT_OWNER: case SEC_E_UNKNOWN_CREDENTIALS: case SEC_E_INTERNAL_ERROR: default: return CURLE_SSL_CONNECT_ERROR; } } } /* Warn if SNI is disabled due to use of an IP address */ if(Curl_inet_pton(AF_INET, hostname, &addr) #ifdef ENABLE_IPV6 || Curl_inet_pton(AF_INET6, hostname, &addr6) #endif ) { infof(data, "schannel: using IP address, SNI is not supported by OS.\n"); } #ifdef HAS_ALPN if(BACKEND->use_alpn) { int cur = 0; int list_start_index = 0; unsigned int *extension_len = NULL; unsigned short* list_len = NULL; /* The first four bytes will be an unsigned int indicating number of bytes of data in the rest of the the buffer. */ extension_len = (unsigned int *)(&alpn_buffer[cur]); cur += sizeof(unsigned int); /* The next four bytes are an indicator that this buffer will contain ALPN data, as opposed to NPN, for example. */ *(unsigned int *)&alpn_buffer[cur] = SecApplicationProtocolNegotiationExt_ALPN; cur += sizeof(unsigned int); /* The next two bytes will be an unsigned short indicating the number of bytes used to list the preferred protocols. */ list_len = (unsigned short*)(&alpn_buffer[cur]); cur += sizeof(unsigned short); list_start_index = cur; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { memcpy(&alpn_buffer[cur], NGHTTP2_PROTO_ALPN, NGHTTP2_PROTO_ALPN_LEN); cur += NGHTTP2_PROTO_ALPN_LEN; infof(data, "schannel: ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif alpn_buffer[cur++] = ALPN_HTTP_1_1_LENGTH; memcpy(&alpn_buffer[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH); cur += ALPN_HTTP_1_1_LENGTH; infof(data, "schannel: ALPN, offering %s\n", ALPN_HTTP_1_1); *list_len = curlx_uitous(cur - list_start_index); *extension_len = *list_len + sizeof(unsigned int) + sizeof(unsigned short); InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur); InitSecBufferDesc(&inbuf_desc, &inbuf, 1); } else { InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&inbuf_desc, &inbuf, 1); } #else /* HAS_ALPN */ InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&inbuf_desc, &inbuf, 1); #endif /* setup output buffer */ InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&outbuf_desc, &outbuf, 1); /* setup request flags */ BACKEND->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; /* allocate memory for the security context handle */ BACKEND->ctxt = (struct curl_schannel_ctxt *) calloc(1, sizeof(struct curl_schannel_ctxt)); if(!BACKEND->ctxt) { failf(data, "schannel: unable to allocate memory"); return CURLE_OUT_OF_MEMORY; } host_name = Curl_convert_UTF8_to_tchar(hostname); if(!host_name) return CURLE_OUT_OF_MEMORY; /* Schannel InitializeSecurityContext: https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx At the moment we don't pass inbuf unless we're using ALPN since we only use it for that, and Wine (for which we currently disable ALPN) is giving us problems with inbuf regardless. https://github.com/curl/curl/issues/983 */ sspi_status = s_pSecFn->InitializeSecurityContext( &BACKEND->cred->cred_handle, NULL, host_name, BACKEND->req_flags, 0, 0, (BACKEND->use_alpn ? &inbuf_desc : NULL), 0, &BACKEND->ctxt->ctxt_handle, &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp); Curl_unicodefree(host_name); if(sspi_status != SEC_I_CONTINUE_NEEDED) { char buffer[STRERROR_LEN]; Curl_safefree(BACKEND->ctxt); switch(sspi_status) { case SEC_E_INSUFFICIENT_MEMORY: failf(data, "schannel: initial InitializeSecurityContext failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_OUT_OF_MEMORY; case SEC_E_WRONG_PRINCIPAL: failf(data, "schannel: SNI or certificate check failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_PEER_FAILED_VERIFICATION; /* case SEC_E_INVALID_HANDLE: case SEC_E_INVALID_TOKEN: case SEC_E_LOGON_DENIED: case SEC_E_TARGET_UNKNOWN: case SEC_E_NO_AUTHENTICATING_AUTHORITY: case SEC_E_INTERNAL_ERROR: case SEC_E_NO_CREDENTIALS: case SEC_E_UNSUPPORTED_FUNCTION: case SEC_E_APPLICATION_PROTOCOL_MISMATCH: */ default: failf(data, "schannel: initial InitializeSecurityContext failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_SSL_CONNECT_ERROR; } } DEBUGF(infof(data, "schannel: sending initial handshake data: " "sending %lu bytes...\n", outbuf.cbBuffer)); /* send initial handshake data which is now stored in output buffer */ result = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer, outbuf.cbBuffer, &written); s_pSecFn->FreeContextBuffer(outbuf.pvBuffer); if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) { failf(data, "schannel: failed to send initial handshake data: " "sent %zd of %lu bytes", written, outbuf.cbBuffer); return CURLE_SSL_CONNECT_ERROR; } DEBUGF(infof(data, "schannel: sent initial handshake data: " "sent %zd bytes\n", written)); BACKEND->recv_unrecoverable_err = CURLE_OK; BACKEND->recv_sspi_close_notify = false; BACKEND->recv_connection_closed = false; BACKEND->encdata_is_incomplete = false; /* continue to second handshake step */ connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode schannel_connect_step2(struct connectdata *conn, int sockindex) { int i; ssize_t nread = -1, written = -1; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; unsigned char *reallocated_buffer; SecBuffer outbuf[3]; SecBufferDesc outbuf_desc; SecBuffer inbuf[2]; SecBufferDesc inbuf_desc; SECURITY_STATUS sspi_status = SEC_E_OK; CURLcode result; bool doread; char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const char *pubkey_ptr; doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE; DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %hu (step 2/3)\n", hostname, conn->remote_port)); if(!BACKEND->cred || !BACKEND->ctxt) return CURLE_SSL_CONNECT_ERROR; /* buffer to store previously received and decrypted data */ if(BACKEND->decdata_buffer == NULL) { BACKEND->decdata_offset = 0; BACKEND->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE; BACKEND->decdata_buffer = malloc(BACKEND->decdata_length); if(BACKEND->decdata_buffer == NULL) { failf(data, "schannel: unable to allocate memory"); return CURLE_OUT_OF_MEMORY; } } /* buffer to store previously received and encrypted data */ if(BACKEND->encdata_buffer == NULL) { BACKEND->encdata_is_incomplete = false; BACKEND->encdata_offset = 0; BACKEND->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE; BACKEND->encdata_buffer = malloc(BACKEND->encdata_length); if(BACKEND->encdata_buffer == NULL) { failf(data, "schannel: unable to allocate memory"); return CURLE_OUT_OF_MEMORY; } } /* if we need a bigger buffer to read a full message, increase buffer now */ if(BACKEND->encdata_length - BACKEND->encdata_offset < CURL_SCHANNEL_BUFFER_FREE_SIZE) { /* increase internal encrypted data buffer */ size_t reallocated_length = BACKEND->encdata_offset + CURL_SCHANNEL_BUFFER_FREE_SIZE; reallocated_buffer = realloc(BACKEND->encdata_buffer, reallocated_length); if(reallocated_buffer == NULL) { failf(data, "schannel: unable to re-allocate memory"); return CURLE_OUT_OF_MEMORY; } else { BACKEND->encdata_buffer = reallocated_buffer; BACKEND->encdata_length = reallocated_length; } } for(;;) { TCHAR *host_name; if(doread) { /* read encrypted handshake data from socket */ result = Curl_read_plain(conn->sock[sockindex], (char *) (BACKEND->encdata_buffer + BACKEND->encdata_offset), BACKEND->encdata_length - BACKEND->encdata_offset, &nread); if(result == CURLE_AGAIN) { if(connssl->connecting_state != ssl_connect_2_writing) connssl->connecting_state = ssl_connect_2_reading; DEBUGF(infof(data, "schannel: failed to receive handshake, " "need more data\n")); return CURLE_OK; } else if((result != CURLE_OK) || (nread == 0)) { failf(data, "schannel: failed to receive handshake, " "SSL/TLS connection failed"); return CURLE_SSL_CONNECT_ERROR; } /* increase encrypted data buffer offset */ BACKEND->encdata_offset += nread; BACKEND->encdata_is_incomplete = false; DEBUGF(infof(data, "schannel: encrypted data got %zd\n", nread)); } DEBUGF(infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n", BACKEND->encdata_offset, BACKEND->encdata_length)); /* setup input buffers */ InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(BACKEND->encdata_offset), curlx_uztoul(BACKEND->encdata_offset)); InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&inbuf_desc, inbuf, 2); /* setup output buffers */ InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0); InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0); InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&outbuf_desc, outbuf, 3); if(inbuf[0].pvBuffer == NULL) { failf(data, "schannel: unable to allocate memory"); return CURLE_OUT_OF_MEMORY; } /* copy received handshake data into input buffer */ memcpy(inbuf[0].pvBuffer, BACKEND->encdata_buffer, BACKEND->encdata_offset); host_name = Curl_convert_UTF8_to_tchar(hostname); if(!host_name) return CURLE_OUT_OF_MEMORY; /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */ sspi_status = s_pSecFn->InitializeSecurityContext( &BACKEND->cred->cred_handle, &BACKEND->ctxt->ctxt_handle, host_name, BACKEND->req_flags, 0, 0, &inbuf_desc, 0, NULL, &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp); Curl_unicodefree(host_name); /* free buffer for received handshake data */ Curl_safefree(inbuf[0].pvBuffer); /* check if the handshake was incomplete */ if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) { BACKEND->encdata_is_incomplete = true; connssl->connecting_state = ssl_connect_2_reading; DEBUGF(infof(data, "schannel: received incomplete message, need more data\n")); return CURLE_OK; } /* If the server has requested a client certificate, attempt to continue the handshake without one. This will allow connections to servers which request a client certificate but do not require it. */ if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS && !(BACKEND->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) { BACKEND->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS; connssl->connecting_state = ssl_connect_2_writing; DEBUGF(infof(data, "schannel: a client certificate has been requested\n")); return CURLE_OK; } /* check if the handshake needs to be continued */ if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) { for(i = 0; i < 3; i++) { /* search for handshake tokens that need to be send */ if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) { DEBUGF(infof(data, "schannel: sending next handshake data: " "sending %lu bytes...\n", outbuf[i].cbBuffer)); /* send handshake token to server */ result = Curl_write_plain(conn, conn->sock[sockindex], outbuf[i].pvBuffer, outbuf[i].cbBuffer, &written); if((result != CURLE_OK) || (outbuf[i].cbBuffer != (size_t) written)) { failf(data, "schannel: failed to send next handshake data: " "sent %zd of %lu bytes", written, outbuf[i].cbBuffer); return CURLE_SSL_CONNECT_ERROR; } } /* free obsolete buffer */ if(outbuf[i].pvBuffer != NULL) { s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer); } } } else { char buffer[STRERROR_LEN]; switch(sspi_status) { case SEC_E_INSUFFICIENT_MEMORY: failf(data, "schannel: next InitializeSecurityContext failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_OUT_OF_MEMORY; case SEC_E_WRONG_PRINCIPAL: failf(data, "schannel: SNI or certificate check failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_PEER_FAILED_VERIFICATION; /* case SEC_E_INVALID_HANDLE: case SEC_E_INVALID_TOKEN: case SEC_E_LOGON_DENIED: case SEC_E_TARGET_UNKNOWN: case SEC_E_NO_AUTHENTICATING_AUTHORITY: case SEC_E_INTERNAL_ERROR: case SEC_E_NO_CREDENTIALS: case SEC_E_UNSUPPORTED_FUNCTION: case SEC_E_APPLICATION_PROTOCOL_MISMATCH: */ default: failf(data, "schannel: next InitializeSecurityContext failed: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); return CURLE_SSL_CONNECT_ERROR; } } /* check if there was additional remaining encrypted data */ if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) { DEBUGF(infof(data, "schannel: encrypted data length: %lu\n", inbuf[1].cbBuffer)); /* There are two cases where we could be getting extra data here: 1) If we're renegotiating a connection and the handshake is already complete (from the server perspective), it can encrypted app data (not handshake data) in an extra buffer at this point. 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a connection and this extra data is part of the handshake. We should process the data immediately; waiting for the socket to be ready may fail since the server is done sending handshake data. */ /* check if the remaining data is less than the total amount and therefore begins after the already processed data */ if(BACKEND->encdata_offset > inbuf[1].cbBuffer) { memmove(BACKEND->encdata_buffer, (BACKEND->encdata_buffer + BACKEND->encdata_offset) - inbuf[1].cbBuffer, inbuf[1].cbBuffer); BACKEND->encdata_offset = inbuf[1].cbBuffer; if(sspi_status == SEC_I_CONTINUE_NEEDED) { doread = FALSE; continue; } } } else { BACKEND->encdata_offset = 0; } break; } /* check if the handshake needs to be continued */ if(sspi_status == SEC_I_CONTINUE_NEEDED) { connssl->connecting_state = ssl_connect_2_reading; return CURLE_OK; } /* check if the handshake is complete */ if(sspi_status == SEC_E_OK) { connssl->connecting_state = ssl_connect_3; DEBUGF(infof(data, "schannel: SSL/TLS handshake complete\n")); } pubkey_ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]; if(pubkey_ptr) { result = pkp_pin_peer_pubkey(conn, sockindex, pubkey_ptr); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; } } #ifdef HAS_MANUAL_VERIFY_API if(conn->ssl_config.verifypeer && BACKEND->use_manual_cred_validation) { return Curl_verify_certificate(conn, sockindex); } #endif return CURLE_OK; } static bool valid_cert_encoding(const CERT_CONTEXT *cert_context) { return (cert_context != NULL) && ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) && (cert_context->pbCertEncoded != NULL) && (cert_context->cbCertEncoded > 0); } typedef bool(*Read_crt_func)(const CERT_CONTEXT *ccert_context, void *arg); static void traverse_cert_store(const CERT_CONTEXT *context, Read_crt_func func, void *arg) { const CERT_CONTEXT *current_context = NULL; bool should_continue = true; while(should_continue && (current_context = CertEnumCertificatesInStore( context->hCertStore, current_context)) != NULL) should_continue = func(current_context, arg); if(current_context) CertFreeCertificateContext(current_context); } static bool cert_counter_callback(const CERT_CONTEXT *ccert_context, void *certs_count) { if(valid_cert_encoding(ccert_context)) (*(int *)certs_count)++; return true; } struct Adder_args { struct connectdata *conn; CURLcode result; int idx; }; static bool add_cert_to_certinfo(const CERT_CONTEXT *ccert_context, void *raw_arg) { struct Adder_args *args = (struct Adder_args*)raw_arg; args->result = CURLE_OK; if(valid_cert_encoding(ccert_context)) { const char *beg = (const char *) ccert_context->pbCertEncoded; const char *end = beg + ccert_context->cbCertEncoded; args->result = Curl_extract_certinfo(args->conn, (args->idx)++, beg, end); } return args->result == CURLE_OK; } static CURLcode schannel_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; SECURITY_STATUS sspi_status = SEC_E_OK; CERT_CONTEXT *ccert_context = NULL; #ifdef DEBUGBUILD const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; #endif #ifdef HAS_ALPN SecPkgContext_ApplicationProtocol alpn_result; #endif DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); DEBUGF(infof(data, "schannel: SSL/TLS connection with %s port %hu (step 3/3)\n", hostname, conn->remote_port)); if(!BACKEND->cred) return CURLE_SSL_CONNECT_ERROR; /* check if the required context attributes are met */ if(BACKEND->ret_flags != BACKEND->req_flags) { if(!(BACKEND->ret_flags & ISC_RET_SEQUENCE_DETECT)) failf(data, "schannel: failed to setup sequence detection"); if(!(BACKEND->ret_flags & ISC_RET_REPLAY_DETECT)) failf(data, "schannel: failed to setup replay detection"); if(!(BACKEND->ret_flags & ISC_RET_CONFIDENTIALITY)) failf(data, "schannel: failed to setup confidentiality"); if(!(BACKEND->ret_flags & ISC_RET_ALLOCATED_MEMORY)) failf(data, "schannel: failed to setup memory allocation"); if(!(BACKEND->ret_flags & ISC_RET_STREAM)) failf(data, "schannel: failed to setup stream orientation"); return CURLE_SSL_CONNECT_ERROR; } #ifdef HAS_ALPN if(BACKEND->use_alpn) { sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result); if(sspi_status != SEC_E_OK) { failf(data, "schannel: failed to retrieve ALPN result"); return CURLE_SSL_CONNECT_ERROR; } if(alpn_result.ProtoNegoStatus == SecApplicationProtocolNegotiationStatus_Success) { infof(data, "schannel: ALPN, server accepted to use %.*s\n", alpn_result.ProtocolIdSize, alpn_result.ProtocolId); #ifdef USE_NGHTTP2 if(alpn_result.ProtocolIdSize == NGHTTP2_PROTO_VERSION_ID_LEN && !memcmp(NGHTTP2_PROTO_VERSION_ID, alpn_result.ProtocolId, NGHTTP2_PROTO_VERSION_ID_LEN)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(alpn_result.ProtocolIdSize == ALPN_HTTP_1_1_LENGTH && !memcmp(ALPN_HTTP_1_1, alpn_result.ProtocolId, ALPN_HTTP_1_1_LENGTH)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } } else infof(data, "ALPN, server did not agree to a protocol\n"); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); } #endif /* save the current session data for possible re-use */ if(SSL_SET_OPTION(primary.sessionid)) { bool incache; struct curl_schannel_cred *old_cred = NULL; Curl_ssl_sessionid_lock(conn); incache = !(Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL, sockindex)); if(incache) { if(old_cred != BACKEND->cred) { DEBUGF(infof(data, "schannel: old credential handle is stale, removing\n")); /* we're not taking old_cred ownership here, no refcount++ is needed */ Curl_ssl_delsessionid(conn, (void *)old_cred); incache = FALSE; } } if(!incache) { result = Curl_ssl_addsessionid(conn, (void *)BACKEND->cred, sizeof(struct curl_schannel_cred), sockindex); if(result) { Curl_ssl_sessionid_unlock(conn); failf(data, "schannel: failed to store credential handle"); return result; } else { /* this cred session is now also referenced by sessionid cache */ BACKEND->cred->refcount++; DEBUGF(infof(data, "schannel: stored credential handle in session cache\n")); } } Curl_ssl_sessionid_unlock(conn); } if(data->set.ssl.certinfo) { int certs_count = 0; sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &ccert_context); if((sspi_status != SEC_E_OK) || (ccert_context == NULL)) { failf(data, "schannel: failed to retrieve remote cert context"); return CURLE_PEER_FAILED_VERIFICATION; } traverse_cert_store(ccert_context, cert_counter_callback, &certs_count); result = Curl_ssl_init_certinfo(data, certs_count); if(!result) { struct Adder_args args; args.conn = conn; args.idx = 0; traverse_cert_store(ccert_context, add_cert_to_certinfo, &args); result = args.result; } CertFreeCertificateContext(ccert_context); if(result) return result; } connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static CURLcode schannel_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; time_t timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* check out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL/TLS connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = schannel_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL/TLS connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state ? sockfd : CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking ? 0 : timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL/TLS connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if * this connection is part of a multi handle and this loop would * execute again. This permits the owner of a multi handle to * abort a connection attempt before step2 has completed while * ensuring that a client using select() or epoll() will always * have a valid fdset to wait on. */ result = schannel_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = schannel_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = schannel_recv; conn->send[sockindex] = schannel_send; #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS /* When SSPI is used in combination with Schannel * we need the Schannel context to create the Schannel * binding to pass the IIS extended protection checks. * Available on Windows 7 or later. */ conn->sslContext = &BACKEND->ctxt->ctxt_handle; #endif *done = TRUE; } else *done = FALSE; /* reset our connection state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static ssize_t schannel_send(struct connectdata *conn, int sockindex, const void *buf, size_t len, CURLcode *err) { ssize_t written = -1; size_t data_len = 0; unsigned char *data = NULL; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; SecBuffer outbuf[4]; SecBufferDesc outbuf_desc; SECURITY_STATUS sspi_status = SEC_E_OK; CURLcode result; /* check if the maximum stream sizes were queried */ if(BACKEND->stream_sizes.cbMaximumMessage == 0) { sspi_status = s_pSecFn->QueryContextAttributes( &BACKEND->ctxt->ctxt_handle, SECPKG_ATTR_STREAM_SIZES, &BACKEND->stream_sizes); if(sspi_status != SEC_E_OK) { *err = CURLE_SEND_ERROR; return -1; } } /* check if the buffer is longer than the maximum message length */ if(len > BACKEND->stream_sizes.cbMaximumMessage) { len = BACKEND->stream_sizes.cbMaximumMessage; } /* calculate the complete message length and allocate a buffer for it */ data_len = BACKEND->stream_sizes.cbHeader + len + BACKEND->stream_sizes.cbTrailer; data = (unsigned char *) malloc(data_len); if(data == NULL) { *err = CURLE_OUT_OF_MEMORY; return -1; } /* setup output buffers (header, data, trailer, empty) */ InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER, data, BACKEND->stream_sizes.cbHeader); InitSecBuffer(&outbuf[1], SECBUFFER_DATA, data + BACKEND->stream_sizes.cbHeader, curlx_uztoul(len)); InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER, data + BACKEND->stream_sizes.cbHeader + len, BACKEND->stream_sizes.cbTrailer); InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&outbuf_desc, outbuf, 4); /* copy data into output buffer */ memcpy(outbuf[1].pvBuffer, buf, len); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */ sspi_status = s_pSecFn->EncryptMessage(&BACKEND->ctxt->ctxt_handle, 0, &outbuf_desc, 0); /* check if the message was encrypted */ if(sspi_status == SEC_E_OK) { written = 0; /* send the encrypted message including header, data and trailer */ len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer; /* It's important to send the full message which includes the header, encrypted payload, and trailer. Until the client receives all the data a coherent message has not been delivered and the client can't read any of it. If we wanted to buffer the unwritten encrypted bytes, we would tell the client that all data it has requested to be sent has been sent. The unwritten encrypted bytes would be the first bytes to send on the next invocation. Here's the catch with this - if we tell the client that all the bytes have been sent, will the client call this method again to send the buffered data? Looking at who calls this function, it seems the answer is NO. */ /* send entire message or fail */ while(len > (size_t)written) { ssize_t this_write; time_t timeleft; int what; this_write = 0; timeleft = Curl_timeleft(conn->data, NULL, FALSE); if(timeleft < 0) { /* we already got the timeout */ failf(conn->data, "schannel: timed out sending data " "(bytes sent: %zd)", written); *err = CURLE_OPERATION_TIMEDOUT; written = -1; break; } what = SOCKET_WRITABLE(conn->sock[sockindex], timeleft); if(what < 0) { /* fatal error */ failf(conn->data, "select/poll on SSL socket, errno: %d", SOCKERRNO); *err = CURLE_SEND_ERROR; written = -1; break; } else if(0 == what) { failf(conn->data, "schannel: timed out sending data " "(bytes sent: %zd)", written); *err = CURLE_OPERATION_TIMEDOUT; written = -1; break; } /* socket is writable */ result = Curl_write_plain(conn, conn->sock[sockindex], data + written, len - written, &this_write); if(result == CURLE_AGAIN) continue; else if(result != CURLE_OK) { *err = result; written = -1; break; } written += this_write; } } else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) { *err = CURLE_OUT_OF_MEMORY; } else{ *err = CURLE_SEND_ERROR; } Curl_safefree(data); if(len == (size_t)written) /* Encrypted message including header, data and trailer entirely sent. The return value is the number of unencrypted bytes that were sent. */ written = outbuf[1].cbBuffer; return written; } static ssize_t schannel_recv(struct connectdata *conn, int sockindex, char *buf, size_t len, CURLcode *err) { size_t size = 0; ssize_t nread = -1; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; unsigned char *reallocated_buffer; size_t reallocated_length; bool done = FALSE; SecBuffer inbuf[4]; SecBufferDesc inbuf_desc; SECURITY_STATUS sspi_status = SEC_E_OK; /* we want the length of the encrypted buffer to be at least large enough that it can hold all the bytes requested and some TLS record overhead. */ size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE; /**************************************************************************** * Don't return or set BACKEND->recv_unrecoverable_err unless in the cleanup. * The pattern for return error is set *err, optional infof, goto cleanup. * * Our priority is to always return as much decrypted data to the caller as * possible, even if an error occurs. The state of the decrypted buffer must * always be valid. Transfer of decrypted data to the caller's buffer is * handled in the cleanup. */ DEBUGF(infof(data, "schannel: client wants to read %zu bytes\n", len)); *err = CURLE_OK; if(len && len <= BACKEND->decdata_offset) { infof(data, "schannel: enough decrypted data is already available\n"); goto cleanup; } else if(BACKEND->recv_unrecoverable_err) { *err = BACKEND->recv_unrecoverable_err; infof(data, "schannel: an unrecoverable error occurred in a prior call\n"); goto cleanup; } else if(BACKEND->recv_sspi_close_notify) { /* once a server has indicated shutdown there is no more encrypted data */ infof(data, "schannel: server indicated shutdown in a prior call\n"); goto cleanup; } else if(!len) { /* It's debatable what to return when !len. Regardless we can't return immediately because there may be data to decrypt (in the case we want to decrypt all encrypted cached data) so handle !len later in cleanup. */ ; /* do nothing */ } else if(!BACKEND->recv_connection_closed) { /* increase enc buffer in order to fit the requested amount of data */ size = BACKEND->encdata_length - BACKEND->encdata_offset; if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE || BACKEND->encdata_length < min_encdata_length) { reallocated_length = BACKEND->encdata_offset + CURL_SCHANNEL_BUFFER_FREE_SIZE; if(reallocated_length < min_encdata_length) { reallocated_length = min_encdata_length; } reallocated_buffer = realloc(BACKEND->encdata_buffer, reallocated_length); if(reallocated_buffer == NULL) { *err = CURLE_OUT_OF_MEMORY; failf(data, "schannel: unable to re-allocate memory"); goto cleanup; } BACKEND->encdata_buffer = reallocated_buffer; BACKEND->encdata_length = reallocated_length; size = BACKEND->encdata_length - BACKEND->encdata_offset; DEBUGF(infof(data, "schannel: encdata_buffer resized %zu\n", BACKEND->encdata_length)); } DEBUGF(infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n", BACKEND->encdata_offset, BACKEND->encdata_length)); /* read encrypted data from socket */ *err = Curl_read_plain(conn->sock[sockindex], (char *)(BACKEND->encdata_buffer + BACKEND->encdata_offset), size, &nread); if(*err) { nread = -1; if(*err == CURLE_AGAIN) DEBUGF(infof(data, "schannel: Curl_read_plain returned CURLE_AGAIN\n")); else if(*err == CURLE_RECV_ERROR) infof(data, "schannel: Curl_read_plain returned CURLE_RECV_ERROR\n"); else infof(data, "schannel: Curl_read_plain returned error %d\n", *err); } else if(nread == 0) { BACKEND->recv_connection_closed = true; DEBUGF(infof(data, "schannel: server closed the connection\n")); } else if(nread > 0) { BACKEND->encdata_offset += (size_t)nread; BACKEND->encdata_is_incomplete = false; DEBUGF(infof(data, "schannel: encrypted data got %zd\n", nread)); } } DEBUGF(infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n", BACKEND->encdata_offset, BACKEND->encdata_length)); /* decrypt loop */ while(BACKEND->encdata_offset > 0 && sspi_status == SEC_E_OK && (!len || BACKEND->decdata_offset < len || BACKEND->recv_connection_closed)) { /* prepare data buffer for DecryptMessage call */ InitSecBuffer(&inbuf[0], SECBUFFER_DATA, BACKEND->encdata_buffer, curlx_uztoul(BACKEND->encdata_offset)); /* we need 3 more empty input buffers for possible output */ InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0); InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0); InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&inbuf_desc, inbuf, 4); /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx */ sspi_status = s_pSecFn->DecryptMessage(&BACKEND->ctxt->ctxt_handle, &inbuf_desc, 0, NULL); /* check if everything went fine (server may want to renegotiate or shutdown the connection context) */ if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE || sspi_status == SEC_I_CONTEXT_EXPIRED) { /* check for successfully decrypted data, even before actual renegotiation or shutdown of the connection context */ if(inbuf[1].BufferType == SECBUFFER_DATA) { DEBUGF(infof(data, "schannel: decrypted data length: %lu\n", inbuf[1].cbBuffer)); /* increase buffer in order to fit the received amount of data */ size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ? inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE; if(BACKEND->decdata_length - BACKEND->decdata_offset < size || BACKEND->decdata_length < len) { /* increase internal decrypted data buffer */ reallocated_length = BACKEND->decdata_offset + size; /* make sure that the requested amount of data fits */ if(reallocated_length < len) { reallocated_length = len; } reallocated_buffer = realloc(BACKEND->decdata_buffer, reallocated_length); if(reallocated_buffer == NULL) { *err = CURLE_OUT_OF_MEMORY; failf(data, "schannel: unable to re-allocate memory"); goto cleanup; } BACKEND->decdata_buffer = reallocated_buffer; BACKEND->decdata_length = reallocated_length; } /* copy decrypted data to internal buffer */ size = inbuf[1].cbBuffer; if(size) { memcpy(BACKEND->decdata_buffer + BACKEND->decdata_offset, inbuf[1].pvBuffer, size); BACKEND->decdata_offset += size; } DEBUGF(infof(data, "schannel: decrypted data added: %zu\n", size)); DEBUGF(infof(data, "schannel: decrypted cached: offset %zu length %zu\n", BACKEND->decdata_offset, BACKEND->decdata_length)); } /* check for remaining encrypted data */ if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) { DEBUGF(infof(data, "schannel: encrypted data length: %lu\n", inbuf[3].cbBuffer)); /* check if the remaining data is less than the total amount * and therefore begins after the already processed data */ if(BACKEND->encdata_offset > inbuf[3].cbBuffer) { /* move remaining encrypted data forward to the beginning of buffer */ memmove(BACKEND->encdata_buffer, (BACKEND->encdata_buffer + BACKEND->encdata_offset) - inbuf[3].cbBuffer, inbuf[3].cbBuffer); BACKEND->encdata_offset = inbuf[3].cbBuffer; } DEBUGF(infof(data, "schannel: encrypted cached: offset %zu length %zu\n", BACKEND->encdata_offset, BACKEND->encdata_length)); } else { /* reset encrypted buffer offset, because there is no data remaining */ BACKEND->encdata_offset = 0; } /* check if server wants to renegotiate the connection context */ if(sspi_status == SEC_I_RENEGOTIATE) { infof(data, "schannel: remote party requests renegotiation\n"); if(*err && *err != CURLE_AGAIN) { infof(data, "schannel: can't renogotiate, an error is pending\n"); goto cleanup; } if(BACKEND->encdata_offset) { *err = CURLE_RECV_ERROR; infof(data, "schannel: can't renogotiate, " "encrypted data available\n"); goto cleanup; } /* begin renegotiation */ infof(data, "schannel: renegotiating SSL/TLS connection\n"); connssl->state = ssl_connection_negotiating; connssl->connecting_state = ssl_connect_2_writing; *err = schannel_connect_common(conn, sockindex, FALSE, &done); if(*err) { infof(data, "schannel: renegotiation failed\n"); goto cleanup; } /* now retry receiving data */ sspi_status = SEC_E_OK; infof(data, "schannel: SSL/TLS connection renegotiated\n"); continue; } /* check if the server closed the connection */ else if(sspi_status == SEC_I_CONTEXT_EXPIRED) { /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not returned so we have to work around that in cleanup. */ BACKEND->recv_sspi_close_notify = true; if(!BACKEND->recv_connection_closed) { BACKEND->recv_connection_closed = true; infof(data, "schannel: server closed the connection\n"); } goto cleanup; } } else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) { BACKEND->encdata_is_incomplete = true; if(!*err) *err = CURLE_AGAIN; infof(data, "schannel: failed to decrypt data, need more data\n"); goto cleanup; } else { char buffer[STRERROR_LEN]; *err = CURLE_RECV_ERROR; infof(data, "schannel: failed to read data from server: %s\n", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); goto cleanup; } } DEBUGF(infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n", BACKEND->encdata_offset, BACKEND->encdata_length)); DEBUGF(infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n", BACKEND->decdata_offset, BACKEND->decdata_length)); cleanup: /* Warning- there is no guarantee the encdata state is valid at this point */ DEBUGF(infof(data, "schannel: schannel_recv cleanup\n")); /* Error if the connection has closed without a close_notify. Behavior here is a matter of debate. We don't want to be vulnerable to a truncation attack however there's some browser precedent for ignoring the close_notify for compatibility reasons. Additionally, Windows 2000 (v5.0) is a special case since it seems it doesn't return close_notify. In that case if the connection was closed we assume it was graceful (close_notify) since there doesn't seem to be a way to tell. */ if(len && !BACKEND->decdata_offset && BACKEND->recv_connection_closed && !BACKEND->recv_sspi_close_notify) { bool isWin2k = Curl_verify_windows_version(5, 0, PLATFORM_WINNT, VERSION_EQUAL); if(isWin2k && sspi_status == SEC_E_OK) BACKEND->recv_sspi_close_notify = true; else { *err = CURLE_RECV_ERROR; infof(data, "schannel: server closed abruptly (missing close_notify)\n"); } } /* Any error other than CURLE_AGAIN is an unrecoverable error. */ if(*err && *err != CURLE_AGAIN) BACKEND->recv_unrecoverable_err = *err; size = len < BACKEND->decdata_offset ? len : BACKEND->decdata_offset; if(size) { memcpy(buf, BACKEND->decdata_buffer, size); memmove(BACKEND->decdata_buffer, BACKEND->decdata_buffer + size, BACKEND->decdata_offset - size); BACKEND->decdata_offset -= size; DEBUGF(infof(data, "schannel: decrypted data returned %zu\n", size)); DEBUGF(infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n", BACKEND->decdata_offset, BACKEND->decdata_length)); *err = CURLE_OK; return (ssize_t)size; } if(!*err && !BACKEND->recv_connection_closed) *err = CURLE_AGAIN; /* It's debatable what to return when !len. We could return whatever error we got from decryption but instead we override here so the return is consistent. */ if(!len) *err = CURLE_OK; return *err ? -1 : 0; } static CURLcode Curl_schannel_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return schannel_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_schannel_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = schannel_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex) { const struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->use) /* SSL/TLS is in use */ return (BACKEND->decdata_offset > 0 || (BACKEND->encdata_offset > 0 && !BACKEND->encdata_is_incomplete)); else return FALSE; } static void Curl_schannel_close(struct connectdata *conn, int sockindex) { if(conn->ssl[sockindex].use) /* if the SSL/TLS channel hasn't been shut down yet, do that now. */ Curl_ssl_shutdown(conn, sockindex); } static void Curl_schannel_session_free(void *ptr) { /* this is expected to be called under sessionid lock */ struct curl_schannel_cred *cred = ptr; cred->refcount--; if(cred->refcount == 0) { s_pSecFn->FreeCredentialsHandle(&cred->cred_handle); Curl_safefree(cred); } } static int Curl_schannel_shutdown(struct connectdata *conn, int sockindex) { /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx * Shutting Down an Schannel Connection */ struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; DEBUGASSERT(data); infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n", hostname, conn->remote_port); if(BACKEND->cred && BACKEND->ctxt) { SecBufferDesc BuffDesc; SecBuffer Buffer; SECURITY_STATUS sspi_status; SecBuffer outbuf; SecBufferDesc outbuf_desc; CURLcode result; TCHAR *host_name; DWORD dwshut = SCHANNEL_SHUTDOWN; InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut)); InitSecBufferDesc(&BuffDesc, &Buffer, 1); sspi_status = s_pSecFn->ApplyControlToken(&BACKEND->ctxt->ctxt_handle, &BuffDesc); if(sspi_status != SEC_E_OK) { char buffer[STRERROR_LEN]; failf(data, "schannel: ApplyControlToken failure: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); } host_name = Curl_convert_UTF8_to_tchar(hostname); if(!host_name) return CURLE_OUT_OF_MEMORY; /* setup output buffer */ InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0); InitSecBufferDesc(&outbuf_desc, &outbuf, 1); sspi_status = s_pSecFn->InitializeSecurityContext( &BACKEND->cred->cred_handle, &BACKEND->ctxt->ctxt_handle, host_name, BACKEND->req_flags, 0, 0, NULL, 0, &BACKEND->ctxt->ctxt_handle, &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp); Curl_unicodefree(host_name); if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) { /* send close message which is in output buffer */ ssize_t written; result = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer, outbuf.cbBuffer, &written); s_pSecFn->FreeContextBuffer(outbuf.pvBuffer); if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) { infof(data, "schannel: failed to send close msg: %s" " (bytes written: %zd)\n", curl_easy_strerror(result), written); } } } /* free SSPI Schannel API security context handle */ if(BACKEND->ctxt) { DEBUGF(infof(data, "schannel: clear security context handle\n")); s_pSecFn->DeleteSecurityContext(&BACKEND->ctxt->ctxt_handle); Curl_safefree(BACKEND->ctxt); } /* free SSPI Schannel API credential handle */ if(BACKEND->cred) { /* * When this function is called from Curl_schannel_close() the connection * might not have an associated transfer so the check for conn->data is * necessary. */ Curl_ssl_sessionid_lock(conn); Curl_schannel_session_free(BACKEND->cred); Curl_ssl_sessionid_unlock(conn); BACKEND->cred = NULL; } /* free internal buffer for received encrypted data */ if(BACKEND->encdata_buffer != NULL) { Curl_safefree(BACKEND->encdata_buffer); BACKEND->encdata_length = 0; BACKEND->encdata_offset = 0; BACKEND->encdata_is_incomplete = false; } /* free internal buffer for received decrypted data */ if(BACKEND->decdata_buffer != NULL) { Curl_safefree(BACKEND->decdata_buffer); BACKEND->decdata_length = 0; BACKEND->decdata_offset = 0; } return CURLE_OK; } static int Curl_schannel_init(void) { return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0); } static void Curl_schannel_cleanup(void) { Curl_sspi_global_cleanup(); } static size_t Curl_schannel_version(char *buffer, size_t size) { size = msnprintf(buffer, size, "Schannel"); return size; } static CURLcode Curl_schannel_random(struct Curl_easy *data UNUSED_PARAM, unsigned char *entropy, size_t length) { HCRYPTPROV hCryptProv = 0; (void)data; if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) return CURLE_FAILED_INIT; if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) { CryptReleaseContext(hCryptProv, 0UL); return CURLE_FAILED_INIT; } CryptReleaseContext(hCryptProv, 0UL); return CURLE_OK; } static CURLcode pkp_pin_peer_pubkey(struct connectdata *conn, int sockindex, const char *pinnedpubkey) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CERT_CONTEXT *pCertContextServer = NULL; /* Result is returned to caller */ CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; /* if a path wasn't specified, don't pin */ if(!pinnedpubkey) return CURLE_OK; do { SECURITY_STATUS sspi_status; const char *x509_der; DWORD x509_der_len; curl_X509certificate x509_parsed; curl_asn1Element *pubkey; sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &pCertContextServer); if((sspi_status != SEC_E_OK) || (pCertContextServer == NULL)) { char buffer[STRERROR_LEN]; failf(data, "schannel: Failed to read remote certificate context: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); break; /* failed */ } if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) && (pCertContextServer->cbCertEncoded > 0))) break; x509_der = (const char *)pCertContextServer->pbCertEncoded; x509_der_len = pCertContextServer->cbCertEncoded; memset(&x509_parsed, 0, sizeof(x509_parsed)); if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len)) break; pubkey = &x509_parsed.subjectPublicKeyInfo; if(!pubkey->header || pubkey->end <= pubkey->header) { failf(data, "SSL: failed retrieving public key from server certificate"); break; } result = Curl_pin_peer_pubkey(data, pinnedpubkey, (const unsigned char *)pubkey->header, (size_t)(pubkey->end - pubkey->header)); if(result) { failf(data, "SSL: public key does not match pinned public key!"); } } while(0); if(pCertContextServer) CertFreeCertificateContext(pCertContextServer); return result; } static void Curl_schannel_checksum(const unsigned char *input, size_t inputlen, unsigned char *checksum, size_t checksumlen, DWORD provType, const unsigned int algId) { HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; DWORD cbHashSize = 0; DWORD dwHashSizeLen = (DWORD)sizeof(cbHashSize); DWORD dwChecksumLen = (DWORD)checksumlen; /* since this can fail in multiple ways, zero memory first so we never * return old data */ memset(checksum, 0, checksumlen); if(!CryptAcquireContext(&hProv, NULL, NULL, provType, CRYPT_VERIFYCONTEXT)) return; /* failed */ do { if(!CryptCreateHash(hProv, algId, 0, 0, &hHash)) break; /* failed */ /* workaround for original MinGW, should be (const BYTE*) */ if(!CryptHashData(hHash, (BYTE*)input, (DWORD)inputlen, 0)) break; /* failed */ /* get hash size */ if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize, &dwHashSizeLen, 0)) break; /* failed */ /* check hash size */ if(checksumlen < cbHashSize) break; /* failed */ if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0)) break; /* failed */ } while(0); if(hHash) CryptDestroyHash(hHash); if(hProv) CryptReleaseContext(hProv, 0); } static CURLcode Curl_schannel_md5sum(unsigned char *input, size_t inputlen, unsigned char *md5sum, size_t md5len) { Curl_schannel_checksum(input, inputlen, md5sum, md5len, PROV_RSA_FULL, CALG_MD5); return CURLE_OK; } static CURLcode Curl_schannel_sha256sum(const unsigned char *input, size_t inputlen, unsigned char *sha256sum, size_t sha256len) { Curl_schannel_checksum(input, inputlen, sha256sum, sha256len, PROV_RSA_AES, CALG_SHA_256); return CURLE_OK; } static void *Curl_schannel_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return &BACKEND->ctxt->ctxt_handle; } const struct Curl_ssl Curl_ssl_schannel = { { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */ SSLSUPP_CERTINFO | SSLSUPP_PINNEDPUBKEY, sizeof(struct ssl_backend_data), Curl_schannel_init, /* init */ Curl_schannel_cleanup, /* cleanup */ Curl_schannel_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_schannel_shutdown, /* shutdown */ Curl_schannel_data_pending, /* data_pending */ Curl_schannel_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_schannel_connect, /* connect */ Curl_schannel_connect_nonblocking, /* connect_nonblocking */ Curl_schannel_get_internals, /* get_internals */ Curl_schannel_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_schannel_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_schannel_md5sum, /* md5sum */ Curl_schannel_sha256sum /* sha256sum */ }; #endif /* USE_SCHANNEL */
YifuLiu/AliOS-Things
components/curl/lib/vtls/schannel.c
C
apache-2.0
77,840
#ifndef HEADER_CURL_SCHANNEL_H #define HEADER_CURL_SCHANNEL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012, Marc Hoersken, <info@marc-hoersken.de>, et al. * Copyright (C) 2012 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_SCHANNEL #include <schnlsp.h> #include <schannel.h> #include "curl_sspi.h" #include "urldata.h" /* <wincrypt.h> has been included via the above <schnlsp.h>. * Or in case of ldap.c, it was included via <winldap.h>. * And since <wincrypt.h> has this: * #define X509_NAME ((LPCSTR) 7) * * And in BoringSSL's <openssl/base.h> there is: * typedef struct X509_name_st X509_NAME; * etc. * * this will cause all kinds of C-preprocessing paste errors in * BoringSSL's <openssl/x509.h>: So just undefine those defines here * (and only here). */ #if defined(HAVE_BORINGSSL) || defined(OPENSSL_IS_BORINGSSL) # undef X509_NAME # undef X509_CERT_PAIR # undef X509_EXTENSIONS #endif extern const struct Curl_ssl Curl_ssl_schannel; CURLcode Curl_verify_certificate(struct connectdata *conn, int sockindex); /* structs to expose only in schannel.c and schannel_verify.c */ #ifdef EXPOSE_SCHANNEL_INTERNAL_STRUCTS #ifdef __MINGW32__ #include <_mingw.h> #ifdef __MINGW64_VERSION_MAJOR #define HAS_MANUAL_VERIFY_API #endif #else #include <wincrypt.h> #ifdef CERT_CHAIN_REVOCATION_CHECK_CHAIN #define HAS_MANUAL_VERIFY_API #endif #endif struct curl_schannel_cred { CredHandle cred_handle; TimeStamp time_stamp; int refcount; }; struct curl_schannel_ctxt { CtxtHandle ctxt_handle; TimeStamp time_stamp; }; struct ssl_backend_data { struct curl_schannel_cred *cred; struct curl_schannel_ctxt *ctxt; SecPkgContext_StreamSizes stream_sizes; size_t encdata_length, decdata_length; size_t encdata_offset, decdata_offset; unsigned char *encdata_buffer, *decdata_buffer; /* encdata_is_incomplete: if encdata contains only a partial record that can't be decrypted without another Curl_read_plain (that is, status is SEC_E_INCOMPLETE_MESSAGE) then set this true. after Curl_read_plain writes more bytes into encdata then set this back to false. */ bool encdata_is_incomplete; unsigned long req_flags, ret_flags; CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */ bool recv_sspi_close_notify; /* true if connection closed by close_notify */ bool recv_connection_closed; /* true if connection closed, regardless how */ bool use_alpn; /* true if ALPN is used for this connection */ #ifdef HAS_MANUAL_VERIFY_API bool use_manual_cred_validation; /* true if manual cred validation is used */ #endif }; #endif /* EXPOSE_SCHANNEL_INTERNAL_STRUCTS */ #endif /* USE_SCHANNEL */ #endif /* HEADER_CURL_SCHANNEL_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/schannel.h
C
apache-2.0
3,675
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2016, Marc Hoersken, <info@marc-hoersken.de> * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com> * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for Schannel-specific certificate verification. This code should * only be invoked by code in schannel.c. */ #include "curl_setup.h" #ifdef USE_SCHANNEL #ifndef USE_WINDOWS_SSPI # error "Can't compile SCHANNEL support without SSPI." #endif #define EXPOSE_SCHANNEL_INTERNAL_STRUCTS #include "schannel.h" #ifdef HAS_MANUAL_VERIFY_API #include "vtls.h" #include "sendf.h" #include "strerror.h" #include "curl_multibyte.h" #include "curl_printf.h" #include "hostcheck.h" #include "system_win32.h" /* The last #include file should be: */ #include "curl_memory.h" #include "memdebug.h" #define BACKEND connssl->backend #define MAX_CAFILE_SIZE 1048576 /* 1 MiB */ #define BEGIN_CERT "-----BEGIN CERTIFICATE-----" #define END_CERT "\n-----END CERTIFICATE-----" typedef struct { DWORD cbSize; HCERTSTORE hRestrictedRoot; HCERTSTORE hRestrictedTrust; HCERTSTORE hRestrictedOther; DWORD cAdditionalStore; HCERTSTORE *rghAdditionalStore; DWORD dwFlags; DWORD dwUrlRetrievalTimeout; DWORD MaximumCachedCertificates; DWORD CycleDetectionModulus; HCERTSTORE hExclusiveRoot; HCERTSTORE hExclusiveTrustedPeople; } CERT_CHAIN_ENGINE_CONFIG_WIN7, *PCERT_CHAIN_ENGINE_CONFIG_WIN7; static int is_cr_or_lf(char c) { return c == '\r' || c == '\n'; } static CURLcode add_certs_to_store(HCERTSTORE trust_store, const char *ca_file, struct connectdata *conn) { CURLcode result; struct Curl_easy *data = conn->data; HANDLE ca_file_handle = INVALID_HANDLE_VALUE; LARGE_INTEGER file_size; char *ca_file_buffer = NULL; char *current_ca_file_ptr = NULL; TCHAR *ca_file_tstr = NULL; size_t ca_file_bufsize = 0; DWORD total_bytes_read = 0; bool more_certs = 0; int num_certs = 0; size_t END_CERT_LEN; ca_file_tstr = Curl_convert_UTF8_to_tchar((char *)ca_file); if(!ca_file_tstr) { char buffer[STRERROR_LEN]; failf(data, "schannel: invalid path name for CA file '%s': %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; goto cleanup; } /* * Read the CA file completely into memory before parsing it. This * optimizes for the common case where the CA file will be relatively * small ( < 1 MiB ). */ ca_file_handle = CreateFile(ca_file_tstr, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(ca_file_handle == INVALID_HANDLE_VALUE) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to open CA file '%s': %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; goto cleanup; } if(!GetFileSizeEx(ca_file_handle, &file_size)) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to determine size of CA file '%s': %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; goto cleanup; } if(file_size.QuadPart > MAX_CAFILE_SIZE) { failf(data, "schannel: CA file exceeds max size of %u bytes", MAX_CAFILE_SIZE); result = CURLE_SSL_CACERT_BADFILE; goto cleanup; } ca_file_bufsize = (size_t)file_size.QuadPart; ca_file_buffer = (char *)malloc(ca_file_bufsize + 1); if(!ca_file_buffer) { result = CURLE_OUT_OF_MEMORY; goto cleanup; } result = CURLE_OK; while(total_bytes_read < ca_file_bufsize) { DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read); DWORD bytes_read = 0; if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read, bytes_to_read, &bytes_read, NULL)) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to read from CA file '%s': %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; goto cleanup; } if(bytes_read == 0) { /* Premature EOF -- adjust the bufsize to the new value */ ca_file_bufsize = total_bytes_read; } else { total_bytes_read += bytes_read; } } /* Null terminate the buffer */ ca_file_buffer[ca_file_bufsize] = '\0'; if(result != CURLE_OK) { goto cleanup; } END_CERT_LEN = strlen(END_CERT); more_certs = 1; current_ca_file_ptr = ca_file_buffer; while(more_certs && *current_ca_file_ptr != '\0') { char *begin_cert_ptr = strstr(current_ca_file_ptr, BEGIN_CERT); if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[strlen(BEGIN_CERT)])) { more_certs = 0; } else { char *end_cert_ptr = strstr(begin_cert_ptr, END_CERT); if(!end_cert_ptr) { failf(data, "schannel: CA file '%s' is not correctly formatted", ca_file); result = CURLE_SSL_CACERT_BADFILE; more_certs = 0; } else { CERT_BLOB cert_blob; CERT_CONTEXT *cert_context = NULL; BOOL add_cert_result = FALSE; DWORD actual_content_type = 0; DWORD cert_size = (DWORD) ((end_cert_ptr + END_CERT_LEN) - begin_cert_ptr); cert_blob.pbData = (BYTE *)begin_cert_ptr; cert_blob.cbData = cert_size; if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &cert_blob, CERT_QUERY_CONTENT_FLAG_CERT, CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL, &actual_content_type, NULL, NULL, NULL, (const void **)&cert_context)) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to extract certificate from CA file " "'%s': %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; more_certs = 0; } else { current_ca_file_ptr = begin_cert_ptr + cert_size; /* Sanity check that the cert_context object is the right type */ if(CERT_QUERY_CONTENT_CERT != actual_content_type) { failf(data, "schannel: unexpected content type '%d' when extracting " "certificate from CA file '%s'", actual_content_type, ca_file); result = CURLE_SSL_CACERT_BADFILE; more_certs = 0; } else { add_cert_result = CertAddCertificateContextToStore(trust_store, cert_context, CERT_STORE_ADD_ALWAYS, NULL); CertFreeCertificateContext(cert_context); if(!add_cert_result) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to add certificate from CA file '%s' " "to certificate store: %s", ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; more_certs = 0; } else { num_certs++; } } } } } } if(result == CURLE_OK) { if(!num_certs) { infof(data, "schannel: did not add any certificates from CA file '%s'\n", ca_file); } else { infof(data, "schannel: added %d certificate(s) from CA file '%s'\n", num_certs, ca_file); } } cleanup: if(ca_file_handle != INVALID_HANDLE_VALUE) { CloseHandle(ca_file_handle); } Curl_safefree(ca_file_buffer); Curl_unicodefree(ca_file_tstr); return result; } static CURLcode verify_host(struct Curl_easy *data, CERT_CONTEXT *pCertContextServer, const char * const conn_hostname) { CURLcode result = CURLE_PEER_FAILED_VERIFICATION; TCHAR *cert_hostname_buff = NULL; size_t cert_hostname_buff_index = 0; DWORD len = 0; DWORD actual_len = 0; /* CertGetNameString will provide the 8-bit character string without * any decoding */ DWORD name_flags = CERT_NAME_DISABLE_IE4_UTF8_FLAG; #ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG name_flags |= CERT_NAME_SEARCH_ALL_NAMES_FLAG; #endif /* Determine the size of the string needed for the cert hostname */ len = CertGetNameString(pCertContextServer, CERT_NAME_DNS_TYPE, name_flags, NULL, NULL, 0); if(len == 0) { failf(data, "schannel: CertGetNameString() returned no " "certificate name information"); result = CURLE_PEER_FAILED_VERIFICATION; goto cleanup; } /* CertGetNameString guarantees that the returned name will not contain * embedded null bytes. This appears to be undocumented behavior. */ cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR)); if(!cert_hostname_buff) { result = CURLE_OUT_OF_MEMORY; goto cleanup; } actual_len = CertGetNameString(pCertContextServer, CERT_NAME_DNS_TYPE, name_flags, NULL, (LPTSTR) cert_hostname_buff, len); /* Sanity check */ if(actual_len != len) { failf(data, "schannel: CertGetNameString() returned certificate " "name information of unexpected size"); result = CURLE_PEER_FAILED_VERIFICATION; goto cleanup; } /* If HAVE_CERT_NAME_SEARCH_ALL_NAMES is available, the output * will contain all DNS names, where each name is null-terminated * and the last DNS name is double null-terminated. Due to this * encoding, use the length of the buffer to iterate over all names. */ result = CURLE_PEER_FAILED_VERIFICATION; while(cert_hostname_buff_index < len && cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') && result == CURLE_PEER_FAILED_VERIFICATION) { char *cert_hostname; /* Comparing the cert name and the connection hostname encoded as UTF-8 * is acceptable since both values are assumed to use ASCII * (or some equivalent) encoding */ cert_hostname = Curl_convert_tchar_to_UTF8( &cert_hostname_buff[cert_hostname_buff_index]); if(!cert_hostname) { result = CURLE_OUT_OF_MEMORY; } else { int match_result; match_result = Curl_cert_hostcheck(cert_hostname, conn_hostname); if(match_result == CURL_HOST_MATCH) { infof(data, "schannel: connection hostname (%s) validated " "against certificate name (%s)\n", conn_hostname, cert_hostname); result = CURLE_OK; } else { size_t cert_hostname_len; infof(data, "schannel: connection hostname (%s) did not match " "against certificate name (%s)\n", conn_hostname, cert_hostname); cert_hostname_len = _tcslen( &cert_hostname_buff[cert_hostname_buff_index]); /* Move on to next cert name */ cert_hostname_buff_index += cert_hostname_len + 1; result = CURLE_PEER_FAILED_VERIFICATION; } Curl_unicodefree(cert_hostname); } } if(result == CURLE_PEER_FAILED_VERIFICATION) { failf(data, "schannel: CertGetNameString() failed to match " "connection hostname (%s) against server certificate names", conn_hostname); } else if(result != CURLE_OK) failf(data, "schannel: server certificate name verification failed"); cleanup: Curl_unicodefree(cert_hostname_buff); return result; } CURLcode Curl_verify_certificate(struct connectdata *conn, int sockindex) { SECURITY_STATUS sspi_status; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CURLcode result = CURLE_OK; CERT_CONTEXT *pCertContextServer = NULL; const CERT_CHAIN_CONTEXT *pChainContext = NULL; HCERTCHAINENGINE cert_chain_engine = NULL; HCERTSTORE trust_store = NULL; const char * const conn_hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &pCertContextServer); if((sspi_status != SEC_E_OK) || (pCertContextServer == NULL)) { char buffer[STRERROR_LEN]; failf(data, "schannel: Failed to read remote certificate context: %s", Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer))); result = CURLE_PEER_FAILED_VERIFICATION; } if(result == CURLE_OK && SSL_CONN_CONFIG(CAfile) && BACKEND->use_manual_cred_validation) { /* * Create a chain engine that uses the certificates in the CA file as * trusted certificates. This is only supported on Windows 7+. */ if(Curl_verify_windows_version(6, 1, PLATFORM_WINNT, VERSION_LESS_THAN)) { failf(data, "schannel: this version of Windows is too old to support " "certificate verification via CA bundle file."); result = CURLE_SSL_CACERT_BADFILE; } else { /* Open the certificate store */ trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, (HCRYPTPROV)NULL, CERT_STORE_CREATE_NEW_FLAG, NULL); if(!trust_store) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to create certificate store: %s", Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; } else { result = add_certs_to_store(trust_store, SSL_CONN_CONFIG(CAfile), conn); } } if(result == CURLE_OK) { CERT_CHAIN_ENGINE_CONFIG_WIN7 engine_config; BOOL create_engine_result; memset(&engine_config, 0, sizeof(engine_config)); engine_config.cbSize = sizeof(engine_config); engine_config.hExclusiveRoot = trust_store; /* CertCreateCertificateChainEngine will check the expected size of the * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size * does not match the expected size. When this occurs, it indicates that * CAINFO is not supported on the version of Windows in use. */ create_engine_result = CertCreateCertificateChainEngine( (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine); if(!create_engine_result) { char buffer[STRERROR_LEN]; failf(data, "schannel: failed to create certificate chain engine: %s", Curl_strerror(GetLastError(), buffer, sizeof(buffer))); result = CURLE_SSL_CACERT_BADFILE; } } } if(result == CURLE_OK) { CERT_CHAIN_PARA ChainPara; memset(&ChainPara, 0, sizeof(ChainPara)); ChainPara.cbSize = sizeof(ChainPara); if(!CertGetCertificateChain(cert_chain_engine, pCertContextServer, NULL, pCertContextServer->hCertStore, &ChainPara, (data->set.ssl.no_revoke ? 0 : CERT_CHAIN_REVOCATION_CHECK_CHAIN), NULL, &pChainContext)) { char buffer[STRERROR_LEN]; failf(data, "schannel: CertGetCertificateChain failed: %s", Curl_strerror(GetLastError(), buffer, sizeof(buffer))); pChainContext = NULL; result = CURLE_PEER_FAILED_VERIFICATION; } if(result == CURLE_OK) { CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0]; DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED); dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus; if(dwTrustErrorMask) { if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_REVOKED"); else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_PARTIAL_CHAIN"); else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_UNTRUSTED_ROOT"); else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_IS_NOT_TIME_VALID"); else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN) failf(data, "schannel: CertGetCertificateChain trust error" " CERT_TRUST_REVOCATION_STATUS_UNKNOWN"); else failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x", dwTrustErrorMask); result = CURLE_PEER_FAILED_VERIFICATION; } } } if(result == CURLE_OK) { if(SSL_CONN_CONFIG(verifyhost)) { result = verify_host(conn->data, pCertContextServer, conn_hostname); } } if(cert_chain_engine) { CertFreeCertificateChainEngine(cert_chain_engine); } if(trust_store) { CertCloseStore(trust_store, 0); } if(pChainContext) CertFreeCertificateChain(pChainContext); if(pCertContextServer) CertFreeCertificateContext(pCertContextServer); return result; } #endif /* HAS_MANUAL_VERIFY_API */ #endif /* USE_SCHANNEL */
YifuLiu/AliOS-Things
components/curl/lib/vtls/schannel_verify.c
C
apache-2.0
19,384
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2017, Nick Zitzmann, <nickzman@gmail.com>. * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all iOS and macOS SecureTransport-specific code for the * TLS/SSL layer. No code but vtls.c should ever call or use these functions. */ #include "curl_setup.h" #include "urldata.h" /* for the Curl_easy definition */ #include "curl_base64.h" #include "strtok.h" #include "multiif.h" #ifdef USE_SECTRANSP #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-pointer-compare" #endif /* __clang__ */ #include <limits.h> #include <Security/Security.h> /* For some reason, when building for iOS, the omnibus header above does * not include SecureTransport.h as of iOS SDK 5.1. */ #include <Security/SecureTransport.h> #include <CoreFoundation/CoreFoundation.h> #include <CommonCrypto/CommonDigest.h> /* The Security framework has changed greatly between iOS and different macOS versions, and we will try to support as many of them as we can (back to Leopard and iOS 5) by using macros and weak-linking. In general, you want to build this using the most recent OS SDK, since some features require curl to be built against the latest SDK. TLS 1.1 and 1.2 support, for instance, require the macOS 10.8 SDK or later. TLS 1.3 requires the macOS 10.13 or iOS 11 SDK or later. */ #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) #if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 #error "The Secure Transport back-end requires Leopard or later." #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */ #define CURL_BUILD_IOS 0 #define CURL_BUILD_IOS_7 0 #define CURL_BUILD_IOS_9 0 #define CURL_BUILD_IOS_11 0 #define CURL_BUILD_MAC 1 /* This is the maximum API level we are allowed to use when building: */ #define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 #define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 #define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 #define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 #define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 #define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 #define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 /* These macros mean "the following code is present to allow runtime backward compatibility with at least this cat or earlier": (You set this at build-time using the compiler command line option "-mmacos-version-min.") */ #define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 #define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060 #define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070 #define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 #define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090 #elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE #define CURL_BUILD_IOS 1 #define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 #define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000 #define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 #define CURL_BUILD_MAC 0 #define CURL_BUILD_MAC_10_5 0 #define CURL_BUILD_MAC_10_6 0 #define CURL_BUILD_MAC_10_7 0 #define CURL_BUILD_MAC_10_8 0 #define CURL_BUILD_MAC_10_9 0 #define CURL_BUILD_MAC_10_11 0 #define CURL_BUILD_MAC_10_13 0 #define CURL_SUPPORT_MAC_10_5 0 #define CURL_SUPPORT_MAC_10_6 0 #define CURL_SUPPORT_MAC_10_7 0 #define CURL_SUPPORT_MAC_10_8 0 #define CURL_SUPPORT_MAC_10_9 0 #else #error "The Secure Transport back-end requires iOS or macOS." #endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */ #if CURL_BUILD_MAC #include <sys/sysctl.h> #endif /* CURL_BUILD_MAC */ #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "connect.h" #include "select.h" #include "vtls.h" #include "sectransp.h" #include "curl_printf.h" #include "strdup.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* From MacTypes.h (which we can't include because it isn't present in iOS: */ #define ioErr -36 #define paramErr -50 struct ssl_backend_data { SSLContextRef ssl_ctx; curl_socket_t ssl_sockfd; bool ssl_direction; /* true if writing, false if reading */ size_t ssl_write_buffered_length; }; #define BACKEND connssl->backend /* pinned public key support tests */ /* version 1 supports macOS 10.12+ and iOS 10+ */ #if ((TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || \ (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)) #define SECTRANSP_PINNEDPUBKEY_V1 1 #endif /* version 2 supports MacOSX 10.7+ */ #if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070) #define SECTRANSP_PINNEDPUBKEY_V2 1 #endif #if defined(SECTRANSP_PINNEDPUBKEY_V1) || defined(SECTRANSP_PINNEDPUBKEY_V2) /* this backend supports CURLOPT_PINNEDPUBLICKEY */ #define SECTRANSP_PINNEDPUBKEY 1 #endif /* SECTRANSP_PINNEDPUBKEY */ #ifdef SECTRANSP_PINNEDPUBKEY /* both new and old APIs return rsa keys missing the spki header (not DER) */ static const unsigned char rsa4096SpkiHeader[] = { 0x30, 0x82, 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00}; static const unsigned char rsa2048SpkiHeader[] = { 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00}; #ifdef SECTRANSP_PINNEDPUBKEY_V1 /* the *new* version doesn't return DER encoded ecdsa certs like the old... */ static const unsigned char ecDsaSecp256r1SpkiHeader[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00}; static const unsigned char ecDsaSecp384r1SpkiHeader[] = { 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x62, 0x00}; #endif /* SECTRANSP_PINNEDPUBKEY_V1 */ #endif /* SECTRANSP_PINNEDPUBKEY */ /* The following two functions were ripped from Apple sample code, * with some modifications: */ static OSStatus SocketRead(SSLConnectionRef connection, void *data, /* owned by * caller, data * RETURNED */ size_t *dataLength) /* IN/OUT */ { size_t bytesToGo = *dataLength; size_t initLen = bytesToGo; UInt8 *currData = (UInt8 *)data; /*int sock = *(int *)connection;*/ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection; int sock = BACKEND->ssl_sockfd; OSStatus rtn = noErr; size_t bytesRead; ssize_t rrtn; int theErr; *dataLength = 0; for(;;) { bytesRead = 0; rrtn = read(sock, currData, bytesToGo); if(rrtn <= 0) { /* this is guesswork... */ theErr = errno; if(rrtn == 0) { /* EOF = server hung up */ /* the framework will turn this into errSSLClosedNoNotify */ rtn = errSSLClosedGraceful; } else /* do the switch */ switch(theErr) { case ENOENT: /* connection closed */ rtn = errSSLClosedGraceful; break; case ECONNRESET: rtn = errSSLClosedAbort; break; case EAGAIN: rtn = errSSLWouldBlock; BACKEND->ssl_direction = false; break; default: rtn = ioErr; break; } break; } else { bytesRead = rrtn; } bytesToGo -= bytesRead; currData += bytesRead; if(bytesToGo == 0) { /* filled buffer with incoming data, done */ break; } } *dataLength = initLen - bytesToGo; return rtn; } static OSStatus SocketWrite(SSLConnectionRef connection, const void *data, size_t *dataLength) /* IN/OUT */ { size_t bytesSent = 0; /*int sock = *(int *)connection;*/ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection; int sock = BACKEND->ssl_sockfd; ssize_t length; size_t dataLen = *dataLength; const UInt8 *dataPtr = (UInt8 *)data; OSStatus ortn; int theErr; *dataLength = 0; do { length = write(sock, (char *)dataPtr + bytesSent, dataLen - bytesSent); } while((length > 0) && ( (bytesSent += length) < dataLen) ); if(length <= 0) { theErr = errno; if(theErr == EAGAIN) { ortn = errSSLWouldBlock; BACKEND->ssl_direction = true; } else { ortn = ioErr; } } else { ortn = noErr; } *dataLength = bytesSent; return ortn; } #ifndef CURL_DISABLE_VERBOSE_STRINGS CF_INLINE const char *SSLCipherNameForNumber(SSLCipherSuite cipher) { switch(cipher) { /* SSL version 3.0 */ case SSL_RSA_WITH_NULL_MD5: return "SSL_RSA_WITH_NULL_MD5"; break; case SSL_RSA_WITH_NULL_SHA: return "SSL_RSA_WITH_NULL_SHA"; break; case SSL_RSA_EXPORT_WITH_RC4_40_MD5: return "SSL_RSA_EXPORT_WITH_RC4_40_MD5"; break; case SSL_RSA_WITH_RC4_128_MD5: return "SSL_RSA_WITH_RC4_128_MD5"; break; case SSL_RSA_WITH_RC4_128_SHA: return "SSL_RSA_WITH_RC4_128_SHA"; break; case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5: return "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"; break; case SSL_RSA_WITH_IDEA_CBC_SHA: return "SSL_RSA_WITH_IDEA_CBC_SHA"; break; case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_RSA_WITH_DES_CBC_SHA: return "SSL_RSA_WITH_DES_CBC_SHA"; break; case SSL_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_DSS_WITH_DES_CBC_SHA: return "SSL_DH_DSS_WITH_DES_CBC_SHA"; break; case SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_RSA_WITH_DES_CBC_SHA: return "SSL_DH_RSA_WITH_DES_CBC_SHA"; break; case SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DHE_DSS_WITH_DES_CBC_SHA: return "SSL_DHE_DSS_WITH_DES_CBC_SHA"; break; case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA: return "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DHE_RSA_WITH_DES_CBC_SHA: return "SSL_DHE_RSA_WITH_DES_CBC_SHA"; break; case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5: return "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"; break; case SSL_DH_anon_WITH_RC4_128_MD5: return "SSL_DH_anon_WITH_RC4_128_MD5"; break; case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_anon_WITH_DES_CBC_SHA: return "SSL_DH_anon_WITH_DES_CBC_SHA"; break; case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; case SSL_FORTEZZA_DMS_WITH_NULL_SHA: return "SSL_FORTEZZA_DMS_WITH_NULL_SHA"; break; case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA: return "SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA"; break; /* TLS 1.0 with AES (RFC 3268) (Apparently these are used in SSLv3 implementations as well.) */ case TLS_RSA_WITH_AES_128_CBC_SHA: return "TLS_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA: return "TLS_DH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_RSA_WITH_AES_256_CBC_SHA: return "TLS_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA: return "TLS_DH_anon_WITH_AES_256_CBC_SHA"; break; /* SSL version 2.0 */ case SSL_RSA_WITH_RC2_CBC_MD5: return "SSL_RSA_WITH_RC2_CBC_MD5"; break; case SSL_RSA_WITH_IDEA_CBC_MD5: return "SSL_RSA_WITH_IDEA_CBC_MD5"; break; case SSL_RSA_WITH_DES_CBC_MD5: return "SSL_RSA_WITH_DES_CBC_MD5"; break; case SSL_RSA_WITH_3DES_EDE_CBC_MD5: return "SSL_RSA_WITH_3DES_EDE_CBC_MD5"; break; } return "SSL_NULL_WITH_NULL_NULL"; } CF_INLINE const char *TLSCipherNameForNumber(SSLCipherSuite cipher) { switch(cipher) { /* TLS 1.0 with AES (RFC 3268) */ case TLS_RSA_WITH_AES_128_CBC_SHA: return "TLS_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA: return "TLS_DH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_RSA_WITH_AES_256_CBC_SHA: return "TLS_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA: return "TLS_DH_anon_WITH_AES_256_CBC_SHA"; break; #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* TLS 1.0 with ECDSA (RFC 4492) */ case TLS_ECDH_ECDSA_WITH_NULL_SHA: return "TLS_ECDH_ECDSA_WITH_NULL_SHA"; break; case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: return "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"; break; case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_NULL_SHA: return "TLS_ECDHE_ECDSA_WITH_NULL_SHA"; break; case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: return "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"; break; case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_NULL_SHA: return "TLS_ECDH_RSA_WITH_NULL_SHA"; break; case TLS_ECDH_RSA_WITH_RC4_128_SHA: return "TLS_ECDH_RSA_WITH_RC4_128_SHA"; break; case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_NULL_SHA: return "TLS_ECDHE_RSA_WITH_NULL_SHA"; break; case TLS_ECDHE_RSA_WITH_RC4_128_SHA: return "TLS_ECDHE_RSA_WITH_RC4_128_SHA"; break; case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDH_anon_WITH_NULL_SHA: return "TLS_ECDH_anon_WITH_NULL_SHA"; break; case TLS_ECDH_anon_WITH_RC4_128_SHA: return "TLS_ECDH_anon_WITH_RC4_128_SHA"; break; case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_anon_WITH_AES_128_CBC_SHA: return "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_anon_WITH_AES_256_CBC_SHA: return "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"; break; #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS /* TLS 1.2 (RFC 5246) */ case TLS_RSA_WITH_NULL_MD5: return "TLS_RSA_WITH_NULL_MD5"; break; case TLS_RSA_WITH_NULL_SHA: return "TLS_RSA_WITH_NULL_SHA"; break; case TLS_RSA_WITH_RC4_128_MD5: return "TLS_RSA_WITH_RC4_128_MD5"; break; case TLS_RSA_WITH_RC4_128_SHA: return "TLS_RSA_WITH_RC4_128_SHA"; break; case TLS_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_RSA_WITH_NULL_SHA256: return "TLS_RSA_WITH_NULL_SHA256"; break; case TLS_RSA_WITH_AES_128_CBC_SHA256: return "TLS_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_RSA_WITH_AES_256_CBC_SHA256: return "TLS_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: return "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA256: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA256: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA256: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA256: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_anon_WITH_RC4_128_MD5: return "TLS_DH_anon_WITH_RC4_128_MD5"; break; case TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA256: return "TLS_DH_anon_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA256: return "TLS_DH_anon_WITH_AES_256_CBC_SHA256"; break; /* TLS 1.2 with AES GCM (RFC 5288) */ case TLS_RSA_WITH_AES_128_GCM_SHA256: return "TLS_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_RSA_WITH_AES_256_GCM_SHA384: return "TLS_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: return "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: return "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_RSA_WITH_AES_128_GCM_SHA256: return "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_RSA_WITH_AES_256_GCM_SHA384: return "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: return "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"; break; case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: return "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_DSS_WITH_AES_128_GCM_SHA256: return "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_DSS_WITH_AES_256_GCM_SHA384: return "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_anon_WITH_AES_128_GCM_SHA256: return "TLS_DH_anon_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_anon_WITH_AES_256_GCM_SHA384: return "TLS_DH_anon_WITH_AES_256_GCM_SHA384"; break; /* TLS 1.2 with elliptic curve ciphers (RFC 5289) */ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_EMPTY_RENEGOTIATION_INFO_SCSV: return "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"; break; #else case SSL_RSA_WITH_NULL_MD5: return "TLS_RSA_WITH_NULL_MD5"; break; case SSL_RSA_WITH_NULL_SHA: return "TLS_RSA_WITH_NULL_SHA"; break; case SSL_RSA_WITH_RC4_128_MD5: return "TLS_RSA_WITH_RC4_128_MD5"; break; case SSL_RSA_WITH_RC4_128_SHA: return "TLS_RSA_WITH_RC4_128_SHA"; break; case SSL_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_anon_WITH_RC4_128_MD5: return "TLS_DH_anon_WITH_RC4_128_MD5"; break; case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 /* TLS PSK (RFC 4279): */ case TLS_PSK_WITH_RC4_128_SHA: return "TLS_PSK_WITH_RC4_128_SHA"; break; case TLS_PSK_WITH_3DES_EDE_CBC_SHA: return "TLS_PSK_WITH_3DES_EDE_CBC_SHA"; break; case TLS_PSK_WITH_AES_128_CBC_SHA: return "TLS_PSK_WITH_AES_128_CBC_SHA"; break; case TLS_PSK_WITH_AES_256_CBC_SHA: return "TLS_PSK_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_PSK_WITH_RC4_128_SHA: return "TLS_DHE_PSK_WITH_RC4_128_SHA"; break; case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: return "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DHE_PSK_WITH_AES_128_CBC_SHA: return "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_PSK_WITH_AES_256_CBC_SHA: return "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"; break; case TLS_RSA_PSK_WITH_RC4_128_SHA: return "TLS_RSA_PSK_WITH_RC4_128_SHA"; break; case TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: return "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"; break; case TLS_RSA_PSK_WITH_AES_128_CBC_SHA: return "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"; break; case TLS_RSA_PSK_WITH_AES_256_CBC_SHA: return "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"; break; /* More TLS PSK (RFC 4785): */ case TLS_PSK_WITH_NULL_SHA: return "TLS_PSK_WITH_NULL_SHA"; break; case TLS_DHE_PSK_WITH_NULL_SHA: return "TLS_DHE_PSK_WITH_NULL_SHA"; break; case TLS_RSA_PSK_WITH_NULL_SHA: return "TLS_RSA_PSK_WITH_NULL_SHA"; break; /* Even more TLS PSK (RFC 5487): */ case TLS_PSK_WITH_AES_128_GCM_SHA256: return "TLS_PSK_WITH_AES_128_GCM_SHA256"; break; case TLS_PSK_WITH_AES_256_GCM_SHA384: return "TLS_PSK_WITH_AES_256_GCM_SHA384"; break; case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: return "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"; break; case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: return "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"; break; case TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: return "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"; break; case TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: return "TLS_PSK_WITH_AES_256_GCM_SHA384"; break; case TLS_PSK_WITH_AES_128_CBC_SHA256: return "TLS_PSK_WITH_AES_128_CBC_SHA256"; break; case TLS_PSK_WITH_AES_256_CBC_SHA384: return "TLS_PSK_WITH_AES_256_CBC_SHA384"; break; case TLS_PSK_WITH_NULL_SHA256: return "TLS_PSK_WITH_NULL_SHA256"; break; case TLS_PSK_WITH_NULL_SHA384: return "TLS_PSK_WITH_NULL_SHA384"; break; case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: return "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"; break; case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: return "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"; break; case TLS_DHE_PSK_WITH_NULL_SHA256: return "TLS_DHE_PSK_WITH_NULL_SHA256"; break; case TLS_DHE_PSK_WITH_NULL_SHA384: return "TLS_RSA_PSK_WITH_NULL_SHA384"; break; case TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: return "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"; break; case TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: return "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"; break; case TLS_RSA_PSK_WITH_NULL_SHA256: return "TLS_RSA_PSK_WITH_NULL_SHA256"; break; case TLS_RSA_PSK_WITH_NULL_SHA384: return "TLS_RSA_PSK_WITH_NULL_SHA384"; break; #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 /* New ChaCha20+Poly1305 cipher-suites used by TLS 1.3: */ case TLS_AES_128_GCM_SHA256: return "TLS_AES_128_GCM_SHA256"; break; case TLS_AES_256_GCM_SHA384: return "TLS_AES_256_GCM_SHA384"; break; case TLS_CHACHA20_POLY1305_SHA256: return "TLS_CHACHA20_POLY1305_SHA256"; break; case TLS_AES_128_CCM_SHA256: return "TLS_AES_128_CCM_SHA256"; break; case TLS_AES_128_CCM_8_SHA256: return "TLS_AES_128_CCM_8_SHA256"; break; case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: return "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"; break; case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: return "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"; break; #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ } return "TLS_NULL_WITH_NULL_NULL"; } #endif /* !CURL_DISABLE_VERBOSE_STRINGS */ #if CURL_BUILD_MAC CF_INLINE void GetDarwinVersionNumber(int *major, int *minor) { int mib[2]; char *os_version; size_t os_version_len; char *os_version_major, *os_version_minor; char *tok_buf; /* Get the Darwin kernel version from the kernel using sysctl(): */ mib[0] = CTL_KERN; mib[1] = KERN_OSRELEASE; if(sysctl(mib, 2, NULL, &os_version_len, NULL, 0) == -1) return; os_version = malloc(os_version_len*sizeof(char)); if(!os_version) return; if(sysctl(mib, 2, os_version, &os_version_len, NULL, 0) == -1) { free(os_version); return; } /* Parse the version: */ os_version_major = strtok_r(os_version, ".", &tok_buf); os_version_minor = strtok_r(NULL, ".", &tok_buf); *major = atoi(os_version_major); *minor = atoi(os_version_minor); free(os_version); } #endif /* CURL_BUILD_MAC */ /* Apple provides a myriad of ways of getting information about a certificate into a string. Some aren't available under iOS or newer cats. So here's a unified function for getting a string describing the certificate that ought to work in all cats starting with Leopard. */ CF_INLINE CFStringRef getsubject(SecCertificateRef cert) { CFStringRef server_cert_summary = CFSTR("(null)"); #if CURL_BUILD_IOS /* iOS: There's only one way to do this. */ server_cert_summary = SecCertificateCopySubjectSummary(cert); #else #if CURL_BUILD_MAC_10_7 /* Lion & later: Get the long description if we can. */ if(SecCertificateCopyLongDescription != NULL) server_cert_summary = SecCertificateCopyLongDescription(NULL, cert, NULL); else #endif /* CURL_BUILD_MAC_10_7 */ #if CURL_BUILD_MAC_10_6 /* Snow Leopard: Get the certificate summary. */ if(SecCertificateCopySubjectSummary != NULL) server_cert_summary = SecCertificateCopySubjectSummary(cert); else #endif /* CURL_BUILD_MAC_10_6 */ /* Leopard is as far back as we go... */ (void)SecCertificateCopyCommonName(cert, &server_cert_summary); #endif /* CURL_BUILD_IOS */ return server_cert_summary; } static CURLcode CopyCertSubject(struct Curl_easy *data, SecCertificateRef cert, char **certp) { CFStringRef c = getsubject(cert); CURLcode result = CURLE_OK; const char *direct; char *cbuf = NULL; *certp = NULL; if(!c) { failf(data, "SSL: invalid CA certificate subject"); return CURLE_PEER_FAILED_VERIFICATION; } /* If the subject is already available as UTF-8 encoded (ie 'direct') then use that, else convert it. */ direct = CFStringGetCStringPtr(c, kCFStringEncodingUTF8); if(direct) { *certp = strdup(direct); if(!*certp) { failf(data, "SSL: out of memory"); result = CURLE_OUT_OF_MEMORY; } } else { size_t cbuf_size = ((size_t)CFStringGetLength(c) * 4) + 1; cbuf = calloc(cbuf_size, 1); if(cbuf) { if(!CFStringGetCString(c, cbuf, cbuf_size, kCFStringEncodingUTF8)) { failf(data, "SSL: invalid CA certificate subject"); result = CURLE_PEER_FAILED_VERIFICATION; } else /* pass back the buffer */ *certp = cbuf; } else { failf(data, "SSL: couldn't allocate %zu bytes of memory", cbuf_size); result = CURLE_OUT_OF_MEMORY; } } if(result) free(cbuf); CFRelease(c); return result; } #if CURL_SUPPORT_MAC_10_6 /* The SecKeychainSearch API was deprecated in Lion, and using it will raise deprecation warnings, so let's not compile this unless it's necessary: */ static OSStatus CopyIdentityWithLabelOldSchool(char *label, SecIdentityRef *out_c_a_k) { OSStatus status = errSecItemNotFound; SecKeychainAttributeList attr_list; SecKeychainAttribute attr; SecKeychainSearchRef search = NULL; SecCertificateRef cert = NULL; /* Set up the attribute list: */ attr_list.count = 1L; attr_list.attr = &attr; /* Set up our lone search criterion: */ attr.tag = kSecLabelItemAttr; attr.data = label; attr.length = (UInt32)strlen(label); /* Start searching: */ status = SecKeychainSearchCreateFromAttributes(NULL, kSecCertificateItemClass, &attr_list, &search); if(status == noErr) { status = SecKeychainSearchCopyNext(search, (SecKeychainItemRef *)&cert); if(status == noErr && cert) { /* If we found a certificate, does it have a private key? */ status = SecIdentityCreateWithCertificate(NULL, cert, out_c_a_k); CFRelease(cert); } } if(search) CFRelease(search); return status; } #endif /* CURL_SUPPORT_MAC_10_6 */ static OSStatus CopyIdentityWithLabel(char *label, SecIdentityRef *out_cert_and_key) { OSStatus status = errSecItemNotFound; #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS CFArrayRef keys_list; CFIndex keys_list_count; CFIndex i; CFStringRef common_name; /* SecItemCopyMatching() was introduced in iOS and Snow Leopard. kSecClassIdentity was introduced in Lion. If both exist, let's use them to find the certificate. */ if(SecItemCopyMatching != NULL && kSecClassIdentity != NULL) { CFTypeRef keys[5]; CFTypeRef values[5]; CFDictionaryRef query_dict; CFStringRef label_cf = CFStringCreateWithCString(NULL, label, kCFStringEncodingUTF8); /* Set up our search criteria and expected results: */ values[0] = kSecClassIdentity; /* we want a certificate and a key */ keys[0] = kSecClass; values[1] = kCFBooleanTrue; /* we want a reference */ keys[1] = kSecReturnRef; values[2] = kSecMatchLimitAll; /* kSecMatchLimitOne would be better if the * label matching below worked correctly */ keys[2] = kSecMatchLimit; /* identity searches need a SecPolicyRef in order to work */ values[3] = SecPolicyCreateSSL(false, NULL); keys[3] = kSecMatchPolicy; /* match the name of the certificate (doesn't work in macOS 10.12.1) */ values[4] = label_cf; keys[4] = kSecAttrLabel; query_dict = CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 5L, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(values[3]); /* Do we have a match? */ status = SecItemCopyMatching(query_dict, (CFTypeRef *) &keys_list); /* Because kSecAttrLabel matching doesn't work with kSecClassIdentity, * we need to find the correct identity ourselves */ if(status == noErr) { keys_list_count = CFArrayGetCount(keys_list); *out_cert_and_key = NULL; status = 1; for(i = 0; i<keys_list_count; i++) { OSStatus err = noErr; SecCertificateRef cert = NULL; SecIdentityRef identity = (SecIdentityRef) CFArrayGetValueAtIndex(keys_list, i); err = SecIdentityCopyCertificate(identity, &cert); if(err == noErr) { #if CURL_BUILD_IOS common_name = SecCertificateCopySubjectSummary(cert); #elif CURL_BUILD_MAC_10_7 SecCertificateCopyCommonName(cert, &common_name); #endif if(CFStringCompare(common_name, label_cf, 0) == kCFCompareEqualTo) { CFRelease(cert); CFRelease(common_name); CFRetain(identity); *out_cert_and_key = identity; status = noErr; break; } CFRelease(common_name); } CFRelease(cert); } } if(keys_list) CFRelease(keys_list); CFRelease(query_dict); CFRelease(label_cf); } else { #if CURL_SUPPORT_MAC_10_6 /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); #endif /* CURL_SUPPORT_MAC_10_6 */ } #elif CURL_SUPPORT_MAC_10_6 /* For developers building on older cats, we have no choice but to fall back to SecKeychainSearch. */ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ return status; } static OSStatus CopyIdentityFromPKCS12File(const char *cPath, const char *cPassword, SecIdentityRef *out_cert_and_key) { OSStatus status = errSecItemNotFound; CFURLRef pkcs_url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)cPath, strlen(cPath), false); CFStringRef password = cPassword ? CFStringCreateWithCString(NULL, cPassword, kCFStringEncodingUTF8) : NULL; CFDataRef pkcs_data = NULL; /* We can import P12 files on iOS or OS X 10.7 or later: */ /* These constants are documented as having first appeared in 10.6 but they raise linker errors when used on that cat for some reason. */ #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS if(CFURLCreateDataAndPropertiesFromResource(NULL, pkcs_url, &pkcs_data, NULL, NULL, &status)) { CFArrayRef items = NULL; /* On iOS SecPKCS12Import will never add the client certificate to the * Keychain. * * It gives us back a SecIdentityRef that we can use directly. */ #if CURL_BUILD_IOS const void *cKeys[] = {kSecImportExportPassphrase}; const void *cValues[] = {password}; CFDictionaryRef options = CFDictionaryCreate(NULL, cKeys, cValues, password ? 1L : 0L, NULL, NULL); if(options != NULL) { status = SecPKCS12Import(pkcs_data, options, &items); CFRelease(options); } /* On macOS SecPKCS12Import will always add the client certificate to * the Keychain. * * As this doesn't match iOS, and apps may not want to see their client * certificate saved in the the user's keychain, we use SecItemImport * with a NULL keychain to avoid importing it. * * This returns a SecCertificateRef from which we can construct a * SecIdentityRef. */ #elif CURL_BUILD_MAC_10_7 SecItemImportExportKeyParameters keyParams; SecExternalFormat inputFormat = kSecFormatPKCS12; SecExternalItemType inputType = kSecItemTypeCertificate; memset(&keyParams, 0x00, sizeof(keyParams)); keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; keyParams.passphrase = password; status = SecItemImport(pkcs_data, NULL, &inputFormat, &inputType, 0, &keyParams, NULL, &items); #endif /* Extract the SecIdentityRef */ if(status == errSecSuccess && items && CFArrayGetCount(items)) { CFIndex i, count; count = CFArrayGetCount(items); for(i = 0; i < count; i++) { CFTypeRef item = (CFTypeRef) CFArrayGetValueAtIndex(items, i); CFTypeID itemID = CFGetTypeID(item); if(itemID == CFDictionaryGetTypeID()) { CFTypeRef identity = (CFTypeRef) CFDictionaryGetValue( (CFDictionaryRef) item, kSecImportItemIdentity); CFRetain(identity); *out_cert_and_key = (SecIdentityRef) identity; break; } #if CURL_BUILD_MAC_10_7 else if(itemID == SecCertificateGetTypeID()) { status = SecIdentityCreateWithCertificate(NULL, (SecCertificateRef) item, out_cert_and_key); break; } #endif } } if(items) CFRelease(items); CFRelease(pkcs_data); } #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ if(password) CFRelease(password); CFRelease(pkcs_url); return status; } /* This code was borrowed from nss.c, with some modifications: * Determine whether the nickname passed in is a filename that needs to * be loaded as a PEM or a regular NSS nickname. * * returns 1 for a file * returns 0 for not a file */ CF_INLINE bool is_file(const char *filename) { struct_stat st; if(filename == NULL) return false; if(stat(filename, &st) == 0) return S_ISREG(st.st_mode); return false; } #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS static CURLcode sectransp_version_from_curl(SSLProtocol *darwinver, long ssl_version) { switch(ssl_version) { case CURL_SSLVERSION_TLSv1_0: *darwinver = kTLSProtocol1; return CURLE_OK; case CURL_SSLVERSION_TLSv1_1: *darwinver = kTLSProtocol11; return CURLE_OK; case CURL_SSLVERSION_TLSv1_2: *darwinver = kTLSProtocol12; return CURLE_OK; case CURL_SSLVERSION_TLSv1_3: /* TLS 1.3 support first appeared in iOS 11 and macOS 10.13 */ #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 if(__builtin_available(macOS 10.13, iOS 11.0, *)) { *darwinver = kTLSProtocol13; return CURLE_OK; } #endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 */ break; } return CURLE_SSL_CONNECT_ERROR; } #endif static CURLcode set_ssl_version_min_max(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long ssl_version = SSL_CONN_CONFIG(version); long ssl_version_max = SSL_CONN_CONFIG(version_max); long max_supported_version_by_os; /* macOS 10.5-10.7 supported TLS 1.0 only. macOS 10.8 and later, and iOS 5 and later, added TLS 1.1 and 1.2. macOS 10.13 and later, and iOS 11 and later, added TLS 1.3. */ #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 if(__builtin_available(macOS 10.13, iOS 11.0, *)) { max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_3; } else { max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2; } #else max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2; #endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 */ switch(ssl_version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: ssl_version = CURL_SSLVERSION_TLSv1_0; break; } switch(ssl_version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: ssl_version_max = max_supported_version_by_os; break; } #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLSetProtocolVersionMax != NULL) { SSLProtocol darwin_ver_min = kTLSProtocol1; SSLProtocol darwin_ver_max = kTLSProtocol1; CURLcode result = sectransp_version_from_curl(&darwin_ver_min, ssl_version); if(result) { failf(data, "unsupported min version passed via CURLOPT_SSLVERSION"); return result; } result = sectransp_version_from_curl(&darwin_ver_max, ssl_version_max >> 16); if(result) { failf(data, "unsupported max version passed via CURLOPT_SSLVERSION"); return result; } (void)SSLSetProtocolVersionMin(BACKEND->ssl_ctx, darwin_ver_min); (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, darwin_ver_max); return result; } else { #if CURL_SUPPORT_MAC_10_8 long i = ssl_version; (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocolAll, false); for(; i <= (ssl_version_max >> 16); i++) { switch(i) { case CURL_SSLVERSION_TLSv1_0: (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol1, true); break; case CURL_SSLVERSION_TLSv1_1: (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol11, true); break; case CURL_SSLVERSION_TLSv1_2: (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol12, true); break; case CURL_SSLVERSION_TLSv1_3: failf(data, "Your version of the OS does not support TLSv1.3"); return CURLE_SSL_CONNECT_ERROR; } } return CURLE_OK; #endif /* CURL_SUPPORT_MAC_10_8 */ } #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ failf(data, "Secure Transport: cannot set SSL protocol"); return CURLE_SSL_CONNECT_ERROR; } static CURLcode sectransp_connect_step1(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile); const bool verifypeer = SSL_CONN_CONFIG(verifypeer); char * const ssl_cert = SSL_SET_OPTION(cert); const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif /* ENABLE_IPV6 */ size_t all_ciphers_count = 0UL, allowed_ciphers_count = 0UL, i; SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; OSStatus err = noErr; #if CURL_BUILD_MAC int darwinver_maj = 0, darwinver_min = 0; GetDarwinVersionNumber(&darwinver_maj, &darwinver_min); #endif /* CURL_BUILD_MAC */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLCreateContext != NULL) { /* use the newer API if available */ if(BACKEND->ssl_ctx) CFRelease(BACKEND->ssl_ctx); BACKEND->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); if(!BACKEND->ssl_ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } } else { /* The old ST API does not exist under iOS, so don't compile it: */ #if CURL_SUPPORT_MAC_10_8 if(BACKEND->ssl_ctx) (void)SSLDisposeContext(BACKEND->ssl_ctx); err = SSLNewContext(false, &(BACKEND->ssl_ctx)); if(err != noErr) { failf(data, "SSL: couldn't create a context: OSStatus %d", err); return CURLE_OUT_OF_MEMORY; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else if(BACKEND->ssl_ctx) (void)SSLDisposeContext(BACKEND->ssl_ctx); err = SSLNewContext(false, &(BACKEND->ssl_ctx)); if(err != noErr) { failf(data, "SSL: couldn't create a context: OSStatus %d", err); return CURLE_OUT_OF_MEMORY; } #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ BACKEND->ssl_write_buffered_length = 0UL; /* reset buffered write length */ /* check to see if we've been told to use an explicit SSL/TLS version */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLSetProtocolVersionMax != NULL) { switch(conn->ssl_config.version) { case CURL_SSLVERSION_TLSv1: (void)SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kTLSProtocol1); #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 if(__builtin_available(macOS 10.13, iOS 11.0, *)) { (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol13); } else { (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol12); } #else (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol12); #endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 */ break; case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(conn, sockindex); if(result != CURLE_OK) return result; break; } case CURL_SSLVERSION_SSLv3: err = SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kSSLProtocol3); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv3"); return CURLE_SSL_CONNECT_ERROR; } (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kSSLProtocol3); break; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kSSLProtocol2); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kSSLProtocol2); break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } } else { #if CURL_SUPPORT_MAC_10_8 (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocolAll, false); switch(conn->ssl_config.version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol1, true); (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol11, true); (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol12, true); break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(conn, sockindex); if(result != CURLE_OK) return result; break; } case CURL_SSLVERSION_SSLv3: err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocol3, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv3"); return CURLE_SSL_CONNECT_ERROR; } break; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocol2, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else if(conn->ssl_config.version_max != CURL_SSLVERSION_MAX_NONE) { failf(data, "Your version of the OS does not support to set maximum" " SSL/TLS version"); return CURLE_SSL_CONNECT_ERROR; } (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocolAll, false); switch(conn->ssl_config.version) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: case CURL_SSLVERSION_TLSv1_0: (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kTLSProtocol1, true); break; case CURL_SSLVERSION_TLSv1_1: failf(data, "Your version of the OS does not support TLSv1.1"); return CURLE_SSL_CONNECT_ERROR; case CURL_SSLVERSION_TLSv1_2: failf(data, "Your version of the OS does not support TLSv1.2"); return CURLE_SSL_CONNECT_ERROR; case CURL_SSLVERSION_TLSv1_3: failf(data, "Your version of the OS does not support TLSv1.3"); return CURLE_SSL_CONNECT_ERROR; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocol2, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } break; case CURL_SSLVERSION_SSLv3: err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocol3, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv3"); return CURLE_SSL_CONNECT_ERROR; } break; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 if(conn->bits.tls_enable_alpn) { if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) { CFMutableArrayRef alpnArr = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2 && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) { CFArrayAppendValue(alpnArr, CFSTR(NGHTTP2_PROTO_VERSION_ID)); infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif CFArrayAppendValue(alpnArr, CFSTR(ALPN_HTTP_1_1)); infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); /* expects length prefixed preference ordered list of protocols in wire * format */ err = SSLSetALPNProtocols(BACKEND->ssl_ctx, alpnArr); if(err != noErr) infof(data, "WARNING: failed to set ALPN protocols; OSStatus %d\n", err); CFRelease(alpnArr); } } #endif if(SSL_SET_OPTION(key)) { infof(data, "WARNING: SSL: CURLOPT_SSLKEY is ignored by Secure " "Transport. The private key must be in the Keychain.\n"); } if(ssl_cert) { SecIdentityRef cert_and_key = NULL; bool is_cert_file = is_file(ssl_cert); /* User wants to authenticate with a client cert. Look for it: If we detect that this is a file on disk, then let's load it. Otherwise, assume that the user wants to use an identity loaded from the Keychain. */ if(is_cert_file) { if(!SSL_SET_OPTION(cert_type)) infof(data, "WARNING: SSL: Certificate type not set, assuming " "PKCS#12 format.\n"); else if(strncmp(SSL_SET_OPTION(cert_type), "P12", strlen(SSL_SET_OPTION(cert_type))) != 0) infof(data, "WARNING: SSL: The Security framework only supports " "loading identities that are in PKCS#12 format.\n"); err = CopyIdentityFromPKCS12File(ssl_cert, SSL_SET_OPTION(key_passwd), &cert_and_key); } else err = CopyIdentityWithLabel(ssl_cert, &cert_and_key); if(err == noErr && cert_and_key) { SecCertificateRef cert = NULL; CFTypeRef certs_c[1]; CFArrayRef certs; /* If we found one, print it out: */ err = SecIdentityCopyCertificate(cert_and_key, &cert); if(err == noErr) { char *certp; CURLcode result = CopyCertSubject(data, cert, &certp); if(!result) { infof(data, "Client certificate: %s\n", certp); free(certp); } CFRelease(cert); if(result == CURLE_PEER_FAILED_VERIFICATION) return CURLE_SSL_CERTPROBLEM; if(result) return result; } certs_c[0] = cert_and_key; certs = CFArrayCreate(NULL, (const void **)certs_c, 1L, &kCFTypeArrayCallBacks); err = SSLSetCertificate(BACKEND->ssl_ctx, certs); if(certs) CFRelease(certs); if(err != noErr) { failf(data, "SSL: SSLSetCertificate() failed: OSStatus %d", err); return CURLE_SSL_CERTPROBLEM; } CFRelease(cert_and_key); } else { switch(err) { case errSecAuthFailed: case -25264: /* errSecPkcs12VerifyFailure */ failf(data, "SSL: Incorrect password for the certificate \"%s\" " "and its private key.", ssl_cert); break; case -26275: /* errSecDecode */ case -25257: /* errSecUnknownFormat */ failf(data, "SSL: Couldn't make sense of the data in the " "certificate \"%s\" and its private key.", ssl_cert); break; case -25260: /* errSecPassphraseRequired */ failf(data, "SSL The certificate \"%s\" requires a password.", ssl_cert); break; case errSecItemNotFound: failf(data, "SSL: Can't find the certificate \"%s\" and its private " "key in the Keychain.", ssl_cert); break; default: failf(data, "SSL: Can't load the certificate \"%s\" and its private " "key: OSStatus %d", ssl_cert, err); break; } return CURLE_SSL_CERTPROBLEM; } } /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* Snow Leopard introduced the SSLSetSessionOption() function, but due to a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag works, it doesn't work as expected under Snow Leopard, Lion or Mountain Lion. So we need to call SSLSetEnableCertVerify() on those older cats in order to disable certificate validation if the user turned that off. (SecureTransport will always validate the certificate chain by default.) Note: Darwin 11.x.x is Lion (10.7) Darwin 12.x.x is Mountain Lion (10.8) Darwin 13.x.x is Mavericks (10.9) Darwin 14.x.x is Yosemite (10.10) Darwin 15.x.x is El Capitan (10.11) */ #if CURL_BUILD_MAC if(SSLSetSessionOption != NULL && darwinver_maj >= 13) { #else if(SSLSetSessionOption != NULL) { #endif /* CURL_BUILD_MAC */ bool break_on_auth = !conn->ssl_config.verifypeer || ssl_cafile; err = SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionBreakOnServerAuth, break_on_auth); if(err != noErr) { failf(data, "SSL: SSLSetSessionOption() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } } else { #if CURL_SUPPORT_MAC_10_8 err = SSLSetEnableCertVerify(BACKEND->ssl_ctx, conn->ssl_config.verifypeer?true:false); if(err != noErr) { failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else err = SSLSetEnableCertVerify(BACKEND->ssl_ctx, conn->ssl_config.verifypeer?true:false); if(err != noErr) { failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ if(ssl_cafile && verifypeer) { bool is_cert_file = is_file(ssl_cafile); if(!is_cert_file) { failf(data, "SSL: can't load CA certificate file %s", ssl_cafile); return CURLE_SSL_CACERT_BADFILE; } } /* Configure hostname check. SNI is used if available. * Both hostname check and SNI require SSLSetPeerDomainName(). * Also: the verifyhost setting influences SNI usage */ if(conn->ssl_config.verifyhost) { err = SSLSetPeerDomainName(BACKEND->ssl_ctx, hostname, strlen(hostname)); if(err != noErr) { infof(data, "WARNING: SSL: SSLSetPeerDomainName() failed: OSStatus %d\n", err); } if((Curl_inet_pton(AF_INET, hostname, &addr)) #ifdef ENABLE_IPV6 || (Curl_inet_pton(AF_INET6, hostname, &addr)) #endif ) { infof(data, "WARNING: using IP address, SNI is being disabled by " "the OS.\n"); } } else { infof(data, "WARNING: disabling hostname validation also disables SNI.\n"); } /* Disable cipher suites that ST supports but are not safe. These ciphers are unlikely to be used in any case since ST gives other ciphers a much higher priority, but it's probably better that we not connect at all than to give the user a false sense of security if the server only supports insecure ciphers. (Note: We don't care about SSLv2-only ciphers.) */ err = SSLGetNumberSupportedCiphers(BACKEND->ssl_ctx, &all_ciphers_count); if(err != noErr) { failf(data, "SSL: SSLGetNumberSupportedCiphers() failed: OSStatus %d", err); return CURLE_SSL_CIPHER; } all_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); if(!all_ciphers) { failf(data, "SSL: Failed to allocate memory for all ciphers"); return CURLE_OUT_OF_MEMORY; } allowed_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); if(!allowed_ciphers) { Curl_safefree(all_ciphers); failf(data, "SSL: Failed to allocate memory for allowed ciphers"); return CURLE_OUT_OF_MEMORY; } err = SSLGetSupportedCiphers(BACKEND->ssl_ctx, all_ciphers, &all_ciphers_count); if(err != noErr) { Curl_safefree(all_ciphers); Curl_safefree(allowed_ciphers); return CURLE_SSL_CIPHER; } for(i = 0UL ; i < all_ciphers_count ; i++) { #if CURL_BUILD_MAC /* There's a known bug in early versions of Mountain Lion where ST's ECC ciphers (cipher suite 0xC001 through 0xC032) simply do not work. Work around the problem here by disabling those ciphers if we are running in an affected version of OS X. */ if(darwinver_maj == 12 && darwinver_min <= 3 && all_ciphers[i] >= 0xC001 && all_ciphers[i] <= 0xC032) { continue; } #endif /* CURL_BUILD_MAC */ switch(all_ciphers[i]) { /* Disable NULL ciphersuites: */ case SSL_NULL_WITH_NULL_NULL: case SSL_RSA_WITH_NULL_MD5: case SSL_RSA_WITH_NULL_SHA: case 0x003B: /* TLS_RSA_WITH_NULL_SHA256 */ case SSL_FORTEZZA_DMS_WITH_NULL_SHA: case 0xC001: /* TLS_ECDH_ECDSA_WITH_NULL_SHA */ case 0xC006: /* TLS_ECDHE_ECDSA_WITH_NULL_SHA */ case 0xC00B: /* TLS_ECDH_RSA_WITH_NULL_SHA */ case 0xC010: /* TLS_ECDHE_RSA_WITH_NULL_SHA */ case 0x002C: /* TLS_PSK_WITH_NULL_SHA */ case 0x002D: /* TLS_DHE_PSK_WITH_NULL_SHA */ case 0x002E: /* TLS_RSA_PSK_WITH_NULL_SHA */ case 0x00B0: /* TLS_PSK_WITH_NULL_SHA256 */ case 0x00B1: /* TLS_PSK_WITH_NULL_SHA384 */ case 0x00B4: /* TLS_DHE_PSK_WITH_NULL_SHA256 */ case 0x00B5: /* TLS_DHE_PSK_WITH_NULL_SHA384 */ case 0x00B8: /* TLS_RSA_PSK_WITH_NULL_SHA256 */ case 0x00B9: /* TLS_RSA_PSK_WITH_NULL_SHA384 */ /* Disable anonymous ciphersuites: */ case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5: case SSL_DH_anon_WITH_RC4_128_MD5: case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_anon_WITH_DES_CBC_SHA: case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: case TLS_DH_anon_WITH_AES_128_CBC_SHA: case TLS_DH_anon_WITH_AES_256_CBC_SHA: case 0xC015: /* TLS_ECDH_anon_WITH_NULL_SHA */ case 0xC016: /* TLS_ECDH_anon_WITH_RC4_128_SHA */ case 0xC017: /* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA */ case 0xC018: /* TLS_ECDH_anon_WITH_AES_128_CBC_SHA */ case 0xC019: /* TLS_ECDH_anon_WITH_AES_256_CBC_SHA */ case 0x006C: /* TLS_DH_anon_WITH_AES_128_CBC_SHA256 */ case 0x006D: /* TLS_DH_anon_WITH_AES_256_CBC_SHA256 */ case 0x00A6: /* TLS_DH_anon_WITH_AES_128_GCM_SHA256 */ case 0x00A7: /* TLS_DH_anon_WITH_AES_256_GCM_SHA384 */ /* Disable weak key ciphersuites: */ case SSL_RSA_EXPORT_WITH_RC4_40_MD5: case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5: case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_RSA_WITH_DES_CBC_SHA: case SSL_DH_DSS_WITH_DES_CBC_SHA: case SSL_DH_RSA_WITH_DES_CBC_SHA: case SSL_DHE_DSS_WITH_DES_CBC_SHA: case SSL_DHE_RSA_WITH_DES_CBC_SHA: /* Disable IDEA: */ case SSL_RSA_WITH_IDEA_CBC_SHA: case SSL_RSA_WITH_IDEA_CBC_MD5: /* Disable RC4: */ case SSL_RSA_WITH_RC4_128_MD5: case SSL_RSA_WITH_RC4_128_SHA: case 0xC002: /* TLS_ECDH_ECDSA_WITH_RC4_128_SHA */ case 0xC007: /* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA*/ case 0xC00C: /* TLS_ECDH_RSA_WITH_RC4_128_SHA */ case 0xC011: /* TLS_ECDHE_RSA_WITH_RC4_128_SHA */ case 0x008A: /* TLS_PSK_WITH_RC4_128_SHA */ case 0x008E: /* TLS_DHE_PSK_WITH_RC4_128_SHA */ case 0x0092: /* TLS_RSA_PSK_WITH_RC4_128_SHA */ break; default: /* enable everything else */ allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i]; break; } } err = SSLSetEnabledCiphers(BACKEND->ssl_ctx, allowed_ciphers, allowed_ciphers_count); Curl_safefree(all_ciphers); Curl_safefree(allowed_ciphers); if(err != noErr) { failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); return CURLE_SSL_CIPHER; } #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 /* We want to enable 1/n-1 when using a CBC cipher unless the user specifically doesn't want us doing that: */ if(SSLSetSessionOption != NULL) { SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionSendOneByteRecord, !data->set.ssl.enable_beast); SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionFalseStart, data->set.ssl.falsestart); /* false start support */ } #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { char *ssl_sessionid; size_t ssl_sessionid_len; Curl_ssl_sessionid_lock(conn); if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid, &ssl_sessionid_len, sockindex)) { /* we got a session id, use it! */ err = SSLSetPeerID(BACKEND->ssl_ctx, ssl_sessionid, ssl_sessionid_len); Curl_ssl_sessionid_unlock(conn); if(err != noErr) { failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } /* If there isn't one, then let's make one up! This has to be done prior to starting the handshake. */ else { CURLcode result; ssl_sessionid = aprintf("%s:%d:%d:%s:%hu", ssl_cafile, verifypeer, SSL_CONN_CONFIG(verifyhost), hostname, port); ssl_sessionid_len = strlen(ssl_sessionid); err = SSLSetPeerID(BACKEND->ssl_ctx, ssl_sessionid, ssl_sessionid_len); if(err != noErr) { Curl_ssl_sessionid_unlock(conn); failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } result = Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_sessionid_len, sockindex); Curl_ssl_sessionid_unlock(conn); if(result) { failf(data, "failed to store ssl session"); return result; } } } err = SSLSetIOFuncs(BACKEND->ssl_ctx, SocketRead, SocketWrite); if(err != noErr) { failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } /* pass the raw socket into the SSL layers */ /* We need to store the FD in a constant memory address, because * SSLSetConnection() will not copy that address. I've found that * conn->sock[sockindex] may change on its own. */ BACKEND->ssl_sockfd = sockfd; err = SSLSetConnection(BACKEND->ssl_ctx, connssl); if(err != noErr) { failf(data, "SSL: SSLSetConnection() failed: %d", err); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static long pem_to_der(const char *in, unsigned char **out, size_t *outlen) { char *sep_start, *sep_end, *cert_start, *cert_end; size_t i, j, err; size_t len; unsigned char *b64; /* Jump through the separators at the beginning of the certificate. */ sep_start = strstr(in, "-----"); if(sep_start == NULL) return 0; cert_start = strstr(sep_start + 1, "-----"); if(cert_start == NULL) return -1; cert_start += 5; /* Find separator after the end of the certificate. */ cert_end = strstr(cert_start, "-----"); if(cert_end == NULL) return -1; sep_end = strstr(cert_end + 1, "-----"); if(sep_end == NULL) return -1; sep_end += 5; len = cert_end - cert_start; b64 = malloc(len + 1); if(!b64) return -1; /* Create base64 string without linefeeds. */ for(i = 0, j = 0; i < len; i++) { if(cert_start[i] != '\r' && cert_start[i] != '\n') b64[j++] = cert_start[i]; } b64[j] = '\0'; err = Curl_base64_decode((const char *)b64, out, outlen); free(b64); if(err) { free(*out); return -1; } return sep_end - in; } static int read_cert(const char *file, unsigned char **out, size_t *outlen) { int fd; ssize_t n, len = 0, cap = 512; unsigned char buf[512], *data; fd = open(file, 0); if(fd < 0) return -1; data = malloc(cap); if(!data) { close(fd); return -1; } for(;;) { n = read(fd, buf, sizeof(buf)); if(n < 0) { close(fd); free(data); return -1; } else if(n == 0) { close(fd); break; } if(len + n >= cap) { cap *= 2; data = Curl_saferealloc(data, cap); if(!data) { close(fd); return -1; } } memcpy(data + len, buf, n); len += n; } data[len] = '\0'; *out = data; *outlen = len; return 0; } static int append_cert_to_array(struct Curl_easy *data, unsigned char *buf, size_t buflen, CFMutableArrayRef array) { CFDataRef certdata = CFDataCreate(kCFAllocatorDefault, buf, buflen); char *certp; CURLcode result; if(!certdata) { failf(data, "SSL: failed to allocate array for CA certificate"); return CURLE_OUT_OF_MEMORY; } SecCertificateRef cacert = SecCertificateCreateWithData(kCFAllocatorDefault, certdata); CFRelease(certdata); if(!cacert) { failf(data, "SSL: failed to create SecCertificate from CA certificate"); return CURLE_SSL_CACERT_BADFILE; } /* Check if cacert is valid. */ result = CopyCertSubject(data, cacert, &certp); switch(result) { case CURLE_OK: break; case CURLE_PEER_FAILED_VERIFICATION: return CURLE_SSL_CACERT_BADFILE; case CURLE_OUT_OF_MEMORY: default: return result; } free(certp); CFArrayAppendValue(array, cacert); CFRelease(cacert); return CURLE_OK; } static int verify_cert(const char *cafile, struct Curl_easy *data, SSLContextRef ctx) { int n = 0, rc; long res; unsigned char *certbuf, *der; size_t buflen, derlen, offset = 0; if(read_cert(cafile, &certbuf, &buflen) < 0) { failf(data, "SSL: failed to read or invalid CA certificate"); return CURLE_SSL_CACERT_BADFILE; } /* * Certbuf now contains the contents of the certificate file, which can be * - a single DER certificate, * - a single PEM certificate or * - a bunch of PEM certificates (certificate bundle). * * Go through certbuf, and convert any PEM certificate in it into DER * format. */ CFMutableArrayRef array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if(array == NULL) { free(certbuf); failf(data, "SSL: out of memory creating CA certificate array"); return CURLE_OUT_OF_MEMORY; } while(offset < buflen) { n++; /* * Check if the certificate is in PEM format, and convert it to DER. If * this fails, we assume the certificate is in DER format. */ res = pem_to_der((const char *)certbuf + offset, &der, &derlen); if(res < 0) { free(certbuf); CFRelease(array); failf(data, "SSL: invalid CA certificate #%d (offset %d) in bundle", n, offset); return CURLE_SSL_CACERT_BADFILE; } offset += res; if(res == 0 && offset == 0) { /* This is not a PEM file, probably a certificate in DER format. */ rc = append_cert_to_array(data, certbuf, buflen, array); free(certbuf); if(rc != CURLE_OK) { CFRelease(array); return rc; } break; } else if(res == 0) { /* No more certificates in the bundle. */ free(certbuf); break; } rc = append_cert_to_array(data, der, derlen, array); free(der); if(rc != CURLE_OK) { free(certbuf); CFRelease(array); return rc; } } SecTrustRef trust; OSStatus ret = SSLCopyPeerTrust(ctx, &trust); if(trust == NULL) { failf(data, "SSL: error getting certificate chain"); CFRelease(array); return CURLE_PEER_FAILED_VERIFICATION; } else if(ret != noErr) { CFRelease(array); failf(data, "SSLCopyPeerTrust() returned error %d", ret); return CURLE_PEER_FAILED_VERIFICATION; } ret = SecTrustSetAnchorCertificates(trust, array); if(ret != noErr) { CFRelease(array); CFRelease(trust); failf(data, "SecTrustSetAnchorCertificates() returned error %d", ret); return CURLE_PEER_FAILED_VERIFICATION; } ret = SecTrustSetAnchorCertificatesOnly(trust, true); if(ret != noErr) { CFRelease(array); CFRelease(trust); failf(data, "SecTrustSetAnchorCertificatesOnly() returned error %d", ret); return CURLE_PEER_FAILED_VERIFICATION; } SecTrustResultType trust_eval = 0; ret = SecTrustEvaluate(trust, &trust_eval); CFRelease(array); CFRelease(trust); if(ret != noErr) { failf(data, "SecTrustEvaluate() returned error %d", ret); return CURLE_PEER_FAILED_VERIFICATION; } switch(trust_eval) { case kSecTrustResultUnspecified: case kSecTrustResultProceed: return CURLE_OK; case kSecTrustResultRecoverableTrustFailure: case kSecTrustResultDeny: default: failf(data, "SSL: certificate verification failed (result: %d)", trust_eval); return CURLE_PEER_FAILED_VERIFICATION; } } #ifdef SECTRANSP_PINNEDPUBKEY static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, SSLContextRef ctx, const char *pinnedpubkey) { /* Scratch */ size_t pubkeylen, realpubkeylen, spkiHeaderLength = 24; unsigned char *pubkey = NULL, *realpubkey = NULL; const unsigned char *spkiHeader = NULL; CFDataRef publicKeyBits = NULL; /* Result is returned to caller */ CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; /* if a path wasn't specified, don't pin */ if(!pinnedpubkey) return CURLE_OK; if(!ctx) return result; do { SecTrustRef trust; OSStatus ret = SSLCopyPeerTrust(ctx, &trust); if(ret != noErr || trust == NULL) break; SecKeyRef keyRef = SecTrustCopyPublicKey(trust); CFRelease(trust); if(keyRef == NULL) break; #ifdef SECTRANSP_PINNEDPUBKEY_V1 publicKeyBits = SecKeyCopyExternalRepresentation(keyRef, NULL); CFRelease(keyRef); if(publicKeyBits == NULL) break; #elif SECTRANSP_PINNEDPUBKEY_V2 OSStatus success = SecItemExport(keyRef, kSecFormatOpenSSL, 0, NULL, &publicKeyBits); CFRelease(keyRef); if(success != errSecSuccess || publicKeyBits == NULL) break; #endif /* SECTRANSP_PINNEDPUBKEY_V2 */ pubkeylen = CFDataGetLength(publicKeyBits); pubkey = (unsigned char *)CFDataGetBytePtr(publicKeyBits); switch(pubkeylen) { case 526: /* 4096 bit RSA pubkeylen == 526 */ spkiHeader = rsa4096SpkiHeader; break; case 270: /* 2048 bit RSA pubkeylen == 270 */ spkiHeader = rsa2048SpkiHeader; break; #ifdef SECTRANSP_PINNEDPUBKEY_V1 case 65: /* ecDSA secp256r1 pubkeylen == 65 */ spkiHeader = ecDsaSecp256r1SpkiHeader; spkiHeaderLength = 26; break; case 97: /* ecDSA secp384r1 pubkeylen == 97 */ spkiHeader = ecDsaSecp384r1SpkiHeader; spkiHeaderLength = 23; break; default: infof(data, "SSL: unhandled public key length: %d\n", pubkeylen); #elif SECTRANSP_PINNEDPUBKEY_V2 default: /* ecDSA secp256r1 pubkeylen == 91 header already included? * ecDSA secp384r1 header already included too * we assume rest of algorithms do same, so do nothing */ result = Curl_pin_peer_pubkey(data, pinnedpubkey, pubkey, pubkeylen); #endif /* SECTRANSP_PINNEDPUBKEY_V2 */ continue; /* break from loop */ } realpubkeylen = pubkeylen + spkiHeaderLength; realpubkey = malloc(realpubkeylen); if(!realpubkey) break; memcpy(realpubkey, spkiHeader, spkiHeaderLength); memcpy(realpubkey + spkiHeaderLength, pubkey, pubkeylen); result = Curl_pin_peer_pubkey(data, pinnedpubkey, realpubkey, realpubkeylen); } while(0); Curl_safefree(realpubkey); if(publicKeyBits != NULL) CFRelease(publicKeyBits); return result; } #endif /* SECTRANSP_PINNEDPUBKEY */ static CURLcode sectransp_connect_step2(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; OSStatus err; SSLCipherSuite cipher; SSLProtocol protocol = 0; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; DEBUGASSERT(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state); /* Here goes nothing: */ err = SSLHandshake(BACKEND->ssl_ctx); if(err != noErr) { switch(err) { case errSSLWouldBlock: /* they're not done with us yet */ connssl->connecting_state = BACKEND->ssl_direction ? ssl_connect_2_writing : ssl_connect_2_reading; return CURLE_OK; /* The below is errSSLServerAuthCompleted; it's not defined in Leopard's headers */ case -9841: if(SSL_CONN_CONFIG(CAfile) && SSL_CONN_CONFIG(verifypeer)) { int res = verify_cert(SSL_CONN_CONFIG(CAfile), data, BACKEND->ssl_ctx); if(res != CURLE_OK) return res; } /* the documentation says we need to call SSLHandshake() again */ return sectransp_connect_step2(conn, sockindex); /* Problem with encrypt / decrypt */ case errSSLPeerDecodeError: failf(data, "Decode failed"); break; case errSSLDecryptionFail: case errSSLPeerDecryptionFail: failf(data, "Decryption failed"); break; case errSSLPeerDecryptError: failf(data, "A decryption error occurred"); break; case errSSLBadCipherSuite: failf(data, "A bad SSL cipher suite was encountered"); break; case errSSLCrypto: failf(data, "An underlying cryptographic error was encountered"); break; #if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9 case errSSLWeakPeerEphemeralDHKey: failf(data, "Indicates a weak ephemeral Diffie-Hellman key"); break; #endif /* Problem with the message record validation */ case errSSLBadRecordMac: case errSSLPeerBadRecordMac: failf(data, "A record with a bad message authentication code (MAC) " "was encountered"); break; case errSSLRecordOverflow: case errSSLPeerRecordOverflow: failf(data, "A record overflow occurred"); break; /* Problem with zlib decompression */ case errSSLPeerDecompressFail: failf(data, "Decompression failed"); break; /* Problem with access */ case errSSLPeerAccessDenied: failf(data, "Access was denied"); break; case errSSLPeerInsufficientSecurity: failf(data, "There is insufficient security for this operation"); break; /* These are all certificate problems with the server: */ case errSSLXCertChainInvalid: failf(data, "SSL certificate problem: Invalid certificate chain"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLUnknownRootCert: failf(data, "SSL certificate problem: Untrusted root certificate"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLNoRootCert: failf(data, "SSL certificate problem: No root certificate"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLCertNotYetValid: failf(data, "SSL certificate problem: The certificate chain had a " "certificate that is not yet valid"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLCertExpired: case errSSLPeerCertExpired: failf(data, "SSL certificate problem: Certificate chain had an " "expired certificate"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLBadCert: case errSSLPeerBadCert: failf(data, "SSL certificate problem: Couldn't understand the server " "certificate format"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLPeerUnsupportedCert: failf(data, "SSL certificate problem: An unsupported certificate " "format was encountered"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLPeerCertRevoked: failf(data, "SSL certificate problem: The certificate was revoked"); return CURLE_PEER_FAILED_VERIFICATION; case errSSLPeerCertUnknown: failf(data, "SSL certificate problem: The certificate is unknown"); return CURLE_PEER_FAILED_VERIFICATION; /* These are all certificate problems with the client: */ case errSecAuthFailed: failf(data, "SSL authentication failed"); break; case errSSLPeerHandshakeFail: failf(data, "SSL peer handshake failed, the server most likely " "requires a client certificate to connect"); break; case errSSLPeerUnknownCA: failf(data, "SSL server rejected the client certificate due to " "the certificate being signed by an unknown certificate " "authority"); break; /* This error is raised if the server's cert didn't match the server's host name: */ case errSSLHostNameMismatch: failf(data, "SSL certificate peer verification failed, the " "certificate did not match \"%s\"\n", conn->host.dispname); return CURLE_PEER_FAILED_VERIFICATION; /* Problem with SSL / TLS negotiation */ case errSSLNegotiation: failf(data, "Could not negotiate an SSL cipher suite with the server"); break; case errSSLBadConfiguration: failf(data, "A configuration error occurred"); break; case errSSLProtocol: failf(data, "SSL protocol error"); break; case errSSLPeerProtocolVersion: failf(data, "A bad protocol version was encountered"); break; case errSSLPeerNoRenegotiation: failf(data, "No renegotiation is allowed"); break; /* Generic handshake errors: */ case errSSLConnectionRefused: failf(data, "Server dropped the connection during the SSL handshake"); break; case errSSLClosedAbort: failf(data, "Server aborted the SSL handshake"); break; case errSSLClosedGraceful: failf(data, "The connection closed gracefully"); break; case errSSLClosedNoNotify: failf(data, "The server closed the session with no notification"); break; /* Sometimes paramErr happens with buggy ciphers: */ case paramErr: case errSSLInternal: case errSSLPeerInternalError: failf(data, "Internal SSL engine error encountered during the " "SSL handshake"); break; case errSSLFatalAlert: failf(data, "Fatal SSL engine error encountered during the SSL " "handshake"); break; /* Unclassified error */ case errSSLBufferOverflow: failf(data, "An insufficient buffer was provided"); break; case errSSLIllegalParam: failf(data, "An illegal parameter was encountered"); break; case errSSLModuleAttach: failf(data, "Module attach failure"); break; case errSSLSessionNotFound: failf(data, "An attempt to restore an unknown session failed"); break; case errSSLPeerExportRestriction: failf(data, "An export restriction occurred"); break; case errSSLPeerUserCancelled: failf(data, "The user canceled the operation"); break; case errSSLPeerUnexpectedMsg: failf(data, "Peer rejected unexpected message"); break; #if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9 /* Treaing non-fatal error as fatal like before */ case errSSLClientHelloReceived: failf(data, "A non-fatal result for providing a server name " "indication"); break; #endif /* Error codes defined in the enum but should never be returned. We list them here just in case. */ #if CURL_BUILD_MAC_10_6 /* Only returned when kSSLSessionOptionBreakOnCertRequested is set */ case errSSLClientCertRequested: failf(data, "The server has requested a client certificate"); break; #endif #if CURL_BUILD_MAC_10_9 /* Alias for errSSLLast, end of error range */ case errSSLUnexpectedRecord: failf(data, "Unexpected (skipped) record in DTLS"); break; #endif default: /* May also return codes listed in Security Framework Result Codes */ failf(data, "Unknown SSL protocol error in connection to %s:%d", hostname, err); break; } return CURLE_SSL_CONNECT_ERROR; } else { /* we have been connected fine, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_3; #ifdef SECTRANSP_PINNEDPUBKEY if(data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]) { CURLcode result = pkp_pin_peer_pubkey(data, BACKEND->ssl_ctx, data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]); if(result) { failf(data, "SSL: public key does not match pinned public key!"); return result; } } #endif /* SECTRANSP_PINNEDPUBKEY */ /* Informational message */ (void)SSLGetNegotiatedCipher(BACKEND->ssl_ctx, &cipher); (void)SSLGetNegotiatedProtocolVersion(BACKEND->ssl_ctx, &protocol); switch(protocol) { case kSSLProtocol2: infof(data, "SSL 2.0 connection using %s\n", SSLCipherNameForNumber(cipher)); break; case kSSLProtocol3: infof(data, "SSL 3.0 connection using %s\n", SSLCipherNameForNumber(cipher)); break; case kTLSProtocol1: infof(data, "TLS 1.0 connection using %s\n", TLSCipherNameForNumber(cipher)); break; #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS case kTLSProtocol11: infof(data, "TLS 1.1 connection using %s\n", TLSCipherNameForNumber(cipher)); break; case kTLSProtocol12: infof(data, "TLS 1.2 connection using %s\n", TLSCipherNameForNumber(cipher)); break; #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 case kTLSProtocol13: infof(data, "TLS 1.3 connection using %s\n", TLSCipherNameForNumber(cipher)); break; #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ default: infof(data, "Unknown protocol connection\n"); break; } #if(CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1 if(conn->bits.tls_enable_alpn) { if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) { CFArrayRef alpnArr = NULL; CFStringRef chosenProtocol = NULL; err = SSLCopyALPNProtocols(BACKEND->ssl_ctx, &alpnArr); if(err == noErr && alpnArr && CFArrayGetCount(alpnArr) >= 1) chosenProtocol = CFArrayGetValueAtIndex(alpnArr, 0); #ifdef USE_NGHTTP2 if(chosenProtocol && !CFStringCompare(chosenProtocol, CFSTR(NGHTTP2_PROTO_VERSION_ID), 0)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(chosenProtocol && !CFStringCompare(chosenProtocol, CFSTR(ALPN_HTTP_1_1), 0)) { conn->negnpn = CURL_HTTP_VERSION_1_1; } else infof(data, "ALPN, server did not agree to a protocol\n"); Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ? BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE); /* chosenProtocol is a reference to the string within alpnArr and doesn't need to be freed separately */ if(alpnArr) CFRelease(alpnArr); } } #endif return CURLE_OK; } } #ifndef CURL_DISABLE_VERBOSE_STRINGS /* This should be called during step3 of the connection at the earliest */ static void show_verbose_server_cert(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CFArrayRef server_certs = NULL; SecCertificateRef server_cert; OSStatus err; CFIndex i, count; SecTrustRef trust = NULL; if(!BACKEND->ssl_ctx) return; #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS #if CURL_BUILD_IOS #pragma unused(server_certs) err = SSLCopyPeerTrust(BACKEND->ssl_ctx, &trust); /* For some reason, SSLCopyPeerTrust() can return noErr and yet return a null trust, so be on guard for that: */ if(err == noErr && trust) { count = SecTrustGetCertificateCount(trust); for(i = 0L ; i < count ; i++) { CURLcode result; char *certp; server_cert = SecTrustGetCertificateAtIndex(trust, i); result = CopyCertSubject(data, server_cert, &certp); if(!result) { infof(data, "Server certificate: %s\n", certp); free(certp); } } CFRelease(trust); } #else /* SSLCopyPeerCertificates() is deprecated as of Mountain Lion. The function SecTrustGetCertificateAtIndex() is officially present in Lion, but it is unfortunately also present in Snow Leopard as private API and doesn't work as expected. So we have to look for a different symbol to make sure this code is only executed under Lion or later. */ if(SecTrustEvaluateAsync != NULL) { #pragma unused(server_certs) err = SSLCopyPeerTrust(BACKEND->ssl_ctx, &trust); /* For some reason, SSLCopyPeerTrust() can return noErr and yet return a null trust, so be on guard for that: */ if(err == noErr && trust) { count = SecTrustGetCertificateCount(trust); for(i = 0L ; i < count ; i++) { char *certp; CURLcode result; server_cert = SecTrustGetCertificateAtIndex(trust, i); result = CopyCertSubject(data, server_cert, &certp); if(!result) { infof(data, "Server certificate: %s\n", certp); free(certp); } } CFRelease(trust); } } else { #if CURL_SUPPORT_MAC_10_8 err = SSLCopyPeerCertificates(BACKEND->ssl_ctx, &server_certs); /* Just in case SSLCopyPeerCertificates() returns null too... */ if(err == noErr && server_certs) { count = CFArrayGetCount(server_certs); for(i = 0L ; i < count ; i++) { char *certp; CURLcode result; server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i); result = CopyCertSubject(data, server_cert, &certp); if(!result) { infof(data, "Server certificate: %s\n", certp); free(certp); } } CFRelease(server_certs); } #endif /* CURL_SUPPORT_MAC_10_8 */ } #endif /* CURL_BUILD_IOS */ #else #pragma unused(trust) err = SSLCopyPeerCertificates(BACKEND->ssl_ctx, &server_certs); if(err == noErr) { count = CFArrayGetCount(server_certs); for(i = 0L ; i < count ; i++) { CURLcode result; char *certp; server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i); result = CopyCertSubject(data, server_cert, &certp); if(!result) { infof(data, "Server certificate: %s\n", certp); free(certp); } } CFRelease(server_certs); } #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ } #endif /* !CURL_DISABLE_VERBOSE_STRINGS */ static CURLcode sectransp_connect_step3(struct connectdata *conn, int sockindex) { struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; /* There is no step 3! * Well, okay, if verbose mode is on, let's print the details of the * server certificates. */ #ifndef CURL_DISABLE_VERBOSE_STRINGS if(data->set.verbose) show_verbose_server_cert(conn, sockindex); #endif connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static Curl_recv sectransp_recv; static Curl_send sectransp_send; static CURLcode sectransp_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct Curl_easy *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } result = sectransp_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if this * connection is done nonblocking and this loop would execute again. This * permits the owner of a multi handle to abort a connection attempt * before step2 has completed while ensuring that a client using select() * or epoll() will always have a valid fdset to wait on. */ result = sectransp_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = sectransp_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = sectransp_recv; conn->send[sockindex] = sectransp_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } static CURLcode Curl_sectransp_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return sectransp_connect_common(conn, sockindex, TRUE, done); } static CURLcode Curl_sectransp_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = sectransp_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } static void Curl_sectransp_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(BACKEND->ssl_ctx) { (void)SSLClose(BACKEND->ssl_ctx); #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLCreateContext != NULL) CFRelease(BACKEND->ssl_ctx); #if CURL_SUPPORT_MAC_10_8 else (void)SSLDisposeContext(BACKEND->ssl_ctx); #endif /* CURL_SUPPORT_MAC_10_8 */ #else (void)SSLDisposeContext(BACKEND->ssl_ctx); #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ BACKEND->ssl_ctx = NULL; } BACKEND->ssl_sockfd = 0; } static int Curl_sectransp_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct Curl_easy *data = conn->data; ssize_t nread; int what; int rc; char buf[120]; if(!BACKEND->ssl_ctx) return 0; #ifndef CURL_DISABLE_FTP if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE) return 0; #endif Curl_sectransp_close(conn, sockindex); rc = 0; what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT); for(;;) { if(what < 0) { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); rc = -1; break; } if(!what) { /* timeout */ failf(data, "SSL shutdown timeout"); break; } /* Something to read, let's do it and hope that it is the close notify alert from the server. No way to SSL_Read now, so use read(). */ nread = read(conn->sock[sockindex], buf, sizeof(buf)); if(nread < 0) { failf(data, "read: %s", strerror(errno)); rc = -1; } if(nread <= 0) break; what = SOCKET_READABLE(conn->sock[sockindex], 0); } return rc; } static void Curl_sectransp_session_free(void *ptr) { /* ST, as of iOS 5 and Mountain Lion, has no public method of deleting a cached session ID inside the Security framework. There is a private function that does this, but I don't want to have to explain to you why I got your application rejected from the App Store due to the use of a private API, so the best we can do is free up our own char array that we created way back in sectransp_connect_step1... */ Curl_safefree(ptr); } static size_t Curl_sectransp_version(char *buffer, size_t size) { return msnprintf(buffer, size, "SecureTransport"); } /* * This function uses SSLGetSessionState to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ static int Curl_sectransp_check_cxn(struct connectdata *conn) { struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET]; OSStatus err; SSLSessionState state; if(BACKEND->ssl_ctx) { err = SSLGetSessionState(BACKEND->ssl_ctx, &state); if(err == noErr) return state == kSSLConnected || state == kSSLHandshake; return -1; } return 0; } static bool Curl_sectransp_data_pending(const struct connectdata *conn, int connindex) { const struct ssl_connect_data *connssl = &conn->ssl[connindex]; OSStatus err; size_t buffer; if(BACKEND->ssl_ctx) { /* SSL is in use */ err = SSLGetBufferedReadSize(BACKEND->ssl_ctx, &buffer); if(err == noErr) return buffer > 0UL; return false; } else return false; } static CURLcode Curl_sectransp_random(struct Curl_easy *data UNUSED_PARAM, unsigned char *entropy, size_t length) { /* arc4random_buf() isn't available on cats older than Lion, so let's do this manually for the benefit of the older cats. */ size_t i; u_int32_t random_number = 0; (void)data; for(i = 0 ; i < length ; i++) { if(i % sizeof(u_int32_t) == 0) random_number = arc4random(); entropy[i] = random_number & 0xFF; random_number >>= 8; } i = random_number = 0; return CURLE_OK; } static CURLcode Curl_sectransp_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len) { (void)md5len; (void)CC_MD5(tmp, (CC_LONG)tmplen, md5sum); return CURLE_OK; } static CURLcode Curl_sectransp_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum, /* output */ size_t sha256len) { assert(sha256len >= CURL_SHA256_DIGEST_LENGTH); (void)CC_SHA256(tmp, (CC_LONG)tmplen, sha256sum); return CURLE_OK; } static bool Curl_sectransp_false_start(void) { #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 if(SSLSetSessionOption != NULL) return TRUE; #endif return FALSE; } static ssize_t sectransp_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { /*struct Curl_easy *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[sockindex]; size_t processed = 0UL; OSStatus err; /* The SSLWrite() function works a little differently than expected. The fourth argument (processed) is currently documented in Apple's documentation as: "On return, the length, in bytes, of the data actually written." Now, one could interpret that as "written to the socket," but actually, it returns the amount of data that was written to a buffer internal to the SSLContextRef instead. So it's possible for SSLWrite() to return errSSLWouldBlock and a number of bytes "written" because those bytes were encrypted and written to a buffer, not to the socket. So if this happens, then we need to keep calling SSLWrite() over and over again with no new data until it quits returning errSSLWouldBlock. */ /* Do we have buffered data to write from the last time we were called? */ if(BACKEND->ssl_write_buffered_length) { /* Write the buffered data: */ err = SSLWrite(BACKEND->ssl_ctx, NULL, 0UL, &processed); switch(err) { case noErr: /* processed is always going to be 0 because we didn't write to the buffer, so return how much was written to the socket */ processed = BACKEND->ssl_write_buffered_length; BACKEND->ssl_write_buffered_length = 0UL; break; case errSSLWouldBlock: /* argh, try again */ *curlcode = CURLE_AGAIN; return -1L; default: failf(conn->data, "SSLWrite() returned error %d", err); *curlcode = CURLE_SEND_ERROR; return -1L; } } else { /* We've got new data to write: */ err = SSLWrite(BACKEND->ssl_ctx, mem, len, &processed); if(err != noErr) { switch(err) { case errSSLWouldBlock: /* Data was buffered but not sent, we have to tell the caller to try sending again, and remember how much was buffered */ BACKEND->ssl_write_buffered_length = len; *curlcode = CURLE_AGAIN; return -1L; default: failf(conn->data, "SSLWrite() returned error %d", err); *curlcode = CURLE_SEND_ERROR; return -1L; } } } return (ssize_t)processed; } static ssize_t sectransp_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { /*struct Curl_easy *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[num]; size_t processed = 0UL; OSStatus err = SSLRead(BACKEND->ssl_ctx, buf, buffersize, &processed); if(err != noErr) { switch(err) { case errSSLWouldBlock: /* return how much we read (if anything) */ if(processed) return (ssize_t)processed; *curlcode = CURLE_AGAIN; return -1L; break; /* errSSLClosedGraceful - server gracefully shut down the SSL session errSSLClosedNoNotify - server hung up on us instead of sending a closure alert notice, read() is returning 0 Either way, inform the caller that the server disconnected. */ case errSSLClosedGraceful: case errSSLClosedNoNotify: *curlcode = CURLE_OK; return -1L; break; default: failf(conn->data, "SSLRead() return error %d", err); *curlcode = CURLE_RECV_ERROR; return -1L; break; } } return (ssize_t)processed; } static void *Curl_sectransp_get_internals(struct ssl_connect_data *connssl, CURLINFO info UNUSED_PARAM) { (void)info; return BACKEND->ssl_ctx; } const struct Curl_ssl Curl_ssl_sectransp = { { CURLSSLBACKEND_SECURETRANSPORT, "secure-transport" }, /* info */ #ifdef SECTRANSP_PINNEDPUBKEY SSLSUPP_PINNEDPUBKEY, #else 0, #endif /* SECTRANSP_PINNEDPUBKEY */ sizeof(struct ssl_backend_data), Curl_none_init, /* init */ Curl_none_cleanup, /* cleanup */ Curl_sectransp_version, /* version */ Curl_sectransp_check_cxn, /* check_cxn */ Curl_sectransp_shutdown, /* shutdown */ Curl_sectransp_data_pending, /* data_pending */ Curl_sectransp_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_sectransp_connect, /* connect */ Curl_sectransp_connect_nonblocking, /* connect_nonblocking */ Curl_sectransp_get_internals, /* get_internals */ Curl_sectransp_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_sectransp_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_sectransp_false_start, /* false_start */ Curl_sectransp_md5sum, /* md5sum */ Curl_sectransp_sha256sum /* sha256sum */ }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif /* USE_SECTRANSP */
YifuLiu/AliOS-Things
components/curl/lib/vtls/sectransp.c
C
apache-2.0
110,790
#ifndef HEADER_CURL_SECTRANSP_H #define HEADER_CURL_SECTRANSP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2014, Nick Zitzmann, <nickzman@gmail.com>. * Copyright (C) 2012 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef USE_SECTRANSP extern const struct Curl_ssl Curl_ssl_sectransp; #endif /* USE_SECTRANSP */ #endif /* HEADER_CURL_SECTRANSP_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/sectransp.h
C
apache-2.0
1,318
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* This file is for implementing all "generic" SSL functions that all libcurl internals should use. It is then responsible for calling the proper "backend" function. SSL-functions in libcurl should call functions in this source file, and not to any specific SSL-layer. Curl_ssl_ - prefix for generic ones Note that this source code uses the functions of the configured SSL backend via the global Curl_ssl instance. "SSL/TLS Strong Encryption: An Introduction" https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html */ #include "curl_setup.h" #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include "urldata.h" #include "vtls.h" /* generic SSL protos etc */ #include "slist.h" #include "sendf.h" #include "strcase.h" #include "url.h" #include "progress.h" #include "share.h" #include "multiif.h" #include "timeval.h" #include "curl_md5.h" #include "warnless.h" #include "curl_base64.h" #include "curl_printf.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* convenience macro to check if this handle is using a shared SSL session */ #define SSLSESSION_SHARED(data) (data->share && \ (data->share->specifier & \ (1<<CURL_LOCK_DATA_SSL_SESSION))) #define CLONE_STRING(var) \ if(source->var) { \ dest->var = strdup(source->var); \ if(!dest->var) \ return FALSE; \ } \ else \ dest->var = NULL; bool Curl_ssl_config_matches(struct ssl_primary_config* data, struct ssl_primary_config* needle) { if((data->version == needle->version) && (data->version_max == needle->version_max) && (data->verifypeer == needle->verifypeer) && (data->verifyhost == needle->verifyhost) && (data->verifystatus == needle->verifystatus) && Curl_safe_strcasecompare(data->CApath, needle->CApath) && Curl_safe_strcasecompare(data->CAfile, needle->CAfile) && Curl_safe_strcasecompare(data->clientcert, needle->clientcert) && Curl_safe_strcasecompare(data->random_file, needle->random_file) && Curl_safe_strcasecompare(data->egdsocket, needle->egdsocket) && Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list) && Curl_safe_strcasecompare(data->cipher_list13, needle->cipher_list13)) return TRUE; return FALSE; } bool Curl_clone_primary_ssl_config(struct ssl_primary_config *source, struct ssl_primary_config *dest) { dest->version = source->version; dest->version_max = source->version_max; dest->verifypeer = source->verifypeer; dest->verifyhost = source->verifyhost; dest->verifystatus = source->verifystatus; dest->sessionid = source->sessionid; CLONE_STRING(CApath); CLONE_STRING(CAfile); CLONE_STRING(clientcert); CLONE_STRING(random_file); CLONE_STRING(egdsocket); CLONE_STRING(cipher_list); CLONE_STRING(cipher_list13); return TRUE; } void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc) { Curl_safefree(sslc->CApath); Curl_safefree(sslc->CAfile); Curl_safefree(sslc->clientcert); Curl_safefree(sslc->random_file); Curl_safefree(sslc->egdsocket); Curl_safefree(sslc->cipher_list); Curl_safefree(sslc->cipher_list13); } #ifdef USE_SSL static int multissl_init(const struct Curl_ssl *backend); #endif int Curl_ssl_backend(void) { #ifdef USE_SSL multissl_init(NULL); return Curl_ssl->info.id; #else return (int)CURLSSLBACKEND_NONE; #endif } #ifdef USE_SSL /* "global" init done? */ static bool init_ssl = FALSE; /** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */ int Curl_ssl_init(void) { /* make sure this is only done once */ if(init_ssl) return 1; init_ssl = TRUE; /* never again */ return Curl_ssl->init(); } /* Global cleanup */ void Curl_ssl_cleanup(void) { if(init_ssl) { /* only cleanup if we did a previous init */ Curl_ssl->cleanup(); init_ssl = FALSE; } } static bool ssl_prefs_check(struct Curl_easy *data) { /* check for CURLOPT_SSLVERSION invalid parameter value */ const long sslver = data->set.ssl.primary.version; if((sslver < 0) || (sslver >= CURL_SSLVERSION_LAST)) { failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION"); return FALSE; } switch(data->set.ssl.primary.version_max) { case CURL_SSLVERSION_MAX_NONE: case CURL_SSLVERSION_MAX_DEFAULT: break; default: if((data->set.ssl.primary.version_max >> 16) < sslver) { failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION"); return FALSE; } } return TRUE; } static CURLcode ssl_connect_init_proxy(struct connectdata *conn, int sockindex) { DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]); if(ssl_connection_complete == conn->ssl[sockindex].state && !conn->proxy_ssl[sockindex].use) { struct ssl_backend_data *pbdata; if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY)) return CURLE_NOT_BUILT_IN; /* The pointers to the ssl backend data, which is opaque here, are swapped rather than move the contents. */ pbdata = conn->proxy_ssl[sockindex].backend; conn->proxy_ssl[sockindex] = conn->ssl[sockindex]; memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex])); memset(pbdata, 0, Curl_ssl->sizeof_ssl_backend_data); conn->ssl[sockindex].backend = pbdata; } return CURLE_OK; } CURLcode Curl_ssl_connect(struct connectdata *conn, int sockindex) { CURLcode result; if(conn->bits.proxy_ssl_connected[sockindex]) { result = ssl_connect_init_proxy(conn, sockindex); if(result) return result; } if(!ssl_prefs_check(conn->data)) return CURLE_SSL_CONNECT_ERROR; /* mark this is being ssl-enabled from here on. */ conn->ssl[sockindex].use = TRUE; conn->ssl[sockindex].state = ssl_connection_negotiating; result = Curl_ssl->connect_blocking(conn, sockindex); if(!result) Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */ return result; } CURLcode Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { CURLcode result; if(conn->bits.proxy_ssl_connected[sockindex]) { result = ssl_connect_init_proxy(conn, sockindex); if(result) return result; } if(!ssl_prefs_check(conn->data)) return CURLE_SSL_CONNECT_ERROR; /* mark this is being ssl requested from here on. */ conn->ssl[sockindex].use = TRUE; result = Curl_ssl->connect_nonblocking(conn, sockindex, done); if(!result && *done) Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */ return result; } /* * Lock shared SSL session data */ void Curl_ssl_sessionid_lock(struct connectdata *conn) { if(SSLSESSION_SHARED(conn->data)) Curl_share_lock(conn->data, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE); } /* * Unlock shared SSL session data */ void Curl_ssl_sessionid_unlock(struct connectdata *conn) { if(SSLSESSION_SHARED(conn->data)) Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION); } /* * Check if there's a session ID for the given connection in the cache, and if * there's one suitable, it is provided. Returns TRUE when no entry matched. */ bool Curl_ssl_getsessionid(struct connectdata *conn, void **ssl_sessionid, size_t *idsize, /* set 0 if unknown */ int sockindex) { struct curl_ssl_session *check; struct Curl_easy *data = conn->data; size_t i; long *general_age; bool no_match = TRUE; const bool isProxy = CONNECT_PROXY_SSL(); struct ssl_primary_config * const ssl_config = isProxy ? &conn->proxy_ssl_config : &conn->ssl_config; const char * const name = isProxy ? conn->http_proxy.host.name : conn->host.name; int port = isProxy ? (int)conn->port : conn->remote_port; *ssl_sessionid = NULL; DEBUGASSERT(SSL_SET_OPTION(primary.sessionid)); if(!SSL_SET_OPTION(primary.sessionid)) /* session ID re-use is disabled */ return TRUE; /* Lock if shared */ if(SSLSESSION_SHARED(data)) general_age = &data->share->sessionage; else general_age = &data->state.sessionage; for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) { check = &data->state.session[i]; if(!check->sessionid) /* not session ID means blank entry */ continue; if(strcasecompare(name, check->name) && ((!conn->bits.conn_to_host && !check->conn_to_host) || (conn->bits.conn_to_host && check->conn_to_host && strcasecompare(conn->conn_to_host.name, check->conn_to_host))) && ((!conn->bits.conn_to_port && check->conn_to_port == -1) || (conn->bits.conn_to_port && check->conn_to_port != -1 && conn->conn_to_port == check->conn_to_port)) && (port == check->remote_port) && strcasecompare(conn->handler->scheme, check->scheme) && Curl_ssl_config_matches(ssl_config, &check->ssl_config)) { /* yes, we have a session ID! */ (*general_age)++; /* increase general age */ check->age = *general_age; /* set this as used in this age */ *ssl_sessionid = check->sessionid; if(idsize) *idsize = check->idsize; no_match = FALSE; break; } } return no_match; } /* * Kill a single session ID entry in the cache. */ void Curl_ssl_kill_session(struct curl_ssl_session *session) { if(session->sessionid) { /* defensive check */ /* free the ID the SSL-layer specific way */ Curl_ssl->session_free(session->sessionid); session->sessionid = NULL; session->age = 0; /* fresh */ Curl_free_primary_ssl_config(&session->ssl_config); Curl_safefree(session->name); Curl_safefree(session->conn_to_host); } } /* * Delete the given session ID from the cache. */ void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid) { size_t i; struct Curl_easy *data = conn->data; for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) { struct curl_ssl_session *check = &data->state.session[i]; if(check->sessionid == ssl_sessionid) { Curl_ssl_kill_session(check); break; } } } /* * Store session id in the session cache. The ID passed on to this function * must already have been extracted and allocated the proper way for the SSL * layer. Curl_XXXX_session_free() will be called to free/kill the session ID * later on. */ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, void *ssl_sessionid, size_t idsize, int sockindex) { size_t i; struct Curl_easy *data = conn->data; /* the mother of all structs */ struct curl_ssl_session *store = &data->state.session[0]; long oldest_age = data->state.session[0].age; /* zero if unused */ char *clone_host; char *clone_conn_to_host; int conn_to_port; long *general_age; const bool isProxy = CONNECT_PROXY_SSL(); struct ssl_primary_config * const ssl_config = isProxy ? &conn->proxy_ssl_config : &conn->ssl_config; DEBUGASSERT(SSL_SET_OPTION(primary.sessionid)); clone_host = strdup(isProxy ? conn->http_proxy.host.name : conn->host.name); if(!clone_host) return CURLE_OUT_OF_MEMORY; /* bail out */ if(conn->bits.conn_to_host) { clone_conn_to_host = strdup(conn->conn_to_host.name); if(!clone_conn_to_host) { free(clone_host); return CURLE_OUT_OF_MEMORY; /* bail out */ } } else clone_conn_to_host = NULL; if(conn->bits.conn_to_port) conn_to_port = conn->conn_to_port; else conn_to_port = -1; /* Now we should add the session ID and the host name to the cache, (remove the oldest if necessary) */ /* If using shared SSL session, lock! */ if(SSLSESSION_SHARED(data)) { general_age = &data->share->sessionage; } else { general_age = &data->state.sessionage; } /* find an empty slot for us, or find the oldest */ for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) && data->state.session[i].sessionid; i++) { if(data->state.session[i].age < oldest_age) { oldest_age = data->state.session[i].age; store = &data->state.session[i]; } } if(i == data->set.general_ssl.max_ssl_sessions) /* cache is full, we must "kill" the oldest entry! */ Curl_ssl_kill_session(store); else store = &data->state.session[i]; /* use this slot */ /* now init the session struct wisely */ store->sessionid = ssl_sessionid; store->idsize = idsize; store->age = *general_age; /* set current age */ /* free it if there's one already present */ free(store->name); free(store->conn_to_host); store->name = clone_host; /* clone host name */ store->conn_to_host = clone_conn_to_host; /* clone connect to host name */ store->conn_to_port = conn_to_port; /* connect to port number */ /* port number */ store->remote_port = isProxy ? (int)conn->port : conn->remote_port; store->scheme = conn->handler->scheme; if(!Curl_clone_primary_ssl_config(ssl_config, &store->ssl_config)) { store->sessionid = NULL; /* let caller free sessionid */ free(clone_host); free(clone_conn_to_host); return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } void Curl_ssl_close_all(struct Curl_easy *data) { /* kill the session ID cache if not shared */ if(data->state.session && !SSLSESSION_SHARED(data)) { size_t i; for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) /* the single-killer function handles empty table slots */ Curl_ssl_kill_session(&data->state.session[i]); /* free the cache data */ Curl_safefree(data->state.session); } Curl_ssl->close_all(data); } #if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \ defined(USE_SECTRANSP) || defined(USE_POLARSSL) || defined(USE_NSS) || \ defined(USE_MBEDTLS) || defined(USE_CYASSL) int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET]; if(!numsocks) return GETSOCK_BLANK; if(connssl->connecting_state == ssl_connect_2_writing) { /* write mode */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_WRITESOCK(0); } if(connssl->connecting_state == ssl_connect_2_reading) { /* read mode */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0); } return GETSOCK_BLANK; } #else int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { (void)conn; (void)socks; (void)numsocks; return GETSOCK_BLANK; } /* USE_OPENSSL || USE_GNUTLS || USE_SCHANNEL || USE_SECTRANSP || USE_NSS */ #endif void Curl_ssl_close(struct connectdata *conn, int sockindex) { DEBUGASSERT((sockindex <= 1) && (sockindex >= -1)); Curl_ssl->close_one(conn, sockindex); } CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex) { if(Curl_ssl->shut_down(conn, sockindex)) return CURLE_SSL_SHUTDOWN_FAILED; conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */ conn->ssl[sockindex].state = ssl_connection_none; conn->recv[sockindex] = Curl_recv_plain; conn->send[sockindex] = Curl_send_plain; return CURLE_OK; } /* Selects an SSL crypto engine */ CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine) { return Curl_ssl->set_engine(data, engine); } /* Selects the default SSL crypto engine */ CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data) { return Curl_ssl->set_engine_default(data); } /* Return list of OpenSSL crypto engine names. */ struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data) { return Curl_ssl->engines_list(data); } /* * This sets up a session ID cache to the specified size. Make sure this code * is agnostic to what underlying SSL technology we use. */ CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount) { struct curl_ssl_session *session; if(data->state.session) /* this is just a precaution to prevent multiple inits */ return CURLE_OK; session = calloc(amount, sizeof(struct curl_ssl_session)); if(!session) return CURLE_OUT_OF_MEMORY; /* store the info in the SSL section */ data->set.general_ssl.max_ssl_sessions = amount; data->state.session = session; data->state.sessionage = 1; /* this is brand new */ return CURLE_OK; } static size_t Curl_multissl_version(char *buffer, size_t size); size_t Curl_ssl_version(char *buffer, size_t size) { #ifdef CURL_WITH_MULTI_SSL return Curl_multissl_version(buffer, size); #else return Curl_ssl->version(buffer, size); #endif } /* * This function tries to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ int Curl_ssl_check_cxn(struct connectdata *conn) { return Curl_ssl->check_cxn(conn); } bool Curl_ssl_data_pending(const struct connectdata *conn, int connindex) { return Curl_ssl->data_pending(conn, connindex); } void Curl_ssl_free_certinfo(struct Curl_easy *data) { struct curl_certinfo *ci = &data->info.certs; if(ci->num_of_certs) { /* free all individual lists used */ int i; for(i = 0; i<ci->num_of_certs; i++) { curl_slist_free_all(ci->certinfo[i]); ci->certinfo[i] = NULL; } free(ci->certinfo); /* free the actual array too */ ci->certinfo = NULL; ci->num_of_certs = 0; } } CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num) { struct curl_certinfo *ci = &data->info.certs; struct curl_slist **table; /* Free any previous certificate information structures */ Curl_ssl_free_certinfo(data); /* Allocate the required certificate information structures */ table = calloc((size_t) num, sizeof(struct curl_slist *)); if(!table) return CURLE_OUT_OF_MEMORY; ci->num_of_certs = num; ci->certinfo = table; return CURLE_OK; } /* * 'value' is NOT a zero terminated string */ CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, int certnum, const char *label, const char *value, size_t valuelen) { struct curl_certinfo *ci = &data->info.certs; char *output; struct curl_slist *nl; CURLcode result = CURLE_OK; size_t labellen = strlen(label); size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */ output = malloc(outlen); if(!output) return CURLE_OUT_OF_MEMORY; /* sprintf the label and colon */ msnprintf(output, outlen, "%s:", label); /* memcpy the value (it might not be zero terminated) */ memcpy(&output[labellen + 1], value, valuelen); /* zero terminate the output */ output[labellen + 1 + valuelen] = 0; nl = Curl_slist_append_nodup(ci->certinfo[certnum], output); if(!nl) { free(output); curl_slist_free_all(ci->certinfo[certnum]); result = CURLE_OUT_OF_MEMORY; } ci->certinfo[certnum] = nl; return result; } /* * This is a convenience function for push_certinfo_len that takes a zero * terminated value. */ CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data, int certnum, const char *label, const char *value) { size_t valuelen = strlen(value); return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen); } CURLcode Curl_ssl_random(struct Curl_easy *data, unsigned char *entropy, size_t length) { return Curl_ssl->random(data, entropy, length); } /* * Public key pem to der conversion */ static CURLcode pubkey_pem_to_der(const char *pem, unsigned char **der, size_t *der_len) { char *stripped_pem, *begin_pos, *end_pos; size_t pem_count, stripped_pem_count = 0, pem_len; CURLcode result; /* if no pem, exit. */ if(!pem) return CURLE_BAD_CONTENT_ENCODING; begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----"); if(!begin_pos) return CURLE_BAD_CONTENT_ENCODING; pem_count = begin_pos - pem; /* Invalid if not at beginning AND not directly following \n */ if(0 != pem_count && '\n' != pem[pem_count - 1]) return CURLE_BAD_CONTENT_ENCODING; /* 26 is length of "-----BEGIN PUBLIC KEY-----" */ pem_count += 26; /* Invalid if not directly following \n */ end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----"); if(!end_pos) return CURLE_BAD_CONTENT_ENCODING; pem_len = end_pos - pem; stripped_pem = malloc(pem_len - pem_count + 1); if(!stripped_pem) return CURLE_OUT_OF_MEMORY; /* * Here we loop through the pem array one character at a time between the * correct indices, and place each character that is not '\n' or '\r' * into the stripped_pem array, which should represent the raw base64 string */ while(pem_count < pem_len) { if('\n' != pem[pem_count] && '\r' != pem[pem_count]) stripped_pem[stripped_pem_count++] = pem[pem_count]; ++pem_count; } /* Place the null terminator in the correct place */ stripped_pem[stripped_pem_count] = '\0'; result = Curl_base64_decode(stripped_pem, der, der_len); Curl_safefree(stripped_pem); return result; } /* * Generic pinned public key check. */ CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, const char *pinnedpubkey, const unsigned char *pubkey, size_t pubkeylen) { FILE *fp; unsigned char *buf = NULL, *pem_ptr = NULL; CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; /* if a path wasn't specified, don't pin */ if(!pinnedpubkey) return CURLE_OK; if(!pubkey || !pubkeylen) return result; /* only do this if pinnedpubkey starts with "sha256//", length 8 */ if(strncmp(pinnedpubkey, "sha256//", 8) == 0) { CURLcode encode; size_t encodedlen, pinkeylen; char *encoded, *pinkeycopy, *begin_pos, *end_pos; unsigned char *sha256sumdigest; if(!Curl_ssl->sha256sum) { /* without sha256 support, this cannot match */ return result; } /* compute sha256sum of public key */ sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH); if(!sha256sumdigest) return CURLE_OUT_OF_MEMORY; encode = Curl_ssl->sha256sum(pubkey, pubkeylen, sha256sumdigest, CURL_SHA256_DIGEST_LENGTH); if(encode != CURLE_OK) return encode; encode = Curl_base64_encode(data, (char *)sha256sumdigest, CURL_SHA256_DIGEST_LENGTH, &encoded, &encodedlen); Curl_safefree(sha256sumdigest); if(encode) return encode; infof(data, "\t public key hash: sha256//%s\n", encoded); /* it starts with sha256//, copy so we can modify it */ pinkeylen = strlen(pinnedpubkey) + 1; pinkeycopy = malloc(pinkeylen); if(!pinkeycopy) { Curl_safefree(encoded); return CURLE_OUT_OF_MEMORY; } memcpy(pinkeycopy, pinnedpubkey, pinkeylen); /* point begin_pos to the copy, and start extracting keys */ begin_pos = pinkeycopy; do { end_pos = strstr(begin_pos, ";sha256//"); /* * if there is an end_pos, null terminate, * otherwise it'll go to the end of the original string */ if(end_pos) end_pos[0] = '\0'; /* compare base64 sha256 digests, 8 is the length of "sha256//" */ if(encodedlen == strlen(begin_pos + 8) && !memcmp(encoded, begin_pos + 8, encodedlen)) { result = CURLE_OK; break; } /* * change back the null-terminator we changed earlier, * and look for next begin */ if(end_pos) { end_pos[0] = ';'; begin_pos = strstr(end_pos, "sha256//"); } } while(end_pos && begin_pos); Curl_safefree(encoded); Curl_safefree(pinkeycopy); return result; } fp = fopen(pinnedpubkey, "rb"); if(!fp) return result; do { long filesize; size_t size, pem_len; CURLcode pem_read; /* Determine the file's size */ if(fseek(fp, 0, SEEK_END)) break; filesize = ftell(fp); if(fseek(fp, 0, SEEK_SET)) break; if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE) break; /* * if the size of our certificate is bigger than the file * size then it can't match */ size = curlx_sotouz((curl_off_t) filesize); if(pubkeylen > size) break; /* * Allocate buffer for the pinned key * With 1 additional byte for null terminator in case of PEM key */ buf = malloc(size + 1); if(!buf) break; /* Returns number of elements read, which should be 1 */ if((int) fread(buf, size, 1, fp) != 1) break; /* If the sizes are the same, it can't be base64 encoded, must be der */ if(pubkeylen == size) { if(!memcmp(pubkey, buf, pubkeylen)) result = CURLE_OK; break; } /* * Otherwise we will assume it's PEM and try to decode it * after placing null terminator */ buf[size] = '\0'; pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len); /* if it wasn't read successfully, exit */ if(pem_read) break; /* * if the size of our certificate doesn't match the size of * the decoded file, they can't be the same, otherwise compare */ if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen)) result = CURLE_OK; } while(0); Curl_safefree(buf); Curl_safefree(pem_ptr); fclose(fp); return result; } #ifndef CURL_DISABLE_CRYPTO_AUTH CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len) { return Curl_ssl->md5sum(tmp, tmplen, md5sum, md5len); } #endif /* * Check whether the SSL backend supports the status_request extension. */ bool Curl_ssl_cert_status_request(void) { return Curl_ssl->cert_status_request(); } /* * Check whether the SSL backend supports false start. */ bool Curl_ssl_false_start(void) { return Curl_ssl->false_start(); } /* * Check whether the SSL backend supports setting TLS 1.3 cipher suites */ bool Curl_ssl_tls13_ciphersuites(void) { return Curl_ssl->supports & SSLSUPP_TLS13_CIPHERSUITES; } /* * Default implementations for unsupported functions. */ int Curl_none_init(void) { return 1; } void Curl_none_cleanup(void) { } int Curl_none_shutdown(struct connectdata *conn UNUSED_PARAM, int sockindex UNUSED_PARAM) { (void)conn; (void)sockindex; return 0; } int Curl_none_check_cxn(struct connectdata *conn UNUSED_PARAM) { (void)conn; return -1; } CURLcode Curl_none_random(struct Curl_easy *data UNUSED_PARAM, unsigned char *entropy UNUSED_PARAM, size_t length UNUSED_PARAM) { (void)data; (void)entropy; (void)length; return CURLE_NOT_BUILT_IN; } void Curl_none_close_all(struct Curl_easy *data UNUSED_PARAM) { (void)data; } void Curl_none_session_free(void *ptr UNUSED_PARAM) { (void)ptr; } bool Curl_none_data_pending(const struct connectdata *conn UNUSED_PARAM, int connindex UNUSED_PARAM) { (void)conn; (void)connindex; return 0; } bool Curl_none_cert_status_request(void) { return FALSE; } CURLcode Curl_none_set_engine(struct Curl_easy *data UNUSED_PARAM, const char *engine UNUSED_PARAM) { (void)data; (void)engine; return CURLE_NOT_BUILT_IN; } CURLcode Curl_none_set_engine_default(struct Curl_easy *data UNUSED_PARAM) { (void)data; return CURLE_NOT_BUILT_IN; } struct curl_slist *Curl_none_engines_list(struct Curl_easy *data UNUSED_PARAM) { (void)data; return (struct curl_slist *)NULL; } bool Curl_none_false_start(void) { return FALSE; } #ifndef CURL_DISABLE_CRYPTO_AUTH CURLcode Curl_none_md5sum(unsigned char *input, size_t inputlen, unsigned char *md5sum, size_t md5len UNUSED_PARAM) { MD5_context *MD5pw; (void)md5len; MD5pw = Curl_MD5_init(Curl_DIGEST_MD5); if(!MD5pw) return CURLE_OUT_OF_MEMORY; Curl_MD5_update(MD5pw, input, curlx_uztoui(inputlen)); Curl_MD5_final(MD5pw, md5sum); return CURLE_OK; } #else CURLcode Curl_none_md5sum(unsigned char *input UNUSED_PARAM, size_t inputlen UNUSED_PARAM, unsigned char *md5sum UNUSED_PARAM, size_t md5len UNUSED_PARAM) { (void)input; (void)inputlen; (void)md5sum; (void)md5len; return CURLE_NOT_BUILT_IN; } #endif static int Curl_multissl_init(void) { if(multissl_init(NULL)) return 1; return Curl_ssl->init(); } static CURLcode Curl_multissl_connect(struct connectdata *conn, int sockindex) { if(multissl_init(NULL)) return CURLE_FAILED_INIT; return Curl_ssl->connect_blocking(conn, sockindex); } static CURLcode Curl_multissl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { if(multissl_init(NULL)) return CURLE_FAILED_INIT; return Curl_ssl->connect_nonblocking(conn, sockindex, done); } static void *Curl_multissl_get_internals(struct ssl_connect_data *connssl, CURLINFO info) { if(multissl_init(NULL)) return NULL; return Curl_ssl->get_internals(connssl, info); } static void Curl_multissl_close(struct connectdata *conn, int sockindex) { if(multissl_init(NULL)) return; Curl_ssl->close_one(conn, sockindex); } static const struct Curl_ssl Curl_ssl_multi = { { CURLSSLBACKEND_NONE, "multi" }, /* info */ 0, /* supports nothing */ (size_t)-1, /* something insanely large to be on the safe side */ Curl_multissl_init, /* init */ Curl_none_cleanup, /* cleanup */ Curl_multissl_version, /* version */ Curl_none_check_cxn, /* check_cxn */ Curl_none_shutdown, /* shutdown */ Curl_none_data_pending, /* data_pending */ Curl_none_random, /* random */ Curl_none_cert_status_request, /* cert_status_request */ Curl_multissl_connect, /* connect */ Curl_multissl_connect_nonblocking, /* connect_nonblocking */ Curl_multissl_get_internals, /* get_internals */ Curl_multissl_close, /* close_one */ Curl_none_close_all, /* close_all */ Curl_none_session_free, /* session_free */ Curl_none_set_engine, /* set_engine */ Curl_none_set_engine_default, /* set_engine_default */ Curl_none_engines_list, /* engines_list */ Curl_none_false_start, /* false_start */ Curl_none_md5sum, /* md5sum */ NULL /* sha256sum */ }; const struct Curl_ssl *Curl_ssl = #if defined(CURL_WITH_MULTI_SSL) &Curl_ssl_multi; #elif defined(USE_CYASSL) &Curl_ssl_cyassl; #elif defined(USE_SECTRANSP) &Curl_ssl_sectransp; #elif defined(USE_GNUTLS) &Curl_ssl_gnutls; #elif defined(USE_GSKIT) &Curl_ssl_gskit; #elif defined(USE_MBEDTLS) &Curl_ssl_mbedtls; #elif defined(USE_NSS) &Curl_ssl_nss; #elif defined(USE_OPENSSL) &Curl_ssl_openssl; #elif defined(USE_POLARSSL) &Curl_ssl_polarssl; #elif defined(USE_SCHANNEL) &Curl_ssl_schannel; #elif defined(USE_MESALINK) &Curl_ssl_mesalink; #else #error "Missing struct Curl_ssl for selected SSL backend" #endif static const struct Curl_ssl *available_backends[] = { #if defined(USE_CYASSL) &Curl_ssl_cyassl, #endif #if defined(USE_SECTRANSP) &Curl_ssl_sectransp, #endif #if defined(USE_GNUTLS) &Curl_ssl_gnutls, #endif #if defined(USE_GSKIT) &Curl_ssl_gskit, #endif #if defined(USE_MBEDTLS) &Curl_ssl_mbedtls, #endif #if defined(USE_NSS) &Curl_ssl_nss, #endif #if defined(USE_OPENSSL) &Curl_ssl_openssl, #endif #if defined(USE_POLARSSL) &Curl_ssl_polarssl, #endif #if defined(USE_SCHANNEL) &Curl_ssl_schannel, #endif #if defined(USE_MESALINK) &Curl_ssl_mesalink, #endif NULL }; static size_t Curl_multissl_version(char *buffer, size_t size) { static const struct Curl_ssl *selected; static char backends[200]; static size_t total; const struct Curl_ssl *current; current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl; if(current != selected) { char *p = backends; char *end = backends + sizeof(backends); int i; selected = current; for(i = 0; available_backends[i] && p < (end - 4); i++) { if(i) *(p++) = ' '; if(selected != available_backends[i]) *(p++) = '('; p += available_backends[i]->version(p, end - p - 2); if(selected != available_backends[i]) *(p++) = ')'; } *p = '\0'; total = p - backends; } if(size > total) memcpy(buffer, backends, total + 1); else { memcpy(buffer, backends, size - 1); buffer[size - 1] = '\0'; } return CURLMIN(size - 1, total); } static int multissl_init(const struct Curl_ssl *backend) { const char *env; char *env_tmp; if(Curl_ssl != &Curl_ssl_multi) return 1; if(backend) { Curl_ssl = backend; return 0; } if(!available_backends[0]) return 1; env = env_tmp = curl_getenv("CURL_SSL_BACKEND"); #ifdef CURL_DEFAULT_SSL_BACKEND if(!env) env = CURL_DEFAULT_SSL_BACKEND; #endif if(env) { int i; for(i = 0; available_backends[i]; i++) { if(strcasecompare(env, available_backends[i]->info.name)) { Curl_ssl = available_backends[i]; curl_free(env_tmp); return 0; } } } /* Fall back to first available backend */ Curl_ssl = available_backends[0]; curl_free(env_tmp); return 0; } CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, const curl_ssl_backend ***avail) { int i; if(avail) *avail = (const curl_ssl_backend **)&available_backends; if(Curl_ssl != &Curl_ssl_multi) return id == Curl_ssl->info.id || (name && strcasecompare(name, Curl_ssl->info.name)) ? CURLSSLSET_OK : #if defined(CURL_WITH_MULTI_SSL) CURLSSLSET_TOO_LATE; #else CURLSSLSET_UNKNOWN_BACKEND; #endif for(i = 0; available_backends[i]; i++) { if(available_backends[i]->info.id == id || (name && strcasecompare(available_backends[i]->info.name, name))) { multissl_init(available_backends[i]); return CURLSSLSET_OK; } } return CURLSSLSET_UNKNOWN_BACKEND; } #else /* USE_SSL */ CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, const curl_ssl_backend ***avail) { (void)id; (void)name; (void)avail; return CURLSSLSET_NO_BACKENDS; } #endif /* !USE_SSL */
YifuLiu/AliOS-Things
components/curl/lib/vtls/vtls.c
C
apache-2.0
36,523
#ifndef HEADER_CURL_VTLS_H #define HEADER_CURL_VTLS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" struct connectdata; struct ssl_connect_data; #define SSLSUPP_CA_PATH (1<<0) /* supports CAPATH */ #define SSLSUPP_CERTINFO (1<<1) /* supports CURLOPT_CERTINFO */ #define SSLSUPP_PINNEDPUBKEY (1<<2) /* supports CURLOPT_PINNEDPUBLICKEY */ #define SSLSUPP_SSL_CTX (1<<3) /* supports CURLOPT_SSL_CTX */ #define SSLSUPP_HTTPS_PROXY (1<<4) /* supports access via HTTPS proxies */ #define SSLSUPP_TLS13_CIPHERSUITES (1<<5) /* supports TLS 1.3 ciphersuites */ struct Curl_ssl { /* * This *must* be the first entry to allow returning the list of available * backends in curl_global_sslset(). */ curl_ssl_backend info; unsigned int supports; /* bitfield, see above */ size_t sizeof_ssl_backend_data; int (*init)(void); void (*cleanup)(void); size_t (*version)(char *buffer, size_t size); int (*check_cxn)(struct connectdata *cxn); int (*shut_down)(struct connectdata *conn, int sockindex); bool (*data_pending)(const struct connectdata *conn, int connindex); /* return 0 if a find random is filled in */ CURLcode (*random)(struct Curl_easy *data, unsigned char *entropy, size_t length); bool (*cert_status_request)(void); CURLcode (*connect_blocking)(struct connectdata *conn, int sockindex); CURLcode (*connect_nonblocking)(struct connectdata *conn, int sockindex, bool *done); void *(*get_internals)(struct ssl_connect_data *connssl, CURLINFO info); void (*close_one)(struct connectdata *conn, int sockindex); void (*close_all)(struct Curl_easy *data); void (*session_free)(void *ptr); CURLcode (*set_engine)(struct Curl_easy *data, const char *engine); CURLcode (*set_engine_default)(struct Curl_easy *data); struct curl_slist *(*engines_list)(struct Curl_easy *data); bool (*false_start)(void); CURLcode (*md5sum)(unsigned char *input, size_t inputlen, unsigned char *md5sum, size_t md5sumlen); CURLcode (*sha256sum)(const unsigned char *input, size_t inputlen, unsigned char *sha256sum, size_t sha256sumlen); }; #ifdef USE_SSL extern const struct Curl_ssl *Curl_ssl; #endif int Curl_none_init(void); void Curl_none_cleanup(void); int Curl_none_shutdown(struct connectdata *conn, int sockindex); int Curl_none_check_cxn(struct connectdata *conn); CURLcode Curl_none_random(struct Curl_easy *data, unsigned char *entropy, size_t length); void Curl_none_close_all(struct Curl_easy *data); void Curl_none_session_free(void *ptr); bool Curl_none_data_pending(const struct connectdata *conn, int connindex); bool Curl_none_cert_status_request(void); CURLcode Curl_none_set_engine(struct Curl_easy *data, const char *engine); CURLcode Curl_none_set_engine_default(struct Curl_easy *data); struct curl_slist *Curl_none_engines_list(struct Curl_easy *data); bool Curl_none_false_start(void); bool Curl_ssl_tls13_ciphersuites(void); CURLcode Curl_none_md5sum(unsigned char *input, size_t inputlen, unsigned char *md5sum, size_t md5len); #include "openssl.h" /* OpenSSL versions */ #include "gtls.h" /* GnuTLS versions */ #include "nssg.h" /* NSS versions */ #include "gskit.h" /* Global Secure ToolKit versions */ #include "polarssl.h" /* PolarSSL versions */ #include "cyassl.h" /* CyaSSL versions */ #include "schannel.h" /* Schannel SSPI version */ #include "sectransp.h" /* SecureTransport (Darwin) version */ #include "mbedtls.h" /* mbedTLS versions */ #include "mesalink.h" /* MesaLink versions */ #ifndef MAX_PINNED_PUBKEY_SIZE #define MAX_PINNED_PUBKEY_SIZE 1048576 /* 1MB */ #endif #ifndef MD5_DIGEST_LENGTH #ifndef LIBWOLFSSL_VERSION_HEX /* because WolfSSL borks this */ #define MD5_DIGEST_LENGTH 16 /* fixed size */ #endif #endif #ifndef CURL_SHA256_DIGEST_LENGTH #define CURL_SHA256_DIGEST_LENGTH 32 /* fixed size */ #endif /* see https://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-04 */ #define ALPN_HTTP_1_1_LENGTH 8 #define ALPN_HTTP_1_1 "http/1.1" /* set of helper macros for the backends to access the correct fields. For the proxy or for the remote host - to properly support HTTPS proxy */ #define SSL_IS_PROXY() (CURLPROXY_HTTPS == conn->http_proxy.proxytype && \ ssl_connection_complete != conn->proxy_ssl[conn->sock[SECONDARYSOCKET] == \ CURL_SOCKET_BAD ? FIRSTSOCKET : SECONDARYSOCKET].state) #define SSL_SET_OPTION(var) (SSL_IS_PROXY() ? data->set.proxy_ssl.var : \ data->set.ssl.var) #define SSL_CONN_CONFIG(var) (SSL_IS_PROXY() ? \ conn->proxy_ssl_config.var : conn->ssl_config.var) bool Curl_ssl_config_matches(struct ssl_primary_config* data, struct ssl_primary_config* needle); bool Curl_clone_primary_ssl_config(struct ssl_primary_config *source, struct ssl_primary_config *dest); void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc); int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks); int Curl_ssl_backend(void); #ifdef USE_SSL int Curl_ssl_init(void); void Curl_ssl_cleanup(void); CURLcode Curl_ssl_connect(struct connectdata *conn, int sockindex); CURLcode Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done); /* tell the SSL stuff to close down all open information regarding connections (and thus session ID caching etc) */ void Curl_ssl_close_all(struct Curl_easy *data); void Curl_ssl_close(struct connectdata *conn, int sockindex); CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex); CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine); /* Sets engine as default for all SSL operations */ CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data); struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data); /* init the SSL session ID cache */ CURLcode Curl_ssl_initsessions(struct Curl_easy *, size_t); size_t Curl_ssl_version(char *buffer, size_t size); bool Curl_ssl_data_pending(const struct connectdata *conn, int connindex); int Curl_ssl_check_cxn(struct connectdata *conn); /* Certificate information list handling. */ void Curl_ssl_free_certinfo(struct Curl_easy *data); CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num); CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data, int certnum, const char *label, const char *value, size_t valuelen); CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data, int certnum, const char *label, const char *value); /* Functions to be used by SSL library adaptation functions */ /* Lock session cache mutex. * Call this before calling other Curl_ssl_*session* functions * Caller should unlock this mutex as soon as possible, as it may block * other SSL connection from making progress. * The purpose of explicitly locking SSL session cache data is to allow * individual SSL engines to manage session lifetime in their specific way. */ void Curl_ssl_sessionid_lock(struct connectdata *conn); /* Unlock session cache mutex */ void Curl_ssl_sessionid_unlock(struct connectdata *conn); /* extract a session ID * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). * Caller must make sure that the ownership of returned sessionid object * is properly taken (e.g. its refcount is incremented * under sessionid mutex). */ bool Curl_ssl_getsessionid(struct connectdata *conn, void **ssl_sessionid, size_t *idsize, /* set 0 if unknown */ int sockindex); /* add a new session ID * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). * Caller must ensure that it has properly shared ownership of this sessionid * object with cache (e.g. incrementing refcount on success) */ CURLcode Curl_ssl_addsessionid(struct connectdata *conn, void *ssl_sessionid, size_t idsize, int sockindex); /* Kill a single session ID entry in the cache * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). * This will call engine-specific curlssl_session_free function, which must * take sessionid object ownership from sessionid cache * (e.g. decrement refcount). */ void Curl_ssl_kill_session(struct curl_ssl_session *session); /* delete a session from the cache * Sessionid mutex must be locked (see Curl_ssl_sessionid_lock). * This will call engine-specific curlssl_session_free function, which must * take sessionid object ownership from sessionid cache * (e.g. decrement refcount). */ void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid); /* get N random bytes into the buffer */ CURLcode Curl_ssl_random(struct Curl_easy *data, unsigned char *buffer, size_t length); CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len); /* Check pinned public key. */ CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data, const char *pinnedpubkey, const unsigned char *pubkey, size_t pubkeylen); bool Curl_ssl_cert_status_request(void); bool Curl_ssl_false_start(void); #define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */ #else /* if not USE_SSL */ /* When SSL support is not present, just define away these function calls */ #define Curl_ssl_init() 1 #define Curl_ssl_cleanup() Curl_nop_stmt #define Curl_ssl_connect(x,y) CURLE_NOT_BUILT_IN #define Curl_ssl_close_all(x) Curl_nop_stmt #define Curl_ssl_close(x,y) Curl_nop_stmt #define Curl_ssl_shutdown(x,y) CURLE_NOT_BUILT_IN #define Curl_ssl_set_engine(x,y) CURLE_NOT_BUILT_IN #define Curl_ssl_set_engine_default(x) CURLE_NOT_BUILT_IN #define Curl_ssl_engines_list(x) NULL #define Curl_ssl_send(a,b,c,d,e) -1 #define Curl_ssl_recv(a,b,c,d,e) -1 #define Curl_ssl_initsessions(x,y) CURLE_OK #define Curl_ssl_version(x,y) 0 #define Curl_ssl_data_pending(x,y) 0 #define Curl_ssl_check_cxn(x) 0 #define Curl_ssl_free_certinfo(x) Curl_nop_stmt #define Curl_ssl_connect_nonblocking(x,y,z) CURLE_NOT_BUILT_IN #define Curl_ssl_kill_session(x) Curl_nop_stmt #define Curl_ssl_random(x,y,z) ((void)x, CURLE_NOT_BUILT_IN) #define Curl_ssl_cert_status_request() FALSE #define Curl_ssl_false_start() FALSE #define Curl_ssl_tls13_ciphersuites() FALSE #endif #endif /* HEADER_CURL_VTLS_H */
YifuLiu/AliOS-Things
components/curl/lib/vtls/vtls.h
C
apache-2.0
11,880
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(__INTEL_COMPILER) && defined(__unix__) #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #endif /* __INTEL_COMPILER && __unix__ */ #define BUILDING_WARNLESS_C 1 #include "warnless.h" #define CURL_MASK_SCHAR 0x7F #define CURL_MASK_UCHAR 0xFF #if (SIZEOF_SHORT == 2) # define CURL_MASK_SSHORT 0x7FFF # define CURL_MASK_USHORT 0xFFFF #elif (SIZEOF_SHORT == 4) # define CURL_MASK_SSHORT 0x7FFFFFFF # define CURL_MASK_USHORT 0xFFFFFFFF #elif (SIZEOF_SHORT == 8) # define CURL_MASK_SSHORT 0x7FFFFFFFFFFFFFFF # define CURL_MASK_USHORT 0xFFFFFFFFFFFFFFFF #else # error "SIZEOF_SHORT not defined" #endif #if (SIZEOF_INT == 2) # define CURL_MASK_SINT 0x7FFF # define CURL_MASK_UINT 0xFFFF #elif (SIZEOF_INT == 4) # define CURL_MASK_SINT 0x7FFFFFFF # define CURL_MASK_UINT 0xFFFFFFFF #elif (SIZEOF_INT == 8) # define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFF # define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFF #elif (SIZEOF_INT == 16) # define CURL_MASK_SINT 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF # define CURL_MASK_UINT 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF #else # error "SIZEOF_INT not defined" #endif #if (SIZEOF_LONG == 2) # define CURL_MASK_SLONG 0x7FFFL # define CURL_MASK_ULONG 0xFFFFUL #elif (SIZEOF_LONG == 4) # define CURL_MASK_SLONG 0x7FFFFFFFL # define CURL_MASK_ULONG 0xFFFFFFFFUL #elif (SIZEOF_LONG == 8) # define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFL # define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFUL #elif (SIZEOF_LONG == 16) # define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL # define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFUL #else # error "SIZEOF_LONG not defined" #endif #if (SIZEOF_CURL_OFF_T == 2) # define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFF) # define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFF) #elif (SIZEOF_CURL_OFF_T == 4) # define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFF) # define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFF) #elif (SIZEOF_CURL_OFF_T == 8) # define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF) # define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFF) #elif (SIZEOF_CURL_OFF_T == 16) # define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) # define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) #else # error "SIZEOF_CURL_OFF_T not defined" #endif #if (SIZEOF_SIZE_T == SIZEOF_SHORT) # define CURL_MASK_SSIZE_T CURL_MASK_SSHORT # define CURL_MASK_USIZE_T CURL_MASK_USHORT #elif (SIZEOF_SIZE_T == SIZEOF_INT) # define CURL_MASK_SSIZE_T CURL_MASK_SINT # define CURL_MASK_USIZE_T CURL_MASK_UINT #elif (SIZEOF_SIZE_T == SIZEOF_LONG) # define CURL_MASK_SSIZE_T CURL_MASK_SLONG # define CURL_MASK_USIZE_T CURL_MASK_ULONG #elif (SIZEOF_SIZE_T == SIZEOF_CURL_OFF_T) # define CURL_MASK_SSIZE_T CURL_MASK_SCOFFT # define CURL_MASK_USIZE_T CURL_MASK_UCOFFT #else # error "SIZEOF_SIZE_T not defined" #endif /* ** unsigned long to unsigned short */ unsigned short curlx_ultous(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_USHORT); return (unsigned short)(ulnum & (unsigned long) CURL_MASK_USHORT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned long to unsigned char */ unsigned char curlx_ultouc(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_UCHAR); return (unsigned char)(ulnum & (unsigned long) CURL_MASK_UCHAR); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned long to signed int */ int curlx_ultosi(unsigned long ulnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(ulnum <= (unsigned long) CURL_MASK_SINT); return (int)(ulnum & (unsigned long) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned size_t to signed curl_off_t */ curl_off_t curlx_uztoso(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #elif defined(_MSC_VER) # pragma warning(push) # pragma warning(disable:4310) /* cast truncates constant value */ #endif DEBUGASSERT(uznum <= (size_t) CURL_MASK_SCOFFT); return (curl_off_t)(uznum & (size_t) CURL_MASK_SCOFFT); #if defined(__INTEL_COMPILER) || defined(_MSC_VER) # pragma warning(pop) #endif } /* ** unsigned size_t to signed int */ int curlx_uztosi(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(uznum <= (size_t) CURL_MASK_SINT); return (int)(uznum & (size_t) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned size_t to unsigned long */ unsigned long curlx_uztoul(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif #if (SIZEOF_LONG < SIZEOF_SIZE_T) DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG); #endif return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned size_t to unsigned int */ unsigned int curlx_uztoui(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif #if (SIZEOF_INT < SIZEOF_SIZE_T) DEBUGASSERT(uznum <= (size_t) CURL_MASK_UINT); #endif return (unsigned int)(uznum & (size_t) CURL_MASK_UINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed long to signed int */ int curlx_sltosi(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); #if (SIZEOF_INT < SIZEOF_LONG) DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT); #endif return (int)(slnum & (long) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed long to unsigned int */ unsigned int curlx_sltoui(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); #if (SIZEOF_INT < SIZEOF_LONG) DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT); #endif return (unsigned int)(slnum & (long) CURL_MASK_UINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed long to unsigned short */ unsigned short curlx_sltous(long slnum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(slnum >= 0); DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_USHORT); return (unsigned short)(slnum & (long) CURL_MASK_USHORT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned size_t to signed ssize_t */ ssize_t curlx_uztosz(size_t uznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(uznum <= (size_t) CURL_MASK_SSIZE_T); return (ssize_t)(uznum & (size_t) CURL_MASK_SSIZE_T); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed curl_off_t to unsigned size_t */ size_t curlx_sotouz(curl_off_t sonum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sonum >= 0); return (size_t)(sonum & (curl_off_t) CURL_MASK_USIZE_T); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed ssize_t to signed int */ int curlx_sztosi(ssize_t sznum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sznum >= 0); #if (SIZEOF_INT < SIZEOF_SIZE_T) DEBUGASSERT((size_t) sznum <= (size_t) CURL_MASK_SINT); #endif return (int)(sznum & (ssize_t) CURL_MASK_SINT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** unsigned int to unsigned short */ unsigned short curlx_uitous(unsigned int uinum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(uinum <= (unsigned int) CURL_MASK_USHORT); return (unsigned short) (uinum & (unsigned int) CURL_MASK_USHORT); #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } /* ** signed int to unsigned size_t */ size_t curlx_sitouz(int sinum) { #ifdef __INTEL_COMPILER # pragma warning(push) # pragma warning(disable:810) /* conversion may lose significant bits */ #endif DEBUGASSERT(sinum >= 0); return (size_t) sinum; #ifdef __INTEL_COMPILER # pragma warning(pop) #endif } #ifdef USE_WINSOCK /* ** curl_socket_t to signed int */ int curlx_sktosi(curl_socket_t s) { return (int)((ssize_t) s); } /* ** signed int to curl_socket_t */ curl_socket_t curlx_sitosk(int i) { return (curl_socket_t)((ssize_t) i); } #endif /* USE_WINSOCK */ #if defined(WIN32) || defined(_WIN32) ssize_t curlx_read(int fd, void *buf, size_t count) { return (ssize_t)read(fd, buf, curlx_uztoui(count)); } ssize_t curlx_write(int fd, const void *buf, size_t count) { return (ssize_t)write(fd, buf, curlx_uztoui(count)); } #endif /* WIN32 || _WIN32 */ #if defined(__INTEL_COMPILER) && defined(__unix__) int curlx_FD_ISSET(int fd, fd_set *fdset) { #pragma warning(push) #pragma warning(disable:1469) /* clobber ignored */ return FD_ISSET(fd, fdset); #pragma warning(pop) } void curlx_FD_SET(int fd, fd_set *fdset) { #pragma warning(push) #pragma warning(disable:1469) /* clobber ignored */ FD_SET(fd, fdset); #pragma warning(pop) } void curlx_FD_ZERO(fd_set *fdset) { #pragma warning(push) #pragma warning(disable:593) /* variable was set but never used */ FD_ZERO(fdset); #pragma warning(pop) } unsigned short curlx_htons(unsigned short usnum) { #if (__INTEL_COMPILER == 910) && defined(__i386__) return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF)); #else #pragma warning(push) #pragma warning(disable:810) /* conversion may lose significant bits */ return htons(usnum); #pragma warning(pop) #endif } unsigned short curlx_ntohs(unsigned short usnum) { #if (__INTEL_COMPILER == 910) && defined(__i386__) return (unsigned short)(((usnum << 8) & 0xFF00) | ((usnum >> 8) & 0x00FF)); #else #pragma warning(push) #pragma warning(disable:810) /* conversion may lose significant bits */ return ntohs(usnum); #pragma warning(pop) #endif } #endif /* __INTEL_COMPILER && __unix__ */
YifuLiu/AliOS-Things
components/curl/lib/warnless.c
C
apache-2.0
11,981
#ifndef HEADER_CURL_WARNLESS_H #define HEADER_CURL_WARNLESS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef USE_WINSOCK #include <curl/curl.h> /* for curl_socket_t */ #endif #define CURLX_FUNCTION_CAST(target_type, func) \ (target_type)(void (*) (void))(func) unsigned short curlx_ultous(unsigned long ulnum); unsigned char curlx_ultouc(unsigned long ulnum); int curlx_ultosi(unsigned long ulnum); int curlx_uztosi(size_t uznum); curl_off_t curlx_uztoso(size_t uznum); unsigned long curlx_uztoul(size_t uznum); unsigned int curlx_uztoui(size_t uznum); int curlx_sltosi(long slnum); unsigned int curlx_sltoui(long slnum); unsigned short curlx_sltous(long slnum); ssize_t curlx_uztosz(size_t uznum); size_t curlx_sotouz(curl_off_t sonum); int curlx_sztosi(ssize_t sznum); unsigned short curlx_uitous(unsigned int uinum); size_t curlx_sitouz(int sinum); #ifdef USE_WINSOCK int curlx_sktosi(curl_socket_t s); curl_socket_t curlx_sitosk(int i); #endif /* USE_WINSOCK */ #if defined(WIN32) || defined(_WIN32) ssize_t curlx_read(int fd, void *buf, size_t count); ssize_t curlx_write(int fd, const void *buf, size_t count); #ifndef BUILDING_WARNLESS_C # undef read # define read(fd, buf, count) curlx_read(fd, buf, count) # undef write # define write(fd, buf, count) curlx_write(fd, buf, count) #endif #endif /* WIN32 || _WIN32 */ #if defined(__INTEL_COMPILER) && defined(__unix__) int curlx_FD_ISSET(int fd, fd_set *fdset); void curlx_FD_SET(int fd, fd_set *fdset); void curlx_FD_ZERO(fd_set *fdset); unsigned short curlx_htons(unsigned short usnum); unsigned short curlx_ntohs(unsigned short usnum); #ifndef BUILDING_WARNLESS_C # undef FD_ISSET # define FD_ISSET(a,b) curlx_FD_ISSET((a),(b)) # undef FD_SET # define FD_SET(a,b) curlx_FD_SET((a),(b)) # undef FD_ZERO # define FD_ZERO(a) curlx_FD_ZERO((a)) # undef htons # define htons(a) curlx_htons((a)) # undef ntohs # define ntohs(a) curlx_ntohs((a)) #endif #endif /* __INTEL_COMPILER && __unix__ */ #endif /* HEADER_CURL_WARNLESS_H */
YifuLiu/AliOS-Things
components/curl/lib/warnless.h
C
apache-2.0
3,043
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #include "wildcard.h" #include "llist.h" #include "fileinfo.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" static void fileinfo_dtor(void *user, void *element) { (void)user; Curl_fileinfo_cleanup(element); } CURLcode Curl_wildcard_init(struct WildcardData *wc) { Curl_llist_init(&wc->filelist, fileinfo_dtor); wc->state = CURLWC_INIT; return CURLE_OK; } void Curl_wildcard_dtor(struct WildcardData *wc) { if(!wc) return; if(wc->dtor) { wc->dtor(wc->protdata); wc->dtor = ZERO_NULL; wc->protdata = NULL; } DEBUGASSERT(wc->protdata == NULL); Curl_llist_destroy(&wc->filelist, NULL); free(wc->path); wc->path = NULL; free(wc->pattern); wc->pattern = NULL; wc->customptr = NULL; wc->state = CURLWC_INIT; } #endif /* if disabled */
YifuLiu/AliOS-Things
components/curl/lib/wildcard.c
C
apache-2.0
1,947
#ifndef HEADER_CURL_WILDCARD_H #define HEADER_CURL_WILDCARD_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_FTP #include "llist.h" /* list of wildcard process states */ typedef enum { CURLWC_CLEAR = 0, CURLWC_INIT = 1, CURLWC_MATCHING, /* library is trying to get list of addresses for downloading */ CURLWC_DOWNLOADING, CURLWC_CLEAN, /* deallocate resources and reset settings */ CURLWC_SKIP, /* skip over concrete file */ CURLWC_ERROR, /* error cases */ CURLWC_DONE /* if is wildcard->state == CURLWC_DONE wildcard loop will end */ } curl_wildcard_states; typedef void (*curl_wildcard_dtor)(void *ptr); /* struct keeping information about wildcard download process */ struct WildcardData { curl_wildcard_states state; char *path; /* path to the directory, where we trying wildcard-match */ char *pattern; /* wildcard pattern */ struct curl_llist filelist; /* llist with struct Curl_fileinfo */ void *protdata; /* pointer to protocol specific temporary data */ curl_wildcard_dtor dtor; void *customptr; /* for CURLOPT_CHUNK_DATA pointer */ }; CURLcode Curl_wildcard_init(struct WildcardData *wc); void Curl_wildcard_dtor(struct WildcardData *wc); struct Curl_easy; #else /* FTP is disabled */ #define Curl_wildcard_dtor(x) #endif #endif /* HEADER_CURL_WILDCARD_H */
YifuLiu/AliOS-Things
components/curl/lib/wildcard.h
C
apache-2.0
2,376
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \ defined(USE_CYASSL) || defined(USE_SCHANNEL) #include <curl/curl.h> #include "urldata.h" #include "strcase.h" #include "hostcheck.h" #include "vtls/vtls.h" #include "sendf.h" #include "inet_pton.h" #include "curl_base64.h" #include "x509asn1.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* ASN.1 OIDs. */ static const char cnOID[] = "2.5.4.3"; /* Common name. */ static const char sanOID[] = "2.5.29.17"; /* Subject alternative name. */ static const curl_OID OIDtable[] = { { "1.2.840.10040.4.1", "dsa" }, { "1.2.840.10040.4.3", "dsa-with-sha1" }, { "1.2.840.10045.2.1", "ecPublicKey" }, { "1.2.840.10045.3.0.1", "c2pnb163v1" }, { "1.2.840.10045.4.1", "ecdsa-with-SHA1" }, { "1.2.840.10046.2.1", "dhpublicnumber" }, { "1.2.840.113549.1.1.1", "rsaEncryption" }, { "1.2.840.113549.1.1.2", "md2WithRSAEncryption" }, { "1.2.840.113549.1.1.4", "md5WithRSAEncryption" }, { "1.2.840.113549.1.1.5", "sha1WithRSAEncryption" }, { "1.2.840.113549.1.1.10", "RSASSA-PSS" }, { "1.2.840.113549.1.1.14", "sha224WithRSAEncryption" }, { "1.2.840.113549.1.1.11", "sha256WithRSAEncryption" }, { "1.2.840.113549.1.1.12", "sha384WithRSAEncryption" }, { "1.2.840.113549.1.1.13", "sha512WithRSAEncryption" }, { "1.2.840.113549.2.2", "md2" }, { "1.2.840.113549.2.5", "md5" }, { "1.3.14.3.2.26", "sha1" }, { cnOID, "CN" }, { "2.5.4.4", "SN" }, { "2.5.4.5", "serialNumber" }, { "2.5.4.6", "C" }, { "2.5.4.7", "L" }, { "2.5.4.8", "ST" }, { "2.5.4.9", "streetAddress" }, { "2.5.4.10", "O" }, { "2.5.4.11", "OU" }, { "2.5.4.12", "title" }, { "2.5.4.13", "description" }, { "2.5.4.17", "postalCode" }, { "2.5.4.41", "name" }, { "2.5.4.42", "givenName" }, { "2.5.4.43", "initials" }, { "2.5.4.44", "generationQualifier" }, { "2.5.4.45", "X500UniqueIdentifier" }, { "2.5.4.46", "dnQualifier" }, { "2.5.4.65", "pseudonym" }, { "1.2.840.113549.1.9.1", "emailAddress" }, { "2.5.4.72", "role" }, { sanOID, "subjectAltName" }, { "2.5.29.18", "issuerAltName" }, { "2.5.29.19", "basicConstraints" }, { "2.16.840.1.101.3.4.2.4", "sha224" }, { "2.16.840.1.101.3.4.2.1", "sha256" }, { "2.16.840.1.101.3.4.2.2", "sha384" }, { "2.16.840.1.101.3.4.2.3", "sha512" }, { (const char *) NULL, (const char *) NULL } }; /* * Lightweight ASN.1 parser. * In particular, it does not check for syntactic/lexical errors. * It is intended to support certificate information gathering for SSL backends * that offer a mean to get certificates as a whole, but do not supply * entry points to get particular certificate sub-fields. * Please note there is no pretention here to rewrite a full SSL library. */ static const char *getASN1Element(curl_asn1Element *elem, const char *beg, const char *end) WARN_UNUSED_RESULT; static const char *getASN1Element(curl_asn1Element *elem, const char *beg, const char *end) { unsigned char b; unsigned long len; curl_asn1Element lelem; /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg' ending at `end'. Returns a pointer in source string after the parsed element, or NULL if an error occurs. */ if(!beg || !end || beg >= end || !*beg || (size_t)(end - beg) > CURL_ASN1_MAX) return NULL; /* Process header byte. */ elem->header = beg; b = (unsigned char) *beg++; elem->constructed = (b & 0x20) != 0; elem->class = (b >> 6) & 3; b &= 0x1F; if(b == 0x1F) return NULL; /* Long tag values not supported here. */ elem->tag = b; /* Process length. */ if(beg >= end) return NULL; b = (unsigned char) *beg++; if(!(b & 0x80)) len = b; else if(!(b &= 0x7F)) { /* Unspecified length. Since we have all the data, we can determine the effective length by skipping element until an end element is found. */ if(!elem->constructed) return NULL; elem->beg = beg; while(beg < end && *beg) { beg = getASN1Element(&lelem, beg, end); if(!beg) return NULL; } if(beg >= end) return NULL; elem->end = beg; return beg + 1; } else if((unsigned)b > (size_t)(end - beg)) return NULL; /* Does not fit in source. */ else { /* Get long length. */ len = 0; do { if(len & 0xFF000000L) return NULL; /* Lengths > 32 bits are not supported. */ len = (len << 8) | (unsigned char) *beg++; } while(--b); } if(len > (size_t)(end - beg)) return NULL; /* Element data does not fit in source. */ elem->beg = beg; elem->end = beg + len; return elem->end; } /* * Search the null terminated OID or OID identifier in local table. * Return the table entry pointer or NULL if not found. */ static const curl_OID * searchOID(const char *oid) { const curl_OID *op; for(op = OIDtable; op->numoid; op++) if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid)) return op; return NULL; } /* * Convert an ASN.1 Boolean value into its string representation. Return the * dynamically allocated string, or NULL if source is not an ASN.1 Boolean * value. */ static const char *bool2str(const char *beg, const char *end) { if(end - beg != 1) return NULL; return strdup(*beg? "TRUE": "FALSE"); } /* * Convert an ASN.1 octet string to a printable string. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *octet2str(const char *beg, const char *end) { size_t n = end - beg; char *buf = NULL; if(n <= (SIZE_T_MAX - 1) / 3) { buf = malloc(3 * n + 1); if(buf) for(n = 0; beg < end; n += 3) msnprintf(buf + n, 4, "%02x:", *(const unsigned char *) beg++); } return buf; } static const char *bit2str(const char *beg, const char *end) { /* Convert an ASN.1 bit string to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ if(++beg > end) return NULL; return octet2str(beg, end); } /* * Convert an ASN.1 integer value into its string representation. * Return the dynamically allocated string, or NULL if source is not an * ASN.1 integer value. */ static const char *int2str(const char *beg, const char *end) { unsigned long val = 0; size_t n = end - beg; if(!n) return NULL; if(n > 4) return octet2str(beg, end); /* Represent integers <= 32-bit as a single value. */ if(*beg & 0x80) val = ~val; do val = (val << 8) | *(const unsigned char *) beg++; while(beg < end); return curl_maprintf("%s%lx", val >= 10? "0x": "", val); } /* * Perform a lazy conversion from an ASN.1 typed string to UTF8. Allocate the * destination buffer dynamically. The allocation size will normally be too * large: this is to avoid buffer overflows. * Terminate the string with a nul byte and return the converted * string length. */ static ssize_t utf8asn1str(char **to, int type, const char *from, const char *end) { size_t inlength = end - from; int size = 1; size_t outlength; char *buf; *to = NULL; switch(type) { case CURL_ASN1_BMP_STRING: size = 2; break; case CURL_ASN1_UNIVERSAL_STRING: size = 4; break; case CURL_ASN1_NUMERIC_STRING: case CURL_ASN1_PRINTABLE_STRING: case CURL_ASN1_TELETEX_STRING: case CURL_ASN1_IA5_STRING: case CURL_ASN1_VISIBLE_STRING: case CURL_ASN1_UTF8_STRING: break; default: return -1; /* Conversion not supported. */ } if(inlength % size) return -1; /* Length inconsistent with character size. */ if(inlength / size > (SIZE_T_MAX - 1) / 4) return -1; /* Too big. */ buf = malloc(4 * (inlength / size) + 1); if(!buf) return -1; /* Not enough memory. */ if(type == CURL_ASN1_UTF8_STRING) { /* Just copy. */ outlength = inlength; if(outlength) memcpy(buf, from, outlength); } else { for(outlength = 0; from < end;) { int charsize; unsigned int wc; wc = 0; switch(size) { case 4: wc = (wc << 8) | *(const unsigned char *) from++; wc = (wc << 8) | *(const unsigned char *) from++; /* FALLTHROUGH */ case 2: wc = (wc << 8) | *(const unsigned char *) from++; /* FALLTHROUGH */ default: /* case 1: */ wc = (wc << 8) | *(const unsigned char *) from++; } charsize = 1; if(wc >= 0x00000080) { if(wc >= 0x00000800) { if(wc >= 0x00010000) { if(wc >= 0x00200000) { free(buf); return -1; /* Invalid char. size for target encoding. */ } buf[outlength + 3] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x00010000; charsize++; } buf[outlength + 2] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x00000800; charsize++; } buf[outlength + 1] = (char) (0x80 | (wc & 0x3F)); wc = (wc >> 6) | 0x000000C0; charsize++; } buf[outlength] = (char) wc; outlength += charsize; } } buf[outlength] = '\0'; *to = buf; return outlength; } /* * Convert an ASN.1 String into its UTF-8 string representation. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *string2str(int type, const char *beg, const char *end) { char *buf; if(utf8asn1str(&buf, type, beg, end) < 0) return NULL; return buf; } /* * Decimal ASCII encode unsigned integer `x' into the buflen sized buffer at * buf. Return the total number of encoded digits, even if larger than * `buflen'. */ static size_t encodeUint(char *buf, size_t buflen, unsigned int x) { size_t i = 0; unsigned int y = x / 10; if(y) { i = encodeUint(buf, buflen, y); x -= y * 10; } if(i < buflen) buf[i] = (char) ('0' + x); i++; if(i < buflen) buf[i] = '\0'; /* Store a terminator if possible. */ return i; } /* * Convert an ASN.1 OID into its dotted string representation. * Store the result in th `n'-byte buffer at `buf'. * Return the converted string length, or 0 on errors. */ static size_t encodeOID(char *buf, size_t buflen, const char *beg, const char *end) { size_t i; unsigned int x; unsigned int y; /* Process the first two numbers. */ y = *(const unsigned char *) beg++; x = y / 40; y -= x * 40; i = encodeUint(buf, buflen, x); if(i < buflen) buf[i] = '.'; i++; if(i >= buflen) i += encodeUint(NULL, 0, y); else i += encodeUint(buf + i, buflen - i, y); /* Process the trailing numbers. */ while(beg < end) { if(i < buflen) buf[i] = '.'; i++; x = 0; do { if(x & 0xFF000000) return 0; y = *(const unsigned char *) beg++; x = (x << 7) | (y & 0x7F); } while(y & 0x80); if(i >= buflen) i += encodeUint(NULL, 0, x); else i += encodeUint(buf + i, buflen - i, x); } if(i < buflen) buf[i] = '\0'; return i; } /* * Convert an ASN.1 OID into its dotted or symbolic string representation. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *OID2str(const char *beg, const char *end, bool symbolic) { char *buf = NULL; if(beg < end) { size_t buflen = encodeOID(NULL, 0, beg, end); if(buflen) { buf = malloc(buflen + 1); /* one extra for the zero byte */ if(buf) { encodeOID(buf, buflen, beg, end); buf[buflen] = '\0'; if(symbolic) { const curl_OID *op = searchOID(buf); if(op) { free(buf); buf = strdup(op->textoid); } } } } } return buf; } static const char *GTime2str(const char *beg, const char *end) { const char *tzp; const char *fracp; char sec1, sec2; size_t fracl; size_t tzl; const char *sep = ""; /* Convert an ASN.1 Generalized time to a printable string. Return the dynamically allocated string, or NULL if an error occurs. */ for(fracp = beg; fracp < end && *fracp >= '0' && *fracp <= '9'; fracp++) ; /* Get seconds digits. */ sec1 = '0'; switch(fracp - beg - 12) { case 0: sec2 = '0'; break; case 2: sec1 = fracp[-2]; /* FALLTHROUGH */ case 1: sec2 = fracp[-1]; break; default: return NULL; } /* Scan for timezone, measure fractional seconds. */ tzp = fracp; fracl = 0; if(fracp < end && (*fracp == '.' || *fracp == ',')) { fracp++; do tzp++; while(tzp < end && *tzp >= '0' && *tzp <= '9'); /* Strip leading zeroes in fractional seconds. */ for(fracl = tzp - fracp - 1; fracl && fracp[fracl - 1] == '0'; fracl--) ; } /* Process timezone. */ if(tzp >= end) ; /* Nothing to do. */ else if(*tzp == 'Z') { tzp = " GMT"; end = tzp + 4; } else { sep = " "; tzp++; } tzl = end - tzp; return curl_maprintf("%.4s-%.2s-%.2s %.2s:%.2s:%c%c%s%.*s%s%.*s", beg, beg + 4, beg + 6, beg + 8, beg + 10, sec1, sec2, fracl? ".": "", fracl, fracp, sep, tzl, tzp); } /* * Convert an ASN.1 UTC time to a printable string. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *UTime2str(const char *beg, const char *end) { const char *tzp; size_t tzl; const char *sec; for(tzp = beg; tzp < end && *tzp >= '0' && *tzp <= '9'; tzp++) ; /* Get the seconds. */ sec = beg + 10; switch(tzp - sec) { case 0: sec = "00"; case 2: break; default: return NULL; } /* Process timezone. */ if(tzp >= end) return NULL; if(*tzp == 'Z') { tzp = "GMT"; end = tzp + 3; } else tzp++; tzl = end - tzp; return curl_maprintf("%u%.2s-%.2s-%.2s %.2s:%.2s:%.2s %.*s", 20 - (*beg >= '5'), beg, beg + 2, beg + 4, beg + 6, beg + 8, sec, tzl, tzp); } /* * Convert an ASN.1 element to a printable string. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *ASN1tostr(curl_asn1Element *elem, int type) { if(elem->constructed) return NULL; /* No conversion of structured elements. */ if(!type) type = elem->tag; /* Type not forced: use element tag as type. */ switch(type) { case CURL_ASN1_BOOLEAN: return bool2str(elem->beg, elem->end); case CURL_ASN1_INTEGER: case CURL_ASN1_ENUMERATED: return int2str(elem->beg, elem->end); case CURL_ASN1_BIT_STRING: return bit2str(elem->beg, elem->end); case CURL_ASN1_OCTET_STRING: return octet2str(elem->beg, elem->end); case CURL_ASN1_NULL: return strdup(""); case CURL_ASN1_OBJECT_IDENTIFIER: return OID2str(elem->beg, elem->end, TRUE); case CURL_ASN1_UTC_TIME: return UTime2str(elem->beg, elem->end); case CURL_ASN1_GENERALIZED_TIME: return GTime2str(elem->beg, elem->end); case CURL_ASN1_UTF8_STRING: case CURL_ASN1_NUMERIC_STRING: case CURL_ASN1_PRINTABLE_STRING: case CURL_ASN1_TELETEX_STRING: case CURL_ASN1_IA5_STRING: case CURL_ASN1_VISIBLE_STRING: case CURL_ASN1_UNIVERSAL_STRING: case CURL_ASN1_BMP_STRING: return string2str(type, elem->beg, elem->end); } return NULL; /* Unsupported. */ } /* * ASCII encode distinguished name at `dn' into the `buflen'-sized buffer at * `buf'. Return the total string length, even if larger than `buflen'. */ static ssize_t encodeDN(char *buf, size_t buflen, curl_asn1Element *dn) { curl_asn1Element rdn; curl_asn1Element atv; curl_asn1Element oid; curl_asn1Element value; size_t l = 0; const char *p1; const char *p2; const char *p3; const char *str; for(p1 = dn->beg; p1 < dn->end;) { p1 = getASN1Element(&rdn, p1, dn->end); if(!p1) return -1; for(p2 = rdn.beg; p2 < rdn.end;) { p2 = getASN1Element(&atv, p2, rdn.end); if(!p2) return -1; p3 = getASN1Element(&oid, atv.beg, atv.end); if(!p3) return -1; if(!getASN1Element(&value, p3, atv.end)) return -1; str = ASN1tostr(&oid, 0); if(!str) return -1; /* Encode delimiter. If attribute has a short uppercase name, delimiter is ", ". */ if(l) { for(p3 = str; isupper(*p3); p3++) ; for(p3 = (*p3 || p3 - str > 2)? "/": ", "; *p3; p3++) { if(l < buflen) buf[l] = *p3; l++; } } /* Encode attribute name. */ for(p3 = str; *p3; p3++) { if(l < buflen) buf[l] = *p3; l++; } free((char *) str); /* Generate equal sign. */ if(l < buflen) buf[l] = '='; l++; /* Generate value. */ str = ASN1tostr(&value, 0); if(!str) return -1; for(p3 = str; *p3; p3++) { if(l < buflen) buf[l] = *p3; l++; } free((char *) str); } } return l; } /* * Convert an ASN.1 distinguished name into a printable string. * Return the dynamically allocated string, or NULL if an error occurs. */ static const char *DNtostr(curl_asn1Element *dn) { char *buf = NULL; ssize_t buflen = encodeDN(NULL, 0, dn); if(buflen >= 0) { buf = malloc(buflen + 1); if(buf) { encodeDN(buf, buflen + 1, dn); buf[buflen] = '\0'; } } return buf; } /* * ASN.1 parse an X509 certificate into structure subfields. * Syntax is assumed to have already been checked by the SSL backend. * See RFC 5280. */ int Curl_parseX509(curl_X509certificate *cert, const char *beg, const char *end) { curl_asn1Element elem; curl_asn1Element tbsCertificate; const char *ccp; static const char defaultVersion = 0; /* v1. */ cert->certificate.header = NULL; cert->certificate.beg = beg; cert->certificate.end = end; /* Get the sequence content. */ if(!getASN1Element(&elem, beg, end)) return -1; /* Invalid bounds/size. */ beg = elem.beg; end = elem.end; /* Get tbsCertificate. */ beg = getASN1Element(&tbsCertificate, beg, end); if(!beg) return -1; /* Skip the signatureAlgorithm. */ beg = getASN1Element(&cert->signatureAlgorithm, beg, end); if(!beg) return -1; /* Get the signatureValue. */ if(!getASN1Element(&cert->signature, beg, end)) return -1; /* Parse TBSCertificate. */ beg = tbsCertificate.beg; end = tbsCertificate.end; /* Get optional version, get serialNumber. */ cert->version.header = NULL; cert->version.beg = &defaultVersion; cert->version.end = &defaultVersion + sizeof(defaultVersion); beg = getASN1Element(&elem, beg, end); if(!beg) return -1; if(elem.tag == 0) { if(!getASN1Element(&cert->version, elem.beg, elem.end)) return -1; beg = getASN1Element(&elem, beg, end); if(!beg) return -1; } cert->serialNumber = elem; /* Get signature algorithm. */ beg = getASN1Element(&cert->signatureAlgorithm, beg, end); /* Get issuer. */ beg = getASN1Element(&cert->issuer, beg, end); if(!beg) return -1; /* Get notBefore and notAfter. */ beg = getASN1Element(&elem, beg, end); if(!beg) return -1; ccp = getASN1Element(&cert->notBefore, elem.beg, elem.end); if(!ccp) return -1; if(!getASN1Element(&cert->notAfter, ccp, elem.end)) return -1; /* Get subject. */ beg = getASN1Element(&cert->subject, beg, end); if(!beg) return -1; /* Get subjectPublicKeyAlgorithm and subjectPublicKey. */ beg = getASN1Element(&cert->subjectPublicKeyInfo, beg, end); if(!beg) return -1; ccp = getASN1Element(&cert->subjectPublicKeyAlgorithm, cert->subjectPublicKeyInfo.beg, cert->subjectPublicKeyInfo.end); if(!ccp) return -1; if(!getASN1Element(&cert->subjectPublicKey, ccp, cert->subjectPublicKeyInfo.end)) return -1; /* Get optional issuerUiqueID, subjectUniqueID and extensions. */ cert->issuerUniqueID.tag = cert->subjectUniqueID.tag = 0; cert->extensions.tag = elem.tag = 0; cert->issuerUniqueID.header = cert->subjectUniqueID.header = NULL; cert->issuerUniqueID.beg = cert->issuerUniqueID.end = ""; cert->subjectUniqueID.beg = cert->subjectUniqueID.end = ""; cert->extensions.header = NULL; cert->extensions.beg = cert->extensions.end = ""; if(beg < end) { beg = getASN1Element(&elem, beg, end); if(!beg) return -1; } if(elem.tag == 1) { cert->issuerUniqueID = elem; if(beg < end) { beg = getASN1Element(&elem, beg, end); if(!beg) return -1; } } if(elem.tag == 2) { cert->subjectUniqueID = elem; if(beg < end) { beg = getASN1Element(&elem, beg, end); if(!beg) return -1; } } if(elem.tag == 3) if(!getASN1Element(&cert->extensions, elem.beg, elem.end)) return -1; return 0; } /* * Copy at most 64-characters, terminate with a newline and returns the * effective number of stored characters. */ static size_t copySubstring(char *to, const char *from) { size_t i; for(i = 0; i < 64; i++) { to[i] = *from; if(!*from++) break; } to[i++] = '\n'; return i; } static const char *dumpAlgo(curl_asn1Element *param, const char *beg, const char *end) { curl_asn1Element oid; /* Get algorithm parameters and return algorithm name. */ beg = getASN1Element(&oid, beg, end); if(!beg) return NULL; param->header = NULL; param->tag = 0; param->beg = param->end = end; if(beg < end) if(!getASN1Element(param, beg, end)) return NULL; return OID2str(oid.beg, oid.end, TRUE); } static void do_pubkey_field(struct Curl_easy *data, int certnum, const char *label, curl_asn1Element *elem) { const char *output; /* Generate a certificate information record for the public key. */ output = ASN1tostr(elem, 0); if(output) { if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, label, output); if(!certnum) infof(data, " %s: %s\n", label, output); free((char *) output); } } static void do_pubkey(struct Curl_easy *data, int certnum, const char *algo, curl_asn1Element *param, curl_asn1Element *pubkey) { curl_asn1Element elem; curl_asn1Element pk; const char *p; /* Generate all information records for the public key. */ /* Get the public key (single element). */ if(!getASN1Element(&pk, pubkey->beg + 1, pubkey->end)) return; if(strcasecompare(algo, "rsaEncryption")) { const char *q; unsigned long len; p = getASN1Element(&elem, pk.beg, pk.end); if(!p) return; /* Compute key length. */ for(q = elem.beg; !*q && q < elem.end; q++) ; len = (unsigned long)((elem.end - q) * 8); if(len) { unsigned int i; for(i = *(unsigned char *) q; !(i & 0x80); i <<= 1) len--; } if(len > 32) elem.beg = q; /* Strip leading zero bytes. */ if(!certnum) infof(data, " RSA Public Key (%lu bits)\n", len); if(data->set.ssl.certinfo) { q = curl_maprintf("%lu", len); if(q) { Curl_ssl_push_certinfo(data, certnum, "RSA Public Key", q); free((char *) q); } } /* Generate coefficients. */ do_pubkey_field(data, certnum, "rsa(n)", &elem); if(!getASN1Element(&elem, p, pk.end)) return; do_pubkey_field(data, certnum, "rsa(e)", &elem); } else if(strcasecompare(algo, "dsa")) { p = getASN1Element(&elem, param->beg, param->end); if(p) { do_pubkey_field(data, certnum, "dsa(p)", &elem); p = getASN1Element(&elem, p, param->end); if(p) { do_pubkey_field(data, certnum, "dsa(q)", &elem); if(getASN1Element(&elem, p, param->end)) { do_pubkey_field(data, certnum, "dsa(g)", &elem); do_pubkey_field(data, certnum, "dsa(pub_key)", &pk); } } } } else if(strcasecompare(algo, "dhpublicnumber")) { p = getASN1Element(&elem, param->beg, param->end); if(p) { do_pubkey_field(data, certnum, "dh(p)", &elem); if(getASN1Element(&elem, param->beg, param->end)) { do_pubkey_field(data, certnum, "dh(g)", &elem); do_pubkey_field(data, certnum, "dh(pub_key)", &pk); } } } } CURLcode Curl_extract_certinfo(struct connectdata *conn, int certnum, const char *beg, const char *end) { curl_X509certificate cert; struct Curl_easy *data = conn->data; curl_asn1Element param; const char *ccp; char *cp1; size_t cl1; char *cp2; CURLcode result; unsigned long version; size_t i; size_t j; if(!data->set.ssl.certinfo) if(certnum) return CURLE_OK; /* Prepare the certificate information for curl_easy_getinfo(). */ /* Extract the certificate ASN.1 elements. */ if(Curl_parseX509(&cert, beg, end)) return CURLE_PEER_FAILED_VERIFICATION; /* Subject. */ ccp = DNtostr(&cert.subject); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Subject", ccp); if(!certnum) infof(data, "%2d Subject: %s\n", certnum, ccp); free((char *) ccp); /* Issuer. */ ccp = DNtostr(&cert.issuer); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Issuer", ccp); if(!certnum) infof(data, " Issuer: %s\n", ccp); free((char *) ccp); /* Version (always fits in less than 32 bits). */ version = 0; for(ccp = cert.version.beg; ccp < cert.version.end; ccp++) version = (version << 8) | *(const unsigned char *) ccp; if(data->set.ssl.certinfo) { ccp = curl_maprintf("%lx", version); if(!ccp) return CURLE_OUT_OF_MEMORY; Curl_ssl_push_certinfo(data, certnum, "Version", ccp); free((char *) ccp); } if(!certnum) infof(data, " Version: %lu (0x%lx)\n", version + 1, version); /* Serial number. */ ccp = ASN1tostr(&cert.serialNumber, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Serial Number", ccp); if(!certnum) infof(data, " Serial Number: %s\n", ccp); free((char *) ccp); /* Signature algorithm .*/ ccp = dumpAlgo(&param, cert.signatureAlgorithm.beg, cert.signatureAlgorithm.end); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Signature Algorithm", ccp); if(!certnum) infof(data, " Signature Algorithm: %s\n", ccp); free((char *) ccp); /* Start Date. */ ccp = ASN1tostr(&cert.notBefore, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Start Date", ccp); if(!certnum) infof(data, " Start Date: %s\n", ccp); free((char *) ccp); /* Expire Date. */ ccp = ASN1tostr(&cert.notAfter, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Expire Date", ccp); if(!certnum) infof(data, " Expire Date: %s\n", ccp); free((char *) ccp); /* Public Key Algorithm. */ ccp = dumpAlgo(&param, cert.subjectPublicKeyAlgorithm.beg, cert.subjectPublicKeyAlgorithm.end); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Public Key Algorithm", ccp); if(!certnum) infof(data, " Public Key Algorithm: %s\n", ccp); do_pubkey(data, certnum, ccp, &param, &cert.subjectPublicKey); free((char *) ccp); /* Signature. */ ccp = ASN1tostr(&cert.signature, 0); if(!ccp) return CURLE_OUT_OF_MEMORY; if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Signature", ccp); if(!certnum) infof(data, " Signature: %s\n", ccp); free((char *) ccp); /* Generate PEM certificate. */ result = Curl_base64_encode(data, cert.certificate.beg, cert.certificate.end - cert.certificate.beg, &cp1, &cl1); if(result) return result; /* Compute the number of characters in final certificate string. Format is: -----BEGIN CERTIFICATE-----\n <max 64 base64 characters>\n . . . -----END CERTIFICATE-----\n */ i = 28 + cl1 + (cl1 + 64 - 1) / 64 + 26; cp2 = malloc(i + 1); if(!cp2) { free(cp1); return CURLE_OUT_OF_MEMORY; } /* Build the certificate string. */ i = copySubstring(cp2, "-----BEGIN CERTIFICATE-----"); for(j = 0; j < cl1; j += 64) i += copySubstring(cp2 + i, cp1 + j); i += copySubstring(cp2 + i, "-----END CERTIFICATE-----"); cp2[i] = '\0'; free(cp1); if(data->set.ssl.certinfo) Curl_ssl_push_certinfo(data, certnum, "Cert", cp2); if(!certnum) infof(data, "%s\n", cp2); free(cp2); return CURLE_OK; } #endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL or USE_SCHANNEL */ #if defined(USE_GSKIT) static const char *checkOID(const char *beg, const char *end, const char *oid) { curl_asn1Element e; const char *ccp; const char *p; bool matched; /* Check if first ASN.1 element at `beg' is the given OID. Return a pointer in the source after the OID if found, else NULL. */ ccp = getASN1Element(&e, beg, end); if(!ccp || e.tag != CURL_ASN1_OBJECT_IDENTIFIER) return NULL; p = OID2str(e.beg, e.end, FALSE); if(!p) return NULL; matched = !strcmp(p, oid); free((char *) p); return matched? ccp: NULL; } CURLcode Curl_verifyhost(struct connectdata *conn, const char *beg, const char *end) { struct Curl_easy *data = conn->data; curl_X509certificate cert; curl_asn1Element dn; curl_asn1Element elem; curl_asn1Element ext; curl_asn1Element name; const char *p; const char *q; char *dnsname; int matched = -1; size_t addrlen = (size_t) -1; ssize_t len; const char * const hostname = SSL_IS_PROXY()? conn->http_proxy.host.name: conn->host.name; const char * const dispname = SSL_IS_PROXY()? conn->http_proxy.host.dispname: conn->host.dispname; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif /* Verify that connection server matches info in X509 certificate at `beg'..`end'. */ if(!SSL_CONN_CONFIG(verifyhost)) return CURLE_OK; if(Curl_parseX509(&cert, beg, end)) return CURLE_PEER_FAILED_VERIFICATION; /* Get the server IP address. */ #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, hostname, &addr)) addrlen = sizeof(struct in6_addr); else #endif if(Curl_inet_pton(AF_INET, hostname, &addr)) addrlen = sizeof(struct in_addr); /* Process extensions. */ for(p = cert.extensions.beg; p < cert.extensions.end && matched != 1;) { p = getASN1Element(&ext, p, cert.extensions.end); if(!p) return CURLE_PEER_FAILED_VERIFICATION; /* Check if extension is a subjectAlternativeName. */ ext.beg = checkOID(ext.beg, ext.end, sanOID); if(ext.beg) { ext.beg = getASN1Element(&elem, ext.beg, ext.end); if(!ext.beg) return CURLE_PEER_FAILED_VERIFICATION; /* Skip critical if present. */ if(elem.tag == CURL_ASN1_BOOLEAN) { ext.beg = getASN1Element(&elem, ext.beg, ext.end); if(!ext.beg) return CURLE_PEER_FAILED_VERIFICATION; } /* Parse the octet string contents: is a single sequence. */ if(!getASN1Element(&elem, elem.beg, elem.end)) return CURLE_PEER_FAILED_VERIFICATION; /* Check all GeneralNames. */ for(q = elem.beg; matched != 1 && q < elem.end;) { q = getASN1Element(&name, q, elem.end); if(!q) break; switch(name.tag) { case 2: /* DNS name. */ len = utf8asn1str(&dnsname, CURL_ASN1_IA5_STRING, name.beg, name.end); if(len > 0 && (size_t)len == strlen(dnsname)) matched = Curl_cert_hostcheck(dnsname, hostname); else matched = 0; free(dnsname); break; case 7: /* IP address. */ matched = (size_t) (name.end - name.beg) == addrlen && !memcmp(&addr, name.beg, addrlen); break; } } } } switch(matched) { case 1: /* an alternative name matched the server hostname */ infof(data, "\t subjectAltName: %s matched\n", dispname); return CURLE_OK; case 0: /* an alternative name field existed, but didn't match and then we MUST fail */ infof(data, "\t subjectAltName does not match %s\n", dispname); return CURLE_PEER_FAILED_VERIFICATION; } /* Process subject. */ name.header = NULL; name.beg = name.end = ""; q = cert.subject.beg; /* we have to look to the last occurrence of a commonName in the distinguished one to get the most significant one. */ while(q < cert.subject.end) { q = getASN1Element(&dn, q, cert.subject.end); if(!q) break; for(p = dn.beg; p < dn.end;) { p = getASN1Element(&elem, p, dn.end); if(!p) return CURLE_PEER_FAILED_VERIFICATION; /* We have a DN's AttributeTypeAndValue: check it in case it's a CN. */ elem.beg = checkOID(elem.beg, elem.end, cnOID); if(elem.beg) name = elem; /* Latch CN. */ } } /* Check the CN if found. */ if(!getASN1Element(&elem, name.beg, name.end)) failf(data, "SSL: unable to obtain common name from peer certificate"); else { len = utf8asn1str(&dnsname, elem.tag, elem.beg, elem.end); if(len < 0) { free(dnsname); return CURLE_OUT_OF_MEMORY; } if(strlen(dnsname) != (size_t) len) /* Nul byte in string ? */ failf(data, "SSL: illegal cert name field"); else if(Curl_cert_hostcheck((const char *) dnsname, hostname)) { infof(data, "\t common name: %s (matched)\n", dnsname); free(dnsname); return CURLE_OK; } else failf(data, "SSL: certificate subject name '%s' does not match " "target host name '%s'", dnsname, dispname); free(dnsname); } return CURLE_PEER_FAILED_VERIFICATION; } #endif /* USE_GSKIT */
YifuLiu/AliOS-Things
components/curl/lib/x509asn1.c
C
apache-2.0
36,144
#ifndef HEADER_CURL_X509ASN1_H #define HEADER_CURL_X509ASN1_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(USE_GSKIT) || defined(USE_NSS) || defined(USE_GNUTLS) || \ defined(USE_CYASSL) || defined(USE_SCHANNEL) #include "urldata.h" /* * Constants. */ /* Largest supported ASN.1 structure. */ #define CURL_ASN1_MAX ((size_t) 0x40000) /* 256K */ /* ASN.1 classes. */ #define CURL_ASN1_UNIVERSAL 0 #define CURL_ASN1_APPLICATION 1 #define CURL_ASN1_CONTEXT_SPECIFIC 2 #define CURL_ASN1_PRIVATE 3 /* ASN.1 types. */ #define CURL_ASN1_BOOLEAN 1 #define CURL_ASN1_INTEGER 2 #define CURL_ASN1_BIT_STRING 3 #define CURL_ASN1_OCTET_STRING 4 #define CURL_ASN1_NULL 5 #define CURL_ASN1_OBJECT_IDENTIFIER 6 #define CURL_ASN1_OBJECT_DESCRIPTOR 7 #define CURL_ASN1_INSTANCE_OF 8 #define CURL_ASN1_REAL 9 #define CURL_ASN1_ENUMERATED 10 #define CURL_ASN1_EMBEDDED 11 #define CURL_ASN1_UTF8_STRING 12 #define CURL_ASN1_RELATIVE_OID 13 #define CURL_ASN1_SEQUENCE 16 #define CURL_ASN1_SET 17 #define CURL_ASN1_NUMERIC_STRING 18 #define CURL_ASN1_PRINTABLE_STRING 19 #define CURL_ASN1_TELETEX_STRING 20 #define CURL_ASN1_VIDEOTEX_STRING 21 #define CURL_ASN1_IA5_STRING 22 #define CURL_ASN1_UTC_TIME 23 #define CURL_ASN1_GENERALIZED_TIME 24 #define CURL_ASN1_GRAPHIC_STRING 25 #define CURL_ASN1_VISIBLE_STRING 26 #define CURL_ASN1_GENERAL_STRING 27 #define CURL_ASN1_UNIVERSAL_STRING 28 #define CURL_ASN1_CHARACTER_STRING 29 #define CURL_ASN1_BMP_STRING 30 /* * Types. */ /* ASN.1 parsed element. */ typedef struct { const char * header; /* Pointer to header byte. */ const char * beg; /* Pointer to element data. */ const char * end; /* Pointer to 1st byte after element. */ unsigned char class; /* ASN.1 element class. */ unsigned char tag; /* ASN.1 element tag. */ bool constructed; /* Element is constructed. */ } curl_asn1Element; /* ASN.1 OID table entry. */ typedef struct { const char * numoid; /* Dotted-numeric OID. */ const char * textoid; /* OID name. */ } curl_OID; /* X509 certificate: RFC 5280. */ typedef struct { curl_asn1Element certificate; curl_asn1Element version; curl_asn1Element serialNumber; curl_asn1Element signatureAlgorithm; curl_asn1Element signature; curl_asn1Element issuer; curl_asn1Element notBefore; curl_asn1Element notAfter; curl_asn1Element subject; curl_asn1Element subjectPublicKeyInfo; curl_asn1Element subjectPublicKeyAlgorithm; curl_asn1Element subjectPublicKey; curl_asn1Element issuerUniqueID; curl_asn1Element subjectUniqueID; curl_asn1Element extensions; } curl_X509certificate; /* * Prototypes. */ const char *Curl_getASN1Element(curl_asn1Element *elem, const char *beg, const char *end); const char *Curl_ASN1tostr(curl_asn1Element *elem, int type); const char *Curl_DNtostr(curl_asn1Element *dn); int Curl_parseX509(curl_X509certificate *cert, const char *beg, const char *end); CURLcode Curl_extract_certinfo(struct connectdata *conn, int certnum, const char *beg, const char *end); CURLcode Curl_verifyhost(struct connectdata *conn, const char *beg, const char *end); #endif /* USE_GSKIT or USE_NSS or USE_GNUTLS or USE_CYASSL or USE_SCHANNEL */ #endif /* HEADER_CURL_X509ASN1_H */
YifuLiu/AliOS-Things
components/curl/lib/x509asn1.h
C
apache-2.0
4,806
set(EXE_NAME curl) if(USE_MANUAL) # Use the C locale to ensure that only ASCII characters appear in the # embedded text. NROFF and MANOPT are set in the parent CMakeLists.txt add_custom_command( OUTPUT tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "#include \"tool_setup.h\"" > tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "#ifndef HAVE_LIBZ" >> tool_hugehelp.c COMMAND env LC_ALL=C "${NROFF}" ${NROFF_MANOPT} "${CURL_BINARY_DIR}/docs/curl.1" | "${PERL_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/mkhelp.pl" >> tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "#else" >> tool_hugehelp.c COMMAND env LC_ALL=C "${NROFF}" ${NROFF_MANOPT} "${CURL_BINARY_DIR}/docs/curl.1" | "${PERL_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/mkhelp.pl" -c >> tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "#endif /* HAVE_LIBZ */" >> tool_hugehelp.c DEPENDS generate-curl.1 "${CURL_BINARY_DIR}/docs/curl.1" "${CMAKE_CURRENT_SOURCE_DIR}/mkhelp.pl" "${CMAKE_CURRENT_SOURCE_DIR}/tool_hugehelp.h" VERBATIM) else() add_custom_command( OUTPUT tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "/* built-in manual is disabled, blank function */" > tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "#include \"tool_hugehelp.h\"" >> tool_hugehelp.c COMMAND ${CMAKE_COMMAND} -E echo "void hugehelp(void) {}" >> tool_hugehelp.c DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tool_hugehelp.h" VERBATIM) endif() transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake) if(MSVC) list(APPEND CURL_FILES curl.rc) endif() # CURL_FILES comes from Makefile.inc add_executable( ${EXE_NAME} ${CURL_FILES} ) source_group("curlX source files" FILES ${CURLX_CFILES}) source_group("curl source files" FILES ${CURL_CFILES}) source_group("curl header files" FILES ${CURL_HFILES}) include_directories( ${CURL_SOURCE_DIR}/lib # To be able to reach "curl_setup_once.h" ${CURL_BINARY_DIR}/lib # To be able to reach "curl_config.h" ${CURL_BINARY_DIR}/include # To be able to reach "curl/curl.h" # This is needed as tool_hugehelp.c is generated in the binary dir ${CURL_SOURCE_DIR}/src # To be able to reach "tool_hugehelp.h" ) #Build curl executable target_link_libraries(${EXE_NAME} libcurl ${CURL_LIBS}) ################################################################################ #SET_TARGET_PROPERTIES(${EXE_NAME} ARCHIVE_OUTPUT_DIRECTORY "blah blah blah") #SET_TARGET_PROPERTIES(${EXE_NAME} RUNTIME_OUTPUT_DIRECTORY "blah blah blah") #SET_TARGET_PROPERTIES(${EXE_NAME} LIBRARY_OUTPUT_DIRECTORY "blah blah blah") #INCLUDE(ModuleInstall OPTIONAL) install(TARGETS ${EXE_NAME} EXPORT ${TARGETS_EXPORT_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) export(TARGETS ${EXE_NAME} APPEND FILE ${PROJECT_BINARY_DIR}/curl-target.cmake NAMESPACE CURL:: )
YifuLiu/AliOS-Things
components/curl/src/CMakeLists.txt
CMake
apache-2.0
2,992
#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### AUTOMAKE_OPTIONS = foreign nostdinc # remove targets if the command fails .DELETE_ON_ERROR: # Specify our include paths here, and do it relative to $(top_srcdir) and # $(top_builddir), to ensure that these paths which belong to the library # being currently built and tested are searched before the library which # might possibly already be installed in the system. # # $(top_srcdir)/include is for libcurl's external include files # $(top_builddir)/lib is for libcurl's generated lib/curl_config.h file # $(top_builddir)/src is for curl's generated src/curl_config.h file # $(top_srcdir)/lib for libcurl's lib/curl_setup.h and other "borrowed" files # $(top_srcdir)/src is for curl's src/tool_setup.h and "curl-private" files AM_CPPFLAGS = -I$(top_srcdir)/include \ -I$(top_builddir)/lib \ -I$(top_builddir)/src \ -I$(top_srcdir)/lib \ -I$(top_srcdir)/src bin_PROGRAMS = curl SUBDIRS = ../docs if USE_CPPFLAG_CURL_STATICLIB AM_CPPFLAGS += -DCURL_STATICLIB endif include Makefile.inc # CURL_FILES comes from Makefile.inc curl_SOURCES = $(CURL_FILES) # This might hold -Werror CFLAGS += @CURL_CFLAG_EXTRAS@ # Prevent LIBS from being used for all link targets LIBS = $(BLANK_AT_MAKETIME) if USE_EXPLICIT_LIB_DEPS curl_LDADD = $(top_builddir)/lib/libcurl.la @LIBMETALINK_LIBS@ @LIBCURL_LIBS@ else curl_LDADD = $(top_builddir)/lib/libcurl.la @LIBMETALINK_LIBS@ @NSS_LIBS@ @SSL_LIBS@ @ZLIB_LIBS@ @CURL_NETWORK_AND_TIME_LIBS@ endif curl_LDFLAGS = @LIBMETALINK_LDFLAGS@ curl_CPPFLAGS = $(AM_CPPFLAGS) $(LIBMETALINK_CPPFLAGS) # if unit tests are enabled, build a static library to link them with if BUILD_UNITTESTS noinst_LTLIBRARIES = libcurltool.la libcurltool_la_CPPFLAGS = $(LIBMETALINK_CPPFLAGS) $(AM_CPPFLAGS) \ -DCURL_STATICLIB -DUNITTESTS libcurltool_la_CFLAGS = libcurltool_la_LDFLAGS = -static $(LINKFLAGS) libcurltool_la_SOURCES = $(curl_SOURCES) endif CLEANFILES = tool_hugehelp.c # Use the C locale to ensure that only ASCII characters appear in the # embedded text. NROFF=env LC_ALL=C @NROFF@ @MANOPT@ # figured out by the configure script EXTRA_DIST = mkhelp.pl makefile.dj \ Makefile.m32 macos/curl.mcp.xml.sit.hqx macos/MACINSTALL.TXT \ macos/src/curl_GUSIConfig.cpp macos/src/macos_main.cpp makefile.amiga \ curl.rc Makefile.netware Makefile.inc Makefile.Watcom CMakeLists.txt # Use absolute directory to disable VPATH MANPAGE=$(abs_top_builddir)/docs/curl.1 MKHELP=$(top_srcdir)/src/mkhelp.pl HUGE=tool_hugehelp.c HUGECMD = $(HUGEIT_$(V)) HUGEIT_0 = @echo " HUGE " $@; HUGEIT_1 = HUGEIT_ = $(HUGEIT_0) CHECKSRC = $(CS_$(V)) CS_0 = @echo " RUN " $@; CS_1 = CS_ = $(CS_0) if USE_MANUAL # Here are the stuff to create a built-in manual $(MANPAGE): cd $(top_builddir)/docs && $(MAKE) if HAVE_LIBZ # This generates the tool_hugehelp.c file in both uncompressed and # compressed formats. $(HUGE): $(MANPAGE) $(MKHELP) $(HUGECMD) (echo '#include "tool_setup.h"' > $(HUGE); \ echo '#ifndef HAVE_LIBZ' >> $(HUGE); \ $(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) >> $(HUGE); \ echo '#else' >> $(HUGE); \ $(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) -c >> $(HUGE); \ echo '#endif /* HAVE_LIBZ */' >> $(HUGE) ) else # HAVE_LIBZ # This generates the tool_hugehelp.c file uncompressed only $(HUGE): $(MANPAGE) $(MKHELP) $(HUGECMD)(echo '#include "tool_setup.h"' > $(HUGE): \ $(NROFF) $(MANPAGE) | $(PERL) $(MKHELP) >> $(HUGE) ) endif else # USE_MANUAL # built-in manual has been disabled, make a blank file $(HUGE): $(HUGECMD)(echo "/* built-in manual is disabled, blank function */" > $(HUGE); \ echo '#include "tool_hugehelp.h"' >> $(HUGE); \ echo "void hugehelp(void) {}" >>$(HUGE) ) endif # ignore tool_hugehelp.c since it is generated source code and it plays # by slightly different rules! checksrc: $(CHECKSRC)(@PERL@ $(top_srcdir)/lib/checksrc.pl -D$(srcdir) \ -W$(srcdir)/tool_hugehelp.c $(srcdir)/*.[ch]) if CURLDEBUG # for debug builds, we scan the sources on all regular make invokes all-local: checksrc endif # disable the tests that are mostly causing false positives TIDYFLAGS=-checks=-clang-analyzer-security.insecureAPI.strcpy,-clang-analyzer-optin.performance.Padding,-clang-analyzer-valist.Uninitialized,-clang-analyzer-core.NonNullParamChecker,-clang-analyzer-core.NullDereference TIDY:=clang-tidy tidy: $(TIDY) $(CURL_CFILES) $(TIDYFLAGS) -- $(curl_CPPFLAGS) $(CPPFLAGS) -DHAVE_CONFIG_H
YifuLiu/AliOS-Things
components/curl/src/Makefile.am
Makefile
apache-2.0
5,583
# ./src/Makefile.inc # Using the backslash as line continuation character might be problematic # with some make flavours, as Watcom's wmake showed us already. If we # ever want to change this in a portable manner then we should consider # this idea (posted to the libcurl list by Adam Kellas): # CSRC1 = file1.c file2.c file3.c # CSRC2 = file4.c file5.c file6.c # CSOURCES = $(CSRC1) $(CSRC2) # libcurl has sources that provide functions named curlx_* that aren't part of # the official API, but we re-use the code here to avoid duplication. CURLX_CFILES = \ ../lib/strtoofft.c \ ../lib/nonblock.c \ ../lib/warnless.c \ ../lib/curl_ctype.c CURLX_HFILES = \ ../lib/curl_setup.h \ ../lib/strtoofft.h \ ../lib/nonblock.h \ ../lib/warnless.h \ ../lib/curl_ctype.h CURL_CFILES = \ slist_wc.c \ tool_binmode.c \ tool_bname.c \ tool_cb_dbg.c \ tool_cb_hdr.c \ tool_cb_prg.c \ tool_cb_rea.c \ tool_cb_see.c \ tool_cb_wrt.c \ tool_cfgable.c \ tool_convert.c \ tool_dirhie.c \ tool_doswin.c \ tool_easysrc.c \ tool_filetime.c \ tool_formparse.c \ tool_getparam.c \ tool_getpass.c \ tool_help.c \ tool_helpers.c \ tool_homedir.c \ tool_hugehelp.c \ tool_libinfo.c \ tool_main.c \ tool_metalink.c \ tool_msgs.c \ tool_operate.c \ tool_operhlp.c \ tool_panykey.c \ tool_paramhlp.c \ tool_parsecfg.c \ tool_strdup.c \ tool_setopt.c \ tool_sleep.c \ tool_urlglob.c \ tool_util.c \ tool_vms.c \ tool_writeout.c \ tool_xattr.c CURL_HFILES = \ slist_wc.h \ tool_binmode.h \ tool_bname.h \ tool_cb_dbg.h \ tool_cb_hdr.h \ tool_cb_prg.h \ tool_cb_rea.h \ tool_cb_see.h \ tool_cb_wrt.h \ tool_cfgable.h \ tool_convert.h \ tool_dirhie.h \ tool_doswin.h \ tool_easysrc.h \ tool_filetime.h \ tool_formparse.h \ tool_getparam.h \ tool_getpass.h \ tool_help.h \ tool_helpers.h \ tool_homedir.h \ tool_hugehelp.h \ tool_libinfo.h \ tool_main.h \ tool_metalink.h \ tool_msgs.h \ tool_operate.h \ tool_operhlp.h \ tool_panykey.h \ tool_paramhlp.h \ tool_parsecfg.h \ tool_sdecls.h \ tool_setopt.h \ tool_setup.h \ tool_sleep.h \ tool_strdup.h \ tool_urlglob.h \ tool_util.h \ tool_version.h \ tool_vms.h \ tool_writeout.h \ tool_xattr.h CURL_RCFILES = curl.rc # curl_SOURCES is special and gets assigned in src/Makefile.am CURL_FILES = $(CURL_CFILES) $(CURLX_CFILES) $(CURL_HFILES)
YifuLiu/AliOS-Things
components/curl/src/Makefile.inc
Makefile
apache-2.0
2,439
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # Yeah, I know, probably 1000 other persons already wrote a script like # this, but I'll tell ya: # THEY DON'T FIT ME :-) # Get readme file as parameter: if($ARGV[0] eq "-c") { $c=1; shift @ARGV; } push @out, " _ _ ____ _\n"; push @out, " Project ___| | | | _ \\| |\n"; push @out, " / __| | | | |_) | |\n"; push @out, " | (__| |_| | _ <| |___\n"; push @out, " \\___|\\___/|_| \\_\\_____|\n"; my $olen=0; while (<STDIN>) { my $line = $_; # this should be removed: $line =~ s/(.|_)//g; # remove trailing CR from line. msysgit checks out files as line+CRLF $line =~ s/\r$//; if($line =~ /^([ \t]*\n|curl)/i) { # cut off headers and empty lines $wline++; # count number of cut off lines next; } my $text = $line; $text =~ s/^\s+//g; # cut off preceding... $text =~ s/\s+$//g; # and trailing whitespaces $tlen = length($text); if($wline && ($olen == $tlen)) { # if the previous line with contents was exactly as long as # this line, then we ignore the newlines! # We do this magic because a header may abort a paragraph at # any line, but we don't want that to be noticed in the output # here $wline=0; } $olen = $tlen; if($wline) { # we only make one empty line max $wline = 0; push @out, "\n"; } push @out, $line; } push @out, "\n"; # just an extra newline print <<HEAD /* * NEVER EVER edit this manually, fix the mkhelp.pl script instead! */ #ifdef USE_MANUAL #include "tool_hugehelp.h" HEAD ; if($c) { # If compression requested, check that the Gzip module is available # or else disable compression $c = eval { require IO::Compress::Gzip; IO::Compress::Gzip->import(); 1; }; print STDERR "Warning: compression requested but Gzip is not available\n" if (!$c) } if($c) { my $content = join("", @out); my $gzippedContent; IO::Compress::Gzip::gzip( \$content, \$gzippedContent, Level => 9, TextFlag => 1, Time=>0) or die "gzip failed:"; $gzip = length($content); $gzipped = length($gzippedContent); print <<HEAD #include <zlib.h> #include "memdebug.h" /* keep this as LAST include */ static const unsigned char hugehelpgz[] = { /* This mumbo-jumbo is the huge help text compressed with gzip. Thanks to this operation, the size of this data shrank from $gzip to $gzipped bytes. You can disable the use of compressed help texts by NOT passing -c to the mkhelp.pl tool. */ HEAD ; my $c=0; print " "; for(split(//, $gzippedContent)) { my $num=ord($_); printf(" 0x%02x,", 0+$num); if(!(++$c % 12)) { print "\n "; } } print "\n};\n"; print <<EOF #define BUF_SIZE 0x10000 static voidpf zalloc_func(voidpf opaque, unsigned int items, unsigned int size) { (void) opaque; /* not a typo, keep it calloc() */ return (voidpf) calloc(items, size); } static void zfree_func(voidpf opaque, voidpf ptr) { (void) opaque; free(ptr); } /* Decompress and send to stdout a gzip-compressed buffer */ void hugehelp(void) { unsigned char* buf; int status,headerlen; z_stream z; /* Make sure no gzip options are set */ if (hugehelpgz[3] & 0xfe) return; headerlen = 10; memset(&z, 0, sizeof(z_stream)); z.zalloc = (alloc_func)zalloc_func; z.zfree = (free_func)zfree_func; z.avail_in = (unsigned int)(sizeof(hugehelpgz) - headerlen); z.next_in = (unsigned char *)hugehelpgz + headerlen; if (inflateInit2(&z, -MAX_WBITS) != Z_OK) return; buf = malloc(BUF_SIZE); if (buf) { while(1) { z.avail_out = BUF_SIZE; z.next_out = buf; status = inflate(&z, Z_SYNC_FLUSH); if (status == Z_OK || status == Z_STREAM_END) { fwrite(buf, BUF_SIZE - z.avail_out, 1, stdout); if (status == Z_STREAM_END) break; } else break; /* Error */ } free(buf); } inflateEnd(&z); } EOF ; foot(); exit; } else { print <<HEAD void hugehelp(void) { fputs( HEAD ; } $outsize=0; for(@out) { chop; $new = $_; $outsize += length($new)+1; # one for the newline $new =~ s/\\/\\\\/g; $new =~ s/\"/\\\"/g; # gcc 2.96 claims ISO C89 only is required to support 509 letter strings if($outsize > 500) { # terminate and make another fputs() call here print ", stdout);\n fputs(\n"; $outsize=length($new)+1; } printf("\"%s\\n\"\n", $new); } print ", stdout) ;\n}\n"; foot(); sub foot { print <<FOOT #else /* !USE_MANUAL */ /* built-in manual is disabled, blank function */ #include "tool_hugehelp.h" void hugehelp(void) {} #endif /* USE_MANUAL */ FOOT ; }
YifuLiu/AliOS-Things
components/curl/src/mkhelp.pl
Perl
apache-2.0
5,934
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifndef CURL_DISABLE_LIBCURL_OPTION #include "slist_wc.h" /* The last #include files should be: */ #include "memdebug.h" /* * slist_wc_append() appends a string to the linked list. This function can be * used as an initialization function as well as an append function. */ struct slist_wc *slist_wc_append(struct slist_wc *list, const char *data) { struct curl_slist *new_item = curl_slist_append(NULL, data); if(!new_item) return NULL; if(!list) { list = malloc(sizeof(struct slist_wc)); if(!list) { curl_slist_free_all(new_item); return NULL; } list->first = new_item; list->last = new_item; return list; } list->last->next = new_item; list->last = list->last->next; return list; } /* be nice and clean up resources */ void slist_wc_free_all(struct slist_wc *list) { if(!list) return; curl_slist_free_all(list->first); free(list); } #endif /* CURL_DISABLE_LIBCURL_OPTION */
YifuLiu/AliOS-Things
components/curl/src/slist_wc.c
C
apache-2.0
2,039
#ifndef HEADER_CURL_SLIST_WC_H #define HEADER_CURL_SLIST_WC_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifndef CURL_DISABLE_LIBCURL_OPTION /* linked-list structure with last node cache for easysrc */ struct slist_wc { struct curl_slist *first; struct curl_slist *last; }; /* * NAME curl_slist_wc_append() * * DESCRIPTION * * Appends a string to a linked list. If no list exists, it will be created * first. Returns the new list, after appending. */ struct slist_wc *slist_wc_append(struct slist_wc *, const char *); /* * NAME curl_slist_free_all() * * DESCRIPTION * * free a previously built curl_slist_wc. */ void slist_wc_free_all(struct slist_wc *); #endif /* CURL_DISABLE_LIBCURL_OPTION */ #endif /* HEADER_CURL_SLIST_WC_H */
YifuLiu/AliOS-Things
components/curl/src/slist_wc.h
C
apache-2.0
1,762
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_SETMODE #ifdef HAVE_IO_H # include <io.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #include "tool_binmode.h" #include "memdebug.h" /* keep this as LAST include */ void set_binmode(FILE *stream) { #ifdef O_BINARY # ifdef __HIGHC__ _setmode(stream, O_BINARY); # else (void)setmode(fileno(stream), O_BINARY); # endif #else (void)stream; #endif } #endif /* HAVE_SETMODE */
YifuLiu/AliOS-Things
components/curl/src/tool_binmode.c
C
apache-2.0
1,462
#ifndef HEADER_CURL_TOOL_BINMODE_H #define HEADER_CURL_TOOL_BINMODE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_SETMODE void set_binmode(FILE *stream); #else #define set_binmode(x) Curl_nop_stmt #endif /* HAVE_SETMODE */ #endif /* HEADER_CURL_TOOL_BINMODE_H */
YifuLiu/AliOS-Things
components/curl/src/tool_binmode.h
C
apache-2.0
1,287
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "tool_bname.h" #include "memdebug.h" /* keep this as LAST include */ #ifndef HAVE_BASENAME char *tool_basename(char *path) { char *s1; char *s2; s1 = strrchr(path, '/'); s2 = strrchr(path, '\\'); if(s1 && s2) { path = (s1 > s2) ? s1 + 1 : s2 + 1; } else if(s1) path = s1 + 1; else if(s2) path = s2 + 1; return path; } #endif /* HAVE_BASENAME */
YifuLiu/AliOS-Things
components/curl/src/tool_bname.c
C
apache-2.0
1,442
#ifndef HEADER_CURL_TOOL_BNAME_H #define HEADER_CURL_TOOL_BNAME_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifndef HAVE_BASENAME char *tool_basename(char *path); #define basename(x) tool_basename((x)) #endif /* HAVE_BASENAME */ #endif /* HEADER_CURL_TOOL_BNAME_H */
YifuLiu/AliOS-Things
components/curl/src/tool_bname.h
C
apache-2.0
1,280
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_convert.h" #include "tool_msgs.h" #include "tool_cb_dbg.h" #include "tool_util.h" #include "memdebug.h" /* keep this as LAST include */ static void dump(const char *timebuf, const char *text, FILE *stream, const unsigned char *ptr, size_t size, trace tracetype, curl_infotype infotype); /* ** callback for CURLOPT_DEBUGFUNCTION */ int tool_debug_cb(CURL *handle, curl_infotype type, char *data, size_t size, void *userdata) { struct OperationConfig *operation = userdata; struct GlobalConfig *config = operation->global; FILE *output = config->errors; const char *text; struct timeval tv; char timebuf[20]; time_t secs; (void)handle; /* not used */ if(config->tracetime) { struct tm *now; static time_t epoch_offset; static int known_offset; tv = tvnow(); if(!known_offset) { epoch_offset = time(NULL) - tv.tv_sec; known_offset = 1; } secs = epoch_offset + tv.tv_sec; now = localtime(&secs); /* not thread safe but we don't care */ msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld ", now->tm_hour, now->tm_min, now->tm_sec, (long)tv.tv_usec); } else timebuf[0] = 0; if(!config->trace_stream) { /* open for append */ if(!strcmp("-", config->trace_dump)) config->trace_stream = stdout; else if(!strcmp("%", config->trace_dump)) /* Ok, this is somewhat hackish but we do it undocumented for now */ config->trace_stream = config->errors; /* aka stderr */ else { config->trace_stream = fopen(config->trace_dump, FOPEN_WRITETEXT); config->trace_fopened = TRUE; } } if(config->trace_stream) output = config->trace_stream; if(!output) { warnf(config, "Failed to create/open output"); return 0; } if(config->tracetype == TRACE_PLAIN) { /* * This is the trace look that is similar to what libcurl makes on its * own. */ static const char * const s_infotype[] = { "*", "<", ">", "{", "}", "{", "}" }; static bool newl = FALSE; static bool traced_data = FALSE; switch(type) { case CURLINFO_HEADER_OUT: if(size > 0) { size_t st = 0; size_t i; for(i = 0; i < size - 1; i++) { if(data[i] == '\n') { /* LF */ if(!newl) { fprintf(output, "%s%s ", timebuf, s_infotype[type]); } (void)fwrite(data + st, i - st + 1, 1, output); st = i + 1; newl = FALSE; } } if(!newl) fprintf(output, "%s%s ", timebuf, s_infotype[type]); (void)fwrite(data + st, i - st + 1, 1, output); } newl = (size && (data[size - 1] != '\n')) ? TRUE : FALSE; traced_data = FALSE; break; case CURLINFO_TEXT: case CURLINFO_HEADER_IN: if(!newl) fprintf(output, "%s%s ", timebuf, s_infotype[type]); (void)fwrite(data, size, 1, output); newl = (size && (data[size - 1] != '\n')) ? TRUE : FALSE; traced_data = FALSE; break; case CURLINFO_DATA_OUT: case CURLINFO_DATA_IN: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: if(!traced_data) { /* if the data is output to a tty and we're sending this debug trace to stderr or stdout, we don't display the alert about the data not being shown as the data _is_ shown then just not via this function */ if(!config->isatty || ((output != stderr) && (output != stdout))) { if(!newl) fprintf(output, "%s%s ", timebuf, s_infotype[type]); fprintf(output, "[%zu bytes data]\n", size); newl = FALSE; traced_data = TRUE; } } break; default: /* nada */ newl = FALSE; traced_data = FALSE; break; } return 0; } #ifdef CURL_DOES_CONVERSIONS /* Special processing is needed for CURLINFO_HEADER_OUT blocks * if they contain both headers and data (separated by CRLFCRLF). * We dump the header text and then switch type to CURLINFO_DATA_OUT. */ if((type == CURLINFO_HEADER_OUT) && (size > 4)) { size_t i; for(i = 0; i < size - 4; i++) { if(memcmp(&data[i], "\r\n\r\n", 4) == 0) { /* dump everything through the CRLFCRLF as a sent header */ text = "=> Send header"; dump(timebuf, text, output, (unsigned char *)data, i + 4, config->tracetype, type); data += i + 3; size -= i + 4; type = CURLINFO_DATA_OUT; data += 1; break; } } } #endif /* CURL_DOES_CONVERSIONS */ switch(type) { case CURLINFO_TEXT: fprintf(output, "%s== Info: %s", timebuf, data); /* FALLTHROUGH */ default: /* in case a new one is introduced to shock us */ return 0; case CURLINFO_HEADER_OUT: text = "=> Send header"; break; case CURLINFO_DATA_OUT: text = "=> Send data"; break; case CURLINFO_HEADER_IN: text = "<= Recv header"; break; case CURLINFO_DATA_IN: text = "<= Recv data"; break; case CURLINFO_SSL_DATA_IN: text = "<= Recv SSL data"; break; case CURLINFO_SSL_DATA_OUT: text = "=> Send SSL data"; break; } dump(timebuf, text, output, (unsigned char *) data, size, config->tracetype, type); return 0; } static void dump(const char *timebuf, const char *text, FILE *stream, const unsigned char *ptr, size_t size, trace tracetype, curl_infotype infotype) { size_t i; size_t c; unsigned int width = 0x10; if(tracetype == TRACE_ASCII) /* without the hex output, we can fit more on screen */ width = 0x40; fprintf(stream, "%s%s, %zu bytes (0x%zx)\n", timebuf, text, size, size); for(i = 0; i < size; i += width) { fprintf(stream, "%04zx: ", i); if(tracetype == TRACE_BIN) { /* hex not disabled, show it */ for(c = 0; c < width; c++) if(i + c < size) fprintf(stream, "%02x ", ptr[i + c]); else fputs(" ", stream); } for(c = 0; (c < width) && (i + c < size); c++) { /* check for 0D0A; if found, skip past and start a new line of output */ if((tracetype == TRACE_ASCII) && (i + c + 1 < size) && (ptr[i + c] == 0x0D) && (ptr[i + c + 1] == 0x0A)) { i += (c + 2 - width); break; } #ifdef CURL_DOES_CONVERSIONS /* repeat the 0D0A check above but use the host encoding for CRLF */ if((tracetype == TRACE_ASCII) && (i + c + 1 < size) && (ptr[i + c] == '\r') && (ptr[i + c + 1] == '\n')) { i += (c + 2 - width); break; } /* convert to host encoding and print this character */ fprintf(stream, "%c", convert_char(infotype, ptr[i + c])); #else (void)infotype; fprintf(stream, "%c", ((ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80)) ? ptr[i + c] : UNPRINTABLE_CHAR); #endif /* CURL_DOES_CONVERSIONS */ /* check again for 0D0A, to avoid an extra \n if it's at width */ if((tracetype == TRACE_ASCII) && (i + c + 2 < size) && (ptr[i + c + 1] == 0x0D) && (ptr[i + c + 2] == 0x0A)) { i += (c + 3 - width); break; } } fputc('\n', stream); /* newline */ } fflush(stream); }
YifuLiu/AliOS-Things
components/curl/src/tool_cb_dbg.c
C
apache-2.0
8,528
#ifndef HEADER_CURL_TOOL_CB_DBG_H #define HEADER_CURL_TOOL_CB_DBG_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" /* ** callback for CURLOPT_DEBUGFUNCTION */ int tool_debug_cb(CURL *handle, curl_infotype type, char *data, size_t size, void *userdata); #endif /* HEADER_CURL_TOOL_CB_DBG_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_dbg.h
C
apache-2.0
1,334
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "strcase.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_doswin.h" #include "tool_msgs.h" #include "tool_cb_hdr.h" #include "tool_cb_wrt.h" #include "memdebug.h" /* keep this as LAST include */ static char *parse_filename(const char *ptr, size_t len); #ifdef WIN32 #define BOLD #define BOLDOFF #else #define BOLD "\x1b[1m" /* Switch off bold by setting "all attributes off" since the explicit bold-off code (21) isn't supported everywhere - like in the mac Terminal. */ #define BOLDOFF "\x1b[0m" #endif /* ** callback for CURLOPT_HEADERFUNCTION */ size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata) { struct HdrCbData *hdrcbdata = userdata; struct OutStruct *outs = hdrcbdata->outs; struct OutStruct *heads = hdrcbdata->heads; const char *str = ptr; const size_t cb = size * nmemb; const char *end = (char *)ptr + cb; long protocol = 0; /* * Once that libcurl has called back tool_header_cb() the returned value * is checked against the amount that was intended to be written, if * it does not match then it fails with CURLE_WRITE_ERROR. So at this * point returning a value different from sz*nmemb indicates failure. */ size_t failure = (size && nmemb) ? 0 : 1; if(!heads->config) return failure; #ifdef DEBUGBUILD if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) { warnf(heads->config->global, "Header data exceeds single call write " "limit!\n"); return failure; } #endif /* * Write header data when curl option --dump-header (-D) is given. */ if(heads->config->headerfile && heads->stream) { size_t rc = fwrite(ptr, size, nmemb, heads->stream); if(rc != cb) return rc; /* flush the stream to send off what we got earlier */ (void)fflush(heads->stream); } /* * This callback sets the filename where output shall be written when * curl options --remote-name (-O) and --remote-header-name (-J) have * been simultaneously given and additionally server returns an HTTP * Content-Disposition header specifying a filename property. */ curl_easy_getinfo(outs->config->easy, CURLINFO_PROTOCOL, &protocol); if(hdrcbdata->honor_cd_filename && (cb > 20) && checkprefix("Content-disposition:", str) && (protocol & (CURLPROTO_HTTPS|CURLPROTO_HTTP))) { const char *p = str + 20; /* look for the 'filename=' parameter (encoded filenames (*=) are not supported) */ for(;;) { char *filename; size_t len; while(*p && (p < end) && !ISALPHA(*p)) p++; if(p > end - 9) break; if(memcmp(p, "filename=", 9)) { /* no match, find next parameter */ while((p < end) && (*p != ';')) p++; continue; } p += 9; /* this expression below typecasts 'cb' only to avoid warning: signed and unsigned type in conditional expression */ len = (ssize_t)cb - (p - str); filename = parse_filename(p, len); if(filename) { if(outs->stream) { int rc; /* already opened and possibly written to */ if(outs->fopened) fclose(outs->stream); outs->stream = NULL; /* rename the initial file name to the new file name */ rc = rename(outs->filename, filename); if(rc != 0) { warnf(outs->config->global, "Failed to rename %s -> %s: %s\n", outs->filename, filename, strerror(errno)); } if(outs->alloc_filename) Curl_safefree(outs->filename); if(rc != 0) { free(filename); return failure; } } outs->is_cd_filename = TRUE; outs->s_isreg = TRUE; outs->fopened = FALSE; outs->filename = filename; outs->alloc_filename = TRUE; hdrcbdata->honor_cd_filename = FALSE; /* done now! */ if(!tool_create_output_file(outs)) return failure; } break; } if(!outs->stream && !tool_create_output_file(outs)) return failure; } if(hdrcbdata->config->show_headers && (protocol & (CURLPROTO_HTTP|CURLPROTO_HTTPS|CURLPROTO_RTSP|CURLPROTO_FILE))) { /* bold headers only for selected protocols */ char *value = NULL; if(!outs->stream && !tool_create_output_file(outs)) return failure; if(hdrcbdata->global->isatty && hdrcbdata->global->styled_output) value = memchr(ptr, ':', cb); if(value) { size_t namelen = value - ptr; fprintf(outs->stream, BOLD "%.*s" BOLDOFF ":", namelen, ptr); fwrite(&value[1], cb - namelen - 1, 1, outs->stream); } else /* not "handled", just show it */ fwrite(ptr, cb, 1, outs->stream); } return cb; } /* * Copies a file name part and returns an ALLOCATED data buffer. */ static char *parse_filename(const char *ptr, size_t len) { char *copy; char *p; char *q; char stop = '\0'; /* simple implementation of strndup() */ copy = malloc(len + 1); if(!copy) return NULL; memcpy(copy, ptr, len); copy[len] = '\0'; p = copy; if(*p == '\'' || *p == '"') { /* store the starting quote */ stop = *p; p++; } else stop = ';'; /* scan for the end letter and stop there */ q = strchr(p, stop); if(q) *q = '\0'; /* if the filename contains a path, only use filename portion */ q = strrchr(p, '/'); if(q) { p = q + 1; if(!*p) { Curl_safefree(copy); return NULL; } } /* If the filename contains a backslash, only use filename portion. The idea is that even systems that don't handle backslashes as path separators probably want the path removed for convenience. */ q = strrchr(p, '\\'); if(q) { p = q + 1; if(!*p) { Curl_safefree(copy); return NULL; } } /* make sure the file name doesn't end in \r or \n */ q = strchr(p, '\r'); if(q) *q = '\0'; q = strchr(p, '\n'); if(q) *q = '\0'; if(copy != p) memmove(copy, p, strlen(p) + 1); #if defined(MSDOS) || defined(WIN32) { char *sanitized; SANITIZEcode sc = sanitize_file_name(&sanitized, copy, 0); Curl_safefree(copy); if(sc) return NULL; copy = sanitized; } #endif /* MSDOS || WIN32 */ /* in case we built debug enabled, we allow an environment variable * named CURL_TESTDIR to prefix the given file name to put it into a * specific directory */ #ifdef DEBUGBUILD { char *tdir = curlx_getenv("CURL_TESTDIR"); if(tdir) { char buffer[512]; /* suitably large */ msnprintf(buffer, sizeof(buffer), "%s/%s", tdir, copy); Curl_safefree(copy); copy = strdup(buffer); /* clone the buffer, we don't use the libcurl aprintf() or similar since we want to use the same memory code as the "real" parse_filename function */ curl_free(tdir); } } #endif return copy; }
YifuLiu/AliOS-Things
components/curl/src/tool_cb_hdr.c
C
apache-2.0
8,137
#ifndef HEADER_CURL_TOOL_CB_HDR_H #define HEADER_CURL_TOOL_CB_HDR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" /* * curl operates using a single HdrCbData struct variable, a * pointer to this is passed as userdata pointer to tool_header_cb. * * 'outs' member is a pointer to the OutStruct variable used to keep * track of information relative to curl's output writing. * * 'heads' member is a pointer to the OutStruct variable used to keep * track of information relative to header response writing. * * 'honor_cd_filename' member is TRUE when tool_header_cb is allowed * to honor Content-Disposition filename property and accordingly * set 'outs' filename, otherwise FALSE; */ struct HdrCbData { struct GlobalConfig *global; struct OperationConfig *config; struct OutStruct *outs; struct OutStruct *heads; bool honor_cd_filename; }; /* ** callback for CURLOPT_HEADERFUNCTION */ size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata); #endif /* HEADER_CURL_TOOL_CB_HDR_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_hdr.h
C
apache-2.0
2,030
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_cb_prg.h" #include "tool_util.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef HAVE_TERMIOS_H # include <termios.h> #elif defined(HAVE_TERMIO_H) # include <termio.h> #endif /* 200 values generated by this perl code: my $pi = 3.1415; foreach my $i (1 .. 200) { printf "%d, ", sin($i/200 * 2 * $pi) * 5000 + 5000; } */ static const unsigned int sinus[] = { 5157, 5313, 5470, 5626, 5782, 5936, 6090, 6243, 6394, 6545, 6693, 6840, 6985, 7128, 7269, 7408, 7545, 7679, 7810, 7938, 8064, 8187, 8306, 8422, 8535, 8644, 8750, 8852, 8950, 9045, 9135, 9221, 9303, 9381, 9454, 9524, 9588, 9648, 9704, 9755, 9801, 9842, 9879, 9911, 9938, 9960, 9977, 9990, 9997, 9999, 9997, 9990, 9977, 9960, 9938, 9911, 9879, 9842, 9801, 9755, 9704, 9648, 9588, 9524, 9455, 9381, 9303, 9221, 9135, 9045, 8950, 8852, 8750, 8645, 8535, 8422, 8306, 8187, 8064, 7939, 7810, 7679, 7545, 7409, 7270, 7129, 6986, 6841, 6694, 6545, 6395, 6243, 6091, 5937, 5782, 5627, 5470, 5314, 5157, 5000, 4843, 4686, 4529, 4373, 4218, 4063, 3909, 3757, 3605, 3455, 3306, 3159, 3014, 2871, 2730, 2591, 2455, 2321, 2190, 2061, 1935, 1813, 1693, 1577, 1464, 1355, 1249, 1147, 1049, 955, 864, 778, 696, 618, 545, 476, 411, 351, 295, 244, 198, 157, 120, 88, 61, 39, 22, 9, 2, 0, 2, 9, 22, 39, 61, 88, 120, 156, 198, 244, 295, 350, 410, 475, 544, 618, 695, 777, 864, 954, 1048, 1146, 1248, 1354, 1463, 1576, 1692, 1812, 1934, 2060, 2188, 2320, 2454, 2590, 2729, 2870, 3013, 3158, 3305, 3454, 3604, 3755, 3908, 4062, 4216, 4372, 4528, 4685, 4842, 4999 }; static void fly(struct ProgressData *bar, bool moved) { char buf[256]; int pos; int check = bar->width - 2; msnprintf(buf, sizeof(buf), "%*s\r", bar->width-1, " "); memcpy(&buf[bar->bar], "-=O=-", 5); pos = sinus[bar->tick%200] / (10000 / check); buf[pos] = '#'; pos = sinus[(bar->tick + 5)%200] / (10000 / check); buf[pos] = '#'; pos = sinus[(bar->tick + 10)%200] / (10000 / check); buf[pos] = '#'; pos = sinus[(bar->tick + 15)%200] / (10000 / check); buf[pos] = '#'; fputs(buf, bar->out); bar->tick += 2; if(bar->tick >= 200) bar->tick -= 200; bar->bar += (moved?bar->barmove:0); if(bar->bar >= (bar->width - 6)) { bar->barmove = -1; bar->bar = bar->width - 6; } else if(bar->bar < 0) { bar->barmove = 1; bar->bar = 0; } } /* ** callback for CURLOPT_XFERINFOFUNCTION */ #define MAX_BARLENGTH 256 #if (SIZEOF_CURL_OFF_T == 4) # define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFF) #else /* assume CURL_SIZEOF_CURL_OFF_T == 8 */ # define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF) #endif int tool_progress_cb(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { /* The original progress-bar source code was written for curl by Lars Aas, and this new edition inherits some of his concepts. */ struct timeval now = tvnow(); struct ProgressData *bar = (struct ProgressData *)clientp; curl_off_t total; curl_off_t point; /* expected transfer size */ if((CURL_OFF_T_MAX - bar->initial_size) < (dltotal + ultotal)) total = CURL_OFF_T_MAX; else total = dltotal + ultotal + bar->initial_size; /* we've come this far */ if((CURL_OFF_T_MAX - bar->initial_size) < (dlnow + ulnow)) point = CURL_OFF_T_MAX; else point = dlnow + ulnow + bar->initial_size; if(bar->calls) { /* after first call... */ if(total) { /* we know the total data to get... */ if(bar->prev == point) /* progress didn't change since last invoke */ return 0; else if((tvdiff(now, bar->prevtime) < 100L) && point < total) /* limit progress-bar updating to 10 Hz except when we're at 100% */ return 0; } else { /* total is unknown */ if(tvdiff(now, bar->prevtime) < 100L) /* limit progress-bar updating to 10 Hz */ return 0; fly(bar, point != bar->prev); } } /* simply count invokes */ bar->calls++; if((total > 0) && (point != bar->prev)) { char line[MAX_BARLENGTH + 1]; char format[40]; double frac; double percent; int barwidth; int num; if(point > total) /* we have got more than the expected total! */ total = point; frac = (double)point / (double)total; percent = frac * 100.0; barwidth = bar->width - 7; num = (int) (((double)barwidth) * frac); if(num > MAX_BARLENGTH) num = MAX_BARLENGTH; memset(line, '#', num); line[num] = '\0'; msnprintf(format, sizeof(format), "\r%%-%ds %%5.1f%%%%", barwidth); fprintf(bar->out, format, line, percent); } fflush(bar->out); bar->prev = point; bar->prevtime = now; return 0; } void progressbarinit(struct ProgressData *bar, struct OperationConfig *config) { char *colp; memset(bar, 0, sizeof(struct ProgressData)); /* pass this through to progress function so * it can display progress towards total file * not just the part that's left. (21-may-03, dbyron) */ if(config->use_resume) bar->initial_size = config->resume_from; colp = curlx_getenv("COLUMNS"); if(colp) { char *endptr; long num = strtol(colp, &endptr, 10); if((endptr != colp) && (endptr == colp + strlen(colp)) && (num > 20)) bar->width = (int)num; curl_free(colp); } if(!bar->width) { int cols = 0; #ifdef TIOCGSIZE struct ttysize ts; if(!ioctl(STDIN_FILENO, TIOCGSIZE, &ts)) cols = ts.ts_cols; #elif defined(TIOCGWINSZ) struct winsize ts; if(!ioctl(STDIN_FILENO, TIOCGWINSZ, &ts)) cols = ts.ws_col; #elif defined(WIN32) { HANDLE stderr_hnd = GetStdHandle(STD_ERROR_HANDLE); CONSOLE_SCREEN_BUFFER_INFO console_info; if((stderr_hnd != INVALID_HANDLE_VALUE) && GetConsoleScreenBufferInfo(stderr_hnd, &console_info)) { /* * Do not use +1 to get the true screen-width since writing a * character at the right edge will cause a line wrap. */ cols = (int) (console_info.srWindow.Right - console_info.srWindow.Left); } } #endif /* TIOCGSIZE */ bar->width = cols; } if(!bar->width) bar->width = 79; else if(bar->width > MAX_BARLENGTH) bar->width = MAX_BARLENGTH; bar->out = config->global->errors; bar->tick = 150; bar->barmove = 1; }
YifuLiu/AliOS-Things
components/curl/src/tool_cb_prg.c
C
apache-2.0
7,628
#ifndef HEADER_CURL_TOOL_CB_PRG_H #define HEADER_CURL_TOOL_CB_PRG_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define CURL_PROGRESS_STATS 0 /* default progress display */ #define CURL_PROGRESS_BAR 1 struct ProgressData { int calls; curl_off_t prev; struct timeval prevtime; int width; FILE *out; /* where to write everything to */ curl_off_t initial_size; unsigned int tick; int bar; int barmove; }; void progressbarinit(struct ProgressData *bar, struct OperationConfig *config); /* ** callback for CURLOPT_PROGRESSFUNCTION */ int tool_progress_cb(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); #endif /* HEADER_CURL_TOOL_CB_PRG_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_prg.h
C
apache-2.0
1,801
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_cb_rea.h" #include "memdebug.h" /* keep this as LAST include */ /* ** callback for CURLOPT_READFUNCTION */ size_t tool_read_cb(void *buffer, size_t sz, size_t nmemb, void *userdata) { ssize_t rc; struct InStruct *in = userdata; rc = read(in->fd, buffer, sz*nmemb); if(rc < 0) { if(errno == EAGAIN) { errno = 0; in->config->readbusy = TRUE; return CURL_READFUNC_PAUSE; } /* since size_t is unsigned we can't return negative values fine */ rc = 0; } in->config->readbusy = FALSE; return (size_t)rc; }
YifuLiu/AliOS-Things
components/curl/src/tool_cb_rea.c
C
apache-2.0
1,728
#ifndef HEADER_CURL_TOOL_CB_REA_H #define HEADER_CURL_TOOL_CB_REA_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" /* ** callback for CURLOPT_READFUNCTION */ size_t tool_read_cb(void *buffer, size_t sz, size_t nmemb, void *userdata); #endif /* HEADER_CURL_TOOL_CB_REA_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_rea.h
C
apache-2.0
1,279
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_cb_see.h" #include "memdebug.h" /* keep this as LAST include */ /* OUR_MAX_SEEK_L has 'long' data type, OUR_MAX_SEEK_O has 'curl_off_t, both represent the same value. Maximum offset used here when we lseek using a 'long' data type offset */ #define OUR_MAX_SEEK_L 2147483647L - 1L #define OUR_MAX_SEEK_O CURL_OFF_T_C(0x7FFFFFFF) - CURL_OFF_T_C(0x1) /* ** callback for CURLOPT_SEEKFUNCTION ** ** Notice that this is not supposed to return the resulting offset. This ** shall only return CURL_SEEKFUNC_* return codes. */ int tool_seek_cb(void *userdata, curl_off_t offset, int whence) { struct InStruct *in = userdata; #if(CURL_SIZEOF_CURL_OFF_T > SIZEOF_OFF_T) && !defined(USE_WIN32_LARGE_FILES) /* The offset check following here is only interesting if curl_off_t is larger than off_t and we are not using the WIN32 large file support macros that provide the support to do 64bit seeks correctly */ if(offset > OUR_MAX_SEEK_O) { /* Some precaution code to work around problems with different data sizes to allow seeking >32bit even if off_t is 32bit. Should be very rare and is really valid on weirdo-systems. */ curl_off_t left = offset; if(whence != SEEK_SET) /* this code path doesn't support other types */ return CURL_SEEKFUNC_FAIL; if(LSEEK_ERROR == lseek(in->fd, 0, SEEK_SET)) /* couldn't rewind to beginning */ return CURL_SEEKFUNC_FAIL; while(left) { long step = (left > OUR_MAX_SEEK_O) ? OUR_MAX_SEEK_L : (long)left; if(LSEEK_ERROR == lseek(in->fd, step, SEEK_CUR)) /* couldn't seek forwards the desired amount */ return CURL_SEEKFUNC_FAIL; left -= step; } return CURL_SEEKFUNC_OK; } #endif if(LSEEK_ERROR == lseek(in->fd, offset, whence)) /* couldn't rewind, the reason is in errno but errno is just not portable enough and we don't actually care that much why we failed. We'll let libcurl know that it may try other means if it wants to. */ return CURL_SEEKFUNC_CANTSEEK; return CURL_SEEKFUNC_OK; } #if defined(WIN32) && !defined(__MINGW64__) #ifdef __BORLANDC__ /* 64-bit lseek-like function unavailable */ # define _lseeki64(hnd,ofs,whence) lseek(hnd,ofs,whence) #endif #ifdef __POCC__ # if(__POCC__ < 450) /* 64-bit lseek-like function unavailable */ # define _lseeki64(hnd,ofs,whence) _lseek(hnd,ofs,whence) # else # define _lseeki64(hnd,ofs,whence) _lseek64(hnd,ofs,whence) # endif #endif #ifdef _WIN32_WCE /* 64-bit lseek-like function unavailable */ # undef _lseeki64 # define _lseeki64(hnd,ofs,whence) lseek(hnd,ofs,whence) # undef _get_osfhandle # define _get_osfhandle(fd) (fd) #endif /* * Truncate a file handle at a 64-bit position 'where'. */ int tool_ftruncate64(int fd, curl_off_t where) { intptr_t handle = _get_osfhandle(fd); if(_lseeki64(fd, where, SEEK_SET) < 0) return -1; if(!SetEndOfFile((HANDLE)handle)) return -1; return 0; } #endif /* WIN32 && ! __MINGW64__ */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_see.c
C
apache-2.0
4,182
#ifndef HEADER_CURL_TOOL_CB_SEE_H #define HEADER_CURL_TOOL_CB_SEE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #if defined(WIN32) && !defined(__MINGW64__) int tool_ftruncate64(int fd, curl_off_t where); #undef ftruncate #define ftruncate(fd,where) tool_ftruncate64(fd,where) #ifndef HAVE_FTRUNCATE # define HAVE_FTRUNCATE 1 #endif #endif /* WIN32 && ! __MINGW64__ */ /* ** callback for CURLOPT_SEEKFUNCTION */ int tool_seek_cb(void *userdata, curl_off_t offset, int whence); #endif /* HEADER_CURL_TOOL_CB_SEE_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_see.h
C
apache-2.0
1,532
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_msgs.h" #include "tool_cb_wrt.h" #include "memdebug.h" /* keep this as LAST include */ /* create a local file for writing, return TRUE on success */ bool tool_create_output_file(struct OutStruct *outs) { struct GlobalConfig *global = outs->config->global; FILE *file; if(!outs->filename || !*outs->filename) { warnf(global, "Remote filename has no length!\n"); return FALSE; } if(outs->is_cd_filename) { /* don't overwrite existing files */ file = fopen(outs->filename, "rb"); if(file) { fclose(file); warnf(global, "Refusing to overwrite %s: %s\n", outs->filename, strerror(EEXIST)); return FALSE; } } /* open file for writing */ file = fopen(outs->filename, "wb"); if(!file) { warnf(global, "Failed to create the file %s: %s\n", outs->filename, strerror(errno)); return FALSE; } outs->s_isreg = TRUE; outs->fopened = TRUE; outs->stream = file; outs->bytes = 0; outs->init = 0; return TRUE; } /* ** callback for CURLOPT_WRITEFUNCTION */ size_t tool_write_cb(char *buffer, size_t sz, size_t nmemb, void *userdata) { size_t rc; struct OutStruct *outs = userdata; struct OperationConfig *config = outs->config; size_t bytes = sz * nmemb; bool is_tty = config->global->isatty; #ifdef WIN32 CONSOLE_SCREEN_BUFFER_INFO console_info; intptr_t fhnd; #endif /* * Once that libcurl has called back tool_write_cb() the returned value * is checked against the amount that was intended to be written, if * it does not match then it fails with CURLE_WRITE_ERROR. So at this * point returning a value different from sz*nmemb indicates failure. */ const size_t failure = bytes ? 0 : 1; #ifdef DEBUGBUILD { char *tty = curlx_getenv("CURL_ISATTY"); if(tty) { is_tty = TRUE; curl_free(tty); } } if(config->show_headers) { if(bytes > (size_t)CURL_MAX_HTTP_HEADER) { warnf(config->global, "Header data size exceeds single call write " "limit!\n"); return failure; } } else { if(bytes > (size_t)CURL_MAX_WRITE_SIZE) { warnf(config->global, "Data size exceeds single call write limit!\n"); return failure; } } { /* Some internal congruency checks on received OutStruct */ bool check_fails = FALSE; if(outs->filename) { /* regular file */ if(!*outs->filename) check_fails = TRUE; if(!outs->s_isreg) check_fails = TRUE; if(outs->fopened && !outs->stream) check_fails = TRUE; if(!outs->fopened && outs->stream) check_fails = TRUE; if(!outs->fopened && outs->bytes) check_fails = TRUE; } else { /* standard stream */ if(!outs->stream || outs->s_isreg || outs->fopened) check_fails = TRUE; if(outs->alloc_filename || outs->is_cd_filename || outs->init) check_fails = TRUE; } if(check_fails) { warnf(config->global, "Invalid output struct data for write callback\n"); return failure; } } #endif if(!outs->stream && !tool_create_output_file(outs)) return failure; if(is_tty && (outs->bytes < 2000) && !config->terminal_binary_ok) { /* binary output to terminal? */ if(memchr(buffer, 0, bytes)) { warnf(config->global, "Binary output can mess up your terminal. " "Use \"--output -\" to tell curl to output it to your terminal " "anyway, or consider \"--output <FILE>\" to save to a file.\n"); config->synthetic_error = ERR_BINARY_TERMINAL; return failure; } } #ifdef WIN32 fhnd = _get_osfhandle(fileno(outs->stream)); if(isatty(fileno(outs->stream)) && GetConsoleScreenBufferInfo((HANDLE)fhnd, &console_info)) { DWORD in_len = (DWORD)(sz * nmemb); wchar_t* wc_buf; DWORD wc_len; /* calculate buffer size for wide characters */ wc_len = MultiByteToWideChar(CP_UTF8, 0, buffer, in_len, NULL, 0); wc_buf = (wchar_t*) malloc(wc_len * sizeof(wchar_t)); if(!wc_buf) return failure; /* calculate buffer size for multi-byte characters */ wc_len = MultiByteToWideChar(CP_UTF8, 0, buffer, in_len, wc_buf, wc_len); if(!wc_len) { free(wc_buf); return failure; } if(!WriteConsoleW( (HANDLE) fhnd, wc_buf, wc_len, &wc_len, NULL)) { free(wc_buf); return failure; } free(wc_buf); rc = bytes; } else #endif rc = fwrite(buffer, sz, nmemb, outs->stream); if(bytes == rc) /* we added this amount of data to the output */ outs->bytes += bytes; if(config->readbusy) { config->readbusy = FALSE; curl_easy_pause(config->easy, CURLPAUSE_CONT); } if(config->nobuffer) { /* output buffering disabled */ int res = fflush(outs->stream); if(res) return failure; } return rc; }
YifuLiu/AliOS-Things
components/curl/src/tool_cb_wrt.c
C
apache-2.0
6,056
#ifndef HEADER_CURL_TOOL_CB_WRT_H #define HEADER_CURL_TOOL_CB_WRT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" /* ** callback for CURLOPT_WRITEFUNCTION */ size_t tool_write_cb(char *buffer, size_t sz, size_t nmemb, void *userdata); /* create a local file for writing, return TRUE on success */ bool tool_create_output_file(struct OutStruct *outs); #endif /* HEADER_CURL_TOOL_CB_WRT_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cb_wrt.h
C
apache-2.0
1,398
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "tool_cfgable.h" #include "tool_main.h" #include "memdebug.h" /* keep this as LAST include */ void config_init(struct OperationConfig* config) { memset(config, 0, sizeof(struct OperationConfig)); config->postfieldsize = -1; config->use_httpget = FALSE; config->create_dirs = FALSE; config->maxredirs = DEFAULT_MAXREDIRS; config->proto = CURLPROTO_ALL; config->proto_present = FALSE; config->proto_redir = CURLPROTO_ALL & /* All except FILE, SCP and SMB */ ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB | CURLPROTO_SMBS); config->proto_redir_present = FALSE; config->proto_default = NULL; config->tcp_nodelay = TRUE; /* enabled by default */ config->happy_eyeballs_timeout_ms = CURL_HET_DEFAULT; config->http09_allowed = TRUE; } static void free_config_fields(struct OperationConfig *config) { struct getout *urlnode; Curl_safefree(config->random_file); Curl_safefree(config->egd_file); Curl_safefree(config->useragent); Curl_safefree(config->altsvc); Curl_safefree(config->cookie); Curl_safefree(config->cookiejar); Curl_safefree(config->cookiefile); Curl_safefree(config->postfields); Curl_safefree(config->referer); Curl_safefree(config->headerfile); Curl_safefree(config->ftpport); Curl_safefree(config->iface); Curl_safefree(config->range); Curl_safefree(config->userpwd); Curl_safefree(config->tls_username); Curl_safefree(config->tls_password); Curl_safefree(config->tls_authtype); Curl_safefree(config->proxy_tls_username); Curl_safefree(config->proxy_tls_password); Curl_safefree(config->proxy_tls_authtype); Curl_safefree(config->proxyuserpwd); Curl_safefree(config->proxy); Curl_safefree(config->dns_ipv6_addr); Curl_safefree(config->dns_ipv4_addr); Curl_safefree(config->dns_interface); Curl_safefree(config->dns_servers); Curl_safefree(config->noproxy); Curl_safefree(config->mail_from); curl_slist_free_all(config->mail_rcpt); Curl_safefree(config->mail_auth); Curl_safefree(config->netrc_file); urlnode = config->url_list; while(urlnode) { struct getout *next = urlnode->next; Curl_safefree(urlnode->url); Curl_safefree(urlnode->outfile); Curl_safefree(urlnode->infile); Curl_safefree(urlnode); urlnode = next; } config->url_list = NULL; config->url_last = NULL; config->url_get = NULL; config->url_out = NULL; Curl_safefree(config->doh_url); Curl_safefree(config->cipher_list); Curl_safefree(config->proxy_cipher_list); Curl_safefree(config->cert); Curl_safefree(config->proxy_cert); Curl_safefree(config->cert_type); Curl_safefree(config->proxy_cert_type); Curl_safefree(config->cacert); Curl_safefree(config->proxy_cacert); Curl_safefree(config->capath); Curl_safefree(config->proxy_capath); Curl_safefree(config->crlfile); Curl_safefree(config->pinnedpubkey); Curl_safefree(config->proxy_pinnedpubkey); Curl_safefree(config->proxy_crlfile); Curl_safefree(config->key); Curl_safefree(config->proxy_key); Curl_safefree(config->key_type); Curl_safefree(config->proxy_key_type); Curl_safefree(config->key_passwd); Curl_safefree(config->proxy_key_passwd); Curl_safefree(config->pubkey); Curl_safefree(config->hostpubmd5); Curl_safefree(config->engine); Curl_safefree(config->request_target); Curl_safefree(config->customrequest); Curl_safefree(config->krblevel); Curl_safefree(config->oauth_bearer); Curl_safefree(config->unix_socket_path); Curl_safefree(config->writeout); Curl_safefree(config->proto_default); curl_slist_free_all(config->quote); curl_slist_free_all(config->postquote); curl_slist_free_all(config->prequote); curl_slist_free_all(config->headers); curl_slist_free_all(config->proxyheaders); curl_mime_free(config->mimepost); config->mimepost = NULL; tool_mime_free(config->mimeroot); config->mimeroot = NULL; config->mimecurrent = NULL; curl_slist_free_all(config->telnet_options); curl_slist_free_all(config->resolve); curl_slist_free_all(config->connect_to); Curl_safefree(config->preproxy); Curl_safefree(config->proxy_service_name); Curl_safefree(config->service_name); Curl_safefree(config->ftp_account); Curl_safefree(config->ftp_alternative_to_user); } void config_free(struct OperationConfig *config) { struct OperationConfig *last = config; /* Free each of the structures in reverse order */ while(last) { struct OperationConfig *prev = last->prev; free_config_fields(last); free(last); last = prev; } }
YifuLiu/AliOS-Things
components/curl/src/tool_cfgable.c
C
apache-2.0
5,593
#ifndef HEADER_CURL_TOOL_CFGABLE_H #define HEADER_CURL_TOOL_CFGABLE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "tool_sdecls.h" #include "tool_metalink.h" #include "tool_formparse.h" typedef enum { ERR_NONE, ERR_BINARY_TERMINAL = 1, /* binary to terminal detected */ ERR_LAST } curl_error; struct GlobalConfig; struct OperationConfig { CURL *easy; /* A copy of the handle from GlobalConfig */ bool remote_time; char *random_file; char *egd_file; char *useragent; char *cookie; /* single line with specified cookies */ char *cookiejar; /* write to this file */ char *cookiefile; /* read from this file */ char *altsvc; /* alt-svc cache file name */ bool cookiesession; /* new session? */ bool encoding; /* Accept-Encoding please */ bool tr_encoding; /* Transfer-Encoding please */ unsigned long authtype; /* auth bitmask */ bool use_resume; bool resume_from_current; bool disable_epsv; bool disable_eprt; bool ftp_pret; long proto; bool proto_present; long proto_redir; bool proto_redir_present; char *proto_default; curl_off_t resume_from; char *postfields; curl_off_t postfieldsize; char *referer; double timeout; double connecttimeout; long maxredirs; curl_off_t max_filesize; char *headerfile; char *ftpport; char *iface; long localport; long localportrange; unsigned short porttouse; char *range; long low_speed_limit; long low_speed_time; char *dns_servers; /* dot notation: 1.1.1.1;2.2.2.2 */ char *dns_interface; /* interface name */ char *dns_ipv4_addr; /* dot notation */ char *dns_ipv6_addr; /* dot notation */ char *userpwd; char *login_options; char *tls_username; char *tls_password; char *tls_authtype; char *proxy_tls_username; char *proxy_tls_password; char *proxy_tls_authtype; char *proxyuserpwd; char *proxy; int proxyver; /* set to CURLPROXY_HTTP* define */ char *noproxy; char *mail_from; struct curl_slist *mail_rcpt; char *mail_auth; bool sasl_ir; /* Enable/disable SASL initial response */ bool proxytunnel; bool ftp_append; /* APPE on ftp */ bool use_ascii; /* select ascii or text transfer */ bool autoreferer; /* automatically set referer */ bool failonerror; /* fail on (HTTP) errors */ bool show_headers; /* show headers to data output */ bool no_body; /* don't get the body */ bool dirlistonly; /* only get the FTP dir list */ bool followlocation; /* follow http redirects */ bool unrestricted_auth; /* Continue to send authentication (user+password) when following ocations, even when hostname changed */ bool netrc_opt; bool netrc; char *netrc_file; struct getout *url_list; /* point to the first node */ struct getout *url_last; /* point to the last/current node */ struct getout *url_get; /* point to the node to fill in URL */ struct getout *url_out; /* point to the node to fill in outfile */ struct getout *url_ul; /* point to the node to fill in upload */ char *doh_url; char *cipher_list; char *proxy_cipher_list; char *cipher13_list; char *proxy_cipher13_list; char *cert; char *proxy_cert; char *cert_type; char *proxy_cert_type; char *cacert; char *proxy_cacert; char *capath; char *proxy_capath; char *crlfile; char *proxy_crlfile; char *pinnedpubkey; char *proxy_pinnedpubkey; char *key; char *proxy_key; char *key_type; char *proxy_key_type; char *key_passwd; char *proxy_key_passwd; char *pubkey; char *hostpubmd5; char *engine; bool crlf; char *customrequest; char *krblevel; char *request_target; long httpversion; bool http09_allowed; bool nobuffer; bool readbusy; /* set when reading input returns EAGAIN */ bool globoff; bool use_httpget; bool insecure_ok; /* set TRUE to allow insecure SSL connects */ bool proxy_insecure_ok; /* set TRUE to allow insecure SSL connects for proxy */ bool terminal_binary_ok; bool verifystatus; bool create_dirs; bool ftp_create_dirs; bool ftp_skip_ip; bool proxynegotiate; bool proxyntlm; bool proxydigest; bool proxybasic; bool proxyanyauth; char *writeout; /* %-styled format string to output */ struct curl_slist *quote; struct curl_slist *postquote; struct curl_slist *prequote; long ssl_version; long ssl_version_max; long proxy_ssl_version; long ip_version; curl_TimeCond timecond; curl_off_t condtime; struct curl_slist *headers; struct curl_slist *proxyheaders; tool_mime *mimeroot; tool_mime *mimecurrent; curl_mime *mimepost; struct curl_slist *telnet_options; struct curl_slist *resolve; struct curl_slist *connect_to; HttpReq httpreq; /* for bandwidth limiting features: */ curl_off_t sendpersecond; /* send to peer */ curl_off_t recvpersecond; /* receive from peer */ bool ftp_ssl; bool ftp_ssl_reqd; bool ftp_ssl_control; bool ftp_ssl_ccc; int ftp_ssl_ccc_mode; char *preproxy; int socks5_gssapi_nec; /* The NEC reference server does not protect the encryption type exchange */ unsigned long socks5_auth;/* auth bitmask for socks5 proxies */ char *proxy_service_name; /* set authentication service name for HTTP and SOCKS5 proxies */ char *service_name; /* set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO */ bool tcp_nodelay; bool tcp_fastopen; long req_retry; /* number of retries */ bool retry_connrefused; /* set connection refused as a transient error */ long retry_delay; /* delay between retries (in seconds) */ long retry_maxtime; /* maximum time to keep retrying */ char *ftp_account; /* for ACCT */ char *ftp_alternative_to_user; /* send command if USER/PASS fails */ int ftp_filemethod; long tftp_blksize; /* TFTP BLKSIZE option */ bool tftp_no_options; /* do not send TFTP options requests */ bool ignorecl; /* --ignore-content-length */ bool disable_sessionid; bool raw; bool post301; bool post302; bool post303; bool nokeepalive; /* for keepalive needs */ long alivetime; bool content_disposition; /* use Content-disposition filename */ int default_node_flags; /* default flags to search for each 'node', which is basically each given URL to transfer */ bool xattr; /* store metadata in extended attributes */ long gssapi_delegation; bool ssl_allow_beast; /* allow this SSL vulnerability */ bool proxy_ssl_allow_beast; /* allow this SSL vulnerability for proxy*/ bool ssl_no_revoke; /* disable SSL certificate revocation checks */ /*bool proxy_ssl_no_revoke; */ bool use_metalink; /* process given URLs as metalink XML file */ metalinkfile *metalinkfile_list; /* point to the first node */ metalinkfile *metalinkfile_last; /* point to the last/current node */ #ifdef CURLDEBUG bool test_event_based; #endif char *oauth_bearer; /* OAuth 2.0 bearer token */ bool nonpn; /* enable/disable TLS NPN extension */ bool noalpn; /* enable/disable TLS ALPN extension */ char *unix_socket_path; /* path to Unix domain socket */ bool abstract_unix_socket; /* path to an abstract Unix domain socket */ bool falsestart; bool path_as_is; double expect100timeout; bool suppress_connect_headers; /* suppress proxy CONNECT response headers from user callbacks */ curl_error synthetic_error; /* if non-zero, it overrides any libcurl error */ bool ssh_compression; /* enable/disable SSH compression */ long happy_eyeballs_timeout_ms; /* happy eyeballs timeout in milliseconds. 0 is valid. default: CURL_HET_DEFAULT. */ bool haproxy_protocol; /* whether to send HAProxy protocol v1 */ bool disallow_username_in_url; /* disallow usernames in URLs */ struct GlobalConfig *global; struct OperationConfig *prev; struct OperationConfig *next; /* Always last in the struct */ }; struct GlobalConfig { CURL *easy; /* Once we have one, we keep it here */ int showerror; /* -1 == unset, default => show errors 0 => -s is used to NOT show errors 1 => -S has been used to show errors */ bool mute; /* don't show messages, --silent given */ bool noprogress; /* don't show progress bar --silent given */ bool isatty; /* Updated internally if output is a tty */ FILE *errors; /* Error stream, defaults to stderr */ bool errors_fopened; /* Whether error stream isn't stderr */ char *trace_dump; /* file to dump the network trace to */ FILE *trace_stream; bool trace_fopened; trace tracetype; bool tracetime; /* include timestamp? */ int progressmode; /* CURL_PROGRESS_BAR / CURL_PROGRESS_STATS */ char *libcurl; /* Output libcurl code to this file name */ bool fail_early; /* exit on first transfer error */ bool styled_output; /* enable fancy output style detection */ struct OperationConfig *first; struct OperationConfig *current; struct OperationConfig *last; /* Always last in the struct */ }; void config_init(struct OperationConfig *config); void config_free(struct OperationConfig *config); #endif /* HEADER_CURL_TOOL_CFGABLE_H */
YifuLiu/AliOS-Things
components/curl/src/tool_cfgable.h
C
apache-2.0
10,956
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef CURL_DOES_CONVERSIONS #ifdef HAVE_ICONV # include <iconv.h> #endif #include "tool_convert.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef HAVE_ICONV /* curl tool iconv conversion descriptors */ static iconv_t inbound_cd = (iconv_t)-1; static iconv_t outbound_cd = (iconv_t)-1; /* set default codesets for iconv */ #ifndef CURL_ICONV_CODESET_OF_NETWORK # define CURL_ICONV_CODESET_OF_NETWORK "ISO8859-1" #endif /* * convert_to_network() is a curl tool function to convert * from the host encoding to ASCII on non-ASCII platforms. */ CURLcode convert_to_network(char *buffer, size_t length) { /* translate from the host encoding to the network encoding */ char *input_ptr, *output_ptr; size_t res, in_bytes, out_bytes; /* open an iconv conversion descriptor if necessary */ if(outbound_cd == (iconv_t)-1) { outbound_cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK, CURL_ICONV_CODESET_OF_HOST); if(outbound_cd == (iconv_t)-1) { return CURLE_CONV_FAILED; } } /* call iconv */ input_ptr = output_ptr = buffer; in_bytes = out_bytes = length; res = iconv(outbound_cd, &input_ptr, &in_bytes, &output_ptr, &out_bytes); if((res == (size_t)-1) || (in_bytes != 0)) { return CURLE_CONV_FAILED; } return CURLE_OK; } /* * convert_from_network() is a curl tool function * for performing ASCII conversions on non-ASCII platforms. */ CURLcode convert_from_network(char *buffer, size_t length) { /* translate from the network encoding to the host encoding */ char *input_ptr, *output_ptr; size_t res, in_bytes, out_bytes; /* open an iconv conversion descriptor if necessary */ if(inbound_cd == (iconv_t)-1) { inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST, CURL_ICONV_CODESET_OF_NETWORK); if(inbound_cd == (iconv_t)-1) { return CURLE_CONV_FAILED; } } /* call iconv */ input_ptr = output_ptr = buffer; in_bytes = out_bytes = length; res = iconv(inbound_cd, &input_ptr, &in_bytes, &output_ptr, &out_bytes); if((res == (size_t)-1) || (in_bytes != 0)) { return CURLE_CONV_FAILED; } return CURLE_OK; } void convert_cleanup(void) { /* close iconv conversion descriptors */ if(inbound_cd != (iconv_t)-1) (void)iconv_close(inbound_cd); if(outbound_cd != (iconv_t)-1) (void)iconv_close(outbound_cd); } #endif /* HAVE_ICONV */ char convert_char(curl_infotype infotype, char this_char) { /* determine how this specific character should be displayed */ switch(infotype) { case CURLINFO_DATA_IN: case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: /* data, treat as ASCII */ if(this_char < 0x20 || this_char >= 0x7f) { /* non-printable ASCII, use a replacement character */ return UNPRINTABLE_CHAR; } /* printable ASCII hex value: convert to host encoding */ (void)convert_from_network(&this_char, 1); /* FALLTHROUGH */ default: /* treat as host encoding */ if(ISPRINT(this_char) && (this_char != '\t') && (this_char != '\r') && (this_char != '\n')) { /* printable characters excluding tabs and line end characters */ return this_char; } break; } /* non-printable, use a replacement character */ return UNPRINTABLE_CHAR; } #endif /* CURL_DOES_CONVERSIONS */
YifuLiu/AliOS-Things
components/curl/src/tool_convert.c
C
apache-2.0
4,458
#ifndef HEADER_CURL_TOOL_CONVERT_H #define HEADER_CURL_TOOL_CONVERT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef CURL_DOES_CONVERSIONS #ifdef HAVE_ICONV CURLcode convert_to_network(char *buffer, size_t length); CURLcode convert_from_network(char *buffer, size_t length); void convert_cleanup(void); #endif /* HAVE_ICONV */ char convert_char(curl_infotype infotype, char this_char); #endif /* CURL_DOES_CONVERSIONS */ #if !defined(CURL_DOES_CONVERSIONS) || !defined(HAVE_ICONV) #define convert_cleanup() Curl_nop_stmt #endif #endif /* HEADER_CURL_TOOL_CONVERT_H */
YifuLiu/AliOS-Things
components/curl/src/tool_convert.h
C
apache-2.0
1,586
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include <sys/stat.h> #ifdef WIN32 # include <direct.h> #endif #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_dirhie.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef NETWARE # ifndef __NOVELL_LIBC__ # define mkdir mkdir_510 # endif #endif #if defined(WIN32) || (defined(MSDOS) && !defined(__DJGPP__)) # define mkdir(x,y) (mkdir)((x)) # ifndef F_OK # define F_OK 0 # endif #endif static void show_dir_errno(FILE *errors, const char *name) { switch(errno) { #ifdef EACCES case EACCES: fprintf(errors, "You don't have permission to create %s.\n", name); break; #endif #ifdef ENAMETOOLONG case ENAMETOOLONG: fprintf(errors, "The directory name %s is too long.\n", name); break; #endif #ifdef EROFS case EROFS: fprintf(errors, "%s resides on a read-only file system.\n", name); break; #endif #ifdef ENOSPC case ENOSPC: fprintf(errors, "No space left on the file system that will " "contain the directory %s.\n", name); break; #endif #ifdef EDQUOT case EDQUOT: fprintf(errors, "Cannot create directory %s because you " "exceeded your quota.\n", name); break; #endif default : fprintf(errors, "Error creating directory %s.\n", name); break; } } /* * Create the needed directory hierarchy recursively in order to save * multi-GETs in file output, ie: * curl "http://my.site/dir[1-5]/file[1-5].txt" -o "dir#1/file#2.txt" * should create all the dir* automagically */ #if defined(WIN32) || defined(__DJGPP__) /* systems that may use either or when specifying a path */ #define PATH_DELIMITERS "\\/" #else #define PATH_DELIMITERS DIR_CHAR #endif CURLcode create_dir_hierarchy(const char *outfile, FILE *errors) { char *tempdir; char *tempdir2; char *outdup; char *dirbuildup; CURLcode result = CURLE_OK; size_t outlen; outlen = strlen(outfile); outdup = strdup(outfile); if(!outdup) return CURLE_OUT_OF_MEMORY; dirbuildup = malloc(outlen + 1); if(!dirbuildup) { Curl_safefree(outdup); return CURLE_OUT_OF_MEMORY; } dirbuildup[0] = '\0'; /* Allow strtok() here since this isn't used threaded */ /* !checksrc! disable BANNEDFUNC 2 */ tempdir = strtok(outdup, PATH_DELIMITERS); while(tempdir != NULL) { tempdir2 = strtok(NULL, PATH_DELIMITERS); /* since strtok returns a token for the last word even if not ending with DIR_CHAR, we need to prune it */ if(tempdir2 != NULL) { size_t dlen = strlen(dirbuildup); if(dlen) msnprintf(&dirbuildup[dlen], outlen - dlen, "%s%s", DIR_CHAR, tempdir); else { if(outdup == tempdir) /* the output string doesn't start with a separator */ strcpy(dirbuildup, tempdir); else msnprintf(dirbuildup, outlen, "%s%s", DIR_CHAR, tempdir); } if((-1 == mkdir(dirbuildup, (mode_t)0000750)) && (errno != EEXIST)) { show_dir_errno(errors, dirbuildup); result = CURLE_WRITE_ERROR; break; /* get out of loop */ } } tempdir = tempdir2; } Curl_safefree(dirbuildup); Curl_safefree(outdup); return result; }
YifuLiu/AliOS-Things
components/curl/src/tool_dirhie.c
C
apache-2.0
4,248
#ifndef HEADER_CURL_TOOL_DIRHIE_H #define HEADER_CURL_TOOL_DIRHIE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" CURLcode create_dir_hierarchy(const char *outfile, FILE *errors); #endif /* HEADER_CURL_TOOL_DIRHIE_H */
YifuLiu/AliOS-Things
components/curl/src/tool_dirhie.h
C
apache-2.0
1,225
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #if defined(MSDOS) || defined(WIN32) #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME) # include <libgen.h> #endif #ifdef WIN32 # include <tlhelp32.h> # include "tool_cfgable.h" # include "tool_libinfo.h" #endif #include "tool_bname.h" #include "tool_doswin.h" #include "memdebug.h" /* keep this as LAST include */ /* * Macros ALWAYS_TRUE and ALWAYS_FALSE are used to avoid compiler warnings. */ #define ALWAYS_TRUE (1) #define ALWAYS_FALSE (0) #if defined(_MSC_VER) && !defined(__POCC__) # undef ALWAYS_TRUE # undef ALWAYS_FALSE # if (_MSC_VER < 1500) # define ALWAYS_TRUE (0, 1) # define ALWAYS_FALSE (1, 0) # else # define ALWAYS_TRUE \ __pragma(warning(push)) \ __pragma(warning(disable:4127)) \ (1) \ __pragma(warning(pop)) # define ALWAYS_FALSE \ __pragma(warning(push)) \ __pragma(warning(disable:4127)) \ (0) \ __pragma(warning(pop)) # endif #endif #ifdef WIN32 # undef PATH_MAX # define PATH_MAX MAX_PATH #endif #ifndef S_ISCHR # ifdef S_IFCHR # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) # else # define S_ISCHR(m) (0) /* cannot tell if file is a device */ # endif #endif #ifdef WIN32 # define _use_lfn(f) ALWAYS_TRUE /* long file names always available */ #elif !defined(__DJGPP__) || (__DJGPP__ < 2) /* DJGPP 2.0 has _use_lfn() */ # define _use_lfn(f) ALWAYS_FALSE /* long file names never available */ #elif defined(__DJGPP__) # include <fcntl.h> /* _use_lfn(f) prototype */ #endif #ifndef UNITTESTS static SANITIZEcode truncate_dryrun(const char *path, const size_t truncate_pos); #ifdef MSDOS static SANITIZEcode msdosify(char **const sanitized, const char *file_name, int flags); #endif static SANITIZEcode rename_if_reserved_dos_device_name(char **const sanitized, const char *file_name, int flags); #endif /* !UNITTESTS (static declarations used if no unit tests) */ /* Sanitize a file or path name. All banned characters are replaced by underscores, for example: f?*foo => f__foo f:foo::$DATA => f_foo__$DATA f:\foo:bar => f__foo_bar f:\foo:bar => f:\foo:bar (flag SANITIZE_ALLOW_PATH) This function was implemented according to the guidelines in 'Naming Files, Paths, and Namespaces' section 'Naming Conventions'. https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx Flags ----- SANITIZE_ALLOW_COLONS: Allow colons. Without this flag colons are sanitized. SANITIZE_ALLOW_PATH: Allow path separators and colons. Without this flag path separators and colons are sanitized. SANITIZE_ALLOW_RESERVED: Allow reserved device names. Without this flag a reserved device name is renamed (COM1 => _COM1) unless it's in a UNC prefixed path. SANITIZE_ALLOW_TRUNCATE: Allow truncating a long filename. Without this flag if the sanitized filename or path will be too long an error occurs. With this flag the filename --and not any other parts of the path-- may be truncated to at least a single character. A filename followed by an alternate data stream (ADS) cannot be truncated in any case. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL. */ SANITIZEcode sanitize_file_name(char **const sanitized, const char *file_name, int flags) { char *p, *target; size_t len; SANITIZEcode sc; size_t max_sanitized_len; if(!sanitized) return SANITIZE_ERR_BAD_ARGUMENT; *sanitized = NULL; if(!file_name) return SANITIZE_ERR_BAD_ARGUMENT; if((flags & SANITIZE_ALLOW_PATH)) { #ifndef MSDOS if(file_name[0] == '\\' && file_name[1] == '\\') /* UNC prefixed path \\ (eg \\?\C:\foo) */ max_sanitized_len = 32767-1; else #endif max_sanitized_len = PATH_MAX-1; } else /* The maximum length of a filename. FILENAME_MAX is often the same as PATH_MAX, in other words it is 260 and does not discount the path information therefore we shouldn't use it. */ max_sanitized_len = (PATH_MAX-1 > 255) ? 255 : PATH_MAX-1; len = strlen(file_name); if(len > max_sanitized_len) { if(!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(file_name, max_sanitized_len)) return SANITIZE_ERR_INVALID_PATH; len = max_sanitized_len; } target = malloc(len + 1); if(!target) return SANITIZE_ERR_OUT_OF_MEMORY; strncpy(target, file_name, len); target[len] = '\0'; #ifndef MSDOS if((flags & SANITIZE_ALLOW_PATH) && !strncmp(target, "\\\\?\\", 4)) /* Skip the literal path prefix \\?\ */ p = target + 4; else #endif p = target; /* replace control characters and other banned characters */ for(; *p; ++p) { const char *banned; if((1 <= *p && *p <= 31) || (!(flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH)) && *p == ':') || (!(flags & SANITIZE_ALLOW_PATH) && (*p == '/' || *p == '\\'))) { *p = '_'; continue; } for(banned = "|<>\"?*"; *banned; ++banned) { if(*p == *banned) { *p = '_'; break; } } } /* remove trailing spaces and periods if not allowing paths */ if(!(flags & SANITIZE_ALLOW_PATH) && len) { char *clip = NULL; p = &target[len]; do { --p; if(*p != ' ' && *p != '.') break; clip = p; } while(p != target); if(clip) { *clip = '\0'; len = clip - target; } } #ifdef MSDOS sc = msdosify(&p, target, flags); free(target); if(sc) return sc; target = p; len = strlen(target); if(len > max_sanitized_len) { free(target); return SANITIZE_ERR_INVALID_PATH; } #endif if(!(flags & SANITIZE_ALLOW_RESERVED)) { sc = rename_if_reserved_dos_device_name(&p, target, flags); free(target); if(sc) return sc; target = p; len = strlen(target); if(len > max_sanitized_len) { free(target); return SANITIZE_ERR_INVALID_PATH; } } *sanitized = target; return SANITIZE_ERR_OK; } /* Test if truncating a path to a file will leave at least a single character in the filename. Filenames suffixed by an alternate data stream can't be truncated. This performs a dry run, nothing is modified. Good truncate_pos 9: C:\foo\bar => C:\foo\ba Good truncate_pos 6: C:\foo => C:\foo Good truncate_pos 5: C:\foo => C:\fo Bad* truncate_pos 5: C:foo => C:foo Bad truncate_pos 5: C:\foo:ads => C:\fo Bad truncate_pos 9: C:\foo:ads => C:\foo:ad Bad truncate_pos 5: C:\foo\bar => C:\fo Bad truncate_pos 5: C:\foo\ => C:\fo Bad truncate_pos 7: C:\foo\ => C:\foo\ Error truncate_pos 7: C:\foo => (pos out of range) Bad truncate_pos 1: C:\foo\ => C * C:foo is ambiguous, C could end up being a drive or file therefore something like C:superlongfilename can't be truncated. Returns SANITIZE_ERR_OK: Good -- 'path' can be truncated SANITIZE_ERR_INVALID_PATH: Bad -- 'path' cannot be truncated != SANITIZE_ERR_OK && != SANITIZE_ERR_INVALID_PATH: Error */ SANITIZEcode truncate_dryrun(const char *path, const size_t truncate_pos) { size_t len; if(!path) return SANITIZE_ERR_BAD_ARGUMENT; len = strlen(path); if(truncate_pos > len) return SANITIZE_ERR_BAD_ARGUMENT; if(!len || !truncate_pos) return SANITIZE_ERR_INVALID_PATH; if(strpbrk(&path[truncate_pos - 1], "\\/:")) return SANITIZE_ERR_INVALID_PATH; /* C:\foo can be truncated but C:\foo:ads can't */ if(truncate_pos > 1) { const char *p = &path[truncate_pos - 1]; do { --p; if(*p == ':') return SANITIZE_ERR_INVALID_PATH; } while(p != path && *p != '\\' && *p != '/'); } return SANITIZE_ERR_OK; } /* The functions msdosify, rename_if_dos_device_name and __crt0_glob_function * were taken with modification from the DJGPP port of tar 1.12. They use * algorithms originally from DJTAR. */ /* Extra sanitization MSDOS for file_name. This is a supporting function for sanitize_file_name. Warning: This is an MSDOS legacy function and was purposely written in a way that some path information may pass through. For example drive letter names (C:, D:, etc) are allowed to pass through. For sanitizing a filename use sanitize_file_name. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL. */ #if defined(MSDOS) || defined(UNITTESTS) SANITIZEcode msdosify(char **const sanitized, const char *file_name, int flags) { char dos_name[PATH_MAX]; static const char illegal_chars_dos[] = ".+, ;=[]" /* illegal in DOS */ "|<>/\\\":?*"; /* illegal in DOS & W95 */ static const char *illegal_chars_w95 = &illegal_chars_dos[8]; int idx, dot_idx; const char *s = file_name; char *d = dos_name; const char *const dlimit = dos_name + sizeof(dos_name) - 1; const char *illegal_aliens = illegal_chars_dos; size_t len = sizeof(illegal_chars_dos) - 1; if(!sanitized) return SANITIZE_ERR_BAD_ARGUMENT; *sanitized = NULL; if(!file_name) return SANITIZE_ERR_BAD_ARGUMENT; if(strlen(file_name) > PATH_MAX-1 && (!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(file_name, PATH_MAX-1))) return SANITIZE_ERR_INVALID_PATH; /* Support for Windows 9X VFAT systems, when available. */ if(_use_lfn(file_name)) { illegal_aliens = illegal_chars_w95; len -= (illegal_chars_w95 - illegal_chars_dos); } /* Get past the drive letter, if any. */ if(s[0] >= 'A' && s[0] <= 'z' && s[1] == ':') { *d++ = *s++; *d = ((flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH))) ? ':' : '_'; ++d, ++s; } for(idx = 0, dot_idx = -1; *s && d < dlimit; s++, d++) { if(memchr(illegal_aliens, *s, len)) { if((flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH)) && *s == ':') *d = ':'; else if((flags & SANITIZE_ALLOW_PATH) && (*s == '/' || *s == '\\')) *d = *s; /* Dots are special: DOS doesn't allow them as the leading character, and a file name cannot have more than a single dot. We leave the first non-leading dot alone, unless it comes too close to the beginning of the name: we want sh.lex.c to become sh_lex.c, not sh.lex-c. */ else if(*s == '.') { if((flags & SANITIZE_ALLOW_PATH) && idx == 0 && (s[1] == '/' || s[1] == '\\' || (s[1] == '.' && (s[2] == '/' || s[2] == '\\')))) { /* Copy "./" and "../" verbatim. */ *d++ = *s++; if(d == dlimit) break; if(*s == '.') { *d++ = *s++; if(d == dlimit) break; } *d = *s; } else if(idx == 0) *d = '_'; else if(dot_idx >= 0) { if(dot_idx < 5) { /* 5 is a heuristic ad-hoc'ery */ d[dot_idx - idx] = '_'; /* replace previous dot */ *d = '.'; } else *d = '-'; } else *d = '.'; if(*s == '.') dot_idx = idx; } else if(*s == '+' && s[1] == '+') { if(idx - 2 == dot_idx) { /* .c++, .h++ etc. */ *d++ = 'x'; if(d == dlimit) break; *d = 'x'; } else { /* libg++ etc. */ if(dlimit - d < 4) { *d++ = 'x'; if(d == dlimit) break; *d = 'x'; } else { memcpy(d, "plus", 4); d += 3; } } s++; idx++; } else *d = '_'; } else *d = *s; if(*s == '/' || *s == '\\') { idx = 0; dot_idx = -1; } else idx++; } *d = '\0'; if(*s) { /* dos_name is truncated, check that truncation requirements are met, specifically truncating a filename suffixed by an alternate data stream or truncating the entire filename is not allowed. */ if(!(flags & SANITIZE_ALLOW_TRUNCATE) || strpbrk(s, "\\/:") || truncate_dryrun(dos_name, d - dos_name)) return SANITIZE_ERR_INVALID_PATH; } *sanitized = strdup(dos_name); return (*sanitized ? SANITIZE_ERR_OK : SANITIZE_ERR_OUT_OF_MEMORY); } #endif /* MSDOS || UNITTESTS */ /* Rename file_name if it's a reserved dos device name. This is a supporting function for sanitize_file_name. Warning: This is an MSDOS legacy function and was purposely written in a way that some path information may pass through. For example drive letter names (C:, D:, etc) are allowed to pass through. For sanitizing a filename use sanitize_file_name. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL. */ SANITIZEcode rename_if_reserved_dos_device_name(char **const sanitized, const char *file_name, int flags) { /* We could have a file whose name is a device on MS-DOS. Trying to * retrieve such a file would fail at best and wedge us at worst. We need * to rename such files. */ char *p, *base; char fname[PATH_MAX]; #ifdef MSDOS struct_stat st_buf; #endif if(!sanitized) return SANITIZE_ERR_BAD_ARGUMENT; *sanitized = NULL; if(!file_name) return SANITIZE_ERR_BAD_ARGUMENT; /* Ignore UNC prefixed paths, they are allowed to contain a reserved name. */ #ifndef MSDOS if((flags & SANITIZE_ALLOW_PATH) && file_name[0] == '\\' && file_name[1] == '\\') { size_t len = strlen(file_name); *sanitized = malloc(len + 1); if(!*sanitized) return SANITIZE_ERR_OUT_OF_MEMORY; strncpy(*sanitized, file_name, len + 1); return SANITIZE_ERR_OK; } #endif if(strlen(file_name) > PATH_MAX-1 && (!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(file_name, PATH_MAX-1))) return SANITIZE_ERR_INVALID_PATH; strncpy(fname, file_name, PATH_MAX-1); fname[PATH_MAX-1] = '\0'; base = basename(fname); /* Rename reserved device names that are known to be accessible without \\.\ Examples: CON => _CON, CON.EXT => CON_EXT, CON:ADS => CON_ADS https://support.microsoft.com/en-us/kb/74496 https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx */ for(p = fname; p; p = (p == fname && fname != base ? base : NULL)) { size_t p_len; int x = (curl_strnequal(p, "CON", 3) || curl_strnequal(p, "PRN", 3) || curl_strnequal(p, "AUX", 3) || curl_strnequal(p, "NUL", 3)) ? 3 : (curl_strnequal(p, "CLOCK$", 6)) ? 6 : (curl_strnequal(p, "COM", 3) || curl_strnequal(p, "LPT", 3)) ? (('1' <= p[3] && p[3] <= '9') ? 4 : 3) : 0; if(!x) continue; /* the devices may be accessible with an extension or ADS, for example CON.AIR and 'CON . AIR' and CON:AIR access console */ for(; p[x] == ' '; ++x) ; if(p[x] == '.') { p[x] = '_'; continue; } else if(p[x] == ':') { if(!(flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH))) { p[x] = '_'; continue; } ++x; } else if(p[x]) /* no match */ continue; /* p points to 'CON' or 'CON ' or 'CON:', etc */ p_len = strlen(p); /* Prepend a '_' */ if(strlen(fname) == PATH_MAX-1) { --p_len; if(!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(p, p_len)) return SANITIZE_ERR_INVALID_PATH; p[p_len] = '\0'; } memmove(p + 1, p, p_len + 1); p[0] = '_'; ++p_len; /* if fname was just modified then the basename pointer must be updated */ if(p == fname) base = basename(fname); } /* This is the legacy portion from rename_if_dos_device_name that checks for reserved device names. It only works on MSDOS. On Windows XP the stat check errors with EINVAL if the device name is reserved. On Windows Vista/7/8 it sets mode S_IFREG (regular file or device). According to MSDN stat doc the latter behavior is correct, but that doesn't help us identify whether it's a reserved device name and not a regular file name. */ #ifdef MSDOS if(base && ((stat(base, &st_buf)) == 0) && (S_ISCHR(st_buf.st_mode))) { /* Prepend a '_' */ size_t blen = strlen(base); if(blen) { if(strlen(fname) == PATH_MAX-1) { --blen; if(!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(base, blen)) return SANITIZE_ERR_INVALID_PATH; base[blen] = '\0'; } memmove(base + 1, base, blen + 1); base[0] = '_'; } } #endif *sanitized = strdup(fname); return (*sanitized ? SANITIZE_ERR_OK : SANITIZE_ERR_OUT_OF_MEMORY); } #if defined(MSDOS) && (defined(__DJGPP__) || defined(__GO32__)) /* * Disable program default argument globbing. We do it on our own. */ char **__crt0_glob_function(char *arg) { (void)arg; return (char **)0; } #endif /* MSDOS && (__DJGPP__ || __GO32__) */ #ifdef WIN32 /* * Function to find CACert bundle on a Win32 platform using SearchPath. * (SearchPath is already declared via inclusions done in setup header file) * (Use the ASCII version instead of the unicode one!) * The order of the directories it searches is: * 1. application's directory * 2. current working directory * 3. Windows System directory (e.g. C:\windows\system32) * 4. Windows Directory (e.g. C:\windows) * 5. all directories along %PATH% * * For WinXP and later search order actually depends on registry value: * HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\SafeProcessSearchMode */ CURLcode FindWin32CACert(struct OperationConfig *config, curl_sslbackend backend, const char *bundle_file) { CURLcode result = CURLE_OK; /* Search and set cert file only if libcurl supports SSL. * * If Schannel is the selected SSL backend then these locations are * ignored. We allow setting CA location for schannel only when explicitly * specified by the user via CURLOPT_CAINFO / --cacert. */ if((curlinfo->features & CURL_VERSION_SSL) && backend != CURLSSLBACKEND_SCHANNEL) { DWORD res_len; char buf[PATH_MAX]; char *ptr = NULL; buf[0] = '\0'; res_len = SearchPathA(NULL, bundle_file, NULL, PATH_MAX, buf, &ptr); if(res_len > 0) { Curl_safefree(config->cacert); config->cacert = strdup(buf); if(!config->cacert) result = CURLE_OUT_OF_MEMORY; } } return result; } /* Get a list of all loaded modules with full paths. * Returns slist on success or NULL on error. */ struct curl_slist *GetLoadedModulePaths(void) { HANDLE hnd = INVALID_HANDLE_VALUE; MODULEENTRY32 mod = {0}; struct curl_slist *slist = NULL; mod.dwSize = sizeof(MODULEENTRY32); do { hnd = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); } while(hnd == INVALID_HANDLE_VALUE && GetLastError() == ERROR_BAD_LENGTH); if(hnd == INVALID_HANDLE_VALUE) goto error; if(!Module32First(hnd, &mod)) goto error; do { char *path; /* points to stack allocated buffer */ struct curl_slist *temp; #ifdef UNICODE /* sizeof(mod.szExePath) is the max total bytes of wchars. the max total bytes of multibyte chars won't be more than twice that. */ char buffer[sizeof(mod.szExePath) * 2]; if(!WideCharToMultiByte(CP_ACP, 0, mod.szExePath, -1, buffer, sizeof(buffer), NULL, NULL)) goto error; path = buffer; #else path = mod.szExePath; #endif temp = curl_slist_append(slist, path); if(!temp) goto error; slist = temp; } while(Module32Next(hnd, &mod)); goto cleanup; error: curl_slist_free_all(slist); slist = NULL; cleanup: if(hnd != INVALID_HANDLE_VALUE) CloseHandle(hnd); return slist; } #endif /* WIN32 */ #endif /* MSDOS || WIN32 */
YifuLiu/AliOS-Things
components/curl/src/tool_doswin.c
C
apache-2.0
21,101
#ifndef HEADER_CURL_TOOL_DOSWIN_H #define HEADER_CURL_TOOL_DOSWIN_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #if defined(MSDOS) || defined(WIN32) #define SANITIZE_ALLOW_COLONS (1<<0) /* Allow colons */ #define SANITIZE_ALLOW_PATH (1<<1) /* Allow path separators and colons */ #define SANITIZE_ALLOW_RESERVED (1<<2) /* Allow reserved device names */ #define SANITIZE_ALLOW_TRUNCATE (1<<3) /* Allow truncating a long filename */ typedef enum { SANITIZE_ERR_OK = 0, /* 0 - OK */ SANITIZE_ERR_INVALID_PATH, /* 1 - the path is invalid */ SANITIZE_ERR_BAD_ARGUMENT, /* 2 - bad function parameter */ SANITIZE_ERR_OUT_OF_MEMORY, /* 3 - out of memory */ SANITIZE_ERR_LAST /* never use! */ } SANITIZEcode; SANITIZEcode sanitize_file_name(char **const sanitized, const char *file_name, int flags); #ifdef UNITTESTS SANITIZEcode truncate_dryrun(const char *path, const size_t truncate_pos); SANITIZEcode msdosify(char **const sanitized, const char *file_name, int flags); SANITIZEcode rename_if_reserved_dos_device_name(char **const sanitized, const char *file_name, int flags); #endif /* UNITTESTS */ #if defined(MSDOS) && (defined(__DJGPP__) || defined(__GO32__)) char **__crt0_glob_function(char *arg); #endif /* MSDOS && (__DJGPP__ || __GO32__) */ #ifdef WIN32 CURLcode FindWin32CACert(struct OperationConfig *config, curl_sslbackend backend, const char *bundle_file); struct curl_slist *GetLoadedModulePaths(void); #endif /* WIN32 */ #endif /* MSDOS || WIN32 */ #endif /* HEADER_CURL_TOOL_DOSWIN_H */
YifuLiu/AliOS-Things
components/curl/src/tool_doswin.h
C
apache-2.0
2,760
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "slist_wc.h" #ifndef CURL_DISABLE_LIBCURL_OPTION #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_easysrc.h" #include "tool_msgs.h" #include "memdebug.h" /* keep this as LAST include */ /* global variable definitions, for easy-interface source code generation */ struct slist_wc *easysrc_decl = NULL; /* Variable declarations */ struct slist_wc *easysrc_data = NULL; /* Build slists, forms etc. */ struct slist_wc *easysrc_code = NULL; /* Setopt calls */ struct slist_wc *easysrc_toohard = NULL; /* Unconvertible setopt */ struct slist_wc *easysrc_clean = NULL; /* Clean up allocated data */ int easysrc_mime_count = 0; int easysrc_slist_count = 0; static const char *const srchead[]={ "/********* Sample code generated by the curl command line tool **********", " * All curl_easy_setopt() options are documented at:", " * https://curl.haxx.se/libcurl/c/curl_easy_setopt.html", " ************************************************************************/", "#include <curl/curl.h>", "", "int main(int argc, char *argv[])", "{", " CURLcode ret;", " CURL *hnd;", NULL }; /* easysrc_decl declarations come here */ /* easysrc_data initialisations come here */ /* easysrc_code statements come here */ static const char *const srchard[]={ "/* Here is a list of options the curl code used that cannot get generated", " as source easily. You may select to either not use them or implement", " them yourself.", "", NULL }; static const char *const srcend[]={ "", " return (int)ret;", "}", "/**** End of sample code ****/", NULL }; /* Clean up all source code if we run out of memory */ static void easysrc_free(void) { slist_wc_free_all(easysrc_decl); easysrc_decl = NULL; slist_wc_free_all(easysrc_data); easysrc_data = NULL; slist_wc_free_all(easysrc_code); easysrc_code = NULL; slist_wc_free_all(easysrc_toohard); easysrc_toohard = NULL; slist_wc_free_all(easysrc_clean); easysrc_clean = NULL; } /* Add a source line to the main code or remarks */ CURLcode easysrc_add(struct slist_wc **plist, const char *line) { CURLcode ret = CURLE_OK; struct slist_wc *list = slist_wc_append(*plist, line); if(!list) { easysrc_free(); ret = CURLE_OUT_OF_MEMORY; } else *plist = list; return ret; } CURLcode easysrc_addf(struct slist_wc **plist, const char *fmt, ...) { CURLcode ret; char *bufp; va_list ap; va_start(ap, fmt); bufp = curlx_mvaprintf(fmt, ap); va_end(ap); if(! bufp) { ret = CURLE_OUT_OF_MEMORY; } else { ret = easysrc_add(plist, bufp); curl_free(bufp); } return ret; } #define CHKRET(v) do {CURLcode ret = (v); if(ret) return ret;} WHILE_FALSE CURLcode easysrc_init(void) { CHKRET(easysrc_add(&easysrc_code, "hnd = curl_easy_init();")); return CURLE_OK; } CURLcode easysrc_perform(void) { /* Note any setopt calls which we could not convert */ if(easysrc_toohard) { int i; struct curl_slist *ptr; const char *c; CHKRET(easysrc_add(&easysrc_code, "")); /* Preamble comment */ for(i = 0; ((c = srchard[i]) != NULL); i++) CHKRET(easysrc_add(&easysrc_code, c)); /* Each unconverted option */ if(easysrc_toohard) { for(ptr = easysrc_toohard->first; ptr; ptr = ptr->next) CHKRET(easysrc_add(&easysrc_code, ptr->data)); } CHKRET(easysrc_add(&easysrc_code, "")); CHKRET(easysrc_add(&easysrc_code, "*/")); slist_wc_free_all(easysrc_toohard); easysrc_toohard = NULL; } CHKRET(easysrc_add(&easysrc_code, "")); CHKRET(easysrc_add(&easysrc_code, "ret = curl_easy_perform(hnd);")); CHKRET(easysrc_add(&easysrc_code, "")); return CURLE_OK; } CURLcode easysrc_cleanup(void) { CHKRET(easysrc_add(&easysrc_code, "curl_easy_cleanup(hnd);")); CHKRET(easysrc_add(&easysrc_code, "hnd = NULL;")); return CURLE_OK; } void dumpeasysrc(struct GlobalConfig *config) { struct curl_slist *ptr; char *o = config->libcurl; FILE *out; bool fopened = FALSE; if(strcmp(o, "-")) { out = fopen(o, FOPEN_WRITETEXT); fopened = TRUE; } else out = stdout; if(!out) warnf(config, "Failed to open %s to write libcurl code!\n", o); else { int i; const char *c; for(i = 0; ((c = srchead[i]) != NULL); i++) fprintf(out, "%s\n", c); /* Declare variables used for complex setopt values */ if(easysrc_decl) { for(ptr = easysrc_decl->first; ptr; ptr = ptr->next) fprintf(out, " %s\n", ptr->data); } /* Set up complex values for setopt calls */ if(easysrc_data) { fprintf(out, "\n"); for(ptr = easysrc_data->first; ptr; ptr = ptr->next) fprintf(out, " %s\n", ptr->data); } fprintf(out, "\n"); if(easysrc_code) { for(ptr = easysrc_code->first; ptr; ptr = ptr->next) { if(ptr->data[0]) { fprintf(out, " %s\n", ptr->data); } else { fprintf(out, "\n"); } } } if(easysrc_clean) { for(ptr = easysrc_clean->first; ptr; ptr = ptr->next) fprintf(out, " %s\n", ptr->data); } for(i = 0; ((c = srcend[i]) != NULL); i++) fprintf(out, "%s\n", c); if(fopened) fclose(out); } easysrc_free(); } #endif /* CURL_DISABLE_LIBCURL_OPTION */
YifuLiu/AliOS-Things
components/curl/src/tool_easysrc.c
C
apache-2.0
6,412
#ifndef HEADER_CURL_TOOL_EASYSRC_H #define HEADER_CURL_TOOL_EASYSRC_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifndef CURL_DISABLE_LIBCURL_OPTION /* global variable declarations, for easy-interface source code generation */ extern struct slist_wc *easysrc_decl; /* Variable declarations */ extern struct slist_wc *easysrc_data; /* Build slists, forms etc. */ extern struct slist_wc *easysrc_code; /* Setopt calls etc. */ extern struct slist_wc *easysrc_toohard; /* Unconvertible setopt */ extern struct slist_wc *easysrc_clean; /* Clean up (reverse order) */ extern int easysrc_mime_count; /* Number of curl_mime variables */ extern int easysrc_slist_count; /* Number of curl_slist variables */ extern CURLcode easysrc_init(void); extern CURLcode easysrc_add(struct slist_wc **plist, const char *bupf); extern CURLcode easysrc_addf(struct slist_wc **plist, const char *fmt, ...); extern CURLcode easysrc_perform(void); extern CURLcode easysrc_cleanup(void); void dumpeasysrc(struct GlobalConfig *config); #endif /* CURL_DISABLE_LIBCURL_OPTION */ #endif /* HEADER_CURL_TOOL_EASYSRC_H */
YifuLiu/AliOS-Things
components/curl/src/tool_easysrc.h
C
apache-2.0
2,134
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_filetime.h" #ifdef HAVE_UTIME_H # include <utime.h> #elif defined(HAVE_SYS_UTIME_H) # include <sys/utime.h> #endif curl_off_t getfiletime(const char *filename, FILE *error_stream) { curl_off_t result = -1; /* Windows stat() may attempt to adjust the unix GMT file time by a daylight saving time offset and since it's GMT that is bad behavior. When we have access to a 64-bit type we can bypass stat and get the times directly. */ #if defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8) HANDLE hfile; hfile = CreateFileA(filename, FILE_READ_ATTRIBUTES, (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), NULL, OPEN_EXISTING, 0, NULL); if(hfile != INVALID_HANDLE_VALUE) { FILETIME ft; if(GetFileTime(hfile, NULL, NULL, &ft)) { curl_off_t converted = (curl_off_t)ft.dwLowDateTime | ((curl_off_t)ft.dwHighDateTime) << 32; if(converted < CURL_OFF_T_C(116444736000000000)) { fprintf(error_stream, "Failed to get filetime: underflow\n"); } else { result = (converted - CURL_OFF_T_C(116444736000000000)) / 10000000; } } else { fprintf(error_stream, "Failed to get filetime: " "GetFileTime failed: GetLastError %u\n", (unsigned int)GetLastError()); } CloseHandle(hfile); } else if(GetLastError() != ERROR_FILE_NOT_FOUND) { fprintf(error_stream, "Failed to get filetime: " "CreateFile failed: GetLastError %u\n", (unsigned int)GetLastError()); } #else struct_stat statbuf; if(-1 != stat(filename, &statbuf)) { result = (curl_off_t)statbuf.st_mtime; } else if(errno != ENOENT) { fprintf(error_stream, "Failed to get filetime: %s\n", strerror(errno)); } #endif return result; } #if defined(HAVE_UTIME) || defined(HAVE_UTIMES) || \ (defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8)) void setfiletime(curl_off_t filetime, const char *filename, FILE *error_stream) { if(filetime >= 0) { /* Windows utime() may attempt to adjust the unix GMT file time by a daylight saving time offset and since it's GMT that is bad behavior. When we have access to a 64-bit type we can bypass utime and set the times directly. */ #if defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8) HANDLE hfile; /* 910670515199 is the maximum unix filetime that can be used as a Windows FILETIME without overflow: 30827-12-31T23:59:59. */ if(filetime > CURL_OFF_T_C(910670515199)) { fprintf(error_stream, "Failed to set filetime %" CURL_FORMAT_CURL_OFF_T " on outfile: overflow\n", filetime); return; } hfile = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), NULL, OPEN_EXISTING, 0, NULL); if(hfile != INVALID_HANDLE_VALUE) { curl_off_t converted = ((curl_off_t)filetime * 10000000) + CURL_OFF_T_C(116444736000000000); FILETIME ft; ft.dwLowDateTime = (DWORD)(converted & 0xFFFFFFFF); ft.dwHighDateTime = (DWORD)(converted >> 32); if(!SetFileTime(hfile, NULL, &ft, &ft)) { fprintf(error_stream, "Failed to set filetime %" CURL_FORMAT_CURL_OFF_T " on outfile: SetFileTime failed: GetLastError %u\n", filetime, (unsigned int)GetLastError()); } CloseHandle(hfile); } else { fprintf(error_stream, "Failed to set filetime %" CURL_FORMAT_CURL_OFF_T " on outfile: CreateFile failed: GetLastError %u\n", filetime, (unsigned int)GetLastError()); } #elif defined(HAVE_UTIMES) struct timeval times[2]; times[0].tv_sec = times[1].tv_sec = (time_t)filetime; times[0].tv_usec = times[1].tv_usec = 0; if(utimes(filename, times)) { fprintf(error_stream, "Failed to set filetime %" CURL_FORMAT_CURL_OFF_T " on outfile: %s\n", filetime, strerror(errno)); } #elif defined(HAVE_UTIME) struct utimbuf times; times.actime = (time_t)filetime; times.modtime = (time_t)filetime; if(utime(filename, &times)) { fprintf(error_stream, "Failed to set filetime %" CURL_FORMAT_CURL_OFF_T " on outfile: %s\n", filetime, strerror(errno)); } #endif } } #endif /* defined(HAVE_UTIME) || defined(HAVE_UTIMES) || \ (defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8)) */
YifuLiu/AliOS-Things
components/curl/src/tool_filetime.c
C
apache-2.0
5,641
#ifndef HEADER_CURL_TOOL_FILETIME_H #define HEADER_CURL_TOOL_FILETIME_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" curl_off_t getfiletime(const char *filename, FILE *error_stream); #if defined(HAVE_UTIME) || defined(HAVE_UTIMES) || \ (defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8)) void setfiletime(curl_off_t filetime, const char *filename, FILE *error_stream); #else #define setfiletime(a,b,c) Curl_nop_stmt #endif /* defined(HAVE_UTIME) || defined(HAVE_UTIMES) || \ (defined(WIN32) && (SIZEOF_CURL_OFF_T >= 8)) */ #endif /* HEADER_CURL_TOOL_FILETIME_H */
YifuLiu/AliOS-Things
components/curl/src/tool_filetime.h
C
apache-2.0
1,583
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "strcase.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_convert.h" #include "tool_msgs.h" #include "tool_binmode.h" #include "tool_getparam.h" #include "tool_paramhlp.h" #include "tool_formparse.h" #include "memdebug.h" /* keep this as LAST include */ /* Macros to free const pointers. */ #define CONST_FREE(x) free((void *) (x)) #define CONST_SAFEFREE(x) Curl_safefree(*((void **) &(x))) /* tool_mime functions. */ static tool_mime *tool_mime_new(tool_mime *parent, toolmimekind kind) { tool_mime *m = (tool_mime *) calloc(1, sizeof(*m)); if(m) { m->kind = kind; m->parent = parent; if(parent) { m->prev = parent->subparts; parent->subparts = m; } } return m; } static tool_mime *tool_mime_new_parts(tool_mime *parent) { return tool_mime_new(parent, TOOLMIME_PARTS); } static tool_mime *tool_mime_new_data(tool_mime *parent, const char *data) { tool_mime *m = NULL; data = strdup(data); if(data) { m = tool_mime_new(parent, TOOLMIME_DATA); if(!m) CONST_FREE(data); else m->data = data; } return m; } static tool_mime *tool_mime_new_filedata(tool_mime *parent, const char *filename, bool isremotefile, CURLcode *errcode) { CURLcode result = CURLE_OK; tool_mime *m = NULL; *errcode = CURLE_OUT_OF_MEMORY; if(strcmp(filename, "-")) { /* This is a normal file. */ filename = strdup(filename); if(filename) { m = tool_mime_new(parent, TOOLMIME_FILE); if(!m) CONST_FREE(filename); else { m->data = filename; if(!isremotefile) m->kind = TOOLMIME_FILEDATA; *errcode = CURLE_OK; } } } else { /* Standard input. */ int fd = fileno(stdin); char *data = NULL; curl_off_t size; curl_off_t origin; struct_stat sbuf; set_binmode(stdin); origin = ftell(stdin); /* If stdin is a regular file, do not buffer data but read it when needed. */ if(fd >= 0 && origin >= 0 && !fstat(fd, &sbuf) && #ifdef __VMS sbuf.st_fab_rfm != FAB$C_VAR && sbuf.st_fab_rfm != FAB$C_VFC && #endif S_ISREG(sbuf.st_mode)) { size = sbuf.st_size - origin; if(size < 0) size = 0; } else { /* Not suitable for direct use, buffer stdin data. */ size_t stdinsize = 0; if(file2memory(&data, &stdinsize, stdin) != PARAM_OK) { /* Out of memory. */ return m; } if(ferror(stdin)) { result = CURLE_READ_ERROR; Curl_safefree(data); data = NULL; } else if(!stdinsize) { /* Zero-length data has been freed. Re-create it. */ data = strdup(""); if(!data) return m; } size = curlx_uztoso(stdinsize); origin = 0; } m = tool_mime_new(parent, TOOLMIME_STDIN); if(!m) Curl_safefree(data); else { m->data = data; m->origin = origin; m->size = size; m->curpos = 0; if(!isremotefile) m->kind = TOOLMIME_STDINDATA; *errcode = result; } } return m; } void tool_mime_free(tool_mime *mime) { if(mime) { if(mime->subparts) tool_mime_free(mime->subparts); if(mime->prev) tool_mime_free(mime->prev); CONST_SAFEFREE(mime->name); CONST_SAFEFREE(mime->filename); CONST_SAFEFREE(mime->type); CONST_SAFEFREE(mime->encoder); CONST_SAFEFREE(mime->data); curl_slist_free_all(mime->headers); free(mime); } } /* Mime part callbacks for stdin. */ size_t tool_mime_stdin_read(char *buffer, size_t size, size_t nitems, void *arg) { tool_mime *sip = (tool_mime *) arg; curl_off_t bytesleft; (void) size; /* Always 1: ignored. */ if(sip->size >= 0) { if(sip->curpos >= sip->size) return 0; /* At eof. */ bytesleft = sip->size - sip->curpos; if(curlx_uztoso(nitems) > bytesleft) nitems = curlx_sotouz(bytesleft); } if(nitems) { if(sip->data) { /* Return data from memory. */ memcpy(buffer, sip->data + curlx_sotouz(sip->curpos), nitems); } else { /* Read from stdin. */ nitems = fread(buffer, 1, nitems, stdin); if(ferror(stdin)) { /* Show error only once. */ if(sip->config) { warnf(sip->config, "stdin: %s\n", strerror(errno)); sip->config = NULL; } return CURL_READFUNC_ABORT; } } sip->curpos += curlx_uztoso(nitems); } return nitems; } int tool_mime_stdin_seek(void *instream, curl_off_t offset, int whence) { tool_mime *sip = (tool_mime *) instream; switch(whence) { case SEEK_CUR: offset += sip->curpos; break; case SEEK_END: offset += sip->size; break; } if(offset < 0) return CURL_SEEKFUNC_CANTSEEK; if(!sip->data) { if(fseek(stdin, (long) (offset + sip->origin), SEEK_SET)) return CURL_SEEKFUNC_CANTSEEK; } sip->curpos = offset; return CURL_SEEKFUNC_OK; } /* Translate an internal mime tree into a libcurl mime tree. */ static CURLcode tool2curlparts(CURL *curl, tool_mime *m, curl_mime *mime) { CURLcode ret = CURLE_OK; curl_mimepart *part = NULL; curl_mime *submime = NULL; const char *filename = NULL; if(m) { ret = tool2curlparts(curl, m->prev, mime); if(!ret) { part = curl_mime_addpart(mime); if(!part) ret = CURLE_OUT_OF_MEMORY; } if(!ret) { filename = m->filename; switch(m->kind) { case TOOLMIME_PARTS: ret = tool2curlmime(curl, m, &submime); if(!ret) { ret = curl_mime_subparts(part, submime); if(ret) curl_mime_free(submime); } break; case TOOLMIME_DATA: #ifdef CURL_DOES_CONVERSIONS /* Our data is always textual: convert it to ASCII. */ { size_t size = strlen(m->data); char *cp = malloc(size + 1); if(!cp) ret = CURLE_OUT_OF_MEMORY; else { memcpy(cp, m->data, size + 1); ret = convert_to_network(cp, size); if(!ret) ret = curl_mime_data(part, cp, CURL_ZERO_TERMINATED); free(cp); } } #else ret = curl_mime_data(part, m->data, CURL_ZERO_TERMINATED); #endif break; case TOOLMIME_FILE: case TOOLMIME_FILEDATA: ret = curl_mime_filedata(part, m->data); if(!ret && m->kind == TOOLMIME_FILEDATA && !filename) ret = curl_mime_filename(part, NULL); break; case TOOLMIME_STDIN: if(!filename) filename = "-"; /* FALLTHROUGH */ case TOOLMIME_STDINDATA: ret = curl_mime_data_cb(part, m->size, (curl_read_callback) tool_mime_stdin_read, (curl_seek_callback) tool_mime_stdin_seek, NULL, m); break; default: /* Other cases not possible in this context. */ break; } } if(!ret && filename) ret = curl_mime_filename(part, filename); if(!ret) ret = curl_mime_type(part, m->type); if(!ret) ret = curl_mime_headers(part, m->headers, 0); if(!ret) ret = curl_mime_encoder(part, m->encoder); if(!ret) ret = curl_mime_name(part, m->name); } return ret; } CURLcode tool2curlmime(CURL *curl, tool_mime *m, curl_mime **mime) { CURLcode ret = CURLE_OK; *mime = curl_mime_init(curl); if(!*mime) ret = CURLE_OUT_OF_MEMORY; else ret = tool2curlparts(curl, m->subparts, *mime); if(ret) { curl_mime_free(*mime); *mime = NULL; } return ret; } /* * helper function to get a word from form param * after call get_parm_word, str either point to string end * or point to any of end chars. */ static char *get_param_word(char **str, char **end_pos, char endchar) { char *ptr = *str; /* the first non-space char is here */ char *word_begin = ptr; char *ptr2; char *escape = NULL; if(*ptr == '"') { ++ptr; while(*ptr) { if(*ptr == '\\') { if(ptr[1] == '\\' || ptr[1] == '"') { /* remember the first escape position */ if(!escape) escape = ptr; /* skip escape of back-slash or double-quote */ ptr += 2; continue; } } if(*ptr == '"') { *end_pos = ptr; if(escape) { /* has escape, we restore the unescaped string here */ ptr = ptr2 = escape; do { if(*ptr == '\\' && (ptr[1] == '\\' || ptr[1] == '"')) ++ptr; *ptr2++ = *ptr++; } while(ptr < *end_pos); *end_pos = ptr2; } while(*ptr && *ptr != ';' && *ptr != endchar) ++ptr; *str = ptr; return word_begin + 1; } ++ptr; } /* end quote is missing, treat it as non-quoted. */ ptr = word_begin; } while(*ptr && *ptr != ';' && *ptr != endchar) ++ptr; *str = *end_pos = ptr; return word_begin; } /* Append slist item and return -1 if failed. */ static int slist_append(struct curl_slist **plist, const char *data) { struct curl_slist *s = curl_slist_append(*plist, data); if(!s) return -1; *plist = s; return 0; } /* Read headers from a file and append to list. */ static int read_field_headers(struct OperationConfig *config, const char *filename, FILE *fp, struct curl_slist **pheaders) { size_t hdrlen = 0; size_t pos = 0; bool incomment = FALSE; int lineno = 1; char hdrbuf[999]; /* Max. header length + 1. */ for(;;) { int c = getc(fp); if(c == EOF || (!pos && !ISSPACE(c))) { /* Strip and flush the current header. */ while(hdrlen && ISSPACE(hdrbuf[hdrlen - 1])) hdrlen--; if(hdrlen) { hdrbuf[hdrlen] = '\0'; if(slist_append(pheaders, hdrbuf)) { fprintf(config->global->errors, "Out of memory for field headers!\n"); return -1; } hdrlen = 0; } } switch(c) { case EOF: if(ferror(fp)) { fprintf(config->global->errors, "Header file %s read error: %s\n", filename, strerror(errno)); return -1; } return 0; /* Done. */ case '\r': continue; /* Ignore. */ case '\n': pos = 0; incomment = FALSE; lineno++; continue; case '#': if(!pos) incomment = TRUE; break; } pos++; if(!incomment) { if(hdrlen == sizeof(hdrbuf) - 1) { warnf(config->global, "File %s line %d: header too long (truncated)\n", filename, lineno); c = ' '; } if(hdrlen <= sizeof(hdrbuf) - 1) hdrbuf[hdrlen++] = (char) c; } } /* NOTREACHED */ } static int get_param_part(struct OperationConfig *config, char endchar, char **str, char **pdata, char **ptype, char **pfilename, char **pencoder, struct curl_slist **pheaders) { char *p = *str; char *type = NULL; char *filename = NULL; char *encoder = NULL; char *endpos; char *tp; char sep; char type_major[128] = ""; char type_minor[128] = ""; char *endct = NULL; struct curl_slist *headers = NULL; if(ptype) *ptype = NULL; if(pfilename) *pfilename = NULL; if(pheaders) *pheaders = NULL; if(pencoder) *pencoder = NULL; while(ISSPACE(*p)) p++; tp = p; *pdata = get_param_word(&p, &endpos, endchar); /* If not quoted, strip trailing spaces. */ if(*pdata == tp) while(endpos > *pdata && ISSPACE(endpos[-1])) endpos--; sep = *p; *endpos = '\0'; while(sep == ';') { while(ISSPACE(*++p)) ; if(!endct && checkprefix("type=", p)) { for(p += 5; ISSPACE(*p); p++) ; /* set type pointer */ type = p; /* verify that this is a fine type specifier */ if(2 != sscanf(type, "%127[^/ ]/%127[^;, \n]", type_major, type_minor)) { warnf(config->global, "Illegally formatted content-type field!\n"); curl_slist_free_all(headers); return -1; /* illegal content-type syntax! */ } /* now point beyond the content-type specifier */ p = type + strlen(type_major) + strlen(type_minor) + 1; for(endct = p; *p && *p != ';' && *p != endchar; p++) if(!ISSPACE(*p)) endct = p + 1; sep = *p; } else if(checkprefix("filename=", p)) { if(endct) { *endct = '\0'; endct = NULL; } for(p += 9; ISSPACE(*p); p++) ; tp = p; filename = get_param_word(&p, &endpos, endchar); /* If not quoted, strip trailing spaces. */ if(filename == tp) while(endpos > filename && ISSPACE(endpos[-1])) endpos--; sep = *p; *endpos = '\0'; } else if(checkprefix("headers=", p)) { if(endct) { *endct = '\0'; endct = NULL; } p += 8; if(*p == '@' || *p == '<') { char *hdrfile; FILE *fp; /* Read headers from a file. */ do { p++; } while(ISSPACE(*p)); tp = p; hdrfile = get_param_word(&p, &endpos, endchar); /* If not quoted, strip trailing spaces. */ if(hdrfile == tp) while(endpos > hdrfile && ISSPACE(endpos[-1])) endpos--; sep = *p; *endpos = '\0'; fp = fopen(hdrfile, FOPEN_READTEXT); if(!fp) warnf(config->global, "Cannot read from %s: %s\n", hdrfile, strerror(errno)); else { int i = read_field_headers(config, hdrfile, fp, &headers); fclose(fp); if(i) { curl_slist_free_all(headers); return -1; } } } else { char *hdr; while(ISSPACE(*p)) p++; tp = p; hdr = get_param_word(&p, &endpos, endchar); /* If not quoted, strip trailing spaces. */ if(hdr == tp) while(endpos > hdr && ISSPACE(endpos[-1])) endpos--; sep = *p; *endpos = '\0'; if(slist_append(&headers, hdr)) { fprintf(config->global->errors, "Out of memory for field header!\n"); curl_slist_free_all(headers); return -1; } } } else if(checkprefix("encoder=", p)) { if(endct) { *endct = '\0'; endct = NULL; } for(p += 8; ISSPACE(*p); p++) ; tp = p; encoder = get_param_word(&p, &endpos, endchar); /* If not quoted, strip trailing spaces. */ if(encoder == tp) while(endpos > encoder && ISSPACE(endpos[-1])) endpos--; sep = *p; *endpos = '\0'; } else if(endct) { /* This is part of content type. */ for(endct = p; *p && *p != ';' && *p != endchar; p++) if(!ISSPACE(*p)) endct = p + 1; sep = *p; } else { /* unknown prefix, skip to next block */ char *unknown = get_param_word(&p, &endpos, endchar); sep = *p; *endpos = '\0'; if(*unknown) warnf(config->global, "skip unknown form field: %s\n", unknown); } } /* Terminate content type. */ if(endct) *endct = '\0'; if(ptype) *ptype = type; else if(type) warnf(config->global, "Field content type not allowed here: %s\n", type); if(pfilename) *pfilename = filename; else if(filename) warnf(config->global, "Field file name not allowed here: %s\n", filename); if(pencoder) *pencoder = encoder; else if(encoder) warnf(config->global, "Field encoder not allowed here: %s\n", encoder); if(pheaders) *pheaders = headers; else if(headers) { warnf(config->global, "Field headers not allowed here: %s\n", headers->data); curl_slist_free_all(headers); } *str = p; return sep & 0xFF; } /*************************************************************************** * * formparse() * * Reads a 'name=value' parameter and builds the appropriate linked list. * * If the value is of the form '<filename', field data is read from the * given file. * Specify files to upload with 'name=@filename', or 'name=@"filename"' * in case the filename contain ',' or ';'. Supports specified * given Content-Type of the files. Such as ';type=<content-type>'. * * If literal_value is set, any initial '@' or '<' in the value string * loses its special meaning, as does any embedded ';type='. * * You may specify more than one file for a single name (field). Specify * multiple files by writing it like: * * 'name=@filename,filename2,filename3' * * or use double-quotes quote the filename: * * 'name=@"filename","filename2","filename3"' * * If you want content-types specified for each too, write them like: * * 'name=@filename;type=image/gif,filename2,filename3' * * If you want custom headers added for a single part, write them in a separate * file and do like this: * * 'name=foo;headers=@headerfile' or why not * 'name=@filemame;headers=@headerfile' * * To upload a file, but to fake the file name that will be included in the * formpost, do like this: * * 'name=@filename;filename=/dev/null' or quote the faked filename like: * 'name=@filename;filename="play, play, and play.txt"' * * If filename/path contains ',' or ';', it must be quoted by double-quotes, * else curl will fail to figure out the correct filename. if the filename * tobe quoted contains '"' or '\', '"' and '\' must be escaped by backslash. * ***************************************************************************/ /* Convenience macros for null pointer check. */ #define NULL_CHECK(ptr, init, retcode) { \ (ptr) = (init); \ if(!(ptr)) { \ warnf(config->global, "out of memory!\n"); \ curl_slist_free_all(headers); \ Curl_safefree(contents); \ return retcode; \ } \ } #define SET_TOOL_MIME_PTR(m, field, retcode) { \ if(field) \ NULL_CHECK((m)->field, strdup(field), retcode); \ } int formparse(struct OperationConfig *config, const char *input, tool_mime **mimeroot, tool_mime **mimecurrent, bool literal_value) { /* input MUST be a string in the format 'name=contents' and we'll build a linked list with the info */ char *name = NULL; char *contents = NULL; char *contp; char *data; char *type = NULL; char *filename = NULL; char *encoder = NULL; struct curl_slist *headers = NULL; tool_mime *part = NULL; CURLcode res; /* Allocate the main mime structure if needed. */ if(!*mimecurrent) { NULL_CHECK(*mimeroot, tool_mime_new_parts(NULL), 1); *mimecurrent = *mimeroot; } /* Make a copy we can overwrite. */ NULL_CHECK(contents, strdup(input), 2); /* Scan for the end of the name. */ contp = strchr(contents, '='); if(contp) { int sep = '\0'; if(contp > contents) name = contents; *contp++ = '\0'; if(*contp == '(' && !literal_value) { /* Starting a multipart. */ sep = get_param_part(config, '\0', &contp, &data, &type, NULL, NULL, &headers); if(sep < 0) { Curl_safefree(contents); return 3; } NULL_CHECK(part, tool_mime_new_parts(*mimecurrent), 4); *mimecurrent = part; part->headers = headers; headers = NULL; SET_TOOL_MIME_PTR(part, type, 5); } else if(!name && !strcmp(contp, ")") && !literal_value) { /* Ending a multipart. */ if(*mimecurrent == *mimeroot) { warnf(config->global, "no multipart to terminate!\n"); Curl_safefree(contents); return 6; } *mimecurrent = (*mimecurrent)->parent; } else if('@' == contp[0] && !literal_value) { /* we use the @-letter to indicate file name(s) */ tool_mime *subparts = NULL; do { /* since this was a file, it may have a content-type specifier at the end too, or a filename. Or both. */ ++contp; sep = get_param_part(config, ',', &contp, &data, &type, &filename, &encoder, &headers); if(sep < 0) { Curl_safefree(contents); return 7; } /* now contp point to comma or string end. If more files to come, make sure we have multiparts. */ if(!subparts) { if(sep != ',') /* If there is a single file. */ subparts = *mimecurrent; else NULL_CHECK(subparts, tool_mime_new_parts(*mimecurrent), 8); } /* Store that file in a part. */ NULL_CHECK(part, tool_mime_new_filedata(subparts, data, TRUE, &res), 9); part->headers = headers; headers = NULL; part->config = config->global; if(res == CURLE_READ_ERROR) { /* An error occurred while reading stdin: if read has started, issue the error now. Else, delay it until processed by libcurl. */ if(part->size > 0) { warnf(config->global, "error while reading standard input\n"); Curl_safefree(contents); return 10; } CONST_SAFEFREE(part->data); part->data = NULL; part->size = -1; res = CURLE_OK; } SET_TOOL_MIME_PTR(part, filename, 11); SET_TOOL_MIME_PTR(part, type, 12); SET_TOOL_MIME_PTR(part, encoder, 13); /* *contp could be '\0', so we just check with the delimiter */ } while(sep); /* loop if there's another file name */ part = (*mimecurrent)->subparts; /* Set name on group. */ } else { if(*contp == '<' && !literal_value) { ++contp; sep = get_param_part(config, '\0', &contp, &data, &type, NULL, &encoder, &headers); if(sep < 0) { Curl_safefree(contents); return 14; } NULL_CHECK(part, tool_mime_new_filedata(*mimecurrent, data, FALSE, &res), 15); part->headers = headers; headers = NULL; part->config = config->global; if(res == CURLE_READ_ERROR) { /* An error occurred while reading stdin: if read has started, issue the error now. Else, delay it until processed by libcurl. */ if(part->size > 0) { warnf(config->global, "error while reading standard input\n"); Curl_safefree(contents); return 16; } CONST_SAFEFREE(part->data); part->data = NULL; part->size = -1; res = CURLE_OK; } } else { if(literal_value) data = contp; else { sep = get_param_part(config, '\0', &contp, &data, &type, &filename, &encoder, &headers); if(sep < 0) { Curl_safefree(contents); return 17; } } NULL_CHECK(part, tool_mime_new_data(*mimecurrent, data), 18); part->headers = headers; headers = NULL; } SET_TOOL_MIME_PTR(part, filename, 19); SET_TOOL_MIME_PTR(part, type, 20); SET_TOOL_MIME_PTR(part, encoder, 21); if(sep) { *contp = (char) sep; warnf(config->global, "garbage at end of field specification: %s\n", contp); } } /* Set part name. */ SET_TOOL_MIME_PTR(part, name, 22); } else { warnf(config->global, "Illegally formatted input field!\n"); Curl_safefree(contents); return 23; } Curl_safefree(contents); return 0; }
YifuLiu/AliOS-Things
components/curl/src/tool_formparse.c
C
apache-2.0
25,588
#ifndef HEADER_CURL_TOOL_FORMPARSE_H #define HEADER_CURL_TOOL_FORMPARSE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" /* Private structure for mime/parts. */ typedef enum { TOOLMIME_NONE = 0, TOOLMIME_PARTS, TOOLMIME_DATA, TOOLMIME_FILE, TOOLMIME_FILEDATA, TOOLMIME_STDIN, TOOLMIME_STDINDATA } toolmimekind; typedef struct tool_mime tool_mime; struct tool_mime { /* Structural fields. */ toolmimekind kind; /* Part kind. */ tool_mime *parent; /* Parent item. */ tool_mime *prev; /* Previous sibling (reverse order link). */ /* Common fields. */ const char *data; /* Actual data or data filename. */ const char *name; /* Part name. */ const char *filename; /* Part's filename. */ const char *type; /* Part's mime type. */ const char *encoder; /* Part's requested encoding. */ struct curl_slist *headers; /* User-defined headers. */ /* TOOLMIME_PARTS fields. */ tool_mime *subparts; /* Part's subparts. */ /* TOOLMIME_STDIN/TOOLMIME_STDINDATA fields. */ curl_off_t origin; /* Stdin read origin offset. */ curl_off_t size; /* Stdin data size. */ curl_off_t curpos; /* Stdin current read position. */ struct GlobalConfig *config; /* For access from callback. */ }; size_t tool_mime_stdin_read(char *buffer, size_t size, size_t nitems, void *arg); int tool_mime_stdin_seek(void *instream, curl_off_t offset, int whence); int formparse(struct OperationConfig *config, const char *input, tool_mime **mimeroot, tool_mime **mimecurrent, bool literal_value); CURLcode tool2curlmime(CURL *curl, tool_mime *m, curl_mime **mime); void tool_mime_free(tool_mime *mime); #endif /* HEADER_CURL_TOOL_FORMPARSE_H */
YifuLiu/AliOS-Things
components/curl/src/tool_formparse.h
C
apache-2.0
2,885
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "strcase.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_binmode.h" #include "tool_cfgable.h" #include "tool_cb_prg.h" #include "tool_convert.h" #include "tool_filetime.h" #include "tool_formparse.h" #include "tool_getparam.h" #include "tool_helpers.h" #include "tool_libinfo.h" #include "tool_metalink.h" #include "tool_msgs.h" #include "tool_paramhlp.h" #include "tool_parsecfg.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef MSDOS # define USE_WATT32 #endif #define GetStr(str,val) do { \ if(*(str)) { \ free(*(str)); \ *(str) = NULL; \ } \ if((val)) { \ *(str) = strdup((val)); \ if(!(*(str))) \ return PARAM_NO_MEM; \ } \ } WHILE_FALSE struct LongShort { const char *letter; /* short name option */ const char *lname; /* long name option */ enum { ARG_NONE, /* stand-alone but not a boolean */ ARG_BOOL, /* accepts a --no-[name] prefix */ ARG_STRING, /* requires an argument */ ARG_FILENAME /* requires an argument, usually a file name */ } desc; }; static const struct LongShort aliases[]= { /* 'letter' strings with more than one character have *no* short option to mention. */ {"*@", "url", ARG_STRING}, {"*4", "dns-ipv4-addr", ARG_STRING}, {"*6", "dns-ipv6-addr", ARG_STRING}, {"*a", "random-file", ARG_FILENAME}, {"*b", "egd-file", ARG_STRING}, {"*B", "oauth2-bearer", ARG_STRING}, {"*c", "connect-timeout", ARG_STRING}, {"*C", "doh-url" , ARG_STRING}, {"*d", "ciphers", ARG_STRING}, {"*D", "dns-interface", ARG_STRING}, {"*e", "disable-epsv", ARG_BOOL}, {"*f", "disallow-username-in-url", ARG_BOOL}, {"*E", "epsv", ARG_BOOL}, /* 'epsv' made like this to make --no-epsv and --epsv to work although --disable-epsv is the documented option */ {"*F", "dns-servers", ARG_STRING}, {"*g", "trace", ARG_FILENAME}, {"*G", "npn", ARG_BOOL}, {"*h", "trace-ascii", ARG_FILENAME}, {"*H", "alpn", ARG_BOOL}, {"*i", "limit-rate", ARG_STRING}, {"*j", "compressed", ARG_BOOL}, {"*J", "tr-encoding", ARG_BOOL}, {"*k", "digest", ARG_BOOL}, {"*l", "negotiate", ARG_BOOL}, {"*m", "ntlm", ARG_BOOL}, {"*M", "ntlm-wb", ARG_BOOL}, {"*n", "basic", ARG_BOOL}, {"*o", "anyauth", ARG_BOOL}, #ifdef USE_WATT32 {"*p", "wdebug", ARG_BOOL}, #endif {"*q", "ftp-create-dirs", ARG_BOOL}, {"*r", "create-dirs", ARG_BOOL}, {"*s", "max-redirs", ARG_STRING}, {"*t", "proxy-ntlm", ARG_BOOL}, {"*u", "crlf", ARG_BOOL}, {"*v", "stderr", ARG_FILENAME}, {"*w", "interface", ARG_STRING}, {"*x", "krb", ARG_STRING}, {"*x", "krb4", ARG_STRING}, /* 'krb4' is the previous name */ {"*X", "haproxy-protocol", ARG_BOOL}, {"*y", "max-filesize", ARG_STRING}, {"*z", "disable-eprt", ARG_BOOL}, {"*Z", "eprt", ARG_BOOL}, /* 'eprt' made like this to make --no-eprt and --eprt to work although --disable-eprt is the documented option */ {"*~", "xattr", ARG_BOOL}, {"$a", "ftp-ssl", ARG_BOOL}, /* 'ftp-ssl' deprecated name since 7.20.0 */ {"$a", "ssl", ARG_BOOL}, /* 'ssl' new option name in 7.20.0, previously this was ftp-ssl */ {"$b", "ftp-pasv", ARG_BOOL}, {"$c", "socks5", ARG_STRING}, {"$d", "tcp-nodelay", ARG_BOOL}, {"$e", "proxy-digest", ARG_BOOL}, {"$f", "proxy-basic", ARG_BOOL}, {"$g", "retry", ARG_STRING}, {"$V", "retry-connrefused", ARG_BOOL}, {"$h", "retry-delay", ARG_STRING}, {"$i", "retry-max-time", ARG_STRING}, {"$k", "proxy-negotiate", ARG_BOOL}, {"$m", "ftp-account", ARG_STRING}, {"$n", "proxy-anyauth", ARG_BOOL}, {"$o", "trace-time", ARG_BOOL}, {"$p", "ignore-content-length", ARG_BOOL}, {"$q", "ftp-skip-pasv-ip", ARG_BOOL}, {"$r", "ftp-method", ARG_STRING}, {"$s", "local-port", ARG_STRING}, {"$t", "socks4", ARG_STRING}, {"$T", "socks4a", ARG_STRING}, {"$u", "ftp-alternative-to-user", ARG_STRING}, {"$v", "ftp-ssl-reqd", ARG_BOOL}, /* 'ftp-ssl-reqd' deprecated name since 7.20.0 */ {"$v", "ssl-reqd", ARG_BOOL}, /* 'ssl-reqd' new in 7.20.0, previously this was ftp-ssl-reqd */ {"$w", "sessionid", ARG_BOOL}, /* 'sessionid' listed as --no-sessionid in the help */ {"$x", "ftp-ssl-control", ARG_BOOL}, {"$y", "ftp-ssl-ccc", ARG_BOOL}, {"$j", "ftp-ssl-ccc-mode", ARG_STRING}, {"$z", "libcurl", ARG_STRING}, {"$#", "raw", ARG_BOOL}, {"$0", "post301", ARG_BOOL}, {"$1", "keepalive", ARG_BOOL}, /* 'keepalive' listed as --no-keepalive in the help */ {"$2", "socks5-hostname", ARG_STRING}, {"$3", "keepalive-time", ARG_STRING}, {"$4", "post302", ARG_BOOL}, {"$5", "noproxy", ARG_STRING}, {"$7", "socks5-gssapi-nec", ARG_BOOL}, {"$8", "proxy1.0", ARG_STRING}, {"$9", "tftp-blksize", ARG_STRING}, {"$A", "mail-from", ARG_STRING}, {"$B", "mail-rcpt", ARG_STRING}, {"$C", "ftp-pret", ARG_BOOL}, {"$D", "proto", ARG_STRING}, {"$E", "proto-redir", ARG_STRING}, {"$F", "resolve", ARG_STRING}, {"$G", "delegation", ARG_STRING}, {"$H", "mail-auth", ARG_STRING}, {"$I", "post303", ARG_BOOL}, {"$J", "metalink", ARG_BOOL}, {"$K", "sasl-ir", ARG_BOOL}, {"$L", "test-event", ARG_BOOL}, {"$M", "unix-socket", ARG_FILENAME}, {"$N", "path-as-is", ARG_BOOL}, {"$O", "socks5-gssapi-service", ARG_STRING}, /* 'socks5-gssapi-service' merged with'proxy-service-name' and deprecated since 7.49.0 */ {"$O", "proxy-service-name", ARG_STRING}, {"$P", "service-name", ARG_STRING}, {"$Q", "proto-default", ARG_STRING}, {"$R", "expect100-timeout", ARG_STRING}, {"$S", "tftp-no-options", ARG_BOOL}, {"$U", "connect-to", ARG_STRING}, {"$W", "abstract-unix-socket", ARG_FILENAME}, {"$X", "tls-max", ARG_STRING}, {"$Y", "suppress-connect-headers", ARG_BOOL}, {"$Z", "compressed-ssh", ARG_BOOL}, {"$~", "happy-eyeballs-timeout-ms", ARG_STRING}, {"0", "http1.0", ARG_NONE}, {"01", "http1.1", ARG_NONE}, {"02", "http2", ARG_NONE}, {"03", "http2-prior-knowledge", ARG_NONE}, {"09", "http0.9", ARG_BOOL}, {"1", "tlsv1", ARG_NONE}, {"10", "tlsv1.0", ARG_NONE}, {"11", "tlsv1.1", ARG_NONE}, {"12", "tlsv1.2", ARG_NONE}, {"13", "tlsv1.3", ARG_NONE}, {"1A", "tls13-ciphers", ARG_STRING}, {"1B", "proxy-tls13-ciphers", ARG_STRING}, {"2", "sslv2", ARG_NONE}, {"3", "sslv3", ARG_NONE}, {"4", "ipv4", ARG_NONE}, {"6", "ipv6", ARG_NONE}, {"a", "append", ARG_BOOL}, {"A", "user-agent", ARG_STRING}, {"b", "cookie", ARG_STRING}, {"ba", "alt-svc", ARG_STRING}, {"B", "use-ascii", ARG_BOOL}, {"c", "cookie-jar", ARG_STRING}, {"C", "continue-at", ARG_STRING}, {"d", "data", ARG_STRING}, {"dr", "data-raw", ARG_STRING}, {"da", "data-ascii", ARG_STRING}, {"db", "data-binary", ARG_STRING}, {"de", "data-urlencode", ARG_STRING}, {"D", "dump-header", ARG_FILENAME}, {"e", "referer", ARG_STRING}, {"E", "cert", ARG_FILENAME}, {"Ea", "cacert", ARG_FILENAME}, {"Eb", "cert-type", ARG_STRING}, {"Ec", "key", ARG_FILENAME}, {"Ed", "key-type", ARG_STRING}, {"Ee", "pass", ARG_STRING}, {"Ef", "engine", ARG_STRING}, {"Eg", "capath", ARG_FILENAME}, {"Eh", "pubkey", ARG_STRING}, {"Ei", "hostpubmd5", ARG_STRING}, {"Ej", "crlfile", ARG_FILENAME}, {"Ek", "tlsuser", ARG_STRING}, {"El", "tlspassword", ARG_STRING}, {"Em", "tlsauthtype", ARG_STRING}, {"En", "ssl-allow-beast", ARG_BOOL}, {"Eo", "login-options", ARG_STRING}, {"Ep", "pinnedpubkey", ARG_STRING}, {"EP", "proxy-pinnedpubkey", ARG_STRING}, {"Eq", "cert-status", ARG_BOOL}, {"Er", "false-start", ARG_BOOL}, {"Es", "ssl-no-revoke", ARG_BOOL}, {"Et", "tcp-fastopen", ARG_BOOL}, {"Eu", "proxy-tlsuser", ARG_STRING}, {"Ev", "proxy-tlspassword", ARG_STRING}, {"Ew", "proxy-tlsauthtype", ARG_STRING}, {"Ex", "proxy-cert", ARG_FILENAME}, {"Ey", "proxy-cert-type", ARG_STRING}, {"Ez", "proxy-key", ARG_FILENAME}, {"E0", "proxy-key-type", ARG_STRING}, {"E1", "proxy-pass", ARG_STRING}, {"E2", "proxy-ciphers", ARG_STRING}, {"E3", "proxy-crlfile", ARG_FILENAME}, {"E4", "proxy-ssl-allow-beast", ARG_BOOL}, {"E5", "login-options", ARG_STRING}, {"E6", "proxy-cacert", ARG_FILENAME}, {"E7", "proxy-capath", ARG_FILENAME}, {"E8", "proxy-insecure", ARG_BOOL}, {"E9", "proxy-tlsv1", ARG_NONE}, {"EA", "socks5-basic", ARG_BOOL}, {"EB", "socks5-gssapi", ARG_BOOL}, {"f", "fail", ARG_BOOL}, {"fa", "fail-early", ARG_BOOL}, {"fb", "styled-output", ARG_BOOL}, {"F", "form", ARG_STRING}, {"Fs", "form-string", ARG_STRING}, {"g", "globoff", ARG_BOOL}, {"G", "get", ARG_NONE}, {"Ga", "request-target", ARG_STRING}, {"h", "help", ARG_BOOL}, {"H", "header", ARG_STRING}, {"Hp", "proxy-header", ARG_STRING}, {"i", "include", ARG_BOOL}, {"I", "head", ARG_BOOL}, {"j", "junk-session-cookies", ARG_BOOL}, {"J", "remote-header-name", ARG_BOOL}, {"k", "insecure", ARG_BOOL}, {"K", "config", ARG_FILENAME}, {"l", "list-only", ARG_BOOL}, {"L", "location", ARG_BOOL}, {"Lt", "location-trusted", ARG_BOOL}, {"m", "max-time", ARG_STRING}, {"M", "manual", ARG_BOOL}, {"n", "netrc", ARG_BOOL}, {"no", "netrc-optional", ARG_BOOL}, {"ne", "netrc-file", ARG_FILENAME}, {"N", "buffer", ARG_BOOL}, /* 'buffer' listed as --no-buffer in the help */ {"o", "output", ARG_FILENAME}, {"O", "remote-name", ARG_NONE}, {"Oa", "remote-name-all", ARG_BOOL}, {"p", "proxytunnel", ARG_BOOL}, {"P", "ftp-port", ARG_STRING}, {"q", "disable", ARG_BOOL}, {"Q", "quote", ARG_STRING}, {"r", "range", ARG_STRING}, {"R", "remote-time", ARG_BOOL}, {"s", "silent", ARG_BOOL}, {"S", "show-error", ARG_BOOL}, {"t", "telnet-option", ARG_STRING}, {"T", "upload-file", ARG_FILENAME}, {"u", "user", ARG_STRING}, {"U", "proxy-user", ARG_STRING}, {"v", "verbose", ARG_BOOL}, {"V", "version", ARG_BOOL}, {"w", "write-out", ARG_STRING}, {"x", "proxy", ARG_STRING}, {"xa", "preproxy", ARG_STRING}, {"X", "request", ARG_STRING}, {"Y", "speed-limit", ARG_STRING}, {"y", "speed-time", ARG_STRING}, {"z", "time-cond", ARG_STRING}, {"#", "progress-bar", ARG_BOOL}, {":", "next", ARG_NONE}, }; /* Split the argument of -E to 'certname' and 'passphrase' separated by colon. * We allow ':' and '\' to be escaped by '\' so that we can use certificate * nicknames containing ':'. See <https://sourceforge.net/p/curl/bugs/1196/> * for details. */ #ifndef UNITTESTS static #endif void parse_cert_parameter(const char *cert_parameter, char **certname, char **passphrase) { size_t param_length = strlen(cert_parameter); size_t span; const char *param_place = NULL; char *certname_place = NULL; *certname = NULL; *passphrase = NULL; /* most trivial assumption: cert_parameter is empty */ if(param_length == 0) return; /* next less trivial: cert_parameter starts 'pkcs11:' and thus * looks like a RFC7512 PKCS#11 URI which can be used as-is. * Also if cert_parameter contains no colon nor backslash, this * means no passphrase was given and no characters escaped */ if(curl_strnequal(cert_parameter, "pkcs11:", 7) || !strpbrk(cert_parameter, ":\\")) { *certname = strdup(cert_parameter); return; } /* deal with escaped chars; find unescaped colon if it exists */ certname_place = malloc(param_length + 1); if(!certname_place) return; *certname = certname_place; param_place = cert_parameter; while(*param_place) { span = strcspn(param_place, ":\\"); strncpy(certname_place, param_place, span); param_place += span; certname_place += span; /* we just ate all the non-special chars. now we're on either a special * char or the end of the string. */ switch(*param_place) { case '\0': break; case '\\': param_place++; switch(*param_place) { case '\0': *certname_place++ = '\\'; break; case '\\': *certname_place++ = '\\'; param_place++; break; case ':': *certname_place++ = ':'; param_place++; break; default: *certname_place++ = '\\'; *certname_place++ = *param_place; param_place++; break; } break; case ':': /* Since we live in a world of weirdness and confusion, the win32 dudes can use : when using drive letters and thus c:\file:password needs to work. In order not to break compatibility, we still use : as separator, but we try to detect when it is used for a file name! On windows. */ #ifdef WIN32 if(param_place && (param_place == &cert_parameter[1]) && (cert_parameter[2] == '\\' || cert_parameter[2] == '/') && (ISALPHA(cert_parameter[0])) ) { /* colon in the second column, followed by a backslash, and the first character is an alphabetic letter: this is a drive letter colon */ *certname_place++ = ':'; param_place++; break; } #endif /* escaped colons and Windows drive letter colons were handled * above; if we're still here, this is a separating colon */ param_place++; if(strlen(param_place) > 0) { *passphrase = strdup(param_place); } goto done; } } done: *certname_place = '\0'; } static void GetFileAndPassword(char *nextarg, char **file, char **password) { char *certname, *passphrase; parse_cert_parameter(nextarg, &certname, &passphrase); Curl_safefree(*file); *file = certname; if(passphrase) { Curl_safefree(*password); *password = passphrase; } cleanarg(nextarg); } /* Get a size parameter for '--limit-rate' or '--max-filesize'. * We support a 'G', 'M' or 'K' suffix too. */ static ParameterError GetSizeParameter(struct GlobalConfig *global, const char *arg, const char *which, curl_off_t *value_out) { char *unit; curl_off_t value; if(curlx_strtoofft(arg, &unit, 0, &value)) { warnf(global, "invalid number specified for %s\n", which); return PARAM_BAD_USE; } if(!*unit) unit = (char *)"b"; else if(strlen(unit) > 1) unit = (char *)"w"; /* unsupported */ switch(*unit) { case 'G': case 'g': if(value > (CURL_OFF_T_MAX / (1024*1024*1024))) return PARAM_NUMBER_TOO_LARGE; value *= 1024*1024*1024; break; case 'M': case 'm': if(value > (CURL_OFF_T_MAX / (1024*1024))) return PARAM_NUMBER_TOO_LARGE; value *= 1024*1024; break; case 'K': case 'k': if(value > (CURL_OFF_T_MAX / 1024)) return PARAM_NUMBER_TOO_LARGE; value *= 1024; break; case 'b': case 'B': /* for plain bytes, leave as-is */ break; default: warnf(global, "unsupported %s unit. Use G, M, K or B!\n", which); return PARAM_BAD_USE; } *value_out = value; return PARAM_OK; } ParameterError getparameter(const char *flag, /* f or -long-flag */ char *nextarg, /* NULL if unset */ bool *usedarg, /* set to TRUE if the arg has been used */ struct GlobalConfig *global, struct OperationConfig *config) { char letter; char subletter = '\0'; /* subletters can only occur on long options */ int rc; const char *parse = NULL; unsigned int j; time_t now; int hit = -1; bool longopt = FALSE; bool singleopt = FALSE; /* when true means '-o foo' used '-ofoo' */ ParameterError err; bool toggle = TRUE; /* how to switch boolean options, on or off. Controlled by using --OPTION or --no-OPTION */ *usedarg = FALSE; /* default is that we don't use the arg */ if(('-' != flag[0]) || ('-' == flag[1])) { /* this should be a long name */ const char *word = ('-' == flag[0]) ? flag + 2 : flag; size_t fnam = strlen(word); int numhits = 0; bool noflagged = FALSE; if(!strncmp(word, "no-", 3)) { /* disable this option but ignore the "no-" part when looking for it */ word += 3; toggle = FALSE; noflagged = TRUE; } for(j = 0; j < sizeof(aliases)/sizeof(aliases[0]); j++) { if(curl_strnequal(aliases[j].lname, word, fnam)) { longopt = TRUE; numhits++; if(curl_strequal(aliases[j].lname, word)) { parse = aliases[j].letter; hit = j; numhits = 1; /* a single unique hit */ break; } parse = aliases[j].letter; hit = j; } } if(numhits > 1) { /* this is at least the second match! */ return PARAM_OPTION_AMBIGUOUS; } if(hit < 0) { return PARAM_OPTION_UNKNOWN; } if(noflagged && (aliases[hit].desc != ARG_BOOL)) /* --no- prefixed an option that isn't boolean! */ return PARAM_NO_NOT_BOOLEAN; } else { flag++; /* prefixed with one dash, pass it */ hit = -1; parse = flag; } do { /* we can loop here if we have multiple single-letters */ if(!longopt) { letter = (char)*parse; subletter = '\0'; } else { letter = parse[0]; subletter = parse[1]; } if(hit < 0) { for(j = 0; j < sizeof(aliases)/sizeof(aliases[0]); j++) { if(letter == aliases[j].letter[0]) { hit = j; break; } } if(hit < 0) { return PARAM_OPTION_UNKNOWN; } } if(aliases[hit].desc >= ARG_STRING) { /* this option requires an extra parameter */ if(!longopt && parse[1]) { nextarg = (char *)&parse[1]; /* this is the actual extra parameter */ singleopt = TRUE; /* don't loop anymore after this */ } else if(!nextarg) return PARAM_REQUIRES_PARAMETER; else *usedarg = TRUE; /* mark it as used */ if((aliases[hit].desc == ARG_FILENAME) && (nextarg[0] == '-') && nextarg[1]) { /* if the file name looks like a command line option */ warnf(global, "The file name argument '%s' looks like a flag.\n", nextarg); } } else if((aliases[hit].desc == ARG_NONE) && !toggle) return PARAM_NO_PREFIX; switch(letter) { case '*': /* options without a short option */ switch(subletter) { case '4': /* --dns-ipv4-addr */ /* addr in dot notation */ GetStr(&config->dns_ipv4_addr, nextarg); break; case '6': /* --dns-ipv6-addr */ /* addr in dot notation */ GetStr(&config->dns_ipv6_addr, nextarg); break; case 'a': /* random-file */ GetStr(&config->random_file, nextarg); break; case 'b': /* egd-file */ GetStr(&config->egd_file, nextarg); break; case 'B': /* OAuth 2.0 bearer token */ GetStr(&config->oauth_bearer, nextarg); config->authtype |= CURLAUTH_BEARER; break; case 'c': /* connect-timeout */ err = str2udouble(&config->connecttimeout, nextarg, LONG_MAX/1000); if(err) return err; break; case 'C': /* doh-url */ GetStr(&config->doh_url, nextarg); break; case 'd': /* ciphers */ GetStr(&config->cipher_list, nextarg); break; case 'D': /* --dns-interface */ /* interface name */ GetStr(&config->dns_interface, nextarg); break; case 'e': /* --disable-epsv */ config->disable_epsv = toggle; break; case 'f': /* --disallow-username-in-url */ config->disallow_username_in_url = toggle; break; case 'E': /* --epsv */ config->disable_epsv = (!toggle)?TRUE:FALSE; break; case 'F': /* --dns-servers */ /* IP addrs of DNS servers */ GetStr(&config->dns_servers, nextarg); break; case 'g': /* --trace */ GetStr(&global->trace_dump, nextarg); if(global->tracetype && (global->tracetype != TRACE_BIN)) warnf(global, "--trace overrides an earlier trace/verbose option\n"); global->tracetype = TRACE_BIN; break; case 'G': /* --npn */ config->nonpn = (!toggle)?TRUE:FALSE; break; case 'h': /* --trace-ascii */ GetStr(&global->trace_dump, nextarg); if(global->tracetype && (global->tracetype != TRACE_ASCII)) warnf(global, "--trace-ascii overrides an earlier trace/verbose option\n"); global->tracetype = TRACE_ASCII; break; case 'H': /* --alpn */ config->noalpn = (!toggle)?TRUE:FALSE; break; case 'i': /* --limit-rate */ { curl_off_t value; ParameterError pe = GetSizeParameter(global, nextarg, "rate", &value); if(pe != PARAM_OK) return pe; config->recvpersecond = value; config->sendpersecond = value; } break; case 'j': /* --compressed */ if(toggle && !(curlinfo->features & (CURL_VERSION_LIBZ | CURL_VERSION_BROTLI))) return PARAM_LIBCURL_DOESNT_SUPPORT; config->encoding = toggle; break; case 'J': /* --tr-encoding */ config->tr_encoding = toggle; break; case 'k': /* --digest */ if(toggle) config->authtype |= CURLAUTH_DIGEST; else config->authtype &= ~CURLAUTH_DIGEST; break; case 'l': /* --negotiate */ if(toggle) { if(curlinfo->features & CURL_VERSION_SPNEGO) config->authtype |= CURLAUTH_NEGOTIATE; else return PARAM_LIBCURL_DOESNT_SUPPORT; } else config->authtype &= ~CURLAUTH_NEGOTIATE; break; case 'm': /* --ntlm */ if(toggle) { if(curlinfo->features & CURL_VERSION_NTLM) config->authtype |= CURLAUTH_NTLM; else return PARAM_LIBCURL_DOESNT_SUPPORT; } else config->authtype &= ~CURLAUTH_NTLM; break; case 'M': /* --ntlm-wb */ if(toggle) { if(curlinfo->features & CURL_VERSION_NTLM_WB) config->authtype |= CURLAUTH_NTLM_WB; else return PARAM_LIBCURL_DOESNT_SUPPORT; } else config->authtype &= ~CURLAUTH_NTLM_WB; break; case 'n': /* --basic for completeness */ if(toggle) config->authtype |= CURLAUTH_BASIC; else config->authtype &= ~CURLAUTH_BASIC; break; case 'o': /* --anyauth, let libcurl pick it */ if(toggle) config->authtype = CURLAUTH_ANY; /* --no-anyauth simply doesn't touch it */ break; #ifdef USE_WATT32 case 'p': /* --wdebug */ dbug_init(); break; #endif case 'q': /* --ftp-create-dirs */ config->ftp_create_dirs = toggle; break; case 'r': /* --create-dirs */ config->create_dirs = toggle; break; case 's': /* --max-redirs */ /* specified max no of redirects (http(s)), this accepts -1 as a special condition */ err = str2num(&config->maxredirs, nextarg); if(err) return err; if(config->maxredirs < -1) return PARAM_BAD_NUMERIC; break; case 't': /* --proxy-ntlm */ if(curlinfo->features & CURL_VERSION_NTLM) config->proxyntlm = toggle; else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'u': /* --crlf */ /* LF -> CRLF conversion? */ config->crlf = toggle; break; case 'v': /* --stderr */ if(strcmp(nextarg, "-")) { FILE *newfile = fopen(nextarg, FOPEN_WRITETEXT); if(!newfile) warnf(global, "Failed to open %s!\n", nextarg); else { if(global->errors_fopened) fclose(global->errors); global->errors = newfile; global->errors_fopened = TRUE; } } else global->errors = stdout; break; case 'w': /* --interface */ /* interface */ GetStr(&config->iface, nextarg); break; case 'x': /* --krb */ /* kerberos level string */ if(curlinfo->features & CURL_VERSION_KERBEROS4) GetStr(&config->krblevel, nextarg); else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'X': /* --haproxy-protocol */ config->haproxy_protocol = toggle; break; case 'y': /* --max-filesize */ { curl_off_t value; ParameterError pe = GetSizeParameter(global, nextarg, "max-filesize", &value); if(pe != PARAM_OK) return pe; config->max_filesize = value; } break; case 'z': /* --disable-eprt */ config->disable_eprt = toggle; break; case 'Z': /* --eprt */ config->disable_eprt = (!toggle)?TRUE:FALSE; break; case '~': /* --xattr */ config->xattr = toggle; break; case '@': /* the URL! */ { struct getout *url; if(!config->url_get) config->url_get = config->url_list; if(config->url_get) { /* there's a node here, if it already is filled-in continue to find an "empty" node */ while(config->url_get && (config->url_get->flags & GETOUT_URL)) config->url_get = config->url_get->next; } /* now there might or might not be an available node to fill in! */ if(config->url_get) /* existing node */ url = config->url_get; else /* there was no free node, create one! */ config->url_get = url = new_getout(config); if(!url) return PARAM_NO_MEM; /* fill in the URL */ GetStr(&url->url, nextarg); url->flags |= GETOUT_URL; } } break; case '$': /* more options without a short option */ switch(subletter) { case 'a': /* --ssl */ if(toggle && !(curlinfo->features & CURL_VERSION_SSL)) return PARAM_LIBCURL_DOESNT_SUPPORT; config->ftp_ssl = toggle; break; case 'b': /* --ftp-pasv */ Curl_safefree(config->ftpport); break; case 'c': /* --socks5 specifies a socks5 proxy to use, and resolves the name locally and passes on the resolved address */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_SOCKS5; break; case 't': /* --socks4 specifies a socks4 proxy to use */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_SOCKS4; break; case 'T': /* --socks4a specifies a socks4a proxy to use */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_SOCKS4A; break; case '2': /* --socks5-hostname specifies a socks5 proxy and enables name resolving with the proxy */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_SOCKS5_HOSTNAME; break; case 'd': /* --tcp-nodelay option */ config->tcp_nodelay = toggle; break; case 'e': /* --proxy-digest */ config->proxydigest = toggle; break; case 'f': /* --proxy-basic */ config->proxybasic = toggle; break; case 'g': /* --retry */ err = str2unum(&config->req_retry, nextarg); if(err) return err; break; case 'V': /* --retry-connrefused */ config->retry_connrefused = toggle; break; case 'h': /* --retry-delay */ err = str2unum(&config->retry_delay, nextarg); if(err) return err; break; case 'i': /* --retry-max-time */ err = str2unum(&config->retry_maxtime, nextarg); if(err) return err; break; case 'k': /* --proxy-negotiate */ if(curlinfo->features & CURL_VERSION_SPNEGO) config->proxynegotiate = toggle; else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'm': /* --ftp-account */ GetStr(&config->ftp_account, nextarg); break; case 'n': /* --proxy-anyauth */ config->proxyanyauth = toggle; break; case 'o': /* --trace-time */ global->tracetime = toggle; break; case 'p': /* --ignore-content-length */ config->ignorecl = toggle; break; case 'q': /* --ftp-skip-pasv-ip */ config->ftp_skip_ip = toggle; break; case 'r': /* --ftp-method (undocumented at this point) */ config->ftp_filemethod = ftpfilemethod(config, nextarg); break; case 's': { /* --local-port */ char lrange[7]; /* 16bit base 10 is 5 digits, but we allow 6 so that this catches overflows, not just truncates */ char *p = nextarg; while(ISDIGIT(*p)) p++; if(*p) { /* if there's anything more than a plain decimal number */ rc = sscanf(p, " - %6s", lrange); *p = 0; /* zero terminate to make str2unum() work below */ } else rc = 0; err = str2unum(&config->localport, nextarg); if(err || (config->localport > 65535)) return PARAM_BAD_USE; if(!rc) config->localportrange = 1; /* default number of ports to try */ else { err = str2unum(&config->localportrange, lrange); if(err || (config->localportrange > 65535)) return PARAM_BAD_USE; config->localportrange -= (config->localport-1); if(config->localportrange < 1) return PARAM_BAD_USE; } break; } case 'u': /* --ftp-alternative-to-user */ GetStr(&config->ftp_alternative_to_user, nextarg); break; case 'v': /* --ssl-reqd */ if(toggle && !(curlinfo->features & CURL_VERSION_SSL)) return PARAM_LIBCURL_DOESNT_SUPPORT; config->ftp_ssl_reqd = toggle; break; case 'w': /* --no-sessionid */ config->disable_sessionid = (!toggle)?TRUE:FALSE; break; case 'x': /* --ftp-ssl-control */ if(toggle && !(curlinfo->features & CURL_VERSION_SSL)) return PARAM_LIBCURL_DOESNT_SUPPORT; config->ftp_ssl_control = toggle; break; case 'y': /* --ftp-ssl-ccc */ config->ftp_ssl_ccc = toggle; if(!config->ftp_ssl_ccc_mode) config->ftp_ssl_ccc_mode = CURLFTPSSL_CCC_PASSIVE; break; case 'j': /* --ftp-ssl-ccc-mode */ config->ftp_ssl_ccc = TRUE; config->ftp_ssl_ccc_mode = ftpcccmethod(config, nextarg); break; case 'z': /* --libcurl */ #ifdef CURL_DISABLE_LIBCURL_OPTION warnf(global, "--libcurl option was disabled at build-time!\n"); return PARAM_OPTION_UNKNOWN; #else GetStr(&global->libcurl, nextarg); break; #endif case '#': /* --raw */ config->raw = toggle; break; case '0': /* --post301 */ config->post301 = toggle; break; case '1': /* --no-keepalive */ config->nokeepalive = (!toggle)?TRUE:FALSE; break; case '3': /* --keepalive-time */ err = str2unum(&config->alivetime, nextarg); if(err) return err; break; case '4': /* --post302 */ config->post302 = toggle; break; case 'I': /* --post303 */ config->post303 = toggle; break; case '5': /* --noproxy */ /* This specifies the noproxy list */ GetStr(&config->noproxy, nextarg); break; case '7': /* --socks5-gssapi-nec*/ config->socks5_gssapi_nec = toggle; break; case '8': /* --proxy1.0 */ /* http 1.0 proxy */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_HTTP_1_0; break; case '9': /* --tftp-blksize */ err = str2unum(&config->tftp_blksize, nextarg); if(err) return err; break; case 'A': /* --mail-from */ GetStr(&config->mail_from, nextarg); break; case 'B': /* --mail-rcpt */ /* append receiver to a list */ err = add2list(&config->mail_rcpt, nextarg); if(err) return err; break; case 'C': /* --ftp-pret */ config->ftp_pret = toggle; break; case 'D': /* --proto */ config->proto_present = TRUE; if(proto2num(config, &config->proto, nextarg)) return PARAM_BAD_USE; break; case 'E': /* --proto-redir */ config->proto_redir_present = TRUE; if(proto2num(config, &config->proto_redir, nextarg)) return PARAM_BAD_USE; break; case 'F': /* --resolve */ err = add2list(&config->resolve, nextarg); if(err) return err; break; case 'G': /* --delegation LEVEL */ config->gssapi_delegation = delegation(config, nextarg); break; case 'H': /* --mail-auth */ GetStr(&config->mail_auth, nextarg); break; case 'J': /* --metalink */ { #ifdef USE_METALINK int mlmaj, mlmin, mlpatch; metalink_get_version(&mlmaj, &mlmin, &mlpatch); if((mlmaj*10000)+(mlmin*100) + mlpatch < CURL_REQ_LIBMETALINK_VERS) { warnf(global, "--metalink option cannot be used because the version of " "the linked libmetalink library is too old. " "Required: %d.%d.%d, found %d.%d.%d\n", CURL_REQ_LIBMETALINK_MAJOR, CURL_REQ_LIBMETALINK_MINOR, CURL_REQ_LIBMETALINK_PATCH, mlmaj, mlmin, mlpatch); return PARAM_BAD_USE; } else config->use_metalink = toggle; #else warnf(global, "--metalink option is ignored because the binary is " "built without the Metalink support.\n"); #endif break; } case 'K': /* --sasl-ir */ config->sasl_ir = toggle; break; case 'L': /* --test-event */ #ifdef CURLDEBUG config->test_event_based = toggle; #else warnf(global, "--test-event is ignored unless a debug build!\n"); #endif break; case 'M': /* --unix-socket */ config->abstract_unix_socket = FALSE; GetStr(&config->unix_socket_path, nextarg); break; case 'N': /* --path-as-is */ config->path_as_is = toggle; break; case 'O': /* --proxy-service-name */ GetStr(&config->proxy_service_name, nextarg); break; case 'P': /* --service-name */ GetStr(&config->service_name, nextarg); break; case 'Q': /* --proto-default */ GetStr(&config->proto_default, nextarg); err = check_protocol(config->proto_default); if(err) return err; break; case 'R': /* --expect100-timeout */ err = str2udouble(&config->expect100timeout, nextarg, LONG_MAX/1000); if(err) return err; break; case 'S': /* --tftp-no-options */ config->tftp_no_options = toggle; break; case 'U': /* --connect-to */ err = add2list(&config->connect_to, nextarg); if(err) return err; break; case 'W': /* --abstract-unix-socket */ config->abstract_unix_socket = TRUE; GetStr(&config->unix_socket_path, nextarg); break; case 'X': /* --tls-max */ err = str2tls_max(&config->ssl_version_max, nextarg); if(err) return err; break; case 'Y': /* --suppress-connect-headers */ config->suppress_connect_headers = toggle; break; case 'Z': /* --compressed-ssh */ config->ssh_compression = toggle; break; case '~': /* --happy-eyeballs-timeout-ms */ err = str2unum(&config->happy_eyeballs_timeout_ms, nextarg); if(err) return err; /* 0 is a valid value for this timeout */ break; } break; case '#': /* --progress-bar */ if(toggle) global->progressmode = CURL_PROGRESS_BAR; else global->progressmode = CURL_PROGRESS_STATS; break; case ':': /* --next */ return PARAM_NEXT_OPERATION; case '0': /* --http* options */ switch(subletter) { case '\0': /* HTTP version 1.0 */ config->httpversion = CURL_HTTP_VERSION_1_0; break; case '1': /* HTTP version 1.1 */ config->httpversion = CURL_HTTP_VERSION_1_1; break; case '2': /* HTTP version 2.0 */ config->httpversion = CURL_HTTP_VERSION_2_0; break; case '3': /* HTTP version 2.0 over clean TCP*/ config->httpversion = CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE; break; case '9': /* Allow HTTP/0.9 responses! */ config->http09_allowed = toggle; break; } break; case '1': /* --tlsv1* options */ switch(subletter) { case '\0': /* TLS version 1.x */ config->ssl_version = CURL_SSLVERSION_TLSv1; break; case '0': /* TLS version 1.0 */ config->ssl_version = CURL_SSLVERSION_TLSv1_0; break; case '1': /* TLS version 1.1 */ config->ssl_version = CURL_SSLVERSION_TLSv1_1; break; case '2': /* TLS version 1.2 */ config->ssl_version = CURL_SSLVERSION_TLSv1_2; break; case '3': /* TLS version 1.3 */ config->ssl_version = CURL_SSLVERSION_TLSv1_3; break; case 'A': /* --tls13-ciphers */ GetStr(&config->cipher13_list, nextarg); break; case 'B': /* --proxy-tls13-ciphers */ GetStr(&config->proxy_cipher13_list, nextarg); break; } break; case '2': /* SSL version 2 */ config->ssl_version = CURL_SSLVERSION_SSLv2; break; case '3': /* SSL version 3 */ config->ssl_version = CURL_SSLVERSION_SSLv3; break; case '4': /* IPv4 */ config->ip_version = 4; break; case '6': /* IPv6 */ config->ip_version = 6; break; case 'a': /* This makes the FTP sessions use APPE instead of STOR */ config->ftp_append = toggle; break; case 'A': /* This specifies the User-Agent name */ GetStr(&config->useragent, nextarg); break; case 'b': switch(subletter) { case 'a': /* --alt-svc */ GetStr(&config->altsvc, nextarg); break; default: /* --cookie string coming up: */ if(nextarg[0] == '@') { nextarg++; } else if(strchr(nextarg, '=')) { /* A cookie string must have a =-letter */ GetStr(&config->cookie, nextarg); break; } /* We have a cookie file to read from! */ GetStr(&config->cookiefile, nextarg); } break; case 'B': /* use ASCII/text when transferring */ config->use_ascii = toggle; break; case 'c': /* get the file name to dump all cookies in */ GetStr(&config->cookiejar, nextarg); break; case 'C': /* This makes us continue an ftp transfer at given position */ if(strcmp(nextarg, "-")) { err = str2offset(&config->resume_from, nextarg); if(err) return err; config->resume_from_current = FALSE; } else { config->resume_from_current = TRUE; config->resume_from = 0; } config->use_resume = TRUE; break; case 'd': /* postfield data */ { char *postdata = NULL; FILE *file; size_t size = 0; bool raw_mode = (subletter == 'r'); if(subletter == 'e') { /* --data-urlencode*/ /* [name]=[content], we encode the content part only * [name]@[file name] * * Case 2: we first load the file using that name and then encode * the content. */ const char *p = strchr(nextarg, '='); size_t nlen; char is_file; if(!p) /* there was no '=' letter, check for a '@' instead */ p = strchr(nextarg, '@'); if(p) { nlen = p - nextarg; /* length of the name part */ is_file = *p++; /* pass the separator */ } else { /* neither @ nor =, so no name and it isn't a file */ nlen = is_file = 0; p = nextarg; } if('@' == is_file) { /* a '@' letter, it means that a file name or - (stdin) follows */ if(!strcmp("-", p)) { file = stdin; set_binmode(stdin); } else { file = fopen(p, "rb"); if(!file) warnf(global, "Couldn't read data from file \"%s\", this makes " "an empty POST.\n", nextarg); } err = file2memory(&postdata, &size, file); if(file && (file != stdin)) fclose(file); if(err) return err; } else { GetStr(&postdata, p); if(postdata) size = strlen(postdata); } if(!postdata) { /* no data from the file, point to a zero byte string to make this get sent as a POST anyway */ postdata = strdup(""); if(!postdata) return PARAM_NO_MEM; size = 0; } else { char *enc = curl_easy_escape(config->easy, postdata, (int)size); Curl_safefree(postdata); /* no matter if it worked or not */ if(enc) { /* now make a string with the name from above and append the encoded string */ size_t outlen = nlen + strlen(enc) + 2; char *n = malloc(outlen); if(!n) { curl_free(enc); return PARAM_NO_MEM; } if(nlen > 0) { /* only append '=' if we have a name */ msnprintf(n, outlen, "%.*s=%s", nlen, nextarg, enc); size = outlen-1; } else { strcpy(n, enc); size = outlen-2; /* since no '=' was inserted */ } curl_free(enc); postdata = n; } else return PARAM_NO_MEM; } } else if('@' == *nextarg && !raw_mode) { /* the data begins with a '@' letter, it means that a file name or - (stdin) follows */ nextarg++; /* pass the @ */ if(!strcmp("-", nextarg)) { file = stdin; if(subletter == 'b') /* forced data-binary */ set_binmode(stdin); } else { file = fopen(nextarg, "rb"); if(!file) warnf(global, "Couldn't read data from file \"%s\", this makes " "an empty POST.\n", nextarg); } if(subletter == 'b') /* forced binary */ err = file2memory(&postdata, &size, file); else { err = file2string(&postdata, file); if(postdata) size = strlen(postdata); } if(file && (file != stdin)) fclose(file); if(err) return err; if(!postdata) { /* no data from the file, point to a zero byte string to make this get sent as a POST anyway */ postdata = strdup(""); if(!postdata) return PARAM_NO_MEM; } } else { GetStr(&postdata, nextarg); if(postdata) size = strlen(postdata); } #ifdef CURL_DOES_CONVERSIONS if(subletter != 'b') { /* NOT forced binary, convert to ASCII */ if(convert_to_network(postdata, strlen(postdata))) { Curl_safefree(postdata); return PARAM_NO_MEM; } } #endif if(config->postfields) { /* we already have a string, we append this one with a separating &-letter */ char *oldpost = config->postfields; curl_off_t oldlen = config->postfieldsize; curl_off_t newlen = oldlen + curlx_uztoso(size) + 2; config->postfields = malloc((size_t)newlen); if(!config->postfields) { Curl_safefree(oldpost); Curl_safefree(postdata); return PARAM_NO_MEM; } memcpy(config->postfields, oldpost, (size_t)oldlen); /* use byte value 0x26 for '&' to accommodate non-ASCII platforms */ config->postfields[oldlen] = '\x26'; memcpy(&config->postfields[oldlen + 1], postdata, size); config->postfields[oldlen + 1 + size] = '\0'; Curl_safefree(oldpost); Curl_safefree(postdata); config->postfieldsize += size + 1; } else { config->postfields = postdata; config->postfieldsize = curlx_uztoso(size); } } /* We can't set the request type here, as this data might be used in a simple GET if -G is used. Already or soon. if(SetHTTPrequest(HTTPREQ_SIMPLEPOST, &config->httpreq)) { Curl_safefree(postdata); return PARAM_BAD_USE; } */ break; case 'D': /* dump-header to given file name */ GetStr(&config->headerfile, nextarg); break; case 'e': { char *ptr = strstr(nextarg, ";auto"); if(ptr) { /* Automatic referer requested, this may be combined with a set initial one */ config->autoreferer = TRUE; *ptr = 0; /* zero terminate here */ } else config->autoreferer = FALSE; GetStr(&config->referer, nextarg); } break; case 'E': switch(subletter) { case '\0': /* certificate file */ GetFileAndPassword(nextarg, &config->cert, &config->key_passwd); break; case 'a': /* CA info PEM file */ GetStr(&config->cacert, nextarg); break; case 'b': /* cert file type */ GetStr(&config->cert_type, nextarg); break; case 'c': /* private key file */ GetStr(&config->key, nextarg); break; case 'd': /* private key file type */ GetStr(&config->key_type, nextarg); break; case 'e': /* private key passphrase */ GetStr(&config->key_passwd, nextarg); cleanarg(nextarg); break; case 'f': /* crypto engine */ GetStr(&config->engine, nextarg); if(config->engine && curl_strequal(config->engine, "list")) return PARAM_ENGINES_REQUESTED; break; case 'g': /* CA cert directory */ GetStr(&config->capath, nextarg); break; case 'h': /* --pubkey public key file */ GetStr(&config->pubkey, nextarg); break; case 'i': /* --hostpubmd5 md5 of the host public key */ GetStr(&config->hostpubmd5, nextarg); if(!config->hostpubmd5 || strlen(config->hostpubmd5) != 32) return PARAM_BAD_USE; break; case 'j': /* CRL file */ GetStr(&config->crlfile, nextarg); break; case 'k': /* TLS username */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) GetStr(&config->tls_username, nextarg); else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'l': /* TLS password */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) GetStr(&config->tls_password, nextarg); else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'm': /* TLS authentication type */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) { GetStr(&config->tls_authtype, nextarg); if(!curl_strequal(config->tls_authtype, "SRP")) return PARAM_LIBCURL_DOESNT_SUPPORT; /* only support TLS-SRP */ } else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'n': /* no empty SSL fragments, --ssl-allow-beast */ if(curlinfo->features & CURL_VERSION_SSL) config->ssl_allow_beast = toggle; break; case 'o': /* --login-options */ GetStr(&config->login_options, nextarg); break; case 'p': /* Pinned public key DER file */ GetStr(&config->pinnedpubkey, nextarg); break; case 'P': /* proxy pinned public key */ GetStr(&config->proxy_pinnedpubkey, nextarg); break; case 'q': /* --cert-status */ config->verifystatus = TRUE; break; case 'r': /* --false-start */ config->falsestart = TRUE; break; case 's': /* --ssl-no-revoke */ if(curlinfo->features & CURL_VERSION_SSL) config->ssl_no_revoke = TRUE; break; case 't': /* --tcp-fastopen */ config->tcp_fastopen = TRUE; break; case 'u': /* TLS username for proxy */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) GetStr(&config->proxy_tls_username, nextarg); else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'v': /* TLS password for proxy */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) GetStr(&config->proxy_tls_password, nextarg); else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'w': /* TLS authentication type for proxy */ if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) { GetStr(&config->proxy_tls_authtype, nextarg); if(!curl_strequal(config->proxy_tls_authtype, "SRP")) return PARAM_LIBCURL_DOESNT_SUPPORT; /* only support TLS-SRP */ } else return PARAM_LIBCURL_DOESNT_SUPPORT; break; case 'x': /* certificate file for proxy */ GetFileAndPassword(nextarg, &config->proxy_cert, &config->proxy_key_passwd); break; case 'y': /* cert file type for proxy */ GetStr(&config->proxy_cert_type, nextarg); break; case 'z': /* private key file for proxy */ GetStr(&config->proxy_key, nextarg); break; case '0': /* private key file type for proxy */ GetStr(&config->proxy_key_type, nextarg); break; case '1': /* private key passphrase for proxy */ GetStr(&config->proxy_key_passwd, nextarg); cleanarg(nextarg); break; case '2': /* ciphers for proxy */ GetStr(&config->proxy_cipher_list, nextarg); break; case '3': /* CRL file for proxy */ GetStr(&config->proxy_crlfile, nextarg); break; case '4': /* no empty SSL fragments for proxy */ if(curlinfo->features & CURL_VERSION_SSL) config->proxy_ssl_allow_beast = toggle; break; case '5': /* --login-options */ GetStr(&config->login_options, nextarg); break; case '6': /* CA info PEM file for proxy */ GetStr(&config->proxy_cacert, nextarg); break; case '7': /* CA cert directory for proxy */ GetStr(&config->proxy_capath, nextarg); break; case '8': /* allow insecure SSL connects for proxy */ config->proxy_insecure_ok = toggle; break; case '9': /* --proxy-tlsv1 */ /* TLS version 1 for proxy */ config->proxy_ssl_version = CURL_SSLVERSION_TLSv1; break; case 'A': /* --socks5-basic */ if(toggle) config->socks5_auth |= CURLAUTH_BASIC; else config->socks5_auth &= ~CURLAUTH_BASIC; break; case 'B': /* --socks5-gssapi */ if(toggle) config->socks5_auth |= CURLAUTH_GSSAPI; else config->socks5_auth &= ~CURLAUTH_GSSAPI; break; default: /* unknown flag */ return PARAM_OPTION_UNKNOWN; } break; case 'f': switch(subletter) { case 'a': /* --fail-early */ global->fail_early = toggle; break; case 'b': /* --styled-output */ global->styled_output = toggle; break; default: /* --fail (hard on errors) */ config->failonerror = toggle; } break; case 'F': /* "form data" simulation, this is a little advanced so lets do our best to sort this out slowly and carefully */ if(formparse(config, nextarg, &config->mimeroot, &config->mimecurrent, (subletter == 's')?TRUE:FALSE)) /* 's' is literal string */ return PARAM_BAD_USE; if(SetHTTPrequest(config, HTTPREQ_MIMEPOST, &config->httpreq)) return PARAM_BAD_USE; break; case 'g': /* g disables URLglobbing */ config->globoff = toggle; break; case 'G': /* HTTP GET */ if(subletter == 'a') { /* --request-target */ GetStr(&config->request_target, nextarg); } else config->use_httpget = TRUE; break; case 'h': /* h for help */ if(toggle) { return PARAM_HELP_REQUESTED; } /* we now actually support --no-help too! */ break; case 'H': /* A custom header to append to a list */ if(nextarg[0] == '@') { /* read many headers from a file or stdin */ char *string; size_t len; bool use_stdin = !strcmp(&nextarg[1], "-"); FILE *file = use_stdin?stdin:fopen(&nextarg[1], FOPEN_READTEXT); if(!file) warnf(global, "Failed to open %s!\n", &nextarg[1]); else { err = file2memory(&string, &len, file); if(!err && string) { /* Allow strtok() here since this isn't used threaded */ /* !checksrc! disable BANNEDFUNC 2 */ char *h = strtok(string, "\r\n"); while(h) { if(subletter == 'p') /* --proxy-header */ err = add2list(&config->proxyheaders, h); else err = add2list(&config->headers, h); if(err) break; h = strtok(NULL, "\r\n"); } free(string); } if(!use_stdin) fclose(file); if(err) return err; } } else { if(subletter == 'p') /* --proxy-header */ err = add2list(&config->proxyheaders, nextarg); else err = add2list(&config->headers, nextarg); if(err) return err; } break; case 'i': config->show_headers = toggle; /* show the headers as well in the general output stream */ break; case 'j': config->cookiesession = toggle; break; case 'I': /* --head */ config->no_body = toggle; config->show_headers = toggle; if(SetHTTPrequest(config, (config->no_body)?HTTPREQ_HEAD:HTTPREQ_GET, &config->httpreq)) return PARAM_BAD_USE; break; case 'J': /* --remote-header-name */ if(config->show_headers) { warnf(global, "--include and --remote-header-name cannot be combined.\n"); return PARAM_BAD_USE; } config->content_disposition = toggle; break; case 'k': /* allow insecure SSL connects */ config->insecure_ok = toggle; break; case 'K': /* parse config file */ if(parseconfig(nextarg, global)) warnf(global, "error trying read config from the '%s' file\n", nextarg); break; case 'l': config->dirlistonly = toggle; /* only list the names of the FTP dir */ break; case 'L': config->followlocation = toggle; /* Follow Location: HTTP headers */ switch(subletter) { case 't': /* Continue to send authentication (user+password) when following * locations, even when hostname changed */ config->unrestricted_auth = toggle; break; } break; case 'm': /* specified max time */ err = str2udouble(&config->timeout, nextarg, LONG_MAX/1000); if(err) return err; break; case 'M': /* M for manual, huge help */ if(toggle) { /* --no-manual shows no manual... */ #ifdef USE_MANUAL return PARAM_MANUAL_REQUESTED; #else warnf(global, "built-in manual was disabled at build-time!\n"); return PARAM_OPTION_UNKNOWN; #endif } break; case 'n': switch(subletter) { case 'o': /* use .netrc or URL */ config->netrc_opt = toggle; break; case 'e': /* netrc-file */ GetStr(&config->netrc_file, nextarg); break; default: /* pick info from .netrc, if this is used for http, curl will automatically enfore user+password with the request */ config->netrc = toggle; break; } break; case 'N': /* disable the output I/O buffering. note that the option is called --buffer but is mostly used in the negative form: --no-buffer */ if(longopt) config->nobuffer = (!toggle)?TRUE:FALSE; else config->nobuffer = toggle; break; case 'O': /* --remote-name */ if(subletter == 'a') { /* --remote-name-all */ config->default_node_flags = toggle?GETOUT_USEREMOTE:0; break; } /* FALLTHROUGH */ case 'o': /* --output */ /* output file */ { struct getout *url; if(!config->url_out) config->url_out = config->url_list; if(config->url_out) { /* there's a node here, if it already is filled-in continue to find an "empty" node */ while(config->url_out && (config->url_out->flags & GETOUT_OUTFILE)) config->url_out = config->url_out->next; } /* now there might or might not be an available node to fill in! */ if(config->url_out) /* existing node */ url = config->url_out; else /* there was no free node, create one! */ config->url_out = url = new_getout(config); if(!url) return PARAM_NO_MEM; /* fill in the outfile */ if('o' == letter) { GetStr(&url->outfile, nextarg); url->flags &= ~GETOUT_USEREMOTE; /* switch off */ } else { url->outfile = NULL; /* leave it */ if(toggle) url->flags |= GETOUT_USEREMOTE; /* switch on */ else url->flags &= ~GETOUT_USEREMOTE; /* switch off */ } url->flags |= GETOUT_OUTFILE; } break; case 'P': /* This makes the FTP sessions use PORT instead of PASV */ /* use <eth0> or <192.168.10.10> style addresses. Anything except this will make us try to get the "default" address. NOTE: this is a changed behaviour since the released 4.1! */ GetStr(&config->ftpport, nextarg); break; case 'p': /* proxy tunnel for non-http protocols */ config->proxytunnel = toggle; break; case 'q': /* if used first, already taken care of, we do it like this so we don't cause an error! */ break; case 'Q': /* QUOTE command to send to FTP server */ switch(nextarg[0]) { case '-': /* prefixed with a dash makes it a POST TRANSFER one */ nextarg++; err = add2list(&config->postquote, nextarg); break; case '+': /* prefixed with a plus makes it a just-before-transfer one */ nextarg++; err = add2list(&config->prequote, nextarg); break; default: err = add2list(&config->quote, nextarg); break; } if(err) return err; break; case 'r': /* Specifying a range WITHOUT A DASH will create an illegal HTTP range (and won't actually be range by definition). The man page previously claimed that to be a good way, why this code is added to work-around it. */ if(ISDIGIT(*nextarg) && !strchr(nextarg, '-')) { char buffer[32]; curl_off_t off; if(curlx_strtoofft(nextarg, NULL, 10, &off)) { warnf(global, "unsupported range point\n"); return PARAM_BAD_USE; } warnf(global, "A specified range MUST include at least one dash (-). " "Appending one for you!\n"); msnprintf(buffer, sizeof(buffer), "%" CURL_FORMAT_CURL_OFF_T "-", off); Curl_safefree(config->range); config->range = strdup(buffer); if(!config->range) return PARAM_NO_MEM; } { /* byte range requested */ char *tmp_range; tmp_range = nextarg; while(*tmp_range != '\0') { if(!ISDIGIT(*tmp_range) && *tmp_range != '-' && *tmp_range != ',') { warnf(global, "Invalid character is found in given range. " "A specified range MUST have only digits in " "\'start\'-\'stop\'. The server's response to this " "request is uncertain.\n"); break; } tmp_range++; } /* byte range requested */ GetStr(&config->range, nextarg); } break; case 'R': /* use remote file's time */ config->remote_time = toggle; break; case 's': /* don't show progress meter, don't show errors : */ if(toggle) global->mute = global->noprogress = TRUE; else global->mute = global->noprogress = FALSE; if(global->showerror < 0) /* if still on the default value, set showerror to the reverse of toggle. This is to allow -S and -s to be used in an independent order but still have the same effect. */ global->showerror = (!toggle)?TRUE:FALSE; /* toggle off */ break; case 'S': /* show errors */ global->showerror = toggle?1:0; /* toggle on if used with -s */ break; case 't': /* Telnet options */ err = add2list(&config->telnet_options, nextarg); if(err) return err; break; case 'T': /* we are uploading */ { struct getout *url; if(!config->url_ul) config->url_ul = config->url_list; if(config->url_ul) { /* there's a node here, if it already is filled-in continue to find an "empty" node */ while(config->url_ul && (config->url_ul->flags & GETOUT_UPLOAD)) config->url_ul = config->url_ul->next; } /* now there might or might not be an available node to fill in! */ if(config->url_ul) /* existing node */ url = config->url_ul; else /* there was no free node, create one! */ config->url_ul = url = new_getout(config); if(!url) return PARAM_NO_MEM; url->flags |= GETOUT_UPLOAD; /* mark -T used */ if(!*nextarg) url->flags |= GETOUT_NOUPLOAD; else { /* "-" equals stdin, but keep the string around for now */ GetStr(&url->infile, nextarg); } } break; case 'u': /* user:password */ GetStr(&config->userpwd, nextarg); cleanarg(nextarg); break; case 'U': /* Proxy user:password */ GetStr(&config->proxyuserpwd, nextarg); cleanarg(nextarg); break; case 'v': if(toggle) { /* the '%' thing here will cause the trace get sent to stderr */ Curl_safefree(global->trace_dump); global->trace_dump = strdup("%"); if(!global->trace_dump) return PARAM_NO_MEM; if(global->tracetype && (global->tracetype != TRACE_PLAIN)) warnf(global, "-v, --verbose overrides an earlier trace/verbose option\n"); global->tracetype = TRACE_PLAIN; } else /* verbose is disabled here */ global->tracetype = TRACE_NONE; break; case 'V': if(toggle) /* --no-version yields no output! */ return PARAM_VERSION_INFO_REQUESTED; break; case 'w': /* get the output string */ if('@' == *nextarg) { /* the data begins with a '@' letter, it means that a file name or - (stdin) follows */ FILE *file; const char *fname; nextarg++; /* pass the @ */ if(!strcmp("-", nextarg)) { fname = "<stdin>"; file = stdin; } else { fname = nextarg; file = fopen(nextarg, FOPEN_READTEXT); } Curl_safefree(config->writeout); err = file2string(&config->writeout, file); if(file && (file != stdin)) fclose(file); if(err) return err; if(!config->writeout) warnf(global, "Failed to read %s", fname); } else GetStr(&config->writeout, nextarg); break; case 'x': switch(subletter) { case 'a': /* --preproxy */ GetStr(&config->preproxy, nextarg); break; default: /* --proxy */ GetStr(&config->proxy, nextarg); config->proxyver = CURLPROXY_HTTP; break; } break; case 'X': /* set custom request */ GetStr(&config->customrequest, nextarg); break; case 'y': /* low speed time */ err = str2unum(&config->low_speed_time, nextarg); if(err) return err; if(!config->low_speed_limit) config->low_speed_limit = 1; break; case 'Y': /* low speed limit */ err = str2unum(&config->low_speed_limit, nextarg); if(err) return err; if(!config->low_speed_time) config->low_speed_time = 30; break; case 'z': /* time condition coming up */ switch(*nextarg) { case '+': nextarg++; /* FALLTHROUGH */ default: /* If-Modified-Since: (section 14.28 in RFC2068) */ config->timecond = CURL_TIMECOND_IFMODSINCE; break; case '-': /* If-Unmodified-Since: (section 14.24 in RFC2068) */ config->timecond = CURL_TIMECOND_IFUNMODSINCE; nextarg++; break; case '=': /* Last-Modified: (section 14.29 in RFC2068) */ config->timecond = CURL_TIMECOND_LASTMOD; nextarg++; break; } now = time(NULL); config->condtime = (curl_off_t)curl_getdate(nextarg, &now); if(-1 == config->condtime) { /* now let's see if it is a file name to get the time from instead! */ curl_off_t filetime = getfiletime(nextarg, config->global->errors); if(filetime >= 0) { /* pull the time out from the file */ config->condtime = filetime; } else { /* failed, remove time condition */ config->timecond = CURL_TIMECOND_NONE; warnf(global, "Illegal date format for -z, --time-cond (and not " "a file name). Disabling time condition. " "See curl_getdate(3) for valid date syntax.\n"); } } break; default: /* unknown flag */ return PARAM_OPTION_UNKNOWN; } hit = -1; } while(!longopt && !singleopt && *++parse && !*usedarg); return PARAM_OK; } ParameterError parse_args(struct GlobalConfig *config, int argc, argv_item_t argv[]) { int i; bool stillflags; char *orig_opt = NULL; ParameterError result = PARAM_OK; struct OperationConfig *operation = config->first; for(i = 1, stillflags = TRUE; i < argc && !result; i++) { orig_opt = argv[i]; if(stillflags && ('-' == argv[i][0])) { bool passarg; char *flag = argv[i]; if(!strcmp("--", argv[i])) /* This indicates the end of the flags and thus enables the following (URL) argument to start with -. */ stillflags = FALSE; else { char *nextarg = (i < (argc - 1)) ? argv[i + 1] : NULL; result = getparameter(flag, nextarg, &passarg, config, operation); if(result == PARAM_NEXT_OPERATION) { /* Reset result as PARAM_NEXT_OPERATION is only used here and not returned from this function */ result = PARAM_OK; if(operation->url_list && operation->url_list->url) { /* Allocate the next config */ operation->next = malloc(sizeof(struct OperationConfig)); if(operation->next) { /* Initialise the newly created config */ config_init(operation->next); /* Copy the easy handle */ operation->next->easy = config->easy; /* Set the global config pointer */ operation->next->global = config; /* Update the last operation pointer */ config->last = operation->next; /* Move onto the new config */ operation->next->prev = operation; operation = operation->next; } else result = PARAM_NO_MEM; } } else if(!result && passarg) i++; /* we're supposed to skip this */ } } else { bool used; /* Just add the URL please */ result = getparameter((char *)"--url", argv[i], &used, config, operation); } } if(result && result != PARAM_HELP_REQUESTED && result != PARAM_MANUAL_REQUESTED && result != PARAM_VERSION_INFO_REQUESTED && result != PARAM_ENGINES_REQUESTED) { const char *reason = param2text(result); if(orig_opt && strcmp(":", orig_opt)) helpf(config->errors, "option %s: %s\n", orig_opt, reason); else helpf(config->errors, "%s\n", reason); } return result; }
YifuLiu/AliOS-Things
components/curl/src/tool_getparam.c
C
apache-2.0
74,466
#ifndef HEADER_CURL_TOOL_GETPARAM_H #define HEADER_CURL_TOOL_GETPARAM_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" typedef enum { PARAM_OK = 0, PARAM_OPTION_AMBIGUOUS, PARAM_OPTION_UNKNOWN, PARAM_REQUIRES_PARAMETER, PARAM_BAD_USE, PARAM_HELP_REQUESTED, PARAM_MANUAL_REQUESTED, PARAM_VERSION_INFO_REQUESTED, PARAM_ENGINES_REQUESTED, PARAM_GOT_EXTRA_PARAMETER, PARAM_BAD_NUMERIC, PARAM_NEGATIVE_NUMERIC, PARAM_LIBCURL_DOESNT_SUPPORT, PARAM_LIBCURL_UNSUPPORTED_PROTOCOL, PARAM_NO_MEM, PARAM_NEXT_OPERATION, PARAM_NO_PREFIX, PARAM_NUMBER_TOO_LARGE, PARAM_NO_NOT_BOOLEAN, PARAM_LAST } ParameterError; struct GlobalConfig; struct OperationConfig; ParameterError getparameter(const char *flag, char *nextarg, bool *usedarg, struct GlobalConfig *global, struct OperationConfig *operation); #ifdef UNITTESTS void parse_cert_parameter(const char *cert_parameter, char **certname, char **passphrase); #endif ParameterError parse_args(struct GlobalConfig *config, int argc, argv_item_t argv[]); #endif /* HEADER_CURL_TOOL_GETPARAM_H */
YifuLiu/AliOS-Things
components/curl/src/tool_getparam.h
C
apache-2.0
2,211
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #if defined(__AMIGA__) && !defined(__amigaos4__) # undef HAVE_TERMIOS_H #endif #ifndef HAVE_GETPASS_R /* this file is only for systems without getpass_r() */ #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_TERMIOS_H # include <termios.h> #elif defined(HAVE_TERMIO_H) # include <termio.h> #endif #ifdef __VMS # include descrip # include starlet # include iodef #endif #ifdef WIN32 # include <conio.h> #endif #ifdef NETWARE # ifdef __NOVELL_LIBC__ # include <screen.h> # else # include <nwconio.h> # endif #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "tool_getpass.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef __VMS /* VMS implementation */ char *getpass_r(const char *prompt, char *buffer, size_t buflen) { long sts; short chan; /* MSK, 23-JAN-2004, iosbdef.h wasn't in VAX V7.2 or CC 6.4 */ /* distribution so I created this. May revert back later to */ /* struct _iosb iosb; */ struct _iosb { short int iosb$w_status; /* status */ short int iosb$w_bcnt; /* byte count */ int unused; /* unused */ } iosb; $DESCRIPTOR(ttdesc, "TT"); buffer[0] = '\0'; sts = sys$assign(&ttdesc, &chan, 0, 0); if(sts & 1) { sts = sys$qiow(0, chan, IO$_READPROMPT | IO$M_NOECHO, &iosb, 0, 0, buffer, buflen, 0, 0, prompt, strlen(prompt)); if((sts & 1) && (iosb.iosb$w_status & 1)) buffer[iosb.iosb$w_bcnt] = '\0'; sts = sys$dassgn(chan); } return buffer; /* we always return success */ } #define DONE #endif /* __VMS */ #ifdef __SYMBIAN32__ # define getch() getchar() #endif #if defined(WIN32) || defined(__SYMBIAN32__) char *getpass_r(const char *prompt, char *buffer, size_t buflen) { size_t i; fputs(prompt, stderr); for(i = 0; i < buflen; i++) { buffer[i] = (char)getch(); if(buffer[i] == '\r' || buffer[i] == '\n') { buffer[i] = '\0'; break; } else if(buffer[i] == '\b') /* remove this letter and if this is not the first key, remove the previous one as well */ i = i - (i >= 1 ? 2 : 1); } #ifndef __SYMBIAN32__ /* since echo is disabled, print a newline */ fputs("\n", stderr); #endif /* if user didn't hit ENTER, terminate buffer */ if(i == buflen) buffer[buflen-1] = '\0'; return buffer; /* we always return success */ } #define DONE #endif /* WIN32 || __SYMBIAN32__ */ #ifdef NETWARE /* NetWare implementation */ #ifdef __NOVELL_LIBC__ char *getpass_r(const char *prompt, char *buffer, size_t buflen) { return getpassword(prompt, buffer, buflen); } #else char *getpass_r(const char *prompt, char *buffer, size_t buflen) { size_t i = 0; printf("%s", prompt); do { buffer[i++] = getch(); if(buffer[i-1] == '\b') { /* remove this letter and if this is not the first key, remove the previous one as well */ if(i > 1) { printf("\b \b"); i = i - 2; } else { RingTheBell(); i = i - 1; } } else if(buffer[i-1] != 13) putchar('*'); } while((buffer[i-1] != 13) && (i < buflen)); buffer[i-1] = '\0'; printf("\r\n"); return buffer; } #endif /* __NOVELL_LIBC__ */ #define DONE #endif /* NETWARE */ #ifndef DONE /* not previously provided */ #ifdef HAVE_TERMIOS_H # define struct_term struct termios #elif defined(HAVE_TERMIO_H) # define struct_term struct termio #else # undef struct_term #endif static bool ttyecho(bool enable, int fd) { #ifdef struct_term static struct_term withecho; static struct_term noecho; #endif if(!enable) { /* disable echo by extracting the current 'withecho' mode and remove the ECHO bit and set back the struct */ #ifdef HAVE_TERMIOS_H tcgetattr(fd, &withecho); noecho = withecho; noecho.c_lflag &= ~ECHO; tcsetattr(fd, TCSANOW, &noecho); #elif defined(HAVE_TERMIO_H) ioctl(fd, TCGETA, &withecho); noecho = withecho; noecho.c_lflag &= ~ECHO; ioctl(fd, TCSETA, &noecho); #else /* neither HAVE_TERMIO_H nor HAVE_TERMIOS_H, we can't disable echo! */ (void)fd; return FALSE; /* not disabled */ #endif return TRUE; /* disabled */ } /* re-enable echo, assumes we disabled it before (and set the structs we now use to reset the terminal status) */ #ifdef HAVE_TERMIOS_H tcsetattr(fd, TCSAFLUSH, &withecho); #elif defined(HAVE_TERMIO_H) ioctl(fd, TCSETA, &withecho); #else return FALSE; /* not enabled */ #endif return TRUE; /* enabled */ } char *getpass_r(const char *prompt, /* prompt to display */ char *password, /* buffer to store password in */ size_t buflen) /* size of buffer to store password in */ { ssize_t nread; bool disabled; int fd = open("/dev/tty", O_RDONLY); if(-1 == fd) fd = STDIN_FILENO; /* use stdin if the tty couldn't be used */ disabled = ttyecho(FALSE, fd); /* disable terminal echo */ fputs(prompt, stderr); nread = read(fd, password, buflen); if(nread > 0) password[--nread] = '\0'; /* zero terminate where enter is stored */ else password[0] = '\0'; /* got nothing */ if(disabled) { /* if echo actually was disabled, add a newline */ fputs("\n", stderr); (void)ttyecho(TRUE, fd); /* enable echo */ } if(STDIN_FILENO != fd) close(fd); return password; /* return pointer to buffer */ } #endif /* DONE */ #endif /* HAVE_GETPASS_R */
YifuLiu/AliOS-Things
components/curl/src/tool_getpass.c
C
apache-2.0
6,569
#ifndef HEADER_CURL_TOOL_GETPASS_H #define HEADER_CURL_TOOL_GETPASS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifndef HAVE_GETPASS_R /* If there's a system-provided function named like this, we trust it is also found in one of the standard headers. */ /* * Returning NULL will abort the continued operation! */ char *getpass_r(const char *prompt, char *buffer, size_t buflen); #endif #endif /* HEADER_CURL_TOOL_GETPASS_H */
YifuLiu/AliOS-Things
components/curl/src/tool_getpass.h
C
apache-2.0
1,442
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_STRCASECMP #include <strings.h> #endif #include "tool_panykey.h" #include "tool_help.h" #include "tool_libinfo.h" #include "tool_version.h" #include "memdebug.h" /* keep this as LAST include */ #ifdef MSDOS # define USE_WATT32 #endif /* * The help output is generated with the following command --------------------------------------------------------- cd $srcroot/docs/cmdline-opts ./gen.pl listhelp */ struct helptxt { const char *opt; const char *desc; }; static const struct helptxt helptext[] = { {" --abstract-unix-socket <path>", "Connect via abstract Unix domain socket"}, {" --alt-svc <file name>", "Enable alt-svc with this cache file"}, {" --anyauth", "Pick any authentication method"}, {"-a, --append", "Append to target file when uploading"}, {" --basic", "Use HTTP Basic Authentication"}, {" --cacert <file>", "CA certificate to verify peer against"}, {" --capath <dir>", "CA directory to verify peer against"}, {"-E, --cert <certificate[:password]>", "Client certificate file and password"}, {" --cert-status", "Verify the status of the server certificate"}, {" --cert-type <type>", "Certificate file type (DER/PEM/ENG)"}, {" --ciphers <list of ciphers>", "SSL ciphers to use"}, {" --compressed", "Request compressed response"}, {" --compressed-ssh", "Enable SSH compression"}, {"-K, --config <file>", "Read config from a file"}, {" --connect-timeout <seconds>", "Maximum time allowed for connection"}, {" --connect-to <HOST1:PORT1:HOST2:PORT2>", "Connect to host"}, {"-C, --continue-at <offset>", "Resumed transfer offset"}, {"-b, --cookie <data|filename>", "Send cookies from string/file"}, {"-c, --cookie-jar <filename>", "Write cookies to <filename> after operation"}, {" --create-dirs", "Create necessary local directory hierarchy"}, {" --crlf", "Convert LF to CRLF in upload"}, {" --crlfile <file>", "Get a CRL list in PEM format from the given file"}, {"-d, --data <data>", "HTTP POST data"}, {" --data-ascii <data>", "HTTP POST ASCII data"}, {" --data-binary <data>", "HTTP POST binary data"}, {" --data-raw <data>", "HTTP POST data, '@' allowed"}, {" --data-urlencode <data>", "HTTP POST data url encoded"}, {" --delegation <LEVEL>", "GSS-API delegation permission"}, {" --digest", "Use HTTP Digest Authentication"}, {"-q, --disable", "Disable .curlrc"}, {" --disable-eprt", "Inhibit using EPRT or LPRT"}, {" --disable-epsv", "Inhibit using EPSV"}, {" --disallow-username-in-url", "Disallow username in url"}, {" --dns-interface <interface>", "Interface to use for DNS requests"}, {" --dns-ipv4-addr <address>", "IPv4 address to use for DNS requests"}, {" --dns-ipv6-addr <address>", "IPv6 address to use for DNS requests"}, {" --dns-servers <addresses>", "DNS server addrs to use"}, {" --doh-url <URL>", "Resolve host names over DOH"}, {"-D, --dump-header <filename>", "Write the received headers to <filename>"}, {" --egd-file <file>", "EGD socket path for random data"}, {" --engine <name>", "Crypto engine to use"}, {" --expect100-timeout <seconds>", "How long to wait for 100-continue"}, {"-f, --fail", "Fail silently (no output at all) on HTTP errors"}, {" --fail-early", "Fail on first transfer error, do not continue"}, {" --false-start", "Enable TLS False Start"}, {"-F, --form <name=content>", "Specify multipart MIME data"}, {" --form-string <name=string>", "Specify multipart MIME data"}, {" --ftp-account <data>", "Account data string"}, {" --ftp-alternative-to-user <command>", "String to replace USER [name]"}, {" --ftp-create-dirs", "Create the remote dirs if not present"}, {" --ftp-method <method>", "Control CWD usage"}, {" --ftp-pasv", "Use PASV/EPSV instead of PORT"}, {"-P, --ftp-port <address>", "Use PORT instead of PASV"}, {" --ftp-pret", "Send PRET before PASV"}, {" --ftp-skip-pasv-ip", "Skip the IP address for PASV"}, {" --ftp-ssl-ccc", "Send CCC after authenticating"}, {" --ftp-ssl-ccc-mode <active/passive>", "Set CCC mode"}, {" --ftp-ssl-control", "Require SSL/TLS for FTP login, clear for transfer"}, {"-G, --get", "Put the post data in the URL and use GET"}, {"-g, --globoff", "Disable URL sequences and ranges using {} and []"}, {" --happy-eyeballs-timeout-ms <milliseconds>", "How long to wait in milliseconds for IPv6 before trying IPv4"}, {" --haproxy-protocol", "Send HAProxy PROXY protocol v1 header"}, {"-I, --head", "Show document info only"}, {"-H, --header <header/@file>", "Pass custom header(s) to server"}, {"-h, --help", "This help text"}, {" --hostpubmd5 <md5>", "Acceptable MD5 hash of the host public key"}, {" --http0.9", "Allow HTTP 0.9 responses"}, {"-0, --http1.0", "Use HTTP 1.0"}, {" --http1.1", "Use HTTP 1.1"}, {" --http2", "Use HTTP 2"}, {" --http2-prior-knowledge", "Use HTTP 2 without HTTP/1.1 Upgrade"}, {" --ignore-content-length", "Ignore the size of the remote resource"}, {"-i, --include", "Include protocol response headers in the output"}, {"-k, --insecure", "Allow insecure server connections when using SSL"}, {" --interface <name>", "Use network INTERFACE (or address)"}, {"-4, --ipv4", "Resolve names to IPv4 addresses"}, {"-6, --ipv6", "Resolve names to IPv6 addresses"}, {"-j, --junk-session-cookies", "Ignore session cookies read from file"}, {" --keepalive-time <seconds>", "Interval time for keepalive probes"}, {" --key <key>", "Private key file name"}, {" --key-type <type>", "Private key file type (DER/PEM/ENG)"}, {" --krb <level>", "Enable Kerberos with security <level>"}, {" --libcurl <file>", "Dump libcurl equivalent code of this command line"}, {" --limit-rate <speed>", "Limit transfer speed to RATE"}, {"-l, --list-only", "List only mode"}, {" --local-port <num/range>", "Force use of RANGE for local port numbers"}, {"-L, --location", "Follow redirects"}, {" --location-trusted", "Like --location, and send auth to other hosts"}, {" --login-options <options>", "Server login options"}, {" --mail-auth <address>", "Originator address of the original email"}, {" --mail-from <address>", "Mail from this address"}, {" --mail-rcpt <address>", "Mail to this address"}, {"-M, --manual", "Display the full manual"}, {" --max-filesize <bytes>", "Maximum file size to download"}, {" --max-redirs <num>", "Maximum number of redirects allowed"}, {"-m, --max-time <seconds>", "Maximum time allowed for the transfer"}, {" --metalink", "Process given URLs as metalink XML file"}, {" --negotiate", "Use HTTP Negotiate (SPNEGO) authentication"}, {"-n, --netrc", "Must read .netrc for user name and password"}, {" --netrc-file <filename>", "Specify FILE for netrc"}, {" --netrc-optional", "Use either .netrc or URL"}, {"-:, --next", "Make next URL use its separate set of options"}, {" --no-alpn", "Disable the ALPN TLS extension"}, {"-N, --no-buffer", "Disable buffering of the output stream"}, {" --no-keepalive", "Disable TCP keepalive on the connection"}, {" --no-npn", "Disable the NPN TLS extension"}, {" --no-sessionid", "Disable SSL session-ID reusing"}, {" --noproxy <no-proxy-list>", "List of hosts which do not use proxy"}, {" --ntlm", "Use HTTP NTLM authentication"}, {" --ntlm-wb", "Use HTTP NTLM authentication with winbind"}, {" --oauth2-bearer <token>", "OAuth 2 Bearer Token"}, {"-o, --output <file>", "Write to file instead of stdout"}, {" --pass <phrase>", "Pass phrase for the private key"}, {" --path-as-is", "Do not squash .. sequences in URL path"}, {" --pinnedpubkey <hashes>", "FILE/HASHES Public key to verify peer against"}, {" --post301", "Do not switch to GET after following a 301"}, {" --post302", "Do not switch to GET after following a 302"}, {" --post303", "Do not switch to GET after following a 303"}, {" --preproxy [protocol://]host[:port]", "Use this proxy first"}, {"-#, --progress-bar", "Display transfer progress as a bar"}, {" --proto <protocols>", "Enable/disable PROTOCOLS"}, {" --proto-default <protocol>", "Use PROTOCOL for any URL missing a scheme"}, {" --proto-redir <protocols>", "Enable/disable PROTOCOLS on redirect"}, {"-x, --proxy [protocol://]host[:port]", "Use this proxy"}, {" --proxy-anyauth", "Pick any proxy authentication method"}, {" --proxy-basic", "Use Basic authentication on the proxy"}, {" --proxy-cacert <file>", "CA certificate to verify peer against for proxy"}, {" --proxy-capath <dir>", "CA directory to verify peer against for proxy"}, {" --proxy-cert <cert[:passwd]>", "Set client certificate for proxy"}, {" --proxy-cert-type <type>", "Client certificate type for HTTPS proxy"}, {" --proxy-ciphers <list>", "SSL ciphers to use for proxy"}, {" --proxy-crlfile <file>", "Set a CRL list for proxy"}, {" --proxy-digest", "Use Digest authentication on the proxy"}, {" --proxy-header <header/@file>", "Pass custom header(s) to proxy"}, {" --proxy-insecure", "Do HTTPS proxy connections without verifying the proxy"}, {" --proxy-key <key>", "Private key for HTTPS proxy"}, {" --proxy-key-type <type>", "Private key file type for proxy"}, {" --proxy-negotiate", "Use HTTP Negotiate (SPNEGO) authentication on the proxy"}, {" --proxy-ntlm", "Use NTLM authentication on the proxy"}, {" --proxy-pass <phrase>", "Pass phrase for the private key for HTTPS proxy"}, {" --proxy-pinnedpubkey <hashes>", "FILE/HASHES public key to verify proxy with"}, {" --proxy-service-name <name>", "SPNEGO proxy service name"}, {" --proxy-ssl-allow-beast", "Allow security flaw for interop for HTTPS proxy"}, {" --proxy-tls13-ciphers <ciphersuite list>", "TLS 1.3 proxy cipher suites"}, {" --proxy-tlsauthtype <type>", "TLS authentication type for HTTPS proxy"}, {" --proxy-tlspassword <string>", "TLS password for HTTPS proxy"}, {" --proxy-tlsuser <name>", "TLS username for HTTPS proxy"}, {" --proxy-tlsv1", "Use TLSv1 for HTTPS proxy"}, {"-U, --proxy-user <user:password>", "Proxy user and password"}, {" --proxy1.0 <host[:port]>", "Use HTTP/1.0 proxy on given port"}, {"-p, --proxytunnel", "Operate through an HTTP proxy tunnel (using CONNECT)"}, {" --pubkey <key>", "SSH Public key file name"}, {"-Q, --quote", "Send command(s) to server before transfer"}, {" --random-file <file>", "File for reading random data from"}, {"-r, --range <range>", "Retrieve only the bytes within RANGE"}, {" --raw", "Do HTTP \"raw\"; no transfer decoding"}, {"-e, --referer <URL>", "Referrer URL"}, {"-J, --remote-header-name", "Use the header-provided filename"}, {"-O, --remote-name", "Write output to a file named as the remote file"}, {" --remote-name-all", "Use the remote file name for all URLs"}, {"-R, --remote-time", "Set the remote file's time on the local output"}, {"-X, --request <command>", "Specify request command to use"}, {" --request-target", "Specify the target for this request"}, {" --resolve <host:port:address[,address]...>", "Resolve the host+port to this address"}, {" --retry <num>", "Retry request if transient problems occur"}, {" --retry-connrefused", "Retry on connection refused (use with --retry)"}, {" --retry-delay <seconds>", "Wait time between retries"}, {" --retry-max-time <seconds>", "Retry only within this period"}, {" --sasl-ir", "Enable initial response in SASL authentication"}, {" --service-name <name>", "SPNEGO service name"}, {"-S, --show-error", "Show error even when -s is used"}, {"-s, --silent", "Silent mode"}, {" --socks4 <host[:port]>", "SOCKS4 proxy on given host + port"}, {" --socks4a <host[:port]>", "SOCKS4a proxy on given host + port"}, {" --socks5 <host[:port]>", "SOCKS5 proxy on given host + port"}, {" --socks5-basic", "Enable username/password auth for SOCKS5 proxies"}, {" --socks5-gssapi", "Enable GSS-API auth for SOCKS5 proxies"}, {" --socks5-gssapi-nec", "Compatibility with NEC SOCKS5 server"}, {" --socks5-gssapi-service <name>", "SOCKS5 proxy service name for GSS-API"}, {" --socks5-hostname <host[:port]>", "SOCKS5 proxy, pass host name to proxy"}, {"-Y, --speed-limit <speed>", "Stop transfers slower than this"}, {"-y, --speed-time <seconds>", "Trigger 'speed-limit' abort after this time"}, {" --ssl", "Try SSL/TLS"}, {" --ssl-allow-beast", "Allow security flaw to improve interop"}, {" --ssl-no-revoke", "Disable cert revocation checks (Schannel)"}, {" --ssl-reqd", "Require SSL/TLS"}, {"-2, --sslv2", "Use SSLv2"}, {"-3, --sslv3", "Use SSLv3"}, {" --stderr", "Where to redirect stderr"}, {" --styled-output", "Enable styled output for HTTP headers"}, {" --suppress-connect-headers", "Suppress proxy CONNECT response headers"}, {" --tcp-fastopen", "Use TCP Fast Open"}, {" --tcp-nodelay", "Use the TCP_NODELAY option"}, {"-t, --telnet-option <opt=val>", "Set telnet option"}, {" --tftp-blksize <value>", "Set TFTP BLKSIZE option"}, {" --tftp-no-options", "Do not send any TFTP options"}, {"-z, --time-cond <time>", "Transfer based on a time condition"}, {" --tls-max <VERSION>", "Set maximum allowed TLS version"}, {" --tls13-ciphers <list of TLS 1.3 ciphersuites>", "TLS 1.3 cipher suites to use"}, {" --tlsauthtype <type>", "TLS authentication type"}, {" --tlspassword", "TLS password"}, {" --tlsuser <name>", "TLS user name"}, {"-1, --tlsv1", "Use TLSv1.0 or greater"}, {" --tlsv1.0", "Use TLSv1.0 or greater"}, {" --tlsv1.1", "Use TLSv1.1 or greater"}, {" --tlsv1.2", "Use TLSv1.2 or greater"}, {" --tlsv1.3", "Use TLSv1.3 or greater"}, {" --tr-encoding", "Request compressed transfer encoding"}, {" --trace <file>", "Write a debug trace to FILE"}, {" --trace-ascii <file>", "Like --trace, but without hex output"}, {" --trace-time", "Add time stamps to trace/verbose output"}, {" --unix-socket <path>", "Connect through this Unix domain socket"}, {"-T, --upload-file <file>", "Transfer local FILE to destination"}, {" --url <url>", "URL to work with"}, {"-B, --use-ascii", "Use ASCII/text transfer"}, {"-u, --user <user:password>", "Server user and password"}, {"-A, --user-agent <name>", "Send User-Agent <name> to server"}, {"-v, --verbose", "Make the operation more talkative"}, {"-V, --version", "Show version number and quit"}, {"-w, --write-out <format>", "Use output FORMAT after completion"}, {" --xattr", "Store metadata in extended file attributes"}, { NULL, NULL } }; #ifdef NETWARE # define PRINT_LINES_PAUSE 23 #endif #ifdef __SYMBIAN32__ # define PRINT_LINES_PAUSE 16 #endif struct feat { const char *name; int bitmask; }; static const struct feat feats[] = { {"AsynchDNS", CURL_VERSION_ASYNCHDNS}, {"Debug", CURL_VERSION_DEBUG}, {"TrackMemory", CURL_VERSION_CURLDEBUG}, {"IDN", CURL_VERSION_IDN}, {"IPv6", CURL_VERSION_IPV6}, {"Largefile", CURL_VERSION_LARGEFILE}, {"SSPI", CURL_VERSION_SSPI}, {"GSS-API", CURL_VERSION_GSSAPI}, {"Kerberos", CURL_VERSION_KERBEROS5}, {"SPNEGO", CURL_VERSION_SPNEGO}, {"NTLM", CURL_VERSION_NTLM}, {"NTLM_WB", CURL_VERSION_NTLM_WB}, {"SSL", CURL_VERSION_SSL}, {"libz", CURL_VERSION_LIBZ}, {"brotli", CURL_VERSION_BROTLI}, {"CharConv", CURL_VERSION_CONV}, {"TLS-SRP", CURL_VERSION_TLSAUTH_SRP}, {"HTTP2", CURL_VERSION_HTTP2}, {"UnixSockets", CURL_VERSION_UNIX_SOCKETS}, {"HTTPS-proxy", CURL_VERSION_HTTPS_PROXY}, {"MultiSSL", CURL_VERSION_MULTI_SSL}, {"PSL", CURL_VERSION_PSL}, {"alt-svc", CURL_VERSION_ALTSVC}, }; void tool_help(void) { int i; puts("Usage: curl [options...] <url>"); for(i = 0; helptext[i].opt; i++) { printf(" %-19s %s\n", helptext[i].opt, helptext[i].desc); #ifdef PRINT_LINES_PAUSE if(i && ((i % PRINT_LINES_PAUSE) == 0)) tool_pressanykey(); #endif } } static int featcomp(const void *p1, const void *p2) { /* The arguments to this function are "pointers to pointers to char", but the comparison arguments are "pointers to char", hence the following cast plus dereference */ #ifdef HAVE_STRCASECMP return strcasecmp(* (char * const *) p1, * (char * const *) p2); #elif defined(HAVE_STRCMPI) return strcmpi(* (char * const *) p1, * (char * const *) p2); #else return strcmp(* (char * const *) p1, * (char * const *) p2); #endif } void tool_version_info(void) { const char *const *proto; printf(CURL_ID "%s\n", curl_version()); #ifdef CURL_PATCHSTAMP printf("Release-Date: %s, security patched: %s\n", LIBCURL_TIMESTAMP, CURL_PATCHSTAMP); #else printf("Release-Date: %s\n", LIBCURL_TIMESTAMP); #endif if(curlinfo->protocols) { printf("Protocols: "); for(proto = curlinfo->protocols; *proto; ++proto) { printf("%s ", *proto); } puts(""); /* newline */ } if(curlinfo->features) { char *featp[ sizeof(feats) / sizeof(feats[0]) + 1]; size_t numfeat = 0; unsigned int i; printf("Features:"); for(i = 0; i < sizeof(feats)/sizeof(feats[0]); i++) { if(curlinfo->features & feats[i].bitmask) featp[numfeat++] = (char *)feats[i].name; } #ifdef USE_METALINK featp[numfeat++] = (char *)"Metalink"; #endif qsort(&featp[0], numfeat, sizeof(char *), featcomp); for(i = 0; i< numfeat; i++) printf(" %s", featp[i]); puts(""); /* newline */ } if(strcmp(CURL_VERSION, curlinfo->version)) { printf("WARNING: curl and libcurl versions do not match. " "Functionality may be affected.\n"); } } void tool_list_engines(CURL *curl) { struct curl_slist *engines = NULL; /* Get the list of engines */ curl_easy_getinfo(curl, CURLINFO_SSL_ENGINES, &engines); puts("Build-time engines:"); if(engines) { for(; engines; engines = engines->next) printf(" %s\n", engines->data); } else { puts(" <none>"); } /* Cleanup the list of engines */ curl_slist_free_all(engines); }
YifuLiu/AliOS-Things
components/curl/src/tool_help.c
C
apache-2.0
20,131
#ifndef HEADER_CURL_TOOL_HELP_H #define HEADER_CURL_TOOL_HELP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" void tool_help(void); void tool_list_engines(CURL *curl); void tool_version_info(void); #endif /* HEADER_CURL_TOOL_HELP_H */
YifuLiu/AliOS-Things
components/curl/src/tool_help.h
C
apache-2.0
1,241
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "strcase.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_cfgable.h" #include "tool_msgs.h" #include "tool_getparam.h" #include "tool_helpers.h" #include "memdebug.h" /* keep this as LAST include */ /* ** Helper functions that are used from more than one source file. */ const char *param2text(int res) { ParameterError error = (ParameterError)res; switch(error) { case PARAM_GOT_EXTRA_PARAMETER: return "had unsupported trailing garbage"; case PARAM_OPTION_UNKNOWN: return "is unknown"; case PARAM_OPTION_AMBIGUOUS: return "is ambiguous"; case PARAM_REQUIRES_PARAMETER: return "requires parameter"; case PARAM_BAD_USE: return "is badly used here"; case PARAM_BAD_NUMERIC: return "expected a proper numerical parameter"; case PARAM_NEGATIVE_NUMERIC: return "expected a positive numerical parameter"; case PARAM_LIBCURL_DOESNT_SUPPORT: return "the installed libcurl version doesn't support this"; case PARAM_LIBCURL_UNSUPPORTED_PROTOCOL: return "a specified protocol is unsupported by libcurl"; case PARAM_NO_MEM: return "out of memory"; case PARAM_NO_PREFIX: return "the given option can't be reversed with a --no- prefix"; case PARAM_NUMBER_TOO_LARGE: return "too large number"; case PARAM_NO_NOT_BOOLEAN: return "used '--no-' for option that isn't a boolean"; default: return "unknown error"; } } int SetHTTPrequest(struct OperationConfig *config, HttpReq req, HttpReq *store) { /* this mirrors the HttpReq enum in tool_sdecls.h */ const char *reqname[]= { "", /* unspec */ "GET (-G, --get)", "HEAD (-I, --head)", "multipart formpost (-F, --form)", "POST (-d, --data)" }; if((*store == HTTPREQ_UNSPEC) || (*store == req)) { *store = req; return 0; } warnf(config->global, "You can only select one HTTP request method! " "You asked for both %s and %s.\n", reqname[req], reqname[*store]); return 1; } void customrequest_helper(struct OperationConfig *config, HttpReq req, char *method) { /* this mirrors the HttpReq enum in tool_sdecls.h */ const char *dflt[]= { "GET", "GET", "HEAD", "POST", "POST" }; if(!method) ; else if(curl_strequal(method, dflt[req])) { notef(config->global, "Unnecessary use of -X or --request, %s is already " "inferred.\n", dflt[req]); } else if(curl_strequal(method, "head")) { warnf(config->global, "Setting custom HTTP method to HEAD with -X/--request may not work " "the way you want. Consider using -I/--head instead.\n"); } }
YifuLiu/AliOS-Things
components/curl/src/tool_helpers.c
C
apache-2.0
3,739
#ifndef HEADER_CURL_TOOL_HELPERS_H #define HEADER_CURL_TOOL_HELPERS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" const char *param2text(int res); int SetHTTPrequest(struct OperationConfig *config, HttpReq req, HttpReq *store); void customrequest_helper(struct OperationConfig *config, HttpReq req, char *method); #endif /* HEADER_CURL_TOOL_HELPERS_H */
YifuLiu/AliOS-Things
components/curl/src/tool_helpers.h
C
apache-2.0
1,409
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #ifdef HAVE_PWD_H # include <pwd.h> #endif #include "tool_homedir.h" #include "memdebug.h" /* keep this as LAST include */ static char *GetEnv(const char *variable, char do_expand) { char *env = NULL; #ifdef WIN32 char buf1[1024], buf2[1024]; DWORD rc; /* Don't use getenv(); it doesn't find variable added after program was * started. Don't accept truncated results (i.e. rc >= sizeof(buf1)). */ rc = GetEnvironmentVariableA(variable, buf1, sizeof(buf1)); if(rc > 0 && rc < sizeof(buf1)) { env = buf1; variable = buf1; } if(do_expand && strchr(variable, '%')) { /* buf2 == variable if not expanded */ rc = ExpandEnvironmentStringsA(variable, buf2, sizeof(buf2)); if(rc > 0 && rc < sizeof(buf2) && !strchr(buf2, '%')) /* no vars still unexpanded */ env = buf2; } #else (void)do_expand; /* no length control */ env = getenv(variable); #endif return (env && env[0]) ? strdup(env) : NULL; } /* return the home directory of the current user as an allocated string */ char *homedir(void) { char *home; home = GetEnv("CURL_HOME", FALSE); if(home) return home; home = GetEnv("HOME", FALSE); if(home) return home; #if defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) { struct passwd *pw = getpwuid(geteuid()); if(pw) { home = pw->pw_dir; if(home && home[0]) home = strdup(home); else home = NULL; } } #endif /* PWD-stuff */ #ifdef WIN32 home = GetEnv("APPDATA", TRUE); if(!home) home = GetEnv("%USERPROFILE%\\Application Data", TRUE); /* Normally only on Win-2K/XP */ #endif /* WIN32 */ return home; }
YifuLiu/AliOS-Things
components/curl/src/tool_homedir.c
C
apache-2.0
2,753
#ifndef HEADER_CURL_TOOL_HOMEDIR_H #define HEADER_CURL_TOOL_HOMEDIR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" char *homedir(void); #endif /* HEADER_CURL_TOOL_HOMEDIR_H */
YifuLiu/AliOS-Things
components/curl/src/tool_homedir.h
C
apache-2.0
1,183
#ifndef HEADER_CURL_TOOL_HUGEHELP_H #define HEADER_CURL_TOOL_HUGEHELP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" void hugehelp(void); #endif /* HEADER_CURL_TOOL_HUGEHELP_H */
YifuLiu/AliOS-Things
components/curl/src/tool_hugehelp.h
C
apache-2.0
1,186
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "tool_setup.h" #include "strcase.h" #define ENABLE_CURLX_PRINTF /* use our own printf() functions */ #include "curlx.h" #include "tool_libinfo.h" #include "memdebug.h" /* keep this as LAST include */ /* global variable definitions, for libcurl run-time info */ curl_version_info_data *curlinfo = NULL; long built_in_protos = 0; /* * libcurl_info_init: retrieves run-time information about libcurl, * setting a global pointer 'curlinfo' to libcurl's run-time info * struct, and a global bit pattern 'built_in_protos' composed of * CURLPROTO_* bits indicating which protocols are actually built * into library being used. */ CURLcode get_libcurl_info(void) { static struct proto_name_pattern { const char *proto_name; long proto_pattern; } const possibly_built_in[] = { { "dict", CURLPROTO_DICT }, { "file", CURLPROTO_FILE }, { "ftp", CURLPROTO_FTP }, { "ftps", CURLPROTO_FTPS }, { "gopher", CURLPROTO_GOPHER }, { "http", CURLPROTO_HTTP }, { "https", CURLPROTO_HTTPS }, { "imap", CURLPROTO_IMAP }, { "imaps", CURLPROTO_IMAPS }, { "ldap", CURLPROTO_LDAP }, { "ldaps", CURLPROTO_LDAPS }, { "pop3", CURLPROTO_POP3 }, { "pop3s", CURLPROTO_POP3S }, { "rtmp", CURLPROTO_RTMP }, { "rtsp", CURLPROTO_RTSP }, { "scp", CURLPROTO_SCP }, { "sftp", CURLPROTO_SFTP }, { "smb", CURLPROTO_SMB }, { "smbs", CURLPROTO_SMBS }, { "smtp", CURLPROTO_SMTP }, { "smtps", CURLPROTO_SMTPS }, { "telnet", CURLPROTO_TELNET }, { "tftp", CURLPROTO_TFTP }, { NULL, 0 } }; const char *const *proto; /* Pointer to libcurl's run-time version information */ curlinfo = curl_version_info(CURLVERSION_NOW); if(!curlinfo) return CURLE_FAILED_INIT; /* Build CURLPROTO_* bit pattern with libcurl's built-in protocols */ built_in_protos = 0; if(curlinfo->protocols) { for(proto = curlinfo->protocols; *proto; proto++) { struct proto_name_pattern const *p; for(p = possibly_built_in; p->proto_name; p++) { if(curl_strequal(*proto, p->proto_name)) { built_in_protos |= p->proto_pattern; break; } } } } return CURLE_OK; }
YifuLiu/AliOS-Things
components/curl/src/tool_libinfo.c
C
apache-2.0
3,329