Hace unos días veíamos un ejemplo de un cliente web SSL con ayuda de openSSL. Ahora vamos a hacer un servidor al que se pueda conectar. Se trata sólo de una prueba de concepto, nada que podamos utilizar en el mundo real, pero está bien para ver cómo funciona la biblioteca.
Tabla de contenidos
Creando un certificado auto-firmado
Lo primero que vamos a hacer es crear una llave y un certificado para utilizarlos. Como estamos probando y no vamos a gastar dinero ni nada en un certificado, podemos crear un autofirmado, ya sabéis, los navegadores no nos detectarán como fuentes de confianza pero tendremos una conexión segura.
Para ello, nos ponemos en un directorio de confianza (vamos a colocar ahí archivos sensibles, al menos vamos a crearlos ahí… por lo menos que no sea una carpeta compartida en emule) y en nuestra consola pondremos:
$ openssl genrsa -out itsme.key 2048
Podremos hacer las claves más complejas, he puesto 2048 porque lo suelo utilizar en muchos casos, y muchas autoridades certificadoras piden claves de este tamaño.
Si queremos cifrar esta clave, o como practican algunos, el famoso y antiguo arte de encerrar datos en una cripta (encriptar), podemos utilizar el argumendo (-des3, -aes256, entre otros), aunque en este caso, nos pedirá una contraseña para empezar a trabajar, y no está bien que un servidor nos pida una contraseña, aunque también podremos manejarla con un callback… bueno, eso ya es decisión vuestra.
Una vez creada la clave, queremos crear una petición de firmado (signing request) porque alguien tiene que dar fe de que soy quien digo que soy, aunque más tarde veremos que yo mismo voy a firmarme… y por eso mismo los navegadores no se fiarán de mí.
$ openssl req -new -key itsme.key -out itsme.csr
Este comando es interactivo, y nos preguntará una serie de datos que mandaremos cuando se conecten a nosotros, para que la gente sepa dónde se está metiendo.
Si no queremos poner un password, lo podemos dejar en blanco.
Tras la creación de la petición de firmado, sólo nos queda firmar, y listo, para ello
$ openssl x509 -req -days 365 -in itsme.csr -signkey itsme.key -out itsme.crt
El parámetro days lo podemos hacer más grande o más pequeño, según decidamos la validez de nuestra firma, podemos poner 1000 años y nadie nos dirá nada, aunque sería un milagro que nuestros datos sobrevivieran tanto.
Ya tenemos nuestros archivos itsme.key e itsme.crt para trabajar con ellos. Podéis visitar esta web para más info sobre creación de certificados.
Creando nuestro servidor
Es sólo una prueba, le pidamos lo que le pidamos, lo hagamos bien o lo hagamos mal, siempre nos devolverá la misma página (tengo en el horno un pequeño proyecto algo más completo al que ya le integraré también SSL).
El caso es que hacemos la conexión TCP, el handshake SSL, leemos la petición del usuario y enviamos una respuesta. Tal vez tenga un montón de bugs en el servidor, no es concurrente y su respuesta es fija, pero para el caso nos vale.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | /** ************************************************************* * @file servtcp.c * @brief Example web server using SSL connection. * It will always send the same web. It's just a test * to stablish a secure connection and send some data * This server cannot attend simultaneous connections * * @author Gaspar Fernández <blakeyed@totaki.com> * @version 0.1 * @date 18 apr 2015 * * To compile * $ gcc -o serverssl serverssl.c -lcrypto -lssl * *************************************************************/ #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <stdio.h> #include <netinet/in.h> #include <resolv.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <openssl/rand.h> #include <openssl/ssl.h> #include <openssl/err.h> /** Port */ #define PORT 1430 #define BUFFERSIZE 16384 #define CRLF "\r\n" #define RESPONSE "HTTP/1.1 200 OK" CRLF \ "Content-Type: text/html charset=utf-8" CRLF \ "Server: ServerTest" CRLF \ CRLF \ "<html><head><title>Server Test</title></head><body>This is just a test</body></html>" CRLF #define CERTFILE "sslserverchain.pem" #define KEYFILE "sslserver.key" /** sslc handles SSL and SSL_CTX and socket. The same as myssl.c */ typedef struct { /** socket handler */ int skt; /** client socket handler */ int client_skt; /** error, if any */ int err; /** SSL handler */ SSL* ssl; /** SSL Context */ SSL_CTX* ctx; } Sslc; /** * * @param h Our struct * @param port Por to listen to * * @return (0 if OK, else fail) */ int TCP_Server(Sslc* h, int port); /** * Uses select to test if there is anything waiting to be read. * The same function as myssl.c * * @param h Our structure. Only the socket will be used * @param timeout Timeout before giving up * * @return (0 timeout, 1 data waiting, <0 fail) */ int TCP_select(Sslc* h, double timeout); /** * Initializes SSL connection and creates the SSL Context * * @param h Our struct to store everything * * @return 0 if OK */ int SSL_init(Sslc* h); /** * Loads certificates in the context. * * @param h Our struct to store everything * @param cert PEM certificate file or chain (we can store several * certificates in one file, just concatenating them. * @param key Encryption key * * @return 0 if OK */ int SSL_load_certificates(Sslc* h, char* cert, char* key); /** * Accepts client and start dialog * * @param h Our struct * * @return 0 if OK */ int TCP_acceptClient(Sslc* h); /** * Just a test, replace SSL_clientDialog() in acceptClient() by * TCP_clientDialog() to create an insecure web server. * * @param h Our struct * * @return 0 if OK */ int TCP_clientDialog(Sslc* h); /** * It's everything we're here for. SSL dialog with the clients * * @param h Our struct * * @return 0 if OK */ int SSL_clientDialog(Sslc* h); /** * Prints a tragic error and exit * * @param msg Error text * * @return void */ void panic(char* msg); /** * ASCII clock to wait for clients * * @param loop Just a number, when it changes, it draws a new character. * If loop == 0, restarts * * @return void */ void aclock(int loop); int main(int argv, char** argc){ Sslc sslc; int activated=1; int loop=0; int sel_res; if (SSL_init(&sslc)<0) panic ("Couldn't initialize SSL"); if (SSL_load_certificates(&sslc, CERTFILE, KEYFILE)) panic ("Couln't load certificates"); if (TCP_Server(&sslc, PORT)<0) panic ("Couldn't make a TCP Connection"); while(activated) { aclock(loop); sel_res =TCP_select(&sslc, 1); if (sel_res<0) panic("Failed on selec()"); else if (sel_res==1) { if (TCP_acceptClient(&sslc)<0) panic ("Tragic error accepting client"); loop = -1; /* Reset clock */ } loop++; } /* Wont' reach this point as the server never ends... */ close(sslc.skt); return 0; } int TCP_Server(Sslc* h, int port) { struct sockaddr_in my_addr; h->skt = socket(AF_INET, SOCK_STREAM, 0); if(h->skt < 0) return -1; my_addr.sin_family = AF_INET ; my_addr.sin_port = htons(port); my_addr.sin_addr.s_addr = INADDR_ANY ; if( bind( h->skt, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ) return -2; if(listen( h->skt, 10) == -1 ) return -3; return 0; } int TCP_select(Sslc* h, double timeout) { fd_set fds; FD_ZERO(&fds); FD_SET(h->skt, &fds); fd_set *rset=&fds; fd_set *wset=NULL; struct timeval tv; tv.tv_sec = (int)(timeout); tv.tv_usec = (int)((timeout - (int)(timeout)) * 1000000.0); int ret = select(h->skt+1, rset, wset, NULL, &tv); return ret; } int TCP_acceptClient(Sslc* h) { struct sockaddr_in client_addr; socklen_t size_addr = sizeof(struct sockaddr_in); if ((h->client_skt = accept( h->skt, (struct sockaddr*)&client_addr, &size_addr))!= -1) { printf("\nNew client connection from %s:%d\n", inet_ntoa(client_addr.sin_addr), client_addr.sin_port); int r = SSL_clientDialog(h); if (r<0) { printf ("There was a problem with this client connection\n"); ERR_print_errors_fp(stderr); } close(h->client_skt); } /* Returns 0 to avoid tragic fails, just display on screen*/ return -6; } int TCP_clientDialog(Sslc* h) { char buffer[BUFFERSIZE]; int bytecount; memset(buffer, 0, BUFFERSIZE); if((bytecount = recv(h->client_skt, buffer, BUFFERSIZE, 0))== -1) return -7; if (send(h->client_skt, RESPONSE, strlen(RESPONSE), 0)<0) return -8; return 0; } int SSL_clientDialog(Sslc* h) { char buffer[BUFFERSIZE]; int bytecount; h->ssl = SSL_new(h->ctx); if (h->ssl == NULL) return -11; /* SSL_set_options(h->ssl, SSL_OP_ALL ); */ if (SSL_set_fd(h->ssl, h->client_skt) == 0) return -12; /* Accept SSL connection and handshake */ if (SSL_accept(h->ssl) < 1) return -13; memset(buffer, 0, BUFFERSIZE); if((bytecount = SSL_read(h->ssl, buffer, BUFFERSIZE)) < 1) return -7; if (SSL_write(h->ssl, RESPONSE, strlen(RESPONSE))< 1) return -8; SSL_free(h->ssl); /* free mem */ return 0; } int SSL_init(Sslc* h) { SSL_library_init(); /* not reentrant! */ SSL_load_error_strings(); OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */ /* We can try SSLv23_server_method() to try several methods, starting from the more secure*/ h->ctx = SSL_CTX_new(TLSv1_2_server_method()); if (h->ctx == NULL) return -4; return 0; } int SSL_load_certificates(Sslc* h, char* cert, char* key) { if ( SSL_CTX_use_certificate_chain_file(h->ctx, cert) < 1 ) return -8; /* set the private key */ if ( SSL_CTX_use_PrivateKey_file(h->ctx, key, SSL_FILETYPE_PEM) <= 0 ) return -9; /* verify private key */ if ( !SSL_CTX_check_private_key(h->ctx) ) { printf("Private key doesn't match the public certificate\n"); return -10; } return 0; } void aclock(int loop) { if (loop==0) printf("[SERVER] Waiting for connections "); printf("\033[1D"); /* ANSI code to go back 2 characters */ switch (loop%4) { case 0: printf("|"); break; case 1: printf("/"); break; case 2: printf("-"); break; case 3: printf("\"); break; default: /* Nothing here */ break; } fflush(stdout); /* Update screen */ } void panic(char *msg) { fprintf (stderr, "Error: %s (errno %d, %s)\n", msg, errno, strerror(errno)); /* Print SSL errors */ ERR_print_errors_fp(stderr); exit(2); } |
Algunas notas finales
Puede que no tengamos sólo un certificado (puede que tengamos varios certificados intermedios), y debamos incluirlos todos en nuestra conexión segura. Gracias a que utilizamos SSL_CTX_use_certificate_chain_file() para cargar el certificado, podemos meter varios certificados concatenados, del tipo:
$ cat certificado1.pem certificado2.pem certificado3.pem > cadena_certificados.pem
Los archivos de certificado y clave pueden ser especificados en la parte superior del archivo, con las constantes CERTFILE y KEYFILE.
El método con el que trabajaremos será TLSv1_2_server_method(), aunque podemos utilizar cualquier otra versión de TLS, incluso SSLv3 (será insegura, pero para fines académicos vale, o para ver si hay servidores que aún pueden conectarte con este método… ¡¡no he dicho nada!!). Tenemos también otro método que es SSLv23_server_method(), que actúa igual que el método cliente compañero. OpenSSL no suele venir compilado ya con soporte SSLv2, y el SSLv3 está prohibido hasta la saciedad, pero si queremos SSLv23_server_method() puede no utilizar ningún SSLvX, y tirar directamente para los TLS si definimos SSL_set_options(SSL*, long options). La opción sería SSL_OP_NO_SSLv3 (es una constante, podemos ver más en el manual de SSL_CTX_set_options).
Foto principal: zoetnet (Flickr CC-by)
Foto cripta: Ismael Alonso (Flickr CC-by)
Pingback: Servidor web seguro (HTTPS) en C usando openSSL (pruebas) | PlanetaLibre /
Pingback: El ataque de los comerciales zombies. Terror en estado puro – Mi visión del mundo /