]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
1781764da5aedc2cfcbc073a32f8bb7f159cdb4d
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <openssl/ssl.h>
16 #include <openssl/err.h>
17 #include "ssl.h"
18
19 #ifdef WINDOWS
20 # pragma comment(lib, "libcrypto.lib")
21 # pragma comment(lib, "libssl.lib")
22 # pragma comment(lib, "user32.lib")
23 # pragma comment(lib, "advapi32.lib")
24 # pragma comment(lib, "libgcc.lib")
25 # pragma comment(lib, "libmingwex.lib")
26 # pragma comment(lib, "gdi32.lib")
27 # undef MAX_DESCRIPTORS
28 # define MAX_DESCRIPTORS 10000
29 #endif
30
31 /* $ModDesc: Provides SSL support for clients */
32
33 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
34 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
35 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
36
37 /* $NoPedantic */
38
39
40 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
41
42 static bool SelfSigned = false;
43
44 char* get_error()
45 {
46         return ERR_error_string(ERR_get_error(), NULL);
47 }
48
49 static int error_callback(const char *str, size_t len, void *u);
50
51 /** Represents an SSL user's extra data
52  */
53 class issl_session
54 {
55 public:
56         SSL* sess;
57         issl_status status;
58         reference<ssl_cert> cert;
59
60         int fd;
61         bool outbound;
62         bool data_to_write;
63
64         issl_session()
65         {
66                 outbound = false;
67                 data_to_write = false;
68         }
69 };
70
71 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
72 {
73         /* XXX: This will allow self signed certificates.
74          * In the future if we want an option to not allow this,
75          * we can just return preverify_ok here, and openssl
76          * will boot off self-signed and invalid peer certs.
77          */
78         int ve = X509_STORE_CTX_get_error(ctx);
79
80         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
81
82         return 1;
83 }
84
85 class ModuleSSLOpenSSL : public Module
86 {
87         int inbufsize;
88         issl_session* sessions;
89
90         SSL_CTX* ctx;
91         SSL_CTX* clictx;
92
93         char cipher[MAXBUF];
94
95         std::string sslports;
96         bool use_sha;
97
98         ServiceProvider iohook;
99  public:
100
101         ModuleSSLOpenSSL() : iohook(this, "ssl/openssl", SERVICE_IOHOOK)
102         {
103                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
104
105                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
106                 inbufsize = ServerInstance->Config->NetBufferSize;
107
108                 /* Global SSL library initialization*/
109                 SSL_library_init();
110                 SSL_load_error_strings();
111
112                 /* Build our SSL contexts:
113                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
114                  */
115                 ctx = SSL_CTX_new( SSLv23_server_method() );
116                 clictx = SSL_CTX_new( SSLv23_client_method() );
117
118                 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
119                 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
120
121                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
122                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
123         }
124
125         void init()
126         {
127                 // Needs the flag as it ignores a plain /rehash
128                 OnModuleRehash(NULL,"ssl");
129                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO, I_OnUserConnect };
130                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
131                 ServerInstance->Modules->AddService(iohook);
132         }
133
134         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
135         {
136                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
137                 {
138                         /* Hook the user with our module */
139                         user->AddIOHook(this);
140                 }
141         }
142
143         void OnRehash(User* user)
144         {
145                 sslports.clear();
146
147                 ConfigTag* Conf = ServerInstance->Config->ConfValue("openssl");
148                 
149                 if (Conf->getBool("showports", true))
150                 {
151                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
152                         {
153                                 ListenSocket* port = ServerInstance->ports[i];
154                                 if (port->bind_tag->getString("ssl") != "openssl")
155                                         continue;
156
157                                 std::string portid = port->bind_desc;
158                                 ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
159                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
160                                         sslports.append(portid).append(";");
161                         }
162
163                         if (!sslports.empty())
164                                 sslports.erase(sslports.end() - 1);
165                 }
166         }
167
168         void OnModuleRehash(User* user, const std::string &param)
169         {
170                 if (param != "ssl")
171                         return;
172
173                 std::string keyfile;
174                 std::string certfile;
175                 std::string cafile;
176                 std::string dhfile;
177                 OnRehash(user);
178
179                 ConfigTag* conf = ServerInstance->Config->ConfValue("openssl");
180
181                 cafile   = conf->getString("cafile", "conf/ca.pem");
182                 certfile = conf->getString("certfile", "conf/cert.pem");
183                 keyfile  = conf->getString("keyfile", "conf/key.pem");
184                 dhfile   = conf->getString("dhfile", "conf/dhparams.pem");
185                 std::string hash = conf->getString("hash", "md5");
186                 if (hash != "sha1" && hash != "md5")
187                         throw ModuleException("Unknown hash type " + hash);
188                 use_sha = (hash == "sha1");
189
190
191                 /* Load our keys and certificates
192                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
193                  */
194                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
195                 {
196                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
197                         ERR_print_errors_cb(error_callback, this);
198                 }
199
200                 if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM)))
201                 {
202                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
203                         ERR_print_errors_cb(error_callback, this);
204                 }
205
206                 /* Load the CAs we trust*/
207                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
208                 {
209                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
210                         ERR_print_errors_cb(error_callback, this);
211                 }
212
213                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
214                 DH* ret;
215
216                 if (dhpfile == NULL)
217                 {
218                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
219                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
220                 }
221                 else
222                 {
223                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
224                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
225                         {
226                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
227                                 ERR_print_errors_cb(error_callback, this);
228                         }
229                 }
230
231                 fclose(dhpfile);
232         }
233
234         void On005Numeric(std::string &output)
235         {
236                 if (!sslports.empty())
237                         output.append(" SSL=" + sslports);
238         }
239
240         ~ModuleSSLOpenSSL()
241         {
242                 SSL_CTX_free(ctx);
243                 SSL_CTX_free(clictx);
244                 delete[] sessions;
245         }
246
247         void OnUserConnect(LocalUser* user)
248         {
249                 if (user->eh.GetIOHook() == this)
250                 {
251                         if (sessions[user->eh.GetFd()].sess)
252                         {
253                                 if (!sessions[user->eh.GetFd()].cert->fingerprint.empty())
254                                         user->WriteServ("NOTICE %s :*** You are connected using SSL fingerprint %s",
255                                                 user->nick.c_str(), sessions[user->eh.GetFd()].cert->fingerprint.c_str());
256                         }
257                 }
258         }
259
260         void OnCleanup(int target_type, void* item)
261         {
262                 if (target_type == TYPE_USER)
263                 {
264                         LocalUser* user = IS_LOCAL((User*)item);
265
266                         if (user && user->eh.GetIOHook() == this)
267                         {
268                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
269                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
270                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
271                         }
272                 }
273         }
274
275         Version GetVersion()
276         {
277                 return Version("Provides SSL support for clients", VF_VENDOR);
278         }
279
280         void OnRequest(Request& request)
281         {
282                 if (strcmp("GET_SSL_CERT", request.id) == 0)
283                 {
284                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
285                         int fd = req.sock->GetFd();
286                         issl_session* session = &sessions[fd];
287
288                         req.cert = session->cert;
289                 }
290         }
291
292         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
293         {
294                 int fd = user->GetFd();
295
296                 issl_session* session = &sessions[fd];
297
298                 session->fd = fd;
299                 session->sess = SSL_new(ctx);
300                 session->status = ISSL_NONE;
301                 session->outbound = false;
302                 session->cert = NULL;
303
304                 if (session->sess == NULL)
305                         return;
306
307                 if (SSL_set_fd(session->sess, fd) == 0)
308                 {
309                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
310                         return;
311                 }
312
313                 Handshake(user, session);
314         }
315
316         void OnStreamSocketConnect(StreamSocket* user)
317         {
318                 int fd = user->GetFd();
319                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
320                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
321                         return;
322
323                 issl_session* session = &sessions[fd];
324
325                 session->fd = fd;
326                 session->sess = SSL_new(clictx);
327                 session->status = ISSL_NONE;
328                 session->outbound = true;
329
330                 if (session->sess == NULL)
331                         return;
332
333                 if (SSL_set_fd(session->sess, fd) == 0)
334                 {
335                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
336                         return;
337                 }
338
339                 Handshake(user, session);
340         }
341
342         void OnStreamSocketClose(StreamSocket* user)
343         {
344                 int fd = user->GetFd();
345                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
346                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
347                         return;
348
349                 CloseSession(&sessions[fd]);
350         }
351
352         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
353         {
354                 int fd = user->GetFd();
355                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
356                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
357                         return -1;
358
359                 issl_session* session = &sessions[fd];
360
361                 if (!session->sess)
362                 {
363                         CloseSession(session);
364                         return -1;
365                 }
366
367                 if (session->status == ISSL_HANDSHAKING)
368                 {
369                         // The handshake isn't finished and it wants to read, try to finish it.
370                         if (!Handshake(user, session))
371                         {
372                                 // Couldn't resume handshake.
373                                 if (session->status == ISSL_NONE)
374                                         return -1;
375                                 return 0;
376                         }
377                 }
378
379                 // If we resumed the handshake then session->status will be ISSL_OPEN
380
381                 if (session->status == ISSL_OPEN)
382                 {
383                         char* buffer = ServerInstance->GetReadBuffer();
384                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
385                         int ret = SSL_read(session->sess, buffer, bufsiz);
386
387                         if (ret > 0)
388                         {
389                                 recvq.append(buffer, ret);
390                                 if (session->data_to_write)
391                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_SINGLE_WRITE);
392                                 return 1;
393                         }
394                         else if (ret == 0)
395                         {
396                                 // Client closed connection.
397                                 CloseSession(session);
398                                 return -1;
399                         }
400                         else if (ret < 0)
401                         {
402                                 int err = SSL_get_error(session->sess, ret);
403
404                                 if (err == SSL_ERROR_WANT_READ)
405                                 {
406                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
407                                         return 0;
408                                 }
409                                 else if (err == SSL_ERROR_WANT_WRITE)
410                                 {
411                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
412                                         return 0;
413                                 }
414                                 else
415                                 {
416                                         CloseSession(session);
417                                         return -1;
418                                 }
419                         }
420                 }
421
422                 return 0;
423         }
424
425         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
426         {
427                 int fd = user->GetFd();
428
429                 issl_session* session = &sessions[fd];
430
431                 if (!session->sess)
432                 {
433                         CloseSession(session);
434                         return -1;
435                 }
436
437                 session->data_to_write = true;
438
439                 if (session->status == ISSL_HANDSHAKING)
440                 {
441                         if (!Handshake(user, session))
442                         {
443                                 // Couldn't resume handshake.
444                                 if (session->status == ISSL_NONE)
445                                         return -1;
446                                 return 0;
447                         }
448                 }
449
450                 if (session->status == ISSL_OPEN)
451                 {
452                         int ret = SSL_write(session->sess, buffer.data(), buffer.size());
453                         if (ret == (int)buffer.length())
454                         {
455                                 session->data_to_write = false;
456                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
457                                 return 1;
458                         }
459                         else if (ret > 0)
460                         {
461                                 buffer = buffer.substr(ret);
462                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
463                                 return 0;
464                         }
465                         else if (ret == 0)
466                         {
467                                 CloseSession(session);
468                                 return -1;
469                         }
470                         else if (ret < 0)
471                         {
472                                 int err = SSL_get_error(session->sess, ret);
473
474                                 if (err == SSL_ERROR_WANT_WRITE)
475                                 {
476                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
477                                         return 0;
478                                 }
479                                 else if (err == SSL_ERROR_WANT_READ)
480                                 {
481                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
482                                         return 0;
483                                 }
484                                 else
485                                 {
486                                         CloseSession(session);
487                                         return -1;
488                                 }
489                         }
490                 }
491                 return 0;
492         }
493
494         bool Handshake(StreamSocket* user, issl_session* session)
495         {
496                 int ret;
497
498                 if (session->outbound)
499                         ret = SSL_connect(session->sess);
500                 else
501                         ret = SSL_accept(session->sess);
502
503                 if (ret < 0)
504                 {
505                         int err = SSL_get_error(session->sess, ret);
506
507                         if (err == SSL_ERROR_WANT_READ)
508                         {
509                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
510                                 session->status = ISSL_HANDSHAKING;
511                                 return true;
512                         }
513                         else if (err == SSL_ERROR_WANT_WRITE)
514                         {
515                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
516                                 session->status = ISSL_HANDSHAKING;
517                                 return true;
518                         }
519                         else
520                         {
521                                 CloseSession(session);
522                         }
523
524                         return false;
525                 }
526                 else if (ret > 0)
527                 {
528                         // Handshake complete.
529                         VerifyCertificate(session, user);
530
531                         session->status = ISSL_OPEN;
532
533                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
534
535                         return true;
536                 }
537                 else if (ret == 0)
538                 {
539                         CloseSession(session);
540                         return true;
541                 }
542
543                 return true;
544         }
545
546         void CloseSession(issl_session* session)
547         {
548                 if (session->sess)
549                 {
550                         SSL_shutdown(session->sess);
551                         SSL_free(session->sess);
552                 }
553
554                 session->sess = NULL;
555                 session->status = ISSL_NONE;
556                 errno = EIO;
557         }
558
559         void VerifyCertificate(issl_session* session, StreamSocket* user)
560         {
561                 if (!session->sess || !user)
562                         return;
563
564                 X509* cert;
565                 ssl_cert* certinfo = new ssl_cert;
566                 session->cert = certinfo;
567                 unsigned int n;
568                 unsigned char md[EVP_MAX_MD_SIZE];
569                 const EVP_MD *digest = use_sha ? EVP_sha1() : EVP_md5();
570
571                 cert = SSL_get_peer_certificate((SSL*)session->sess);
572
573                 if (!cert)
574                 {
575                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
576                         return;
577                 }
578
579                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
580
581                 if (SelfSigned)
582                 {
583                         certinfo->unknownsigner = false;
584                         certinfo->trusted = true;
585                 }
586                 else
587                 {
588                         certinfo->unknownsigner = true;
589                         certinfo->trusted = false;
590                 }
591
592                 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
593                 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
594
595                 if (!X509_digest(cert, digest, md, &n))
596                 {
597                         certinfo->error = "Out of memory generating fingerprint";
598                 }
599                 else
600                 {
601                         certinfo->fingerprint = irc::hex(md, n);
602                 }
603
604                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0))
605                 {
606                         certinfo->error = "Not activated, or expired certificate";
607                 }
608
609                 X509_free(cert);
610         }
611 };
612
613 static int error_callback(const char *str, size_t len, void *u)
614 {
615         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
616
617         //
618         // XXX: Remove this line, it causes valgrind warnings...
619         //
620         // MD_update(&m, buf, j);
621         //
622         //
623         // ... ONLY JOKING! :-)
624         //
625
626         return 0;
627 }
628
629 MODULE_INIT(ModuleSSLOpenSSL)