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