SSLContext::SSLContext(int _method){ #ifdef USE_EMBEDDED_CLASSNAMES setClassName(__xvr2_Net_SSLContext); #endif __init_ssl_library(this); pem = 0; method = _method; ctx = 0; mydata = 0; switch(method){ case SSL_V2: ctx = SSL_CTX_new(SSLv2_method()); break; case SSL_V2_CLIENT: ctx = SSL_CTX_new(SSLv2_client_method()); break; case SSL_V2_SERVER: ctx = SSL_CTX_new(SSLv2_server_method()); break; case SSL_V3: ctx = SSL_CTX_new(SSLv3_method()); break; case SSL_V3_CLIENT: ctx = SSL_CTX_new(SSLv3_client_method()); break; case SSL_V3_SERVER: ctx = SSL_CTX_new(SSLv3_server_method()); break; case SSL_V23_CLIENT: ctx = SSL_CTX_new(SSLv23_client_method()); break; case SSL_V23_SERVER: ctx = SSL_CTX_new(SSLv23_server_method()); break; case SSL_V23: default: ctx = SSL_CTX_new(SSLv23_method()); } if(ctx == 0){ throw SSLContextCreation(); } //Initialize password callback __ssl_ctx_cb_args *x; x = new __ssl_ctx_cb_args(this, 0, 0); mydata = x; #ifdef USE_DEBUG debugmsgln(this, "Initializing password callback..."); #endif SSL_CTX_set_default_passwd_cb((SSL_CTX *)ctx, passwdCB); #ifdef USE_DEBUG debugmsgln(this, "Initializing default password callback userdata..."); #endif SSL_CTX_set_default_passwd_cb_userdata((SSL_CTX *)ctx, mydata); }
/** * Find the protocol. */ static LSEC_SSL_METHOD* str2method(const char *method) { if (!strcmp(method, "sslv23")) return SSLv23_method(); if (!strcmp(method, "sslv3")) return SSLv3_method(); if (!strcmp(method, "tlsv1")) return TLSv1_method(); #if (OPENSSL_VERSION_NUMBER >= 0x1000100fL) if (!strcmp(method, "tlsv1_1")) return TLSv1_1_method(); if (!strcmp(method, "tlsv1_2")) return TLSv1_2_method(); #endif return NULL; }
static SSL_METHOD *ssl23_get_method(int ver) { if (ver == SSL2_VERSION) return(SSLv2_method()); else if (ver == SSL3_VERSION) return(SSLv3_method()); else if (ver == TLS1_VERSION) return(TLSv1_method()); else return(NULL); }
int init_conn(CONN *conn) { // Initialise OpenSSL SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); SSL_library_init(); // Set up the SSL context conn->ctx = SSL_CTX_new(SSLv3_method()); return 0; }
// nassl.SSL_CTX.new() static PyObject* nassl_SSL_CTX_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { nassl_SSL_CTX_Object *self; int sslVersion; SSL_CTX *sslCtx; self = (nassl_SSL_CTX_Object *)type->tp_alloc(type, 0); if (self == NULL) return NULL; self->sslCtx = NULL; self->pkeyPasswordBuf = NULL; if (!PyArg_ParseTuple(args, "I", &sslVersion)) { Py_DECREF(self); return NULL; } switch (sslVersion) { case sslv23: sslCtx = SSL_CTX_new(SSLv23_method()); break; case sslv2: sslCtx = SSL_CTX_new(SSLv2_method()); break; case sslv3: sslCtx = SSL_CTX_new(SSLv3_method()); break; case tlsv1: sslCtx = SSL_CTX_new(TLSv1_method()); break; case tlsv1_1: sslCtx = SSL_CTX_new(TLSv1_1_method()); break; case tlsv1_2: sslCtx = SSL_CTX_new(TLSv1_2_method()); break; default: PyErr_SetString(PyExc_ValueError, "Invalid value for ssl version"); Py_DECREF(self); return NULL; } if (sslCtx == NULL) { raise_OpenSSL_error(); Py_DECREF(self); return NULL; } // Add the client certificate callback SSL_CTX_set_client_cert_cb(sslCtx, client_cert_cb); self->sslCtx = sslCtx; return (PyObject *)self; }
static const SSL_METHOD * ssl23_get_method(int ver) { if (ver == SSL3_VERSION) return (SSLv3_method()); if (ver == TLS1_VERSION) return (TLSv1_method()); if (ver == TLS1_1_VERSION) return (TLSv1_1_method()); if (ver == TLS1_2_VERSION) return (TLSv1_2_method()); return (NULL); }
static const SSL_METHOD *swSSL_get_method(int method) { switch (method) { #ifndef OPENSSL_NO_SSL3_METHOD case SW_SSLv3_METHOD: return SSLv3_method(); case SW_SSLv3_SERVER_METHOD: return SSLv3_server_method(); case SW_SSLv3_CLIENT_METHOD: return SSLv3_client_method(); #endif case SW_SSLv23_SERVER_METHOD: return SSLv23_server_method(); case SW_SSLv23_CLIENT_METHOD: return SSLv23_client_method(); case SW_TLSv1_METHOD: return TLSv1_method(); case SW_TLSv1_SERVER_METHOD: return TLSv1_server_method(); case SW_TLSv1_CLIENT_METHOD: return TLSv1_client_method(); #ifdef TLS1_1_VERSION case SW_TLSv1_1_METHOD: return TLSv1_1_method(); case SW_TLSv1_1_SERVER_METHOD: return TLSv1_1_server_method(); case SW_TLSv1_1_CLIENT_METHOD: return TLSv1_1_client_method(); #endif #ifdef TLS1_2_VERSION case SW_TLSv1_2_METHOD: return TLSv1_2_method(); case SW_TLSv1_2_SERVER_METHOD: return TLSv1_2_server_method(); case SW_TLSv1_2_CLIENT_METHOD: return TLSv1_2_client_method(); #endif case SW_DTLSv1_METHOD: return DTLSv1_method(); case SW_DTLSv1_SERVER_METHOD: return DTLSv1_server_method(); case SW_DTLSv1_CLIENT_METHOD: return DTLSv1_client_method(); case SW_SSLv23_METHOD: default: return SSLv23_method(); } return SSLv23_method(); }
/*------------------------------------------------------------------------ * TCPecho - send input to ECHO service on specified host and print reply *------------------------------------------------------------------------ */ int TCPecho(const char *host, const char *portnum) { char buf[LINELEN+1]; /* buffer for one line of text */ int s, n; /* socket descriptor, read count*/ int outchars, inchars; /* characters sent and received */ SSL_CTX *ctx; SSL *ssl; X509 *server_cert; EVP_PKEY *pkey; SSL_library_init(); SSL_load_error_strings(); const SSL_METHOD *meth = SSLv3_method(); ctx = SSL_CTX_new(meth); // Consider verifying the client (or server i guess) if (!SSL_CTX_load_verify_locations(ctx, RSA_CLIENT_CA_CERT, NULL)) { fprintf(stderr, "SSL load verify locations\n"); ERR_print_errors_fp(stderr); exit(1); } SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL); SSL_CTX_set_verify_depth(ctx,1); ssl = SSL_new(ctx); s = connectsock(host, portnum); SSL_set_fd(ssl, s); SSL_connect(ssl); printf("SSL CONNECTION USING %s\n", SSL_get_cipher(ssl)); while (fgets(buf, sizeof(buf), stdin)) { buf[LINELEN] = '\0'; /* insure line null-terminated */ outchars = strlen(buf); (void) SSL_write(ssl, buf, outchars); /* read it back */ for (inchars = 0; inchars < outchars; inchars+=n ) { n = SSL_read(ssl, &buf[inchars], outchars - inchars); if (n < 0) errexit("socket read failed: %s\n", strerror(errno)); } fputs(buf, stdout); } }
static const SSL_METHOD *ssl23_get_method(int ver) { #ifndef OPENSSL_NO_SSL3 if (ver == SSL3_VERSION) return (SSLv3_method()); else #endif if (ver == TLS1_VERSION) return (TLSv1_method()); else if (ver == TLS1_1_VERSION) return (TLSv1_1_method()); else if (ver == TLS1_2_VERSION) return (TLSv1_2_method()); else return (NULL); }
static const SSL_METHOD *tls1_get_method(int ver) { if (ver == TLS_ANY_VERSION) return TLS_method(); if (ver == TLS1_2_VERSION) return TLSv1_2_method(); if (ver == TLS1_1_VERSION) return TLSv1_1_method(); if (ver == TLS1_VERSION) return TLSv1_method(); #ifndef OPENSSL_NO_SSL3 if (ver == SSL3_VERSION) return (SSLv3_method()); else #endif return NULL; }
int easyssl_setup(EASYSSL *ctx) { SSL_load_error_strings(); if(SSL_library_init() != 1) { printf("Error: SSL lib init failure\n"); return -SSL_ERR_INIT; } if((ctx->ctx = SSL_CTX_new(SSLv3_method())) == NULL) { printf("Create SSLv3 failure\n"); if((ctx->ctx = SSL_CTX_new(TLSv1_method())) == NULL) { printf("Create TLSv1 failure\n"); return -SSL_ERR_TLS; } } if(ctx->cert_auth == 0){ SSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, NULL); }else{ SSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, easyssl_ca_verify_cb); SSL_CTX_set_verify_depth(ctx->ctx, EASYSSL_DEPTH); if(SSL_CTX_load_verify_locations(ctx->ctx, ctx->cert_path, NULL) != 1) { return -SSL_ERR_CERT; } } SSL_CTX_set_default_passwd_cb_userdata(ctx->ctx, ctx->passwd); if(SSL_CTX_use_certificate_chain_file(ctx->ctx, ctx->cert_path) == 1){ printf("Load certificate success\n"); } if(SSL_CTX_use_PrivateKey_file(ctx->ctx, ctx->pkey_path, SSL_FILETYPE_PEM) == 1) { printf("Load private key success\n"); } if(SSL_CTX_check_private_key(ctx->ctx) == 1) { printf("Check private key success\n"); } if((ctx->ssl = SSL_new(ctx->ctx)) == NULL) { printf("Error: create SSL failure\n"); return -SSL_ERR_NEW; } if(SSL_set_fd(ctx->ssl, ctx->fd) != 1) { printf("Error: set SSL fd failure\n"); } if(SSL_connect(ctx->ssl) != 1) { return -SSL_ERR_CONN; } printf("Connected to SSL success\n"); return SSL_ERR_SUCCESS; }
static const SSL_METHOD *swSSL_get_method(int method) { switch (method) { case SW_SSLv3_METHOD: return SSLv3_method(); case SW_SSLv3_SERVER_METHOD: return SSLv3_server_method(); case SW_SSLv3_CLIENT_METHOD: return SSLv3_client_method(); case SW_SSLv23_SERVER_METHOD: return SSLv23_server_method(); case SW_SSLv23_CLIENT_METHOD: return SSLv23_client_method(); case SW_TLSv1_METHOD: return TLSv1_method(); case SW_TLSv1_SERVER_METHOD: return TLSv1_server_method(); case SW_TLSv1_CLIENT_METHOD: return TLSv1_client_method(); case SW_TLSv1_1_METHOD: return TLSv1_1_method(); case SW_TLSv1_1_SERVER_METHOD: return TLSv1_1_server_method(); case SW_TLSv1_1_CLIENT_METHOD: return TLSv1_1_client_method(); case SW_TLSv1_2_METHOD: return TLSv1_2_method(); case SW_TLSv1_2_SERVER_METHOD: return TLSv1_2_server_method(); case SW_TLSv1_2_CLIENT_METHOD: return TLSv1_2_client_method(); case SW_DTLSv1_METHOD: return DTLSv1_method(); case SW_DTLSv1_SERVER_METHOD: return DTLSv1_server_method(); case SW_DTLSv1_CLIENT_METHOD: return DTLSv1_client_method(); case SW_SSLv23_METHOD: default: return SSLv23_method(); } return SSLv23_method(); }
static SSL_METHOD *ssl23_get_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_method()); else #endif #ifndef OPENSSL_NO_SSL3 if (ver == SSL3_VERSION) return(SSLv3_method()); else #endif #ifndef OPENSSL_NO_TLS1 if (ver == TLS1_VERSION) return(TLSv1_method()); else #endif return(NULL); }
/* * initialize ssl methods */ static void init_ssl_methods(void) { DBG("init_methods: Entered\n"); ssl_methods[TLS_USE_SSLv2_cli - 1] = SSLv2_client_method(); ssl_methods[TLS_USE_SSLv2_srv - 1] = SSLv2_server_method(); ssl_methods[TLS_USE_SSLv2 - 1] = SSLv2_method(); ssl_methods[TLS_USE_SSLv3_cli - 1] = SSLv3_client_method(); ssl_methods[TLS_USE_SSLv3_srv - 1] = SSLv3_server_method(); ssl_methods[TLS_USE_SSLv3 - 1] = SSLv3_method(); ssl_methods[TLS_USE_TLSv1_cli - 1] = TLSv1_client_method(); ssl_methods[TLS_USE_TLSv1_srv - 1] = TLSv1_server_method(); ssl_methods[TLS_USE_TLSv1 - 1] = TLSv1_method(); ssl_methods[TLS_USE_SSLv23_cli - 1] = SSLv23_client_method(); ssl_methods[TLS_USE_SSLv23_srv - 1] = SSLv23_server_method(); ssl_methods[TLS_USE_SSLv23 - 1] = SSLv23_method(); }
ContextImpl::ContextImpl(Protocol protocol) : _protocol(protocol) , _verify(TryVerify) , _verifyDepth(1) , _x509(0) , _pkey(0) { // Create the context for the given protocol switch(_protocol) { case SSLv2: // SSLv2_method is not available everywhere (check OPENSSL_NO_SSL2) _ctx = SSL_CTX_new( SSLv23_method () ); break; case SSLv3or2: _ctx = SSL_CTX_new( SSLv23_method() ); break; default: case SSLv3: _ctx = SSL_CTX_new( SSLv3_method () ); break; case TLSv1: _ctx = SSL_CTX_new( TLSv1_method () ); break; } // Set some options #if (OPENSSL_VERSION_NUMBER < 0x00905100L) SSL_CTX_set_verify_depth(_ctx, _verifyDepth); #endif SSL_CTX_set_options(_ctx, SSL_OP_SINGLE_DH_USE); SSL_CTX_set_mode(_ctx, SSL_MODE_NO_AUTO_CHAIN); SSL_CTX_set_mode(_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE); //SSL_CTX_set_read_ahead(_ctx, 1); SSL_CTX_set_session_cache_mode(_ctx, SSL_SESS_CACHE_OFF); }
SSL_CTX *create_CTX_to_authenticate() { SSL_CTX *ctx; /* Create an SSL_CTX structure */ ctx = SSL_CTX_new(SSLv3_method()); if(ctx == NULL) { errexit("could not create SSL_CTX structure\n"); } /* Load CA certificate into SSL_CTX structure in */ /* order to authenticate the server's certificate */ if((SSL_CTX_load_verify_locations(ctx, CA_CRT, NULL)) == 0) { errexit("could not load CA certificate: %s\n", strerror(errno)); } /* Certificate must be signed by a CA */ SSL_CTX_set_verify_depth(ctx, 1); return ctx; }
int ssl_init_server(char *certfile, char *privkeyfile, int type){ const SSL_METHOD *meth; /* Create an SSL_METHOD structure * (choose an SSL/TLS protocol version) */ meth = SSLv3_method(); /* Create an SSL_CTX structure */ ctx = SSL_CTX_new(meth); if (ctx == NULL){ ERR_print_errors_fp( stderr); return -1; } /* Load the server certificate into the SSL_CTX structure */ TRACE(L_VERBOSE, "server-ssl: load the server certificate"); if (SSL_CTX_use_certificate_file(ctx, certfile, type) <= 0) { ERR_print_errors_fp( stderr); return -1; } /* Load the private-key corresponding to the server certificate */ TRACE(L_VERBOSE, "server-ssl: load the private-key"); if (SSL_CTX_use_PrivateKey_file(ctx, privkeyfile, type) <= 0) { ERR_print_errors_fp( stderr); return -1; } TRACE(L_VERBOSE, "server-ssl: check if the server certificate "\ "and private-key matches"); /* Check if the server certificate and private-key matches */ if (!SSL_CTX_check_private_key(ctx)) { ERROR(L_VERBOSE,"Private key does not match the "\ "certificate public key"); return -1; } return 0; }
mysocket::mysocket() { new_socket=INVALID_SOCKET; old_socket=INVALID_SOCKET; // title_msg=NULL; // uid=0; m_protocol=TCP; frag=send_size=recv_size=0; time_value=0; memset(&addr,0,sizeof(addr)); #ifdef USE_SSL SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); sslContext =SSL_CTX_new(SSLv3_method()); if(sslContext==NULL) fprintf(stderr,"ssl_ctx_new function error\n"); #endif #ifdef USE_UDP_E last_sequence=1; #endif }
static int tls_sc_create(lua_State *L) { tls_sc_t *ctx; const char *method_string = lua_tostring(L, 1); const SSL_METHOD *method = SSLv23_method(); if (method_string) { if (strcmp(method_string, "SSLv3_method") == 0) { method = SSLv3_method(); } else if (strcmp(method_string, "SSLv3_server_method") == 0) { method = SSLv3_server_method(); } else if (strcmp(method_string, "SSLv3_client_method") == 0) { method = SSLv3_client_method(); } else if (strcmp(method_string, "SSLv23_method") == 0) { method = SSLv23_method(); } else if (strcmp(method_string, "SSLv23_server_method") == 0) { method = SSLv23_server_method(); } else if (strcmp(method_string, "SSLv23_client_method") == 0) { method = SSLv23_client_method(); } else if (strcmp(method_string, "TLSv1_method") == 0) { method = TLSv1_method(); } else if (strcmp(method_string, "TLSv1_server_method") == 0) { method = TLSv1_server_method(); } else if (strcmp(method_string, "TLSv1_client_method") == 0) { method = TLSv1_client_method(); } else { return luaL_error(L, "method not supported: %s", method_string); } } ctx = newSC(L); ctx->ctx = SSL_CTX_new(method); /* TODO: customize Session cache */ SSL_CTX_set_session_cache_mode(ctx->ctx, SSL_SESS_CACHE_SERVER); return 1; }
DskSslContext * dsk_ssl_context_new (DskSslContextOptions *options, DskError **error) { const SSL_METHOD *method = SSLv3_method (); SSL_CTX *ctx = SSL_CTX_new (method); DskSslContext *rv = dsk_object_new (&dsk_ssl_context_class); rv->ctx = ctx; if (options->password) { rv->password = dsk_strdup (options->password); SSL_CTX_set_default_passwd_cb (ctx, set_password_cb); SSL_CTX_set_default_passwd_cb_userdata (ctx, rv); } if (options->cert_filename) { if (SSL_CTX_use_certificate_file (ctx, options->cert_filename, SSL_FILETYPE_PEM) != 1) { dsk_set_error (error, "error using certificate file %s", options->cert_filename); dsk_object_unref (rv); return NULL; } } if (options->key_filename) { if (SSL_CTX_use_PrivateKey_file (ctx, options->key_filename, SSL_FILETYPE_PEM) != 1) { dsk_set_error (error, "error using key file %s", options->key_filename); dsk_object_unref (rv); return NULL; } } return rv; }
// ./client_PFS <Client Name> <Server IP> <Server Port> <Private Key> <Certificate of this Client> <CA Cert> int main(int argc, char const *argv[]) { const char *keyName = argv[4]; const char *certName = argv[5]; const char *CACert = argv[6]; // ssl setup SSL_CTX *ctx; SSL *clieSSL, *p2pSSL; SSL_METHOD *meth; // Load encryption & hashing algorithms for the SSL program SSL_library_init(); // Load the error strings for SSL & CRYPTO APIs SSL_load_error_strings(); // Create an SSL_METHOD structure (choose an SSL/TLS protocol version) meth = SSLv3_method(); // Create an SSL_CTX structure ctx = SSL_CTX_new(meth); // Create an SSL_CTX structure ctx = SSL_CTX_new(meth); if(ctx == NULL) { ERR_print_errors_fp(stderr); exit(1); } // Load the client certificate into the SSL_CTX structure if(SSL_CTX_use_certificate_file(ctx, argv[5], SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(1); } // Load the private-key corresponding to the client certificate if(SSL_CTX_use_PrivateKey_file(ctx, argv[4], SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(1); } // Check if the client certificate and private-key matches if(!SSL_CTX_check_private_key(ctx)) { printf("Private key does not match the certificate public key\n"); exit(1); } // Load the RSA CA certificate into the SSL_CTX structure // This will allow this client to verify the server's certificate if(!SSL_CTX_load_verify_locations(ctx, argv[6], NULL)) { ERR_print_errors_fp(stderr); exit(1); } // Set flag in context to require peer (server) certificate verification SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify_depth(ctx, 1); struct sockaddr_in remoteAddr, p2pAddr; int clieSock; // for connecting to server int p2pSock; // for p2p transfer int peerSock = -1; // setup sockaddr bzero(&remoteAddr, sizeof(remoteAddr)); remoteAddr.sin_family = AF_INET; remoteAddr.sin_addr.s_addr = inet_addr(argv[2]); remoteAddr.sin_port = htons(atoi(argv[3])); bzero(&p2pAddr, sizeof(p2pAddr)); p2pAddr.sin_family = AF_INET; p2pAddr.sin_addr.s_addr = inet_addr(argv[2]); p2pAddr.sin_port = htons((int)(9500 + (argv[1][0] - 'A'))); // create socket clieSock = socket(AF_INET, SOCK_STREAM, 0); p2pSock = socket(AF_INET, SOCK_STREAM, 0); if(clieSock < 0 || p2pSock < 0){ perror("socket creation"); exit(1); } if (fcntl(p2pSock, F_SETFL, O_NDELAY)<0) { perror("error set non-block for client-p2p socket"); exit(1); } // bind socket with p2p port if(bind(p2pSock, (struct sockaddr *)&p2pAddr, sizeof(p2pAddr)) < 0){ perror("bind socket"); exit(1); } // listen on the p2p port if(listen(p2pSock, MAX) < 0){ perror("listen on the port"); exit(1); } // connect to server if(connect(clieSock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){ perror("connect to server"); exit(1); } // create ssl struct clieSSL = SSL_new(ctx); // Assign the socket into the SSL structure SSL_set_fd(clieSSL, clieSock); // Perform SSL Handshake on the SSL client if(SSL_connect(clieSSL) == 1) { printf("ssl connected to server\n"); } // set sockets to non-block mode if (fcntl(clieSock, F_SETFL, O_NDELAY) < 0) { perror("error set non-block for client-server socket"); exit(1); } // get local file info list FileList masterList; Packet localFileListPacket, sendCmdPacket, recvPacket; localFileListPacket.type = 1; sendCmdPacket.type = 0; struct stat st; getFileList(&(localFileListPacket.fileList)); strcpy(localFileListPacket.fileList.owner, argv[1]); strcpy(sendCmdPacket.fileList.owner, argv[1]); int i; for(i = 0; i < localFileListPacket.fileList.num; i++) { stat(localFileListPacket.fileList.files[i].fileName, &st); localFileListPacket.fileList.files[i].fileSize = st.st_size; strcpy(localFileListPacket.fileList.files[i].fileOwner, argv[1]); strcpy(localFileListPacket.fileList.files[i].ownerIP, argv[2]); localFileListPacket.fileList.files[i].ownerPort = 9500 + (argv[1][0] - 'A'); } printFileList(&(localFileListPacket.fileList)); // upload file list to server int nbytes; nbytes = SSL_write(clieSSL, &localFileListPacket, sizeof(Packet)); if(nbytes < 0){ perror("init upload"); exit(1); } char command[128]; while(1) { printf("Input command: ls, get, exit\n"); while(!kbhit()) { // no user input, recv from server nbytes = SSL_read(clieSSL, &recvPacket, sizeof(Packet)); if (nbytes > 0) { if (recvPacket.type == 0) { if (strcmp(recvPacket.cmd, "Client existed")==0) { // client already existed, quit printf("Client %s already registered with server, exiting...\n", argv[1]); exit(1); } } else {// recv file list printf("Received master file list from server\n"); copyFileList(&(masterList), &(recvPacket.fileList)); printFileList(&(masterList)); } printf("input command: ls, get, exit\n"); } // try to accept on p2p listen socket peerSock = accept(p2pSock, NULL, sizeof(struct sockaddr_in)); if(peerSock > 0) { // create p2p ssl p2pSSL = SSL_new(ctx); // Assign the socket into the SSL structure SSL_set_fd(p2pSSL, peerSock); // Perform SSL Handshake on the client recv cmd nbytes = SSL_accept(p2pSSL); if(nbytes == 1) { printf("Accpeted connection from remote client via SSL\n"); } sleep(1); // connection established // peer-2-peer connection handling int rtn = 1, fsize, size_per_send; char fname[128]; DataPacket recvDataPacket, sendDataPacket; FILE *file; // try to receive from remote peer nbytes = SSL_read(p2pSSL, &recvDataPacket, sizeof(DataPacket)); if (nbytes > 0) { // check cmd field printf("Receive command '%s' from remote peer\n", recvDataPacket.cmd); if (strstr(recvDataPacket.cmd, "get")) { // parse file name char* sec_arg = strstr(recvDataPacket.cmd, " "); strcpy(fname, sec_arg+1); file = fopen(fname, "rb"); if (file == NULL) { printf("Failed open file %s.\n", fname); strcpy(sendDataPacket.cmd, "File Not Found"); // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0); nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket)); if (nbytes < 0) { perror("error send cmd File Not Found to remote peer"); } rtn = 0; } strcpy(sendDataPacket.cmd, "Sending"); // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0); nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket)); if (nbytes < 0) { perror("error send cmd Sending to remote peer"); } struct stat st; stat(fname, &st); fsize = st.st_size; int repeats = (int) (fsize/MAXBUFFSIZE) + 1; for (i = 0; i < repeats; i++) { size_per_send = (MAXBUFFSIZE) < (fsize-i*MAXBUFFSIZE) ? (MAXBUFFSIZE):(fsize-i*MAXBUFFSIZE); int readed = fread(sendDataPacket.payload, sizeof(char), size_per_send, file); sendDataPacket.size = readed; // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0); nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket)); if (nbytes < 0) { perror("error send file to remote peer"); } } fclose(file); printf("File sent\n"); // receive response from reomte peer nbytes = SSL_read(p2pSSL, &recvDataPacket, sizeof(DataPacket)); if (nbytes > 0) { if (strcmp(recvDataPacket.cmd, "File received")==0) { printf("Remote peer received file %s\n", fname); } } else { perror("error recv peer file received msg"); } } else { printf("Unexpected remote command: %s\n", recvDataPacket.cmd); rtn = 0; } } else { perror("error recv in handleRemotePeerConnection"); rtn = 0; } sleep(1); close(peerSock); printf("Input command: ls, get, exit\n"); } } gets(command); // ls command if(strcmp(command, "ls") == 0) { strcpy(sendCmdPacket.cmd, command); nbytes = SSL_write(clieSSL, &sendCmdPacket, sizeof(Packet)); if(nbytes < 0) { perror("send ls command"); } } if (strcmp(command, "exit") == 0) { // deregister with server strcpy(sendCmdPacket.cmd, command); nbytes = SSL_write(clieSSL, &sendCmdPacket, sizeof(Packet)); if (nbytes < 0) { perror("send exit command"); } else { printf("Client %s exiting...\n", argv[1]); exit(1); } } if (strstr(command, "get")) { connectRemotePeer(command, &masterList, argv[1], keyName, certName, CACert); } } return 0; }
bool CSSLCOMM::ssl_connect(const char *host, int port, const char *certfile, const char *keyfile, const char* capath) { Reset(); int err; SSL_library_init(); SSL_load_error_strings(); m_pmeth = SSLv3_method(); m_pctx = SSL_CTX_new(m_pmeth); if(!m_pctx) { printf("Could not get SSL Context\n"); return false; } if(SSL_CTX_load_verify_locations(m_pctx, NULL, capath) <= 0) { printf("Failed to set CA location...\n"); ERR_print_errors_fp(stderr); return false; } if (SSL_CTX_use_certificate_file(m_pctx, certfile, SSL_FILETYPE_PEM) <= 0) { printf("Cannot use Certificate File\n"); ERR_print_errors_fp(stderr); return false; } if (SSL_CTX_use_PrivateKey_file(m_pctx, keyfile, SSL_FILETYPE_PEM) <= 0) { printf("Cannot use Private Key\n"); ERR_print_errors_fp(stderr); return false; } if (!SSL_CTX_check_private_key(m_pctx)) { printf("Private key does not match the certificate public key\n"); return false; } m_sockfd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if(m_sockfd == -1) { printf("Could not get Socket\n"); return false; } memset (&m_server_addr, '\0', sizeof(m_server_addr)); m_server_addr.sin_family = AF_INET; m_server_addr.sin_port = htons(port); m_phost_info = gethostbyname(host); if(m_phost_info) { struct in_addr *address = (struct in_addr*)m_phost_info->h_addr_list[0]; m_server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(*address)); } else { printf("Could not resolve hostname %s\n", host); return false; } err = connect(m_sockfd, (struct sockaddr*) &m_server_addr, sizeof(m_server_addr)); if(err == -1) { printf("Could not connect\n"); return false; } m_pssl = SSL_new(m_pctx); if(!m_pssl) { printf("Could not get SSL Socket\n"); return false; } SSL_set_fd(m_pssl, m_sockfd); err = SSL_connect(m_pssl); if(err == -1) { printf("Could not connect to SSL Server\n"); return false; } return true; }
int main(int argc, char *argv[]) { char *CApath = NULL, *CAfile = NULL; int badop = 0; int ret = 1; int client_auth = 0; int server_auth = 0; SSL_CTX *s_ctx = NULL; SSL_CTX *c_ctx = NULL; char *scert = TEST_SERVER_CERT; char *ccert = TEST_CLIENT_CERT; SSL_METHOD *ssl_method = SSLv23_method(); RAND_seed(rnd_seed, sizeof rnd_seed); if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (bio_stdout == NULL) bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE); argc--; argv++; while (argc >= 1) { if (sgx_strcmp(*argv, "-server_auth") == 0) server_auth = 1; else if (sgx_strcmp(*argv, "-client_auth") == 0) client_auth = 1; else if (sgx_strcmp(*argv, "-reconnect") == 0) reconnect = 1; else if (sgx_strcmp(*argv, "-stats") == 0) cache_stats = 1; else if (sgx_strcmp(*argv, "-ssl3") == 0) ssl_method = SSLv3_method(); else if (sgx_strcmp(*argv, "-ssl2") == 0) ssl_method = SSLv2_method(); else if (sgx_strcmp(*argv, "-CApath") == 0) { if (--argc < 1) goto bad; CApath = *(++argv); } else if (sgx_strcmp(*argv, "-CAfile") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); } else if (sgx_strcmp(*argv, "-cert") == 0) { if (--argc < 1) goto bad; scert = *(++argv); } else if (sgx_strcmp(*argv, "-ccert") == 0) { if (--argc < 1) goto bad; ccert = *(++argv); } else if (sgx_strcmp(*argv, "-threads") == 0) { if (--argc < 1) goto bad; thread_number = atoi(*(++argv)); if (thread_number == 0) thread_number = 1; if (thread_number > MAX_THREAD_NUMBER) thread_number = MAX_THREAD_NUMBER; } else if (sgx_strcmp(*argv, "-loops") == 0) { if (--argc < 1) goto bad; number_of_loops = atoi(*(++argv)); if (number_of_loops == 0) number_of_loops = 1; } else { fprintf(stderr, "unknown option %s\n", *argv); badop = 1; break; } argc--; argv++; } if (badop) { bad: sv_usage(); goto end; } if (cipher == NULL && OPENSSL_issetugid() == 0) cipher = getenv("SSL_CIPHER"); SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); c_ctx = SSL_CTX_new(ssl_method); s_ctx = SSL_CTX_new(ssl_method); if ((c_ctx == NULL) || (s_ctx == NULL)) { ERR_print_errors(bio_err); goto end; } SSL_CTX_set_session_cache_mode(s_ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR | SSL_SESS_CACHE_SERVER); SSL_CTX_set_session_cache_mode(c_ctx, SSL_SESS_CACHE_NO_AUTO_CLEAR | SSL_SESS_CACHE_SERVER); if (!SSL_CTX_use_certificate_file(s_ctx, scert, SSL_FILETYPE_PEM)) { ERR_print_errors(bio_err); } else if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx, scert, SSL_FILETYPE_PEM)) { ERR_print_errors(bio_err); goto end; } if (client_auth) { SSL_CTX_use_certificate_file(c_ctx, ccert, SSL_FILETYPE_PEM); SSL_CTX_use_RSAPrivateKey_file(c_ctx, ccert, SSL_FILETYPE_PEM); } if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) || (!SSL_CTX_set_default_verify_paths(s_ctx)) || (!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) || (!SSL_CTX_set_default_verify_paths(c_ctx))) { fprintf(stderr, "SSL_load_verify_locations\n"); ERR_print_errors(bio_err); goto end; } if (client_auth) { fprintf(stderr, "client authentication\n"); SSL_CTX_set_verify(s_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback); } if (server_auth) { fprintf(stderr, "server authentication\n"); SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback); } thread_setup(); do_threads(s_ctx, c_ctx); thread_cleanup(); end: if (c_ctx != NULL) { fprintf(stderr, "Client SSL_CTX stats then free it\n"); print_stats(stderr, c_ctx); SSL_CTX_free(c_ctx); } if (s_ctx != NULL) { fprintf(stderr, "Server SSL_CTX stats then free it\n"); print_stats(stderr, s_ctx); if (cache_stats) { fprintf(stderr, "-----\n"); lh_stats(SSL_CTX_sessions(s_ctx), stderr); fprintf(stderr, "-----\n"); /*- lh_node_stats(SSL_CTX_sessions(s_ctx),stderr); fprintf(stderr,"-----\n"); */ lh_node_usage_stats(SSL_CTX_sessions(s_ctx), stderr); fprintf(stderr, "-----\n"); } SSL_CTX_free(s_ctx); fprintf(stderr, "done free\n"); } exit(ret); return (0); }
int zc_socket_ssl(zcSocket *s, char *key_file, char *cert_file, zcSSLCertRequire certreq, zcSSLVer ver, char *cacerts_file, bool isclient) { char *errstr = NULL; int ret; //int err; //int sockstate; if (!isclient && (key_file == NULL || cert_file == NULL)) { ZCERROR("both key and cert files must be specified for server"); goto zc_socket_ssl_fail; } memset(s->server, '\0', sizeof(char) * X509_NAME_MAXLEN); memset(s->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN); s->peer_cert = NULL; s->ssl = NULL; s->ctx = NULL; //s->Socket = NULL; /* Init OpenSSL */ SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); (void) ERR_get_state(); ERR_clear_error(); if ((key_file && !cert_file) || (!key_file && cert_file)) { errstr = "Both the key & certificate files must be specified"; goto zc_socket_ssl_fail; } //SSL_load_error_strings(); //SSLeay_add_ssl_algorithms(); if (s->sslver == ZC_SSL_VER_TLS1) s->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ else if (ver == ZC_SSL_VER_SSL3) s->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ else if (ver == ZC_SSL_VER_SSL2) s->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ else if (ver == ZC_SSL_VER_SSL23) s->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ //s->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ if (s->ctx == NULL) { errstr = "SSL_CTX_new error"; goto zc_socket_ssl_fail; } if (certreq != ZC_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = "No root certificates specified for verification of other-side certificates."; goto zc_socket_ssl_fail; } else { ret = SSL_CTX_load_verify_locations(s->ctx, cacerts_file, NULL); if (ret != 1) { //_setSSLError(NULL, 0, __FILE__, __LINE__); ZCERROR("load verify locations error: %d", ret); goto zc_socket_ssl_fail; } } } if (key_file) { ret = SSL_CTX_use_PrivateKey_file(s->ctx, key_file, SSL_FILETYPE_PEM); if (ret != 1) { //_setSSLError(NULL, ret, __FILE__, __LINE__); ZCERROR("use privatekey file error:%d", ret); goto zc_socket_ssl_fail; } ret = SSL_CTX_use_certificate_chain_file(s->ctx, cert_file); if (ret != 1) { /* fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); */ if (ERR_peek_last_error() != 0) { //_setSSLError(NULL, ret, __FILE__, __LINE__); ZCERROR("peek last error failed:%d", ret); goto zc_socket_ssl_fail; } } } /* ssl compatibility */ SSL_CTX_set_options(s->ctx, SSL_OP_ALL); int verification_mode = SSL_VERIFY_NONE; if (certreq == ZC_SSL_CERT_OPTIONAL) verification_mode = SSL_VERIFY_PEER; else if (certreq == ZC_SSL_CERT_REQUIRED) verification_mode = (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT); SSL_CTX_set_verify(s->ctx, verification_mode, NULL); /* set verify lvl */ s->ssl = SSL_new(s->ctx); /* New ssl struct */ SSL_set_fd(s->ssl, s->fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY SSL_set_mode(s->ssl, SSL_MODE_AUTO_RETRY); #endif /* If the socket is in non-blocking mode or timeout mode, set the BIO * to non-blocking mode (blocking is the default) */ if (!s->blocked) { /* Set both the read and write BIO's to non-blocking mode */ BIO_set_nbio(SSL_get_rbio(s->ssl), 1); BIO_set_nbio(SSL_get_wbio(s->ssl), 1); } if (isclient) { SSL_set_connect_state(s->ssl); }else{ SSL_set_accept_state(s->ssl); } if (isclient) { ret = zc_socket_ssl_handshake(s); if (ret != ZC_OK) { ZCERROR("ssl handshake error: %d", ret); goto zc_socket_ssl_fail; } } return ZC_OK; zc_socket_ssl_fail: if (errstr) { ZCERROR("ssl error: %s\n", errstr); } return -1; }
static int openssl_ssl_ctx_new(lua_State*L) { const char* meth = luaL_optstring(L, 1, "TLSv1"); #if OPENSSL_VERSION_NUMBER >= 0x01000000L const #endif SSL_METHOD* method = NULL; const char* ciphers; SSL_CTX* ctx; if (strcmp(meth, "SSLv3") == 0) method = SSLv3_method(); /* SSLv3 */ else if (strcmp(meth, "SSLv3_server") == 0) method = SSLv3_server_method(); /* SSLv3 */ else if (strcmp(meth, "SSLv3_client") == 0) method = SSLv3_client_method(); /* SSLv3 */ else if (strcmp(meth, "SSLv23") == 0) method = SSLv23_method(); /* SSLv3 but can rollback to v2 */ else if (strcmp(meth, "SSLv23_server") == 0) method = SSLv23_server_method(); /* SSLv3 but can rollback to v2 */ else if (strcmp(meth, "SSLv23_client") == 0) method = SSLv23_client_method(); /* SSLv3 but can rollback to v2 */ else if (strcmp(meth, "TLSv1_1") == 0) method = TLSv1_1_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_1_server") == 0) method = TLSv1_1_server_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_1_client") == 0) method = TLSv1_1_client_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_2") == 0) method = TLSv1_2_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_2_server") == 0) method = TLSv1_2_server_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_2_client") == 0) method = TLSv1_2_client_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1") == 0) method = TLSv1_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_server") == 0) method = TLSv1_server_method(); /* TLSv1.0 */ else if (strcmp(meth, "TLSv1_client") == 0) method = TLSv1_client_method(); /* TLSv1.0 */ else if (strcmp(meth, "DTLSv1") == 0) method = DTLSv1_method(); /* DTLSv1.0 */ else if (strcmp(meth, "DTLSv1_server") == 0) method = DTLSv1_server_method(); /* DTLSv1.0 */ else if (strcmp(meth, "DTLSv1_client") == 0) method = DTLSv1_client_method(); /* DTLSv1.0 */ #ifndef OPENSSL_NO_SSL2 #if OPENSSL_VERSION_NUMBER < 0x10100000L else if (strcmp(meth, "SSLv2") == 0) method = SSLv2_method(); /* SSLv2 */ else if (strcmp(meth, "SSLv2_server") == 0) method = SSLv2_server_method(); /* SSLv2 */ else if (strcmp(meth, "SSLv2_client") == 0) method = SSLv2_client_method(); #endif #ifdef LOAD_SSL_CUSTOM LOAD_SSL_CUSTOM #endif #endif else luaL_error(L, "#1:%s not supported\n" "Maybe SSLv3 SSLv23 TLSv1 TLSv1_1 TLSv1_2 DTLSv1 [SSLv2], option followed by _client or _server\n", "default is SSLv3", meth); ciphers = luaL_optstring(L, 2, SSL_DEFAULT_CIPHER_LIST); ctx = SSL_CTX_new(method); if (!ctx) luaL_error(L, "#1:%s not supported\n" "Maybe SSLv3 SSLv23 TLSv1 TLSv1_1 TLSv1_2 DTLSv1 [SSLv2], option followed by _client or _server\n", "default is SSLv3", meth); openssl_newvalue(L, ctx); SSL_CTX_set_cipher_list(ctx, ciphers); PUSH_OBJECT(ctx, "openssl.ssl_ctx"); SSL_CTX_set_app_data(ctx, L); return 1; }
/** * Enables SSL for the given connection. * * @param connection The connection to enable SSL for. * * @return IDEVICE_E_SUCCESS on success, IDEVICE_E_INVALID_ARG when connection * is NULL or connection->ssl_data is non-NULL, or IDEVICE_E_SSL_ERROR when * SSL initialization, setup, or handshake fails. */ idevice_error_t idevice_connection_enable_ssl(idevice_connection_t connection) { if (!connection || connection->ssl_data) return IDEVICE_E_INVALID_ARG; idevice_error_t ret = IDEVICE_E_SSL_ERROR; uint32_t return_me = 0; #ifdef HAVE_OPENSSL key_data_t root_cert = { NULL, 0 }; key_data_t root_privkey = { NULL, 0 }; userpref_error_t uerr = userpref_device_record_get_keys_and_certs(connection->udid, &root_privkey, &root_cert, NULL, NULL); if (uerr != USERPREF_E_SUCCESS) { debug_info("Error %d when loading keys and certificates! %d", uerr); } /* Set up OpenSSL */ if (openssl_init_done == 0) { SSL_library_init(); openssl_init_done = 1; } BIO *ssl_bio = BIO_new(BIO_s_socket()); if (!ssl_bio) { debug_info("ERROR: Could not create SSL bio."); return ret; } BIO_set_fd(ssl_bio, (int)(long)connection->data, BIO_NOCLOSE); SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv3_method()); if (ssl_ctx == NULL) { debug_info("ERROR: Could not create SSL context."); BIO_free(ssl_bio); return ret; } BIO* membp; X509* rootCert = NULL; membp = BIO_new_mem_buf(root_cert.data, root_cert.size); PEM_read_bio_X509(membp, &rootCert, NULL, NULL); BIO_free(membp); if (SSL_CTX_use_certificate(ssl_ctx, rootCert) != 1) { debug_info("WARNING: Could not load RootCertificate"); } X509_free(rootCert); free(root_cert.data); RSA* rootPrivKey = NULL; membp = BIO_new_mem_buf(root_privkey.data, root_privkey.size); PEM_read_bio_RSAPrivateKey(membp, &rootPrivKey, NULL, NULL); BIO_free(membp); if (SSL_CTX_use_RSAPrivateKey(ssl_ctx, rootPrivKey) != 1) { debug_info("WARNING: Could not load RootPrivateKey"); } RSA_free(rootPrivKey); free(root_privkey.data); SSL *ssl = SSL_new(ssl_ctx); if (!ssl) { debug_info("ERROR: Could not create SSL object"); BIO_free(ssl_bio); SSL_CTX_free(ssl_ctx); return ret; } SSL_set_connect_state(ssl); SSL_set_verify(ssl, 0, ssl_verify_callback); SSL_set_bio(ssl, ssl_bio, ssl_bio); return_me = SSL_do_handshake(ssl); if (return_me != 1) { debug_info("ERROR in SSL_do_handshake: %s", errorstring(SSL_get_error(ssl, return_me))); BIO_free(ssl_bio); SSL_CTX_free(ssl_ctx); } else { ssl_data_t ssl_data_loc = (ssl_data_t)malloc(sizeof(struct ssl_data_private)); ssl_data_loc->session = ssl; ssl_data_loc->ctx = ssl_ctx; ssl_data_loc->bio = ssl_bio; connection->ssl_data = ssl_data_loc; ret = IDEVICE_E_SUCCESS; debug_info("SSL mode enabled, cipher: %s", SSL_get_cipher(ssl)); } #else ssl_data_t ssl_data_loc = (ssl_data_t)malloc(sizeof(struct ssl_data_private)); /* Set up GnuTLS... */ debug_info("enabling SSL mode"); errno = 0; gnutls_global_init(); gnutls_certificate_allocate_credentials(&ssl_data_loc->certificate); gnutls_certificate_client_set_retrieve_function (ssl_data_loc->certificate, internal_cert_callback); gnutls_init(&ssl_data_loc->session, GNUTLS_CLIENT); gnutls_priority_set_direct(ssl_data_loc->session, "NONE:+VERS-SSL3.0:+ANON-DH:+RSA:+AES-128-CBC:+AES-256-CBC:+SHA1:+MD5:+COMP-NULL", NULL); gnutls_credentials_set(ssl_data_loc->session, GNUTLS_CRD_CERTIFICATE, ssl_data_loc->certificate); gnutls_session_set_ptr(ssl_data_loc->session, ssl_data_loc); gnutls_x509_crt_init(&ssl_data_loc->root_cert); gnutls_x509_crt_init(&ssl_data_loc->host_cert); gnutls_x509_privkey_init(&ssl_data_loc->root_privkey); gnutls_x509_privkey_init(&ssl_data_loc->host_privkey); userpref_error_t uerr = userpref_device_record_get_keys_and_certs(connection->udid, ssl_data_loc->root_privkey, ssl_data_loc->root_cert, ssl_data_loc->host_privkey, ssl_data_loc->host_cert); if (uerr != USERPREF_E_SUCCESS) { debug_info("Error %d when loading keys and certificates! %d", uerr); } debug_info("GnuTLS step 1..."); gnutls_transport_set_ptr(ssl_data_loc->session, (gnutls_transport_ptr_t)connection); debug_info("GnuTLS step 2..."); gnutls_transport_set_push_function(ssl_data_loc->session, (gnutls_push_func) & internal_ssl_write); debug_info("GnuTLS step 3..."); gnutls_transport_set_pull_function(ssl_data_loc->session, (gnutls_pull_func) & internal_ssl_read); debug_info("GnuTLS step 4 -- now handshaking..."); if (errno) { debug_info("WARN: errno says %s before handshake!", strerror(errno)); } return_me = gnutls_handshake(ssl_data_loc->session); debug_info("GnuTLS handshake done..."); if (return_me != GNUTLS_E_SUCCESS) { internal_ssl_cleanup(ssl_data_loc); free(ssl_data_loc); debug_info("GnuTLS reported something wrong."); gnutls_perror(return_me); debug_info("oh.. errno says %s", strerror(errno)); } else { connection->ssl_data = ssl_data_loc; ret = IDEVICE_E_SUCCESS; debug_info("SSL mode enabled"); } #endif return ret; }
const SSL_METHOD *SSLv3_server_method(void) { return SSLv3_method(); }
void OpenSSLSession::Start() { if(m_bStarted) { return; } SSL_load_error_strings(); SSL_library_init(); ERR_load_BIO_strings(); //OpenSSL_add_all_algorithms(); //SSL protocol method const SSL_METHOD *meth = SSLv3_method(); //Connection context using SSL protocol method m_ConnectionCtx = SSL_CTX_new(meth); if(!m_ConnectionCtx) { ERR_print_errors_fp(stderr); return; } if(SSL_CTX_set_cipher_list(m_ConnectionCtx, (char*)m_CipherList.c_str()) == 0) { ERR_print_errors_fp(stderr); } //Send SARA certificate to remote location if(m_bLocalVerification) { /* Load our keys and certificates*/ //1. Load the certificates in to "m_ConnectionCtx" if (!SSL_CTX_use_certificate_file(m_ConnectionCtx, m_SARACertificate.c_str(), SSL_FILETYPE_PEM)) { ERR_print_errors_fp(stderr); return; } //2. Set the default password callback when loading/storing a PEM certificate with encryption SSL_CTX_set_default_passwd_cb(m_ConnectionCtx, GetPassword_CB); //3. Add the first private key found in file "m_SARACertificate" to "m_ConnectionCtx" if (!SSL_CTX_use_PrivateKey_file(m_ConnectionCtx, m_SARAPvtKeyFile.c_str(), SSL_FILETYPE_PEM)) { ERR_print_errors_fp(stderr); return; } //3_A. Check the private key is correct if(SSL_CTX_check_private_key(m_ConnectionCtx) == -1) { ERR_print_errors_fp(stderr); return; } } //Evaluation of remote certificate by SARA if(m_bRemoteVerification) { //4. Specify the location ("m_TrustedCACertificate") where CA certificates for verification purposes are located // Used to authenticate the host to which we are connected. Loading all the CAs that we trust. if(!(SSL_CTX_load_verify_locations(m_ConnectionCtx, 0, m_TrustedCACertificate.c_str()))) { ERR_print_errors_fp(stderr); return; } #if (OPENSSL_VERSION_NUMBER < 0x00905100L) SSL_CTX_set_verify_depth(m_ConnectionCtx,1); #else SSL_CTX_set_verify_depth(m_ConnectionCtx, m_iDepth); #endif //5. Set verification for host. SSL_CTX_set_verify(m_ConnectionCtx, SSL_VERIFY_PEER, OpenSSLSession::SSL_VerifyCallback); } m_bStarted = true; }
const SSL_METHOD *SSLv3_client_method(void) { return SSLv3_method(); }
/* デフォルトの証明書は 自分:/usr/local/ct/cert/tn.pem 認証局:/usr/local/ct/cert/root.pem */ int kTLSInitialize(int sessionMode,int initialmode,int timeout,char *passwd,char *rootPEM,char *myPEM, char *dhPEM,int version,int nagle,int clientveri,int tmprsa,char *enc) { BIO *bio; SSL_METHOD *meth; RSA *rsa; DH *dh=0; struct stat tmp; /* Nagleアルゴリズムの無効化フラグの保存 */ NagleFlag=nagle; if(TLSctx){ /* 強制初期化モードがある場合 */ if(initialmode){ TLSClose(NULL,0); kLogWrite(L_TLS, "%s: TLS ReInitialize", __FUNCTION__); } else return RETURN_OK; } /* パラメータの取得 */ timeout = timeout<=0 ? SESSION_TIMEOUT : timeout; TLSSessionMode = sessionMode; kLogWrite(L_TLS,"%s: Session cache mode : %s Session timeout : %d(s)",__FUNCTION__,sessionMode?"Enable":"Disable",timeout); rootPEM = (rootPEM && rootPEM[0]) ? rootPEM : ROOT_PEM; myPEM = (myPEM && myPEM[0]) ? myPEM : MY_PEM; dhPEM = (dhPEM && dhPEM[0]) ? dhPEM : DHFILE1024; strcpy(TLSPasswd,(passwd && passwd[0]) ? passwd : PASSWORD); if(lstat(rootPEM,&tmp)<0){ kLogWrite(L_ERROR, "%s: TLS Initialize file[%s] not exist", __FUNCTION__,rootPEM); return(RETURN_NG); } if(lstat(myPEM,&tmp)<0){ kLogWrite(L_ERROR, "%s: TLS Initialize file[%s] not exist", __FUNCTION__,myPEM); return(RETURN_NG); } if(lstat(dhPEM,&tmp)<0){ kLogWrite(L_ERROR, "%s: TLS Initialize file[%s] not exist", __FUNCTION__,dhPEM); return(RETURN_NG); } /* SSLライブラリの初期化 */ if(!SSL_library_init()){ kLogWrite(L_ERROR, "%s: OpenSSL initialization failed!",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_library_init OK",__FUNCTION__); /* エラーメッセージの視覚化 */ SSL_load_error_strings(); RAND_load_file("/dev/urandom", 1024); kLogWrite(L_TLS,"%s: RAND_load_file OK",__FUNCTION__); /* SSL_METHODオブジェクトの取得 */ if(version == 2) meth=SSLv2_method(); else if(version == 3) meth=SSLv3_method(); else if(version == 1) meth=TLSv1_method(); else if(version == 23) meth=SSLv23_method(); else meth=TLSv1_method(); kLogWrite(L_TLS,"%s: SSL verion [%d] 2:SSLv2 23:SSLv23 3:SSLv3 1:TLSv1",__FUNCTION__,version); /* SSL_CTXオブジェクトの取得 */ TLSctx=SSL_CTX_new(meth); kLogWrite(L_TLS,"%s: SSL_CTX_new OK",__FUNCTION__); /* SSL_CTXオブジェクトに証明書と秘密鍵を同時にロードする */ if(!(SSL_CTX_use_certificate_file(TLSctx,myPEM,SSL_FILETYPE_PEM))){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't read certificate file",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_CTX_use_certificate_file[%s] OK",__FUNCTION__,myPEM); /* パスフレーズのコールバック関数を登録する */ SSL_CTX_set_default_passwd_cb(TLSctx,password_cb); if(!(SSL_CTX_use_PrivateKey_file(TLSctx,myPEM,SSL_FILETYPE_PEM))){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't read key file",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_CTX_use_PrivateKey_file[%s] OK",__FUNCTION__,myPEM); /* SSL_CTXオブジェクトに信頼できるCA証明書をロードする */ if(!(SSL_CTX_load_verify_locations(TLSctx,rootPEM,0))){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't read CA list",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_CTX_load_verify_locations[%s] OK",__FUNCTION__,rootPEM); /* 認証コールバック関数の登録 */ /* Server Key Exchange オプションを付与する (クライアント認証を行う) */ kLogWrite(L_TLS,"%s: Server Key Exchange option : %s",__FUNCTION__,clientveri?"Enable":"Disable"); SSL_CTX_set_verify(TLSctx, clientveri?SSL_VERIFY_PEER:SSL_VERIFY_NONE,VerifyCallback); kLogWrite(L_TLS,"%s: SSL_CTX_set_verify[%s] OK",__FUNCTION__,clientveri?"PEER":"NONE"); /* 信頼できる証明書に到達するまでのチェーンの回数を指定する */ /* SSL_CTX_set_verify_depth(TLSctx,1); */ /* SSLv2を選択不可にする */ if(version != 2 && version != 23){ SSL_CTX_set_options(TLSctx,SSL_OP_NO_SSLv2); kLogWrite(L_TLS,"%s: SSL_CTX_set_options NO_SSLv2",__FUNCTION__); } /* Certificate Request オプションを付与する (一時的RSAを使う ) */ kLogWrite(L_TLS,"%s: Certificate Request option : %s",__FUNCTION__,tmprsa?"Enable":"Disable"); if(tmprsa){ /* BIOオブジェクトを使ってファイルをオープンする */ if ((bio=BIO_new_file(dhPEM,"r")) == NULL){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't open DH file",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: BIO_new_file[%s] OK",__FUNCTION__,dhPEM); /* DHパラメータを読み込む */ dh=PEM_read_bio_DHparams(bio,NULL,NULL,NULL); kLogWrite(L_TLS,"%s: PEM_read_bio_DHparams[%s] OK",__FUNCTION__,dhPEM); /* ファイルをクローズする */ BIO_free(bio); /* DHパラメータをCTXオブジェクトにロードする */ if(SSL_CTX_set_tmp_dh(TLSctx,dh)<0){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't set DH parameters",__FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_CTX_set_tmp_dh OK",__FUNCTION__); } /* 暗号スイートの選択 */ if(enc && enc[0]){ kLogWrite(L_TLS,"%s: Encrypt suit specified",__FUNCTION__); if(SSL_CTX_set_cipher_list(TLSctx,enc)) kLogWrite(L_TLS,"%s: SSL_CTX_set_cipher_list[%s] OK",__FUNCTION__,enc); else kLogWrite(L_TLS,"%s: SSL_CTX_set_cipher_list[%s] invalid",__FUNCTION__,enc); } /* RSA鍵のペアを生成する */ rsa=RSA_generate_key(512,RSA_F4,NULL,NULL); kLogWrite(L_TLS,"%s: RSA_generate_key OK",__FUNCTION__); /* RSA鍵をCTXオブジェクトにロードする */ if (!SSL_CTX_set_tmp_rsa(TLSctx,rsa)){ TLSClose(NULL,0); kLogWrite(L_ERROR, "%s: Couldn't set RSA key", __FUNCTION__); return(RETURN_NG); } kLogWrite(L_TLS,"%s: SSL_CTX_set_tmp_rsa OK",__FUNCTION__); RSA_free(rsa); /* セッションキャッシュを有効モードに設定する */ SSL_CTX_set_session_id_context(TLSctx,(void*)&TLSServerSessionIdContext, sizeof(TLSServerSessionIdContext)); kLogWrite(L_TLS,"%s: SSL_CTX_set_session_id_context OK", __FUNCTION__); /* セッション削除時のコールバック設定 */ SSL_CTX_sess_set_remove_cb(TLSctx,remove_session_cb); SSL_CTX_set_timeout(TLSctx,timeout); kLogWrite(L_TLS,"%s: Nagle algorithm : %s",__FUNCTION__,NagleFlag?"Enable":"Disable"); return(RETURN_OK); }