Skip to content

Instantly share code, notes, and snippets.

@0xdeadbeer
Created February 19, 2024 21:02
Show Gist options
  • Save 0xdeadbeer/fb8cff731d9838c68509b5bac1781e75 to your computer and use it in GitHub Desktop.
Save 0xdeadbeer/fb8cff731d9838c68509b5bac1781e75 to your computer and use it in GitHub Desktop.
Example OpenSSL Server + Client code to exchange data
#include <stdlib.h>
#include <unistd.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#define HOST_ADDR "localhost:4433"
#define MSG_SIZE 512
int main(void) {
BIO *out = NULL;
char buf[MSG_SIZE];
char *msg = "GET / HTTP/1.0\r\n\r\n";
size_t msg_len = strlen(msg);
fprintf(stdout, "Len of string -> %d\n", msg_len);
int left_off = 0;
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
ctx = SSL_CTX_new(TLS_client_method());
if (ctx == NULL) {
fprintf(stderr, "Failed creating SSL context\n");
return EXIT_FAILURE;
}
ssl = SSL_new(ctx);
if (ssl == NULL) {
fprintf(stderr, "Failed creating SSL object\n");
return EXIT_FAILURE;
}
out = BIO_new(BIO_s_connect());
BIO_set_conn_hostname(out, HOST_ADDR);
BIO_set_nbio(out, 1);
for (;;) {
int bytes = BIO_write(out, &(msg[left_off]), msg_len);
if (bytes <= 0) {
if (BIO_should_retry(out)) {
fprintf(stderr, "Retrying..\n");
sleep (1);
continue;
}
fprintf(stderr, "Failed writing a message through the socket\n");
return EXIT_FAILURE;
}
left_off += bytes;
msg_len -= bytes;
if (msg_len <= 0)
break;
}
fprintf(stdout, "Finished writing the whole message to the server\n");
fprintf(stdout, "Exiting..\n");
BIO_free(out);
SSL_CTX_free(ctx);
return EXIT_SUCCESS;
}
#include <stdlib.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#define HOST_PORT "4433"
#define MSG_SIZE 512
int main(void) {
SSL_library_init();
SSL_CTX *ctx = NULL;
BIO *in = NULL;
BIO *tmp = NULL;
char *buf[MSG_SIZE];
ctx = SSL_CTX_new(TLS_server_method());
if (ctx == NULL) {
fprintf(stderr, "Failed creating ctx object\n");
return EXIT_FAILURE;
}
in = BIO_new_accept(HOST_PORT);
if (in == NULL) {
fprintf(stderr, "Failed starting up service on port %s\n", HOST_PORT);
return EXIT_FAILURE;
}
fprintf(stdout, "Listening on port %s...\n", HOST_PORT);
again:
if (BIO_do_accept(in) <= 0) {
fprintf(stderr, "Failed accepting bio\n");
return EXIT_FAILURE;
}
for (;;) {
int bytes = BIO_read(in, buf, MSG_SIZE);
if (bytes == 0) {
printf("We don't got anything to read bro we're chilling\n");
tmp = BIO_pop(in);
BIO_free_all(tmp);
goto again;
}
if (bytes < 0) {
fprintf(stderr, "Failed reading from stream\n");
ERR_print_errors_fp(stderr);
return EXIT_FAILURE;
}
fflush(stdout);
fprintf(stdout, "Reading %d bytes from stream: '%s'\n", bytes, buf);
}
BIO_free(in);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment