int main() { SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); BIO *bio = BIO_new_connect("gateway.sandbox.push.apple.com:2195"); if (bio == NULL) { ERR_print_errors_fp(stdout); exit(1); } if (BIO_do_connect(bio) <= 0) { ERR_print_errors_fp(stdout); exit(1); } char buf[MAXBUF]; char *json = "{\"aps\":{\"badge\":123}}"; sendPayload(bio, token, json, strlen(json)); int ret = BIO_read(bio, buf, MAXBUF); if (ret <= 0) { printf("BIO_read return 0\n"); } BIO_free_all(bio); return 0; }
bool getHTTPData(const char *host, const uint16_t port, const char *fileName, std::stringstream &data) { BIO *socket; std::stringstream authority, request; char buffer[2048]; int bytesRead; authority << host << ':' << port; request << "GET " << fileName << " HTTP/1.1\r\n" << "Host: " << host << "\r\n" << "Connection: close\r\n\r\n"; socket = BIO_new_connect((char*)authority.str().c_str()); if (BIO_do_connect(socket) < 1) { BIO_free(socket); return false; } if (BIO_write(socket, request.str().c_str(), request.str().length()) < 1) { BIO_free(socket); return false; } while ((bytesRead = BIO_read(socket, buffer, sizeof(buffer)))) { buffer[bytesRead] = 0; data << buffer; } BIO_free(socket); return true; }
int open_connection( SSL **ssl, SSL_CTX **ctx, char *server_addr, char *server_port) { BIO *conn; long err; char addr_buf[100] = ""; sprintf(addr_buf, "%s:%s", server_addr, server_port); printf("[%s]\n",addr_buf); *ctx = setup_client_ctx( ); conn = BIO_new_connect(addr_buf); if (!conn) handle_error("Error creating connection BIO"); if (BIO_do_connect(conn) <= 0) handle_error("Error connecting to remote machine"); *ssl = SSL_new(*ctx); SSL_set_bio(*ssl, conn, conn); if (SSL_connect(*ssl) <= 0) handle_error("Error connecting SSL object"); if ((err = post_connection_check(*ssl, SERVER)) != X509_V_OK) { fprintf(stderr, "-Error: peer certificate: %s\n", X509_verify_cert_error_string(err)); handle_error("Error checking SSL object after connection"); } fprintf(stderr, "SSL Connection opened\n"); return 0; }
static enum pbpal_resolv_n_connect_result resolv_and_connect_wout_SSL(pubnub_t *pb) { PUBNUB_LOG_TRACE("resolv_and_connect_wout_SSL\n"); if (NULL == pb->pal.socket) { char const*origin = PUBNUB_ORIGIN_SETTABLE ? pb->origin : PUBNUB_ORIGIN; PUBNUB_LOG_TRACE("pb=%p: Don't have BIO\n", pb); pb->pal.socket = BIO_new_connect((char*)origin); } if (NULL == pb->pal.socket) { return pbpal_resolv_resource_failure; } BIO_set_conn_port(pb->pal.socket, "http"); BIO_set_nbio(pb->pal.socket, !pb->options.use_blocking_io); WATCH_ENUM(pb->options.use_blocking_io); if (BIO_do_connect(pb->pal.socket) <= 0) { if (BIO_should_retry(pb->pal.socket)) { return pbpal_connect_wouldblock; } ERR_print_errors_cb(print_to_pubnub_log, NULL); PUBNUB_LOG_ERROR("BIO_do_connect failed\n"); return pbpal_connect_failed; } PUBNUB_LOG_TRACE("pb=%p: BIO connected\n", pb); { int fd = BIO_get_fd(pb->pal.socket, NULL); socket_set_rcv_timeout(fd, pb->transaction_timeout_ms); } return pbpal_connect_success; }
int send(char *socket, char *filename) { BIO *send = BIO_new_connect(socket); char *fname = filename; BIO *file = BIO_new_file(fname, "r"); struct stat st; stat(fname, &st); // find out the length of the file to send unsigned int size = st.st_size; char fileLen[BUFSIZ]; sprintf(fileLen, "%d\n", size); //send an init piece of information about the file length printf("Sending length of file: %s\n", fileLen); BIO_puts(send, fileLen); //now we transmit 'file' of 'size' to 'send' transmit(file, send, size); BIO_flush(send); BIO_free(send); BIO_free(file); return 1; }
static boolean connect_to_emergency_phr_list_loading_service(SSL **ssl_conn_ret) { BIO *bio_conn = NULL; SSL_CTX *ctx = NULL; int err; char *hosts[1]; char phr_server_addr[IP_ADDRESS_LENGTH + PORT_NUMBER_LENGTH + 2]; // Connect to PHR Server sprintf(phr_server_addr, "%s:%s", GLOBAL_phr_server_ip_addr, PHRSV_EMERGENCY_PHR_LIST_LOADING_PORT); bio_conn = BIO_new_connect(phr_server_addr); if(!bio_conn) int_error("Creating BIO connection failed"); if(BIO_do_connect(bio_conn) <= 0) { fprintf(stderr, "Connecting to PHR server failed\n"); goto ERROR_AT_BIO_LAYER; } ctx = setup_client_ctx(EMS_CERTFILE_PATH, EMS_CERTFILE_PASSWD, PHR_ROOT_CA_ONLY_CERT_CERTFILE_PATH); if(!(*ssl_conn_ret = SSL_new(ctx))) int_error("Creating SSL context failed"); SSL_set_bio(*ssl_conn_ret, bio_conn, bio_conn); if(SSL_connect(*ssl_conn_ret) <= 0) { fprintf(stderr, "Connecting SSL object failed\n"); goto ERROR_AT_SSL_LAYER; } hosts[0] = PHR_SERVER_CN; if((err = post_connection_check(*ssl_conn_ret, hosts, 1, false, NULL)) != X509_V_OK) { fprintf(stderr, "Checking peer certificate failed\n\"%s\"\n", X509_verify_cert_error_string(err)); goto ERROR_AT_SSL_LAYER; } // Return value of *ssl_conn_ret SSL_CTX_free(ctx); ERR_remove_state(0); return true; ERROR_AT_BIO_LAYER: BIO_free(bio_conn); bio_conn = NULL; ERR_remove_state(0); return false; ERROR_AT_SSL_LAYER: SSL_cleanup(*ssl_conn_ret); *ssl_conn_ret = NULL; SSL_CTX_free(ctx); ERR_remove_state(0); return false; }
static boolean connect_to_phr_transaction_log_synchronization_service(SSL **ssl_conn_ret) { BIO *bio_conn = NULL; SSL_CTX *ctx = NULL; int err; char *hosts[1]; char audit_server_addr[IP_ADDRESS_LENGTH + PORT_NUMBER_LENGTH + 2]; // Connect to Audit Server sprintf(audit_server_addr, "%s:%s", GLOBAL_audit_server_ip_addr, AS_PHR_TRANSACTION_LOG_SYNCHRONIZATION_PORT); bio_conn = BIO_new_connect(audit_server_addr); if(!bio_conn) int_error("Creating BIO connection failed"); if(BIO_do_connect(bio_conn) <= 0) { fprintf(stderr, "Connecting to audit server failed\n"); goto ERROR_AT_BIO_LAYER; } ctx = setup_client_ctx(UA_CERTFILE_PATH, UA_CERTFILE_PASSWD, PHR_ROOT_CA_ONLY_CERT_CERTFILE_PATH); if(!(*ssl_conn_ret = SSL_new(ctx))) int_error("Creating SSL context failed"); SSL_set_bio(*ssl_conn_ret, bio_conn, bio_conn); if(SSL_connect(*ssl_conn_ret) <= 0) { fprintf(stderr, "Connecting SSL object failed\n"); goto ERROR_AT_SSL_LAYER; } hosts[0] = AUDIT_SERVER_CN; if((err = post_connection_check(*ssl_conn_ret, hosts, 1, true, GLOBAL_authority_name)) != X509_V_OK) { fprintf(stderr, "Checking peer certificate failed\n\"%s\"\n", X509_verify_cert_error_string(err)); goto ERROR_AT_SSL_LAYER; } // Return value of *ssl_conn_ret SSL_CTX_free(ctx); ERR_remove_state(0); return true; ERROR_AT_BIO_LAYER: BIO_free(bio_conn); bio_conn = NULL; ERR_remove_state(0); return false; ERROR_AT_SSL_LAYER: SSL_cleanup(*ssl_conn_ret); *ssl_conn_ret = NULL; SSL_CTX_free(ctx); ERR_remove_state(0); return false; }
bool SSLClient::sslConnect(int fd, std::string &hostname, short port) { GNASH_REPORT_FUNCTION; int ret; if (!_ctx) { if (!sslSetupCTX()) { return false; } } _ssl.reset(SSL_new(_ctx.get())); // // Make a tcp/ip connect to the server // if (createClient(hostname, getPort()) == false) { // log_error("Can't connect to server %s", hostname); // return false; // } // Handshake the server ERR_clear_error(); #if 0 _bio.reset(BIO_new_socket(fd, BIO_NOCLOSE)); #else // BIO_set_conn_hostname(_bio.get(), _hostname.c_str()); _bio.reset(BIO_new_connect(const_cast<char *>(_hostname.c_str()))); BIO_set_conn_int_port(_bio.get(), &port); log_debug("PORT is: %d", BIO_get_conn_port(_bio.get())); if (BIO_do_connect(_bio.get()) <= 0) { log_error("Error connecting to remote machine: %s", ERR_reason_error_string(ERR_get_error())); } #endif SSL_set_bio(_ssl.get(), _bio.get(), _bio.get()); SSL_set_connect_state(_ssl.get()); if ((ret = SSL_connect(_ssl.get())) < 0) { log_error("Can't connect to SSL server %s", hostname); log_error("Error was: \"%s\"!", ERR_reason_error_string(ERR_get_error())); return false; } else { log_debug("Connected to SSL server %s", hostname); } ERR_clear_error(); #if 0 if (_need_server_auth) { checkCert(hostname); } #endif return true; }
int main (int argc, const char * argv[]) { // char token[] = "2b2474e5 ac7670f3 08fabf3a 9c1d1295 ed50e9aa f11b941a d6e3d213 4f535408"; char *token ="aa994d28c89422d11c58ba4ab6d18309427699719e6f208395d0d5a40eb90d21"; char payload[] = "{\"aps\":{\"alert\":\"Hello world!!!\",\"badge\":1}}"; char payload2[] = "{\"aps\":{\"alert\":\"Hello kitty!!!\",\"badge\":12}}"; char host[] = "gateway.sandbox.push.apple.com:2195"; BIO *conn; // init SSL_library_init(); ctx = setup_client_ctx(); conn = BIO_new_connect(host); if (!conn) { error("Error creating connection BIO\n"); } if (BIO_do_connect(conn) <= 0) { error("Error connection to remote machine"); } if (!(ssl = SSL_new(ctx))) { error("Error creating an SSL contexxt"); } SSL_set_bio(ssl, conn, conn); if (SSL_connect(ssl) <= 0) { error("Error connecting SSL object"); } printf("SSL Connection opened\n"); // push message int ret = push(token, payload); printf("push ret[%d]\n", ret); // push [Hello kitty] after 5s sleep(5); ret = push(token, payload2); printf("push2 ret[%d]\n", ret); char buf[256]; SSL_read(ssl, buf, 256); printf("Close SSL Connection\n"); SSL_shutdown(ssl); SSL_free(ssl); SSL_CTX_free(ctx); return 0; }
int STS_ClientConnect(STS * sts, char * addr) { sts->conn = BIO_new_connect(addr); if(BIO_do_connect(sts->conn) <= 0) { fprintf(stderr, "Не удалось подключиться к серверу!\n"); return 1; } return 0; }
static int openssl_bio_new_connect(lua_State *L) { const char *host = luaL_checkstring(L, 1); BIO* bio = BIO_new_connect((char*)host); int doconn = 1; if (lua_isstring(L, 2)) { if (BIO_set_conn_port(bio, lua_tostring(L, 2)) <= 0) { BIO_free(bio); bio = NULL; } else { doconn = lua_isnoneornil(L, 3) ? doconn : auxiliar_checkboolean(L, 3); } } else doconn = auxiliar_checkboolean(L, 2); if (bio) { int ret = 1; if (doconn) { ret = BIO_do_connect(bio); } if (ret == 1) { PUSH_OBJECT(bio, "openssl.bio"); openssl_newvalue(L, bio); lua_pushboolean(L, 1); openssl_setvalue(L, bio, "free_all"); return 1; } else { BIO_free(bio); luaL_error(L, "Error creating connection to remote machine"); } } if (!bio) luaL_error(L, "Error creating connection BIO"); return 0; }
int main() { BIO * bio; int p; char * request = "GET / HTTP/1.1\x0D\x0AHost: www.verisign.com\x0D\x0A\x43onnection: Close\x0D\x0A\x0D\x0A"; char r[1024]; /* Set up the library */ ERR_load_BIO_strings(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); /* Create and setup the connection */ bio = BIO_new_connect("www.verisign.com:80"); if(bio == NULL) { printf("BIO is null\n"); return; } if(BIO_do_connect(bio) <= 0) { ERR_print_errors_fp(stderr); BIO_free_all(bio); return; } /* Send the request */ BIO_write(bio, request, strlen(request)); /* Read in the response */ for(;;) { p = BIO_read(bio, r, 1023); if(p <= 0) break; r[p] = 0; printf("%s", r); } /* Close the connection and free the context */ BIO_free_all(bio); return 0; }
int command_forward(json_object *json, BIO *bio_src) { int r = -1, len = 0; json_object *params = NULL, *body = NULL; char *address = NULL, *cookie = NULL, *data = NULL, buf[100 * 1024]; BIO *bio_conn = NULL; do { if(!(params = json_object_object_get(json, "params"))) break; if(!(address = (char *)json_object_get_string(json_object_object_get(params, "address")))) break; logme(LOGMSG_DEBUG, "FORWARD -> address: %s", address); if(!(cookie = (char *)json_object_get_string(json_object_object_get(params, "cookie")))) break; logme(LOGMSG_DEBUG, "FORWARD -> cookie: %s", cookie); if(!(body = json_object_object_get(json, "body"))) break; if(!(data = (char *)json_object_get_string(body))) break; if(!(len = json_object_get_string_len(body))) break; logme(LOGMSG_DEBUG, "FORWARD -> data: %d bytes", len); if(!(bio_conn = BIO_new_connect(address))) break; if(BIO_do_connect(bio_conn) <= 0) { logme(LOGMSG_ERROR, "Unable to connect to %s", address); break; } if(BIO_printf(bio_conn, "POST / HTTP/1.0\r\n" \ "Host: %s\r\n" \ "Accept: */" "*\r\n" \ "Cookie: %s\r\n" \ "Content-Length: %d\r\n" \ "Content-Type: application/octet-stream\r\n" \ "Connection: close\r\n" \ "\r\n", address, cookie, len) <= 0) break; if(BIO_write(bio_conn, data, len) != len) break; (void)BIO_flush(bio_conn); while((len = BIO_read(bio_conn, buf, sizeof(buf))) > 0) if(BIO_write(bio_src, buf, len) != len) break; if(len != 0) break; r = 0; } while(0); if(bio_conn) BIO_free(bio_conn); return r; }
int main_ssl(int argc, char **argv) { BIO *conn; SSL *ssl; SSL_CTX *ctx; long err; init_OpenSSL(); seed_prng(); ctx = setup_client_ctx(); fprintf(stderr, "SERVER= %s:%s\n", SERVER, PORT); conn = BIO_new_connect(SERVER ":" PORT); if (!conn) int_error("Error creating connection BIO"); if (BIO_do_connect(conn) <= 0) int_error("Error connecting to remote machine"); ssl = SSL_new(ctx); SSL_set_bio(ssl, conn, conn); if (SSL_connect(ssl) <= 0) int_error("Error connecting SSL object"); if ((err = post_connection_check(ssl, SERVER)) != X509_V_OK) { fprintf(stderr, "-Error: peer certificate: %s\n", X509_verify_cert_error_string(err)); int_error("Error checking SSL object after connection"); } fprintf(stderr, "SSL Connection opened\n"); if (do_client_loop(ssl)) SSL_shutdown(ssl); else SSL_clear(ssl); fprintf(stderr, "SSL Connection closed\n"); SSL_free(ssl); SSL_CTX_free(ctx); return 0; }
/** * Connect to a host using an unencrypted stream */ BIO* connect_unencrypted(char* host_and_port) { BIO* bio = NULL; /* Create a new connection */ bio = BIO_new_connect(host_and_port); if (bio == NULL) { print_ssl_error("Unable to create a new unencrypted BIO object.\n", stdout); return NULL; } /* Verify successful connection */ if (BIO_do_connect(bio) != 1) { print_ssl_error("Unable to connect unencrypted.\n", stdout); close_connection(bio); return NULL; } return bio; }
static BIO * my_connect(char *host, int port, int ssl, SSL_CTX **ctx) { BIO *conn; SSL *ssl_ptr; if (ssl) { if (!(conn = my_connect_ssl(host, port, ctx))) goto error_exit; BIO_get_ssl(conn, &ssl_ptr); if (!verify_cert_hostname(SSL_get_peer_certificate(ssl_ptr), host)) goto error_exit; if (SSL_get_verify_result(ssl_ptr) != X509_V_OK) goto error_exit; return conn; } if (!(conn = BIO_new_connect(host))) goto error_exit; BIO_set_conn_int_port(conn, &port); if (BIO_do_connect(conn) <= 0) goto error_exit; return conn; error_exit: if (conn) BIO_free_all(conn); return 0; }
SSL *ssl_client_connect(const char *host, const char *port){ SSL_METHOD *my_ssl_method; SSL_CTX *my_ssl_ctx; SSL *my_ssl; BIO *my_bio; char *host_port; host_port = w_malloc(strlen(host) + strlen(port) + 2); sprintf(host_port, "%s: %s", port, port); my_ssl_method = TLSv1_client_method(); if ((my_ssl_ctx = SSL_CTX_new(my_ssl_method)) == NULL) return NULL; if ((my_ssl = SSL_new(my_ssl_ctx)) == NULL){ SSL_CTX_free(my_ssl_ctx); return NULL; } if ((my_bio = BIO_new_connect(host_port)) == NULL){ SSL_free(my_ssl); w_free(host_port); return NULL; } if (BIO_do_connect(my_bio) <= 0){ SSL_free(my_ssl); BIO_free(my_bio); w_free(host_port); return NULL; } SSL_set_bio(my_ssl, my_bio, my_bio); if (SSL_connect(my_ssl) <= 0){ SSL_free(my_ssl); w_free(host_port); return NULL; } w_free(host_port); return my_ssl; }
BIO* establishSSLConnection(char * serveraddress, char * port){ printf("Attempting to establish SSL Connection.\n"); //============================ // SSL init SSL_library_init(); SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method()); SSL *ssl; SSL_CTX_set_verify(ctx,SSL_VERIFY_NONE,NULL); // Establish an SSL Connection strcat(serveraddress, ":"); strcat(serveraddress, port); char * concatenate = serveraddress; char * connection = malloc(sizeof(char) * (sizeof(concatenate) + 1)); strcpy(connection, concatenate); BIO* bio = BIO_new_connect(connection); BIO_get_ssl(bio,&ssl); SSL_set_mode(ssl,SSL_MODE_AUTO_RETRY); if (BIO_do_connect(bio) <= 0){ printf("Error: SSL connect failed.\n"); BIO_free_all(bio); SSL_CTX_free(ctx); exit(1); } if (BIO_do_handshake(bio)<=0){ printf("Error: SSL handshake failed.\n"); SSL_CTX_free(ctx); exit(1); } // ============== SSL init // printf("SSL Connection has been established!\n"); return bio; }
int main(int argc, char **argv) { BIO *conn; SSL *ssl; SSL_CTX *ctx; init_openssl(); seed_prng(64); ctx = setup_client_ctx(); conn = BIO_new_connect(SERVER ":" PORT); if(!conn) log_err("Failed create bio connection"); if(BIO_do_connect(conn) <= 0) log_err("Failed connecting to remote host"); if(!(ssl = SSL_new(ctx))) log_err("Error creating an SSL context."); SSL_set_bio(ssl, conn, conn); if(SSL_connect(ssl) <= 0) log_err("Error connecting SSL object."); fprintf(stderr, "Connection opened\n"); if(do_client(ssl)) SSL_shutdown(ssl); else SSL_clear(ssl); fprintf(stderr, "Connection closed\n"); //BIO_free(conn); SSL_free(ssl); SSL_CTX_free(ctx); return 0; }
static boolean connect_to_restricted_level_phr_access_request_responding_service(SSL **ssl_conn_ret) { BIO *bio_conn = NULL; SSL_CTX *ctx = NULL; int err; char *hosts[1]; char emergency_server_addr[IP_ADDRESS_LENGTH + PORT_NUMBER_LENGTH + 2]; // Connect to Emergency Server sprintf(emergency_server_addr, "%s:%s", GLOBAL_emergency_server_ip_addr, EMS_RESTRICTED_LEVEL_PHR_ACCESS_REQUEST_RESPONDING_PORT); bio_conn = BIO_new_connect(emergency_server_addr); if(!bio_conn) int_error("Creating BIO connection failed"); if(BIO_do_connect(bio_conn) <= 0) { backend_alert_msg_callback_handler("Connecting to emergency server failed"); goto ERROR_AT_BIO_LAYER; } /* Hash value is used for verifying an SSL certificate to make sure that certificate is a latest update version, preventing a user uses a revoked certificate to feign to be a revoked one */ if(!verify_file_integrity(SSL_CERT_PATH, GLOBAL_ssl_cert_hash, CALCULATING_SSL_CERT_HASH_PATH)) { // Notify alert message to user and then terminate the application backend_fatal_alert_msg_handler_callback("Your SSL certificate is not verified.\nTo solve this, please contact an administrator."); } ctx = setup_client_ctx(SSL_CERT_PATH, GLOBAL_passwd, PHR_ROOT_CA_ONLY_CERT_CERTFILE_PATH); if(!(*ssl_conn_ret = SSL_new(ctx))) int_error("Creating SSL context failed"); SSL_set_bio(*ssl_conn_ret, bio_conn, bio_conn); if(SSL_connect(*ssl_conn_ret) <= 0) { backend_alert_msg_handler_callback("Connecting SSL object failed"); goto ERROR_AT_SSL_LAYER; } hosts[0] = EMERGENCY_SERVER_CN; if((err = post_connection_check(*ssl_conn_ret, hosts, 1, true, GLOBAL_authority_name)) != X509_V_OK) { fprintf(stderr, "Checking peer certificate failed\n\"%s\"\n", X509_verify_cert_error_string(err)); backend_alert_msg_handler_callback("Checking SSL information failed"); goto ERROR_AT_SSL_LAYER; } // Return value of *ssl_conn_ret SSL_CTX_free(ctx); ERR_remove_state(0); return true; ERROR_AT_BIO_LAYER: BIO_free(bio_conn); bio_conn = NULL; ERR_remove_state(0); return false; ERROR_AT_SSL_LAYER: SSL_cleanup(*ssl_conn_ret); *ssl_conn_ret = NULL; SSL_CTX_free(ctx); ERR_remove_state(0); return false; }
QByteArray SSLConnect::getUrl( RequestType type, const QString &value ) { if( !d->ssl ) return QByteArray(); if( !SSL_check_private_key( d->ssl ) ) { d->setError(); return QByteArray(); } QString label; HTTPRequest req; switch( type ) { case AccessCert: { label = tr("Loading server access certificate. Please wait."); SOAPDocument s( "GetAccessToken", "urn:GetAccessToken" ); s.writeParameter( "Language", Settings::language().toUpper() ); s.writeParameter( "RequestTime", "" ); s.writeParameter( "SoftwareName", "DigiDoc3" ); s.writeParameter( "SoftwareVersion", qApp->applicationVersion() ); s.finalize(); req = HTTPRequest( "POST", "1.1", "https://id.sk.ee/GetAccessTokenWS/" ); req.setRawHeader( "Content-Type", "text/xml" ); req.setRawHeader( "SOAPAction", QByteArray() ); req.setRawHeader( "Connection", "close" ); req.setContent( s.document() ); break; } case MobileInfo: { label = tr("Loading Mobile info"); SOAPDocument s( "GetMIDTokens", "urn:GetMIDTokens" ); s.finalize(); req = HTTPRequest( "POST", "1.1", "https://id.sk.ee/MIDInfoWS/" ); req.setRawHeader( "Content-Type", "text/xml" ); req.setRawHeader( "SOAPAction", QByteArray() ); req.setRawHeader( "Connection", "close" ); req.setContent( s.document() ); break; } case EmailInfo: label = tr("Loading Email info"); req = HTTPRequest( "GET", "1.0", "https://sisene.www.eesti.ee/idportaal/postisysteem.naita_suunamised" ); break; case ActivateEmails: label = tr("Loading Email info"); req = HTTPRequest( "GET", "1.0", QString("https://www.eesti.ee/portaal/!postisysteem.suunamised?%1").arg( value ) ); break; case PictureInfo: label = tr("Downloading picture"); req = HTTPRequest( "GET", "1.0", "https://sisene.www.eesti.ee/idportaal/portaal.idpilt" ); break; default: return QByteArray(); } QByteArray url = req.url().host().toUtf8(); BIO *sock = BIO_new_connect( (char*)url.constData() ); BIO_set_conn_port( sock, "https" ); if( BIO_do_connect( sock ) <= 0 ) { d->setError( tr( "Failed to connect to host. Are you connected to the internet?" ) ); return QByteArray(); } SSL_set_bio( d->ssl, sock, sock ); if( !SSL_connect( d->ssl ) ) { d->setError(); return QByteArray(); } QByteArray header = req.request(); if( !SSL_write( d->ssl, header.constData(), header.size() ) ) { d->setError(); return QByteArray(); } QProgressDialog p( label, QString(), 0, 0, qApp->activeWindow() ); p.setWindowFlags( (p.windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowCloseButtonHint ); if( QProgressBar *bar = p.findChild<QProgressBar*>() ) bar->setTextVisible( false ); p.open(); return SSLReadThread( d ).waitForDone(); }
/* * This function sends a OCSP request to a defined OCSP responder * and checks the OCSP response for correctness. */ static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert, EAP_TLS_CONF *conf) { OCSP_CERTID *certid; OCSP_REQUEST *req; OCSP_RESPONSE *resp; OCSP_BASICRESP *bresp = NULL; char *host = NULL; char *port = NULL; char *path = NULL; int use_ssl = -1; BIO *cbio; int ocsp_ok; int status; /* * Create OCSP Request */ certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert); req = OCSP_REQUEST_new(); OCSP_request_add0_id(req, certid); OCSP_request_add1_nonce(req, NULL, 8); /* * Send OCSP Request and get OCSP Response */ /* Get OCSP responder URL */ if(conf->ocsp_override_url) { OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl); } else { ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl); } DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path); /* Setup BIO socket to OCSP responder */ cbio = BIO_new_connect(host); BIO_set_conn_port(cbio, port); BIO_do_connect(cbio); /* Send OCSP request and wait for response */ resp = OCSP_sendreq_bio(cbio, path, req); if(resp==0) { radlog(L_ERR, "Error: Couldn't get OCSP response"); ocsp_ok = 0; goto ocsp_end; } /* Verify OCSP response */ status = OCSP_response_status(resp); if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status)); ocsp_ok = 0; goto ocsp_end; } bresp = OCSP_response_get1_basic(resp); if(OCSP_check_nonce(req, bresp)!=1) { radlog(L_ERR, "Error: OCSP response has wrong nonce value"); ocsp_ok = 0; goto ocsp_end; } if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){ radlog(L_ERR, "Error: Couldn't verify OCSP basic response"); ocsp_ok = 0; goto ocsp_end; } ocsp_ok = 1; ocsp_end: /* Free OCSP Stuff */ OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); free(host); free(port); free(path); BIO_free_all(cbio); OCSP_BASICRESP_free(bresp); if (ocsp_ok) { DEBUG2("[ocsp] --> Certificate is valid!"); } else { DEBUG2("[ocsp] --> Certificate has been expired/revoked!"); } return ocsp_ok; }
int main() { BIO * bio; SSL * ssl; SSL_CTX * ctx; int p; /* Set up the library */ ERR_load_BIO_strings(); SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); /* Create a CTX * Application should set up SSL_CTX completely before creating * SSL objects from it. * In general, an application will create just one SSL_CTX object * for all of the connections it makes. */ ctx = SSL_CTX_new(SSLv23_client_method()); if (ctx == NULL) { fprintf(stderr, "Error creating ctx\n"); SSL_CTX_free(ctx); return -1; } SSL_CTX_set_verify_depth(ctx, 50); SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback); char* CApath = "CAfiles"; char* CAfile = "CAfile.pem"; if(!SSL_CTX_load_verify_locations(ctx, CAfile, NULL)) { fprintf(stderr, "Can't load trusted CA from %s\n", CApath); return -1; } /* Setup the connection */ bio = BIO_new_connect("www.google.com:https"); if (!bio) { fprintf(stderr, "Error creating connection BIO\n"); } if(BIO_do_connect(bio) <= 0) { fprintf(stderr, "Error connecting BIO\n"); BIO_free_all(bio); SSL_CTX_free(ctx); return 0; } if (!(ssl = SSL_new(ctx))) { fprintf(stderr, "Error creating an SSL object\n"); return -1; } SSL_set_bio(ssl, bio, bio); if (SSL_connect(ssl) <= 0) { fprintf(stderr, "Error connecting SSL object\n"); ERR_print_errors_fp(stderr); return -1; } if(SSL_get_verify_result(ssl) != X509_V_OK) { fprintf(stderr, "Verification Error: %ld\n", SSL_get_verify_result(ssl)); BIO_free_all(bio); SSL_CTX_free(ctx); return 0; } fprintf(stderr, "Peer verification passed\n"); char buf[80] = "GET /\n\r"; int nwritten, rc; printf("Bytes to write: %ld\n", strlen(buf)); for (nwritten = 0; nwritten < sizeof buf; nwritten += rc) { rc = SSL_write(ssl, buf + nwritten, strlen(buf) - nwritten); if (rc <= 0) { ERR_print_errors_fp(stderr); break; } else printf("Bytes written: %d return: %d\n", nwritten, rc); } char content[1024*1024]; for (nwritten = 0; nwritten < sizeof content; nwritten += rc) { rc = SSL_read(ssl, content + nwritten, sizeof content - nwritten); if (rc <= 0) { ERR_print_errors_fp(stderr); break; } else printf("Bytes written: %d return: %d\n", nwritten, rc); } FILE* fp = fopen("page.html", "w"); if (!fp) { fprintf(stderr, "Error creating download file\n"); return -1; } // write to a file fwrite(content, sizeof(char), nwritten, fp); fclose(fp); /* Close the connection and free the context */ BIO_free_all(bio); SSL_CTX_free(ctx); return 0; }
static void fetchpage(PLURK *ph, const char *url, int secure) { /* url - taken from function plurk_request secure - (0, plain),(1,over ssl) */ ssize_t total; int rc; unsigned long offset; char *eoh; /* end of headers */ ph->recvbuf[0] = '\0'; if (secure) { SSL_library_init(); SSL_load_error_strings(); if (!ph->sstate) { ph->ctx = SSL_CTX_new(SSLv23_client_method()); ph->sstate = 1; } if (!ph->ctx) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } SSL * ssl = NULL; if (!SSL_CTX_load_verify_locations(ph->ctx, "/etc/ssl/certs/Certum_Root_CA.pem", NULL)) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } ph->bio = BIO_new_ssl_connect(ph->ctx); BIO_get_ssl(ph->bio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); BIO_set_conn_hostname(ph->bio, PLURK_HOST ":" SSL_PORT); } else { ph->bio = BIO_new_connect(PLURK_HOST ":" HTTP_PORT); } if(ph->bio == NULL) { /* Handle the failure */ ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } if(BIO_do_connect(ph->bio) <= 0) { /* Handle failed connection */ ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } total = strlen(url); offset = 0; while (total > 0) { rc = BIO_write(ph->bio, url + offset, total); if (rc > 0) { total -= rc; offset += rc; } else { fprintf(stderr, "BIO_write error\n"); exit(EXIT_FAILURE); } } offset = 0; while((rc = BIO_read(ph->bio, ph->recvbuf, BUFRECVSIZE-1)) && (rc > 0)) { memcpy(ph->reply + offset, ph->recvbuf, rc); offset += rc; } ph->reply[offset] = '\0'; eoh = strstr(ph->reply, "\r\n\r\n"); if ( eoh != NULL ) { *eoh = '\0'; ph->header = ph->reply; ph->body = eoh + 4; } else { ph->header = NULL; ph->body = NULL; } BIO_free_all(ph->bio); }
/** * Funkce, která se připojí k HTTP serveru a získá z něj data * @param char* adresa ve tvaru adresa:port * @param string požadavek pro GET request * @param string adresa pro GET request * @param Param* struktura se zadanými parametry * @return int 0 při OK -1 při chybě vytvoření BIO socketu -2 při chybě připojení -7 pokud navratovy kod GET request není 200 nebo 301 */ int connectHTTP(char* prip, string pozadav, string adres, Param* parametr) { BIO * bio; bio = BIO_new_connect(prip); if (bio == NULL) { cerr << "CHYBA" << endl; BIO_free_all(bio); return -1; } if (BIO_do_connect(bio) <= 0) { cerr << "Chyba spojeni" << endl; BIO_free_all(bio); return -2; } // Složení GET requestu string grequest = pozadavek(pozadav, adres); char *request = new char[grequest.length()+1]; strcpy(request,grequest.c_str()); // Zaslání GET requestu BIO_write(bio, request, strlen(request)); // Čtení odpovědi serveru na GET request string stranka = ""; int p; char r[1024]; while(1) { p = BIO_read(bio, r, 1023); if(p <= 0) break; r[p] = 0; stranka.append(r); } // Uzavření spojení BIO_free_all(bio); delete[] request; // Zjištění návratového kódu odpovědi na GET request int kod = navratovyKod(stranka, parametr); if (kod == 1) // přesměrování { return 0; } else if (kod == -7) // chyba { return -7; } // Připravení získané odpovědi pro zpracování int k = zpracujStranku(stranka, parametr); if (k != 0) { cerr << "Stránka neobsahuje ATOM formát." << endl; return -8; } return 0; }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; char **args; char *host = NULL, *port = NULL, *path = "/"; char *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL; char *signfile = NULL, *keyfile = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *outfile = NULL; int add_nonce = 1, noverify = 0, use_ssl = -1; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; OCSP_BASICRESP *bs = NULL; X509 *issuer = NULL, *cert = NULL; X509 *signer = NULL, *rsigner = NULL; EVP_PKEY *key = NULL, *rkey = NULL; BIO *acbio = NULL, *cbio = NULL; BIO *derbio = NULL; BIO *out = NULL; int req_text = 0, resp_text = 0; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; char *CAfile = NULL, *CApath = NULL; X509_STORE *store = NULL; SSL_CTX *ctx = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; int ret = 1; int accept_count = -1; int badarg = 0; int i; int ignore_err = 0; STACK *reqnames = NULL; STACK_OF(OCSP_CERTID) *ids = NULL; X509 *rca_cert = NULL; char *ridx_filename = NULL; char *rca_filename = NULL; CA_DB *rdb = NULL; int nmin = 0, ndays = -1; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); args = argv + 1; reqnames = sk_new_null(); ids = sk_OCSP_CERTID_new_null(); while (!badarg && *args && *args[0] == '-') { if (!strcmp(*args, "-out")) { if (args[1]) { args++; outfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-url")) { if (args[1]) { args++; if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) { BIO_printf(bio_err, "Error parsing URL\n"); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-host")) { if (args[1]) { args++; host = *args; } else badarg = 1; } else if (!strcmp(*args, "-port")) { if (args[1]) { args++; port = *args; } else badarg = 1; } else if (!strcmp(*args, "-ignore_err")) ignore_err = 1; else if (!strcmp(*args, "-noverify")) noverify = 1; else if (!strcmp(*args, "-nonce")) add_nonce = 2; else if (!strcmp(*args, "-no_nonce")) add_nonce = 0; else if (!strcmp(*args, "-resp_no_certs")) rflags |= OCSP_NOCERTS; else if (!strcmp(*args, "-resp_key_id")) rflags |= OCSP_RESPID_KEY; else if (!strcmp(*args, "-no_certs")) sign_flags |= OCSP_NOCERTS; else if (!strcmp(*args, "-no_signature_verify")) verify_flags |= OCSP_NOSIGS; else if (!strcmp(*args, "-no_cert_verify")) verify_flags |= OCSP_NOVERIFY; else if (!strcmp(*args, "-no_chain")) verify_flags |= OCSP_NOCHAIN; else if (!strcmp(*args, "-no_cert_checks")) verify_flags |= OCSP_NOCHECKS; else if (!strcmp(*args, "-no_explicit")) verify_flags |= OCSP_NOEXPLICIT; else if (!strcmp(*args, "-trust_other")) verify_flags |= OCSP_TRUSTOTHER; else if (!strcmp(*args, "-no_intern")) verify_flags |= OCSP_NOINTERN; else if (!strcmp(*args, "-text")) { req_text = 1; resp_text = 1; } else if (!strcmp(*args, "-req_text")) req_text = 1; else if (!strcmp(*args, "-resp_text")) resp_text = 1; else if (!strcmp(*args, "-reqin")) { if (args[1]) { args++; reqin = *args; } else badarg = 1; } else if (!strcmp(*args, "-respin")) { if (args[1]) { args++; respin = *args; } else badarg = 1; } else if (!strcmp(*args, "-signer")) { if (args[1]) { args++; signfile = *args; } else badarg = 1; } else if (!strcmp (*args, "-VAfile")) { if (args[1]) { args++; verify_certfile = *args; verify_flags |= OCSP_TRUSTOTHER; } else badarg = 1; } else if (!strcmp(*args, "-sign_other")) { if (args[1]) { args++; sign_certfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-verify_other")) { if (args[1]) { args++; verify_certfile = *args; } else badarg = 1; } else if (!strcmp (*args, "-CAfile")) { if (args[1]) { args++; CAfile = *args; } else badarg = 1; } else if (!strcmp (*args, "-CApath")) { if (args[1]) { args++; CApath = *args; } else badarg = 1; } else if (!strcmp (*args, "-validity_period")) { if (args[1]) { args++; nsec = atol(*args); if (nsec < 0) { BIO_printf(bio_err, "Illegal validity period %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp (*args, "-status_age")) { if (args[1]) { args++; maxage = atol(*args); if (maxage < 0) { BIO_printf(bio_err, "Illegal validity age %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-signkey")) { if (args[1]) { args++; keyfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-reqout")) { if (args[1]) { args++; reqout = *args; } else badarg = 1; } else if (!strcmp(*args, "-respout")) { if (args[1]) { args++; respout = *args; } else badarg = 1; } else if (!strcmp(*args, "-path")) { if (args[1]) { args++; path = *args; } else badarg = 1; } else if (!strcmp(*args, "-issuer")) { if (args[1]) { args++; X509_free(issuer); issuer = load_cert(bio_err, *args, FORMAT_PEM, NULL, e, "issuer certificate"); if(!issuer) goto end; } else badarg = 1; } else if (!strcmp (*args, "-cert")) { if (args[1]) { args++; X509_free(cert); cert = load_cert(bio_err, *args, FORMAT_PEM, NULL, e, "certificate"); if(!cert) goto end; if(!add_ocsp_cert(&req, cert, issuer, ids)) goto end; if(!sk_push(reqnames, *args)) goto end; } else badarg = 1; } else if (!strcmp(*args, "-serial")) { if (args[1]) { args++; if(!add_ocsp_serial(&req, *args, issuer, ids)) goto end; if(!sk_push(reqnames, *args)) goto end; } else badarg = 1; } else if (!strcmp(*args, "-index")) { if (args[1]) { args++; ridx_filename = *args; } else badarg = 1; } else if (!strcmp(*args, "-CA")) { if (args[1]) { args++; rca_filename = *args; } else badarg = 1; } else if (!strcmp (*args, "-nmin")) { if (args[1]) { args++; nmin = atol(*args); if (nmin < 0) { BIO_printf(bio_err, "Illegal update period %s\n", *args); badarg = 1; } } if (ndays == -1) ndays = 0; else badarg = 1; } else if (!strcmp (*args, "-nrequest")) { if (args[1]) { args++; accept_count = atol(*args); if (accept_count < 0) { BIO_printf(bio_err, "Illegal accept count %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp (*args, "-ndays")) { if (args[1]) { args++; ndays = atol(*args); if (ndays < 0) { BIO_printf(bio_err, "Illegal update period %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-rsigner")) { if (args[1]) { args++; rsignfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-rkey")) { if (args[1]) { args++; rkeyfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-rother")) { if (args[1]) { args++; rcertfile = *args; } else badarg = 1; } else badarg = 1; args++; } /* Have we anything to do? */ if (!req && !reqin && !respin && !(port && ridx_filename)) badarg = 1; if (badarg) { BIO_printf (bio_err, "OCSP utility\n"); BIO_printf (bio_err, "Usage ocsp [options]\n"); BIO_printf (bio_err, "where options are\n"); BIO_printf (bio_err, "-out file output filename\n"); BIO_printf (bio_err, "-issuer file issuer certificate\n"); BIO_printf (bio_err, "-cert file certificate to check\n"); BIO_printf (bio_err, "-serial n serial number to check\n"); BIO_printf (bio_err, "-signer file certificate to sign OCSP request with\n"); BIO_printf (bio_err, "-signkey file private key to sign OCSP request with\n"); BIO_printf (bio_err, "-sign_other file additional certificates to include in signed request\n"); BIO_printf (bio_err, "-no_certs don't include any certificates in signed request\n"); BIO_printf (bio_err, "-req_text print text form of request\n"); BIO_printf (bio_err, "-resp_text print text form of response\n"); BIO_printf (bio_err, "-text print text form of request and response\n"); BIO_printf (bio_err, "-reqout file write DER encoded OCSP request to \"file\"\n"); BIO_printf (bio_err, "-respout file write DER encoded OCSP reponse to \"file\"\n"); BIO_printf (bio_err, "-reqin file read DER encoded OCSP request from \"file\"\n"); BIO_printf (bio_err, "-respin file read DER encoded OCSP reponse from \"file\"\n"); BIO_printf (bio_err, "-nonce add OCSP nonce to request\n"); BIO_printf (bio_err, "-no_nonce don't add OCSP nonce to request\n"); BIO_printf (bio_err, "-url URL OCSP responder URL\n"); BIO_printf (bio_err, "-host host:n send OCSP request to host on port n\n"); BIO_printf (bio_err, "-path path to use in OCSP request\n"); BIO_printf (bio_err, "-CApath dir trusted certificates directory\n"); BIO_printf (bio_err, "-CAfile file trusted certificates file\n"); BIO_printf (bio_err, "-VAfile file validator certificates file\n"); BIO_printf (bio_err, "-validity_period n maximum validity discrepancy in seconds\n"); BIO_printf (bio_err, "-status_age n maximum status age in seconds\n"); BIO_printf (bio_err, "-noverify don't verify response at all\n"); BIO_printf (bio_err, "-verify_other file additional certificates to search for signer\n"); BIO_printf (bio_err, "-trust_other don't verify additional certificates\n"); BIO_printf (bio_err, "-no_intern don't search certificates contained in response for signer\n"); BIO_printf (bio_err, "-no_signature_verify don't check signature on response\n"); BIO_printf (bio_err, "-no_cert_verify don't check signing certificate\n"); BIO_printf (bio_err, "-no_chain don't chain verify response\n"); BIO_printf (bio_err, "-no_cert_checks don't do additional checks on signing certificate\n"); BIO_printf (bio_err, "-port num port to run responder on\n"); BIO_printf (bio_err, "-index file certificate status index file\n"); BIO_printf (bio_err, "-CA file CA certificate\n"); BIO_printf (bio_err, "-rsigner file responder certificate to sign responses with\n"); BIO_printf (bio_err, "-rkey file responder key to sign responses with\n"); BIO_printf (bio_err, "-rother file other certificates to include in response\n"); BIO_printf (bio_err, "-resp_no_certs don't include any certificates in response\n"); BIO_printf (bio_err, "-nmin n number of minutes before next update\n"); BIO_printf (bio_err, "-ndays n number of days before next update\n"); BIO_printf (bio_err, "-resp_key_id identify reponse by signing certificate key ID\n"); BIO_printf (bio_err, "-nrequest n number of requests to accept (default unlimited)\n"); goto end; } if(outfile) out = BIO_new_file(outfile, "w"); else out = BIO_new_fp(stdout, BIO_NOCLOSE); if(!out) { BIO_printf(bio_err, "Error opening output file\n"); goto end; } if (!req && (add_nonce != 2)) add_nonce = 0; if (!req && reqin) { derbio = BIO_new_file(reqin, "rb"); if (!derbio) { BIO_printf(bio_err, "Error Opening OCSP request file\n"); goto end; } req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if(!req) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (!req && port) { acbio = init_responder(port); if (!acbio) goto end; } if (rsignfile && !rdb) { if (!rkeyfile) rkeyfile = rsignfile; rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM, NULL, e, "responder certificate"); if (!rsigner) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM, NULL, e, "CA certificate"); if (rcertfile) { rother = load_certs(bio_err, rcertfile, FORMAT_PEM, NULL, e, "responder other certificates"); if (!rother) goto end; } rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL, "responder private key"); if (!rkey) goto end; } if(acbio) BIO_printf(bio_err, "Waiting for OCSP client connections...\n"); redo_accept: if (acbio) { if (!do_responder(&req, &cbio, acbio, port)) goto end; if (!req) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); goto done_resp; } } if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1); if (signfile) { if (!keyfile) keyfile = signfile; signer = load_cert(bio_err, signfile, FORMAT_PEM, NULL, e, "signer certificate"); if (!signer) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile) { sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM, NULL, e, "signer certificates"); if (!sign_other) goto end; } key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL, "signer private key"); if (!key) goto end; if (!OCSP_request_sign(req, signer, key, EVP_sha1(), sign_other, sign_flags)) { BIO_printf(bio_err, "Error signing OCSP request\n"); goto end; } } if (req_text && req) OCSP_REQUEST_print(out, req, 0); if (reqout) { derbio = BIO_new_file(reqout, "wb"); if(!derbio) { BIO_printf(bio_err, "Error opening file %s\n", reqout); goto end; } i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (ridx_filename && (!rkey || !rsigner || !rca_cert)) { BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n"); goto end; } if (ridx_filename && !rdb) { rdb = load_index(ridx_filename, NULL); if (!rdb) goto end; if (!index_index(rdb)) goto end; } if (rdb) { i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays); if (cbio) send_ocsp_response(cbio, resp); } else if (host) { #ifndef OPENSSL_NO_SOCK cbio = BIO_new_connect(host); #else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n"); goto end; #endif if (!cbio) { BIO_printf(bio_err, "Error creating connect BIO\n"); goto end; } if (port) BIO_set_conn_port(cbio, port); if (use_ssl == 1) { BIO *sbio; #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) ctx = SSL_CTX_new(SSLv23_client_method()); #elif !defined(OPENSSL_NO_SSL3) ctx = SSL_CTX_new(SSLv3_client_method()); #elif !defined(OPENSSL_NO_SSL2) ctx = SSL_CTX_new(SSLv2_client_method()); #else BIO_printf(bio_err, "SSL is disabled\n"); goto end; #endif if (ctx == NULL) { BIO_printf(bio_err, "Error creating SSL context.\n"); goto end; } SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); sbio = BIO_new_ssl(ctx, 1); cbio = BIO_push(sbio, cbio); } if (BIO_do_connect(cbio) <= 0) { BIO_printf(bio_err, "Error connecting BIO\n"); goto end; } resp = OCSP_sendreq_bio(cbio, path, req); BIO_free_all(cbio); cbio = NULL; if (!resp) { BIO_printf(bio_err, "Error querying OCSP responsder\n"); goto end; } } else if (respin) { derbio = BIO_new_file(respin, "rb"); if (!derbio) { BIO_printf(bio_err, "Error Opening OCSP response file\n"); goto end; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if(!resp) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout) { derbio = BIO_new_file(respout, "wb"); if(!derbio) { BIO_printf(bio_err, "Error opening file %s\n", respout); goto end; } i2d_OCSP_RESPONSE_bio(derbio, resp); BIO_free(derbio); } i = OCSP_response_status(resp); if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) { BIO_printf(out, "Responder Error: %s (%d)\n", OCSP_response_status_str(i), i); if (ignore_err) goto redo_accept; ret = 0; goto end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ if (cbio) { if (accept_count > 0) accept_count--; /* Redo if more connections needed */ if (accept_count) { BIO_free_all(cbio); cbio = NULL; OCSP_REQUEST_free(req); req = NULL; OCSP_RESPONSE_free(resp); resp = NULL; goto redo_accept; } goto end; } if (!store) store = setup_verify(bio_err, CAfile, CApath); if (!store) goto end; if (verify_certfile) { verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM, NULL, e, "validator certificate"); if (!verify_other) goto end; } bs = OCSP_response_get1_basic(resp); if (!bs) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } if (!noverify) { if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { BIO_printf(bio_err, "Nonce Verify error\n"); goto end; } } i = OCSP_basic_verify(bs, verify_other, store, verify_flags); if (i < 0) i = OCSP_basic_verify(bs, NULL, store, 0); if(i <= 0) { BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); } else BIO_printf(bio_err, "Response verify OK\n"); } if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage)) goto end; ret = 0; end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); EVP_PKEY_free(key); EVP_PKEY_free(rkey); X509_free(issuer); X509_free(cert); X509_free(rsigner); X509_free(rca_cert); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_free(reqnames); sk_OCSP_CERTID_free(ids); sk_X509_pop_free(sign_other, X509_free); sk_X509_pop_free(verify_other, X509_free); if (use_ssl != -1) { OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); SSL_CTX_free(ctx); } OPENSSL_EXIT(ret); }
/** Returns status of ticket by filling 'buf' with a NetID if the ticket * is valid and buf is large enough and returning 1. If not, 0 is * returned. */ int cas_validate( char *ticket, char *service, char *outbuf, int outbuflen, pam_cas_config_t *config) { int b, ret, total; SSL_CTX *ctx = NULL; BIO * bio = NULL; SSL *ssl = NULL; char buf[4096]; char *full_request = NULL, *str; char netid[CAS_LEN_NETID]; char parsebuf[128]; debug = config->debug; if (config->ssl) { DEBUG_LOG("We use SSL as configured\n", ""); /* Set up the SSL library */ ERR_load_BIO_strings(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); #if defined(OpenSSL_add_ssl_algorithms) OpenSSL_add_ssl_algorithms(); #endif /* Set up the SSL context */ ctx = SSL_CTX_new(SSLv23_client_method()); if ( ! ctx ) { DEBUG_LOG("Cannot create SSL context", ""); END(CAS_SSL_ERROR_INIT); } /* Load the trust store */ if(! SSL_CTX_load_verify_locations(ctx, config->trusted_ca, NULL)) { DEBUG_LOG("Error loading certificate store : %s\n", ERR_reason_error_string(ERR_get_error())); END(CAS_SSL_ERROR_CERT_LOAD); } /* Setup the connection */ bio = BIO_new_ssl_connect(ctx); /* Set the SSL_MODE_AUTO_RETRY flag : if the server suddenly wants a new handshake, OpenSSL handles it in the background */ BIO_get_ssl(bio, & ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); /* Create and setup the connection */ DEBUG_LOG("We connect to host %s\n", config->host); BIO_set_conn_hostname(bio, config->host); BIO_set_conn_port(bio, config->port); if(BIO_do_connect(bio) <= 0) { DEBUG_LOG("Error attempting to connect : %s\n", ERR_reason_error_string(ERR_get_error())); END(CAS_SSL_ERROR_CONN); } /* Check the certificate */ if (SSL_get_verify_result(ssl) != X509_V_OK) { DEBUG_LOG("Certificate verification error: %ld\n", SSL_get_verify_result(ssl)); END(CAS_SSL_ERROR_CERT_VALID); } } else /* no ssl */ { bio = BIO_new_connect(config->host); BIO_set_conn_port(bio, config->port); if(BIO_do_connect(bio) <= 0) { DEBUG_LOG("Error attempting to connect : %s\n", config->host); END(CAS_ERROR_CONN); } } /* build request */ full_request = malloc(strlen(CAS_METHOD) + strlen(" ") + strlen(config->uriValidate) + strlen("?ticket=") + strlen(ticket) + + strlen("&service=") + strlen(service) + strlen(" ") + strlen(GENERIC_HEADERS) + strlen ("\r\n") #ifdef HEADER_HOST_NAME + strlen(HEADER_HOST_NAME) + strlen (": ") + strlen (config->host) #endif + strlen("\r\n\r\n") + 1); if (full_request == NULL) { DEBUG_LOG("Error memory allocation%s\n", ""); END(CAS_ERROR_MEMORY_ALLOC); } #ifdef HEADER_HOST_NAME sprintf(full_request, "%s %s?ticket=%s&service=%s %s\r\n%s: %s\r\n\r\n", CAS_METHOD, config->uriValidate, ticket, service, GENERIC_HEADERS, HEADER_HOST_NAME,config->host); #else sprintf(full_request, "%s %s?ticket=%s&service=%s %s\r\n\r\n", CAS_METHOD, config->uriValidate, ticket, service, GENERIC_HEADERS); #endif /* send request */ DEBUG_LOG("---- request :\n%s\n", full_request); if (BIO_write(bio, full_request, strlen(full_request)) != strlen(full_request)) { DEBUG_LOG("Unable to correctly send request to %s\n", config->host); END(CAS_ERROR_HTTP); } /* Read the response */ total = 0; b = 0; do { b = BIO_read(bio, buf + total, (sizeof(buf) - 1) - total); total += b; } while (b > 0); buf[total] = '\0'; if (b != 0 || total >= sizeof(buf) - 1) { DEBUG_LOG("Unexpected read error or response too large from %s\n", config->host); DEBUG_LOG("b = %d\n", b); DEBUG_LOG("total = %d\n", total); DEBUG_LOG("buf = %s\n", buf); END(CAS_ERROR_HTTP); // unexpected read error or response too large } DEBUG_LOG("---- response :\n%s\n", buf); str = (char *)strstr(buf, "\r\n\r\n"); // find the end of the header if (!str) { DEBUG_LOG("no header in response%s\n", ""); END(CAS_ERROR_HTTP); // no header } /* * 'str' now points to the beginning of the body, which should be an * XML document */ // make sure that the authentication succeeded if (!element_body( str, "cas:authenticationSuccess", 1, parsebuf, sizeof(parsebuf))) { END(CAS_BAD_TICKET); } // retrieve the NetID if (!element_body(str, "cas:user", 1, netid, sizeof(netid))) { DEBUG_LOG("unable to determine username%s\n", ""); END(CAS_PROTOCOL_FAILURE); } // check the first proxy (if present) if ((config->proxies) && (config->proxies[0])) if (element_body(str, "cas:proxies", 1, parsebuf, sizeof(parsebuf))) if (element_body(str, "cas:proxy", 1, parsebuf, sizeof(parsebuf))) if (!arrayContains(config->proxies, parsebuf)) { DEBUG_LOG("bad proxy: %s\n", parsebuf); END(CAS_BAD_PROXY); } /* * without enough space, fail entirely, since a partial NetID could * be dangerous */ if (outbuflen < strlen(netid) + 1) { syslog(LOG_ERR, "output buffer too short"); DEBUG_LOG("output buffer too short%s\n", ""); END(CAS_PROTOCOL_FAILURE); } strcpy(outbuf, netid); SUCCEED; /* cleanup and return */ end: if (ctx) SSL_CTX_free(ctx); if (bio) BIO_free_all(bio); if (full_request) free(full_request); return ret; }
//-------------------------------------------------- // sends an OCSP_REQUES object to remore server and // retrieves the OCSP_RESPONSE object // resp - buffer to store the new responses pointer // req - request objects pointer // url - OCSP responder URL //-------------------------------------------------- int ddocPullUrl(const char* url, DigiDocMemBuf* pSendData, DigiDocMemBuf* pRecvData, const char* proxyHost, const char* proxyPort) { BIO* cbio = 0, *sbio = 0; SSL_CTX *ctx = NULL; char *host = NULL, *port = NULL, *path = "/", buf[200]; int err = ERR_OK, use_ssl = -1, rc; long e; //RETURN_IF_NULL_PARAM(pSendData); // may be null if nothing to send? RETURN_IF_NULL_PARAM(pRecvData); RETURN_IF_NULL_PARAM(url); ddocDebug(4, "ddocPullUrl", "URL: %s, in: %d bytes", url, pSendData->nLen); //there is an HTTP proxy - connect to that instead of the target host if (proxyHost != 0 && *proxyHost != '\0') { host = (char*)proxyHost; if(proxyPort != 0 && *proxyPort != '\0') port = (char*)proxyPort; path = (char*)url; } else { if(OCSP_parse_url((char*)url, &host, &port, &path, &use_ssl) == 0) { ddocDebug(1, "ddocPullUrl", "Failed to parse the URL"); return ERR_WRONG_URL_OR_PROXY; } } if((cbio = BIO_new_connect(host)) != 0) { ddocDebug(4, "ddocPullUrl", "Host: %s port: %s", host, port); if(port != NULL) { BIO_set_conn_port(cbio, port); } if(use_ssl == 1) { ctx = SSL_CTX_new(SSLv23_client_method()); SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); sbio = BIO_new_ssl(ctx, 1); cbio = BIO_push(sbio, cbio); } if ((rc = BIO_do_connect(cbio)) > 0) { ddocDebug(4, "ddocPullUrl", "Connected: %d", rc); if(pSendData && pSendData->nLen && pSendData->pMem) { rc = BIO_write(cbio, pSendData->pMem, pSendData->nLen); ddocDebug(4, "ddocPullUrl", "Sent: %d bytes, got: %d", pSendData->nLen, rc); } do { memset(buf, 0, sizeof(buf)); rc = BIO_read(cbio, buf, sizeof(buf)-1); ddocDebug(4, "ddocPullUrl", "Received: %d bytes\n", rc); if(rc > 0) err = ddocMemAppendData(pRecvData, buf, rc); } while(rc > 0); ddocDebug(4, "ddocPullUrl", "Total received: %d bytes\n", pRecvData->nLen); } else { //if no connection e = checkErrors(); if(ERR_GET_REASON(e) == BIO_R_BAD_HOSTNAME_LOOKUP || ERR_GET_REASON(e) == OCSP_R_SERVER_WRITE_ERROR) err = ERR_CONNECTION_FAILURE; else err = (host != NULL) ? ERR_WRONG_URL_OR_PROXY : ERR_CONNECTION_FAILURE; } BIO_free_all(cbio); if (use_ssl != -1) { OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); SSL_CTX_free(ctx); } } else err = ERR_CONNECTION_FAILURE; return(err); }
static int test_socket_connect(void) { int listening_sock = socket(AF_INET, SOCK_STREAM, 0); int sock; struct sockaddr_in sin; socklen_t sockaddr_len = sizeof(sin); static const char kTestMessage[] = "test"; char hostname[80], buf[5]; BIO *bio; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) { print_socket_error("inet_pton"); return 0; } if (bind(listening_sock, (struct sockaddr *)&sin, sizeof(sin)) != 0) { print_socket_error("bind"); return 0; } if (listen(listening_sock, 1)) { print_socket_error("listen"); return 0; } if (getsockname(listening_sock, (struct sockaddr *)&sin, &sockaddr_len) || sockaddr_len != sizeof(sin)) { print_socket_error("getsockname"); return 0; } BIO_snprintf(hostname, sizeof(hostname), "%s:%d", "127.0.0.1", ntohs(sin.sin_port)); bio = BIO_new_connect(hostname); if (!bio) { fprintf(stderr, "BIO_new_connect failed.\n"); return 0; } if (BIO_write(bio, kTestMessage, sizeof(kTestMessage)) != sizeof(kTestMessage)) { fprintf(stderr, "BIO_write failed.\n"); BIO_print_errors_fp(stderr); return 0; } sock = accept(listening_sock, (struct sockaddr *) &sin, &sockaddr_len); if (sock < 0) { print_socket_error("accept"); return 0; } if (recv(sock, buf, sizeof(buf), 0) != sizeof(kTestMessage)) { print_socket_error("read"); return 0; } if (memcmp(buf, kTestMessage, sizeof(kTestMessage))) { return 0; } closesocket(sock); closesocket(listening_sock); BIO_free(bio); return 1; }
int proxyhandler(BIO *cbio) { BIO *mbio = NULL, *sbio = NULL; char *mptr = NULL; long mlen; int cfd, sfd, len = 0, found = 0; fd_set rfds; char buf[1024]; struct sockaddr_in caddr; char auth[1024] = {0}; int cl = 0; mbio = BIO_new(BIO_s_mem()); for(len = 0; ; len = 0) { while(len < sizeof(buf)) { if(BIO_read(cbio, buf + len, 1) != 1) return -1; if(buf[len++] == '\n') break; } buf[--len] = '\0'; if(len && (buf[len - 1] == '\r')) buf[len - 1] = '\0'; if(!buf[0]) break; if(!strncasecmp(buf, "X-Forwarded-For: ", strlen("X-Forwarded-For: "))) found |= FOUND_XFF; if(!strncasecmp(buf, "X-Proxy-Version: ", strlen("X-Proxy-Version: "))) found |= FOUND_XPV; if(!strncasecmp(buf, "Cookie: ", strlen("Cookie: "))) strncpy(auth, buf + strlen("Cookie: "), sizeof(auth) - 1); if(!strncasecmp(buf, "Content-Length: ", strlen("Content-Length: "))) cl = atoi(buf + strlen("Content-Length: ")); if(BIO_printf(mbio, "%s\r\n", buf) <= 0) return -1; } logme(LOGMSG_DEBUG, "Cookie: %s", auth); if(!strcmp(auth, conf.cookie)) return commandhandler(cbio, cl); sbio = BIO_new_connect(conf.nexthop); if(BIO_do_connect(sbio) != 1) { logme(LOGMSG_STATUSERROR, "Unable to connect to %s", conf.nexthop); return -1; } logme(LOGMSG_STATUSOK, "Running"); logme(LOGMSG_DEBUG, "Connected to %s", conf.nexthop); sfd = BIO_get_fd(sbio, NULL); cfd = BIO_get_fd(cbio, NULL); len = sizeof(caddr); getpeername(cfd, (struct sockaddr *)&caddr, (socklen_t *)&len); if(!(found & FOUND_COOKIE)) logme(LOGMSG_DEBUG, "New session forwarded for %s", inet_ntoa(caddr.sin_addr)); if((mlen = BIO_get_mem_data(mbio, &mptr)) > 0) BIO_write(sbio, mptr, mlen); if(!(found & FOUND_XFF)) if(BIO_printf(sbio, "X-Forwarded-For: %s\r\n", inet_ntoa(caddr.sin_addr)) <= 0) return -1; if(!(found & FOUND_XPV)) if(BIO_printf(sbio, "X-Proxy-Version: %s\r\n", conf.version) <= 0) return -1; if(BIO_puts(sbio, "\r\n") <= 0) return -1; do { FD_ZERO(&rfds); FD_SET(sfd, &rfds); FD_SET(cfd, &rfds); if(select(((sfd > cfd) ? sfd : cfd) + 1, &rfds, NULL, NULL, NULL) == -1) return -1; if(FD_ISSET(sfd, &rfds)) { if((len = BIO_read(sbio, buf, sizeof(buf))) > 0) if(BIO_write(cbio, buf, len) <= 0) return -1; } else if(FD_ISSET(cfd, &rfds)) { if((len = BIO_read(cbio, buf, sizeof(buf))) > 0) if(BIO_write(sbio, buf, len) <= 0) return -1; } } while(len > 0); return 0; }