]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
MetaData rework
[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-2009 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 "transport.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 /* $ModDep: transport.h */
33 /* $NoPedantic */
34 /* $CopyInstall: conf/key.pem $(CONPATH) */
35 /* $CopyInstall: conf/cert.pem $(CONPATH) */
36
37
38 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
39 enum issl_io_status { ISSL_WRITE, ISSL_READ };
40
41 static bool SelfSigned = false;
42
43 bool isin(const std::string &host, int port, const std::vector<std::string> &portlist)
44 {
45         if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
46                 return true;
47
48         if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
49                 return true;
50
51         return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
52 }
53
54 char* get_error()
55 {
56         return ERR_error_string(ERR_get_error(), NULL);
57 }
58
59 static int error_callback(const char *str, size_t len, void *u);
60
61 /** Represents an SSL user's extra data
62  */
63 class issl_session : public classbase
64 {
65 public:
66         SSL* sess;
67         issl_status status;
68         issl_io_status rstat;
69         issl_io_status wstat;
70
71         unsigned int inbufoffset;
72         char* inbuf;                    // Buffer OpenSSL reads into.
73         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
74         int fd;
75         bool outbound;
76
77         issl_session()
78         {
79                 outbound = false;
80                 rstat = ISSL_READ;
81                 wstat = ISSL_WRITE;
82         }
83 };
84
85 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
86 {
87         /* XXX: This will allow self signed certificates.
88          * In the future if we want an option to not allow this,
89          * we can just return preverify_ok here, and openssl
90          * will boot off self-signed and invalid peer certs.
91          */
92         int ve = X509_STORE_CTX_get_error(ctx);
93
94         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
95
96         return 1;
97 }
98
99 class ModuleSSLOpenSSL : public Module
100 {
101         std::vector<std::string> listenports;
102
103         int inbufsize;
104         issl_session* sessions;
105
106         SSL_CTX* ctx;
107         SSL_CTX* clictx;
108
109         char* dummy;
110         char cipher[MAXBUF];
111
112         std::string keyfile;
113         std::string certfile;
114         std::string cafile;
115         // std::string crlfile;
116         std::string dhfile;
117         std::string sslports;
118
119         int clientactive;
120
121  public:
122
123         InspIRCd* PublicInstance;
124
125         ModuleSSLOpenSSL(InspIRCd* Me)
126         : Module(Me), PublicInstance(Me)
127         {
128                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
129
130                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
131
132                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
133                 inbufsize = ServerInstance->Config->NetBufferSize;
134
135                 /* Global SSL library initialization*/
136                 SSL_library_init();
137                 SSL_load_error_strings();
138
139                 /* Build our SSL contexts:
140                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
141                  */
142                 ctx = SSL_CTX_new( SSLv23_server_method() );
143                 clictx = SSL_CTX_new( SSLv23_client_method() );
144
145                 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
146                 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
147
148                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
149                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
150
151                 // Needs the flag as it ignores a plain /rehash
152                 OnModuleRehash(NULL,"ssl");
153                 Implementation eventlist[] = { I_OnRawSocketConnect, I_OnRawSocketAccept,
154                         I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup, I_On005Numeric,
155                         I_OnBufferFlushed, I_OnRequest, I_OnUnloadModule, I_OnRehash, I_OnModuleRehash,
156                         I_OnPostConnect, I_OnHookUserIO };
157                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
158         }
159
160         virtual void OnHookUserIO(User* user)
161         {
162                 if (!user->GetIOHook() && isin(user->GetServerIP(),user->GetServerPort(), listenports))
163                 {
164                         /* Hook the user with our module */
165                         user->AddIOHook(this);
166                 }
167         }
168
169         virtual void OnRehash(User* user)
170         {
171                 ConfigReader Conf(ServerInstance);
172
173                 listenports.clear();
174                 clientactive = 0;
175                 sslports.clear();
176
177                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
178                 {
179                         // For each <bind> tag
180                         std::string x = Conf.ReadValue("bind", "type", index);
181                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
182                         {
183                                 // Get the port we're meant to be listening on with SSL
184                                 std::string port = Conf.ReadValue("bind", "port", index);
185                                 std::string addr = Conf.ReadValue("bind", "address", index);
186
187                                 if (!addr.empty())
188                                 {
189                                         // normalize address, important for IPv6
190                                         int portint = 0;
191                                         irc::sockets::sockaddrs bin;
192                                         if (irc::sockets::aptosa(addr.c_str(), portint, &bin))
193                                                 irc::sockets::satoap(&bin, addr, portint);
194                                 }
195
196                                 irc::portparser portrange(port, false);
197                                 long portno = -1;
198                                 while ((portno = portrange.GetToken()))
199                                 {
200                                         clientactive++;
201                                         try
202                                         {
203                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
204
205                                                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
206                                                         if ((ServerInstance->ports[i]->GetPort() == portno) && (ServerInstance->ports[i]->GetIP() == addr))
207                                                                 ServerInstance->ports[i]->SetDescription("ssl");
208                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %ld", portno);
209
210                                                 if (addr != "127.0.0.1")
211                                                         sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
212                                         }
213                                         catch (ModuleException &e)
214                                         {
215                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %ld: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason());
216                                         }
217                                 }
218                         }
219                 }
220
221                 if (!sslports.empty())
222                         sslports.erase(sslports.end() - 1);
223         }
224
225         virtual void OnModuleRehash(User* user, const std::string &param)
226         {
227                 if (param != "ssl")
228                         return;
229
230                 OnRehash(user);
231
232                 ConfigReader Conf(ServerInstance);
233
234                 std::string confdir(ServerInstance->ConfigFileName);
235                 // +1 so we the path ends with a /
236                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
237
238                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
239                 certfile = Conf.ReadValue("openssl", "certfile", 0);
240                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
241                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
242
243                 // Set all the default values needed.
244                 if (cafile.empty())
245                         cafile = "ca.pem";
246
247                 if (certfile.empty())
248                         certfile = "cert.pem";
249
250                 if (keyfile.empty())
251                         keyfile = "key.pem";
252
253                 if (dhfile.empty())
254                         dhfile = "dhparams.pem";
255
256                 // Prepend relative paths with the path to the config directory.
257                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
258                         cafile = confdir + cafile;
259
260                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
261                         certfile = confdir + certfile;
262
263                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
264                         keyfile = confdir + keyfile;
265
266                 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
267                         dhfile = confdir + dhfile;
268
269                 /* Load our keys and certificates
270                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
271                  */
272                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
273                 {
274                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
275                         ERR_print_errors_cb(error_callback, this);
276                 }
277
278                 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)))
279                 {
280                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
281                         ERR_print_errors_cb(error_callback, this);
282                 }
283
284                 /* Load the CAs we trust*/
285                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
286                 {
287                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
288                         ERR_print_errors_cb(error_callback, this);
289                 }
290
291                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
292                 DH* ret;
293
294                 if (dhpfile == NULL)
295                 {
296                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
297                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
298                 }
299                 else
300                 {
301                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
302                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
303                         {
304                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
305                                 ERR_print_errors_cb(error_callback, this);
306                         }
307                 }
308
309                 fclose(dhpfile);
310         }
311
312         virtual void On005Numeric(std::string &output)
313         {
314                 output.append(" SSL=" + sslports);
315         }
316
317         virtual ~ModuleSSLOpenSSL()
318         {
319                 SSL_CTX_free(ctx);
320                 SSL_CTX_free(clictx);
321                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
322                 delete[] sessions;
323         }
324
325         virtual void OnCleanup(int target_type, void* item)
326         {
327                 if (target_type == TYPE_USER)
328                 {
329                         User* user = (User*)item;
330
331                         if (user->GetIOHook() == this)
332                         {
333                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
334                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
335                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
336                                 user->DelIOHook();
337                         }
338                         if (user->GetExt("ssl_cert", dummy))
339                         {
340                                 ssl_cert* tofree;
341                                 user->GetExt("ssl_cert", tofree);
342                                 delete tofree;
343                                 user->Shrink("ssl_cert");
344                         }
345                 }
346         }
347
348         virtual void OnUnloadModule(Module* mod, const std::string &name)
349         {
350                 if (mod == this)
351                 {
352                         for(unsigned int i = 0; i < listenports.size(); i++)
353                         {
354                                 for (size_t j = 0; j < ServerInstance->ports.size(); j++)
355                                         if (listenports[i] == (ServerInstance->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->ports[j]->GetPort())))
356                                                 ServerInstance->ports[j]->SetDescription("plaintext");
357                         }
358                 }
359         }
360
361         virtual Version GetVersion()
362         {
363                 return Version("$Id$", VF_VENDOR, API_VERSION);
364         }
365
366
367         virtual const char* OnRequest(Request* request)
368         {
369                 ISHRequest* ISR = (ISHRequest*)request;
370                 if (strcmp("IS_NAME", request->GetId()) == 0)
371                 {
372                         return "openssl";
373                 }
374                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
375                 {
376                         const char* ret = "OK";
377                         try
378                         {
379                                 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
380                         }
381                         catch (ModuleException &e)
382                         {
383                                 return NULL;
384                         }
385
386                         return ret;
387                 }
388                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
389                 {
390                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
391                 }
392                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
393                 {
394                         if (ISR->Sock->GetFd() < 0)
395                                 return "OK";
396
397                         issl_session* session = &sessions[ISR->Sock->GetFd()];
398                         return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
399                 }
400                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
401                 {
402                         issl_session* session = &sessions[ISR->Sock->GetFd()];
403                         if (session->sess)
404                         {
405                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
406                                 return "OK";
407                         }
408                 }
409                 else if (strcmp("GET_FP", request->GetId()) == 0)
410                 {
411                         if (ISR->Sock->GetFd() > -1)
412                         {
413                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
414                                 if (session->sess)
415                                 {
416                                         Extensible* ext = ISR->Sock;
417                                         ssl_cert* certinfo;
418                                         if (ext->GetExt("ssl_cert",certinfo))
419                                                 return certinfo->GetFingerprint().c_str();
420                                 }
421                         }
422                 }
423                 return NULL;
424         }
425
426
427         virtual void OnRawSocketAccept(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
428         {
429                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
430                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
431                         return;
432
433                 issl_session* session = &sessions[fd];
434
435                 session->fd = fd;
436                 session->inbuf = new char[inbufsize];
437                 session->inbufoffset = 0;
438                 session->sess = SSL_new(ctx);
439                 session->status = ISSL_NONE;
440                 session->outbound = false;
441
442                 if (session->sess == NULL)
443                         return;
444
445                 if (SSL_set_fd(session->sess, fd) == 0)
446                 {
447                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
448                         return;
449                 }
450
451                 Handshake(session);
452         }
453
454         virtual void OnRawSocketConnect(int fd)
455         {
456                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
457                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
458                         return;
459
460                 issl_session* session = &sessions[fd];
461
462                 session->fd = fd;
463                 session->inbuf = new char[inbufsize];
464                 session->inbufoffset = 0;
465                 session->sess = SSL_new(clictx);
466                 session->status = ISSL_NONE;
467                 session->outbound = true;
468
469                 if (session->sess == NULL)
470                         return;
471
472                 if (SSL_set_fd(session->sess, fd) == 0)
473                 {
474                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
475                         return;
476                 }
477
478                 Handshake(session);
479         }
480
481         virtual void OnRawSocketClose(int fd)
482         {
483                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
484                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
485                         return;
486
487                 CloseSession(&sessions[fd]);
488
489                 EventHandler* user = ServerInstance->SE->GetRef(fd);
490
491                 if ((user) && (user->GetExt("ssl_cert", dummy)))
492                 {
493                         ssl_cert* tofree;
494                         user->GetExt("ssl_cert", tofree);
495                         delete tofree;
496                         user->Shrink("ssl_cert");
497                 }
498         }
499
500         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
501         {
502                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
503                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
504                         return 0;
505
506                 issl_session* session = &sessions[fd];
507
508                 if (!session->sess)
509                 {
510                         readresult = 0;
511                         CloseSession(session);
512                         return 1;
513                 }
514
515                 if (session->status == ISSL_HANDSHAKING)
516                 {
517                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
518                         {
519                                 // The handshake isn't finished and it wants to read, try to finish it.
520                                 if (!Handshake(session))
521                                 {
522                                         // Couldn't resume handshake.
523                                         errno = session->status == ISSL_NONE ? EIO : EAGAIN;
524                                         return -1;
525                                 }
526                         }
527                         else
528                         {
529                                 errno = EAGAIN;
530                                 return -1;
531                         }
532                 }
533
534                 // If we resumed the handshake then session->status will be ISSL_OPEN
535
536                 if (session->status == ISSL_OPEN)
537                 {
538                         if (session->wstat == ISSL_READ)
539                         {
540                                 if(DoWrite(session) == 0)
541                                         return 0;
542                         }
543
544                         if (session->rstat == ISSL_READ)
545                         {
546                                 int ret = DoRead(session);
547
548                                 if (ret > 0)
549                                 {
550                                         if (count <= session->inbufoffset)
551                                         {
552                                                 memcpy(buffer, session->inbuf, count);
553                                                 // Move the stuff left in inbuf to the beginning of it
554                                                 memmove(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
555                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
556                                                 session->inbufoffset -= count;
557                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
558                                                 readresult = count;
559                                         }
560                                         else
561                                         {
562                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
563                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
564
565                                                 readresult = session->inbufoffset;
566                                                 // Zero the offset, as there's nothing there..
567                                                 session->inbufoffset = 0;
568                                         }
569                                         return 1;
570                                 }
571                                 return ret;
572                         }
573                 }
574
575                 return -1;
576         }
577
578         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
579         {
580                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
581                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
582                         return 0;
583
584                 errno = EAGAIN;
585                 issl_session* session = &sessions[fd];
586
587                 if (!session->sess)
588                 {
589                         CloseSession(session);
590                         return -1;
591                 }
592
593                 session->outbuf.append(buffer, count);
594                 MakePollWrite(session);
595
596                 if (session->status == ISSL_HANDSHAKING)
597                 {
598                         // The handshake isn't finished, try to finish it.
599                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
600                         {
601                                 if (!Handshake(session))
602                                 {
603                                         // Couldn't resume handshake.
604                                         errno = session->status == ISSL_NONE ? EIO : EAGAIN;
605                                         return -1;
606                                 }
607                         }
608                 }
609
610                 if (session->status == ISSL_OPEN)
611                 {
612                         if (session->rstat == ISSL_WRITE)
613                         {
614                                 DoRead(session);
615                         }
616
617                         if (session->wstat == ISSL_WRITE)
618                         {
619                                 return DoWrite(session);
620                         }
621                 }
622
623                 return 1;
624         }
625
626         int DoWrite(issl_session* session)
627         {
628                 if (!session->outbuf.size())
629                         return -1;
630
631                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
632
633                 if (ret == 0)
634                 {
635                         CloseSession(session);
636                         return 0;
637                 }
638                 else if (ret < 0)
639                 {
640                         int err = SSL_get_error(session->sess, ret);
641
642                         if (err == SSL_ERROR_WANT_WRITE)
643                         {
644                                 session->wstat = ISSL_WRITE;
645                                 return -1;
646                         }
647                         else if (err == SSL_ERROR_WANT_READ)
648                         {
649                                 session->wstat = ISSL_READ;
650                                 return -1;
651                         }
652                         else
653                         {
654                                 CloseSession(session);
655                                 return 0;
656                         }
657                 }
658                 else
659                 {
660                         session->outbuf = session->outbuf.substr(ret);
661                         return ret;
662                 }
663         }
664
665         int DoRead(issl_session* session)
666         {
667                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
668                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
669
670                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
671
672                 if (ret == 0)
673                 {
674                         // Client closed connection.
675                         CloseSession(session);
676                         return 0;
677                 }
678                 else if (ret < 0)
679                 {
680                         int err = SSL_get_error(session->sess, ret);
681
682                         if (err == SSL_ERROR_WANT_READ)
683                         {
684                                 session->rstat = ISSL_READ;
685                                 return -1;
686                         }
687                         else if (err == SSL_ERROR_WANT_WRITE)
688                         {
689                                 session->rstat = ISSL_WRITE;
690                                 MakePollWrite(session);
691                                 return -1;
692                         }
693                         else
694                         {
695                                 CloseSession(session);
696                                 return 0;
697                         }
698                 }
699                 else
700                 {
701                         // Read successfully 'ret' bytes into inbuf + inbufoffset
702                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
703                         // 'buffer' is 'count' long
704
705                         session->inbufoffset += ret;
706
707                         return ret;
708                 }
709         }
710
711         bool Handshake(issl_session* session)
712         {
713                 int ret;
714
715                 if (session->outbound)
716                         ret = SSL_connect(session->sess);
717                 else
718                         ret = SSL_accept(session->sess);
719
720                 if (ret < 0)
721                 {
722                         int err = SSL_get_error(session->sess, ret);
723
724                         if (err == SSL_ERROR_WANT_READ)
725                         {
726                                 session->rstat = ISSL_READ;
727                                 session->status = ISSL_HANDSHAKING;
728                                 return true;
729                         }
730                         else if (err == SSL_ERROR_WANT_WRITE)
731                         {
732                                 session->wstat = ISSL_WRITE;
733                                 session->status = ISSL_HANDSHAKING;
734                                 MakePollWrite(session);
735                                 return true;
736                         }
737                         else
738                         {
739                                 CloseSession(session);
740                         }
741
742                         return false;
743                 }
744                 else if (ret > 0)
745                 {
746                         // Handshake complete.
747                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
748                         EventHandler *u = ServerInstance->SE->GetRef(session->fd);
749                         if (u)
750                         {
751                                 if (!u->GetExt("ssl", dummy))
752                                         u->Extend("ssl", "ON");
753                         }
754
755                         session->status = ISSL_OPEN;
756
757                         MakePollWrite(session);
758
759                         return true;
760                 }
761                 else if (ret == 0)
762                 {
763                         CloseSession(session);
764                         return true;
765                 }
766
767                 return true;
768         }
769
770         virtual void OnPostConnect(User* user)
771         {
772                 // This occurs AFTER OnUserConnect so we can be sure the
773                 // protocol module has propagated the NICK message.
774                 if ((user->GetIOHook() == this) && (IS_LOCAL(user)))
775                 {
776                         ssl_cert* certdata = VerifyCertificate(&sessions[user->GetFd()], user);
777                         if (sessions[user->GetFd()].sess)
778                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->GetFd()].sess));
779
780                         ServerInstance->PI->SendMetaData(user, "ssl", "ON");
781                         if (certdata)
782                                 ServerInstance->PI->SendMetaData(user, "ssl_cert", certdata->GetMetaLine().c_str());
783                 }
784         }
785
786         void MakePollWrite(issl_session* session)
787         {
788                 //OnRawSocketWrite(session->fd, NULL, 0);
789                 EventHandler* eh = ServerInstance->SE->GetRef(session->fd);
790                 if (eh)
791                 {
792                         ServerInstance->SE->WantWrite(eh);
793                 }
794         }
795
796         virtual void OnBufferFlushed(User* user)
797         {
798                 if (user->GetIOHook() == this)
799                 {
800                         issl_session* session = &sessions[user->GetFd()];
801                         if (session && session->outbuf.size())
802                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
803                 }
804         }
805
806         void CloseSession(issl_session* session)
807         {
808                 if (session->sess)
809                 {
810                         SSL_shutdown(session->sess);
811                         SSL_free(session->sess);
812                 }
813
814                 if (session->inbuf)
815                 {
816                         delete[] session->inbuf;
817                 }
818
819                 session->outbuf.clear();
820                 session->inbuf = NULL;
821                 session->sess = NULL;
822                 session->status = ISSL_NONE;
823                 errno = EIO;
824         }
825
826         ssl_cert* VerifyCertificate(issl_session* session, Extensible* user)
827         {
828                 if (!session->sess || !user)
829                         return NULL;
830
831                 X509* cert;
832                 ssl_cert* certinfo = new ssl_cert;
833                 unsigned int n;
834                 unsigned char md[EVP_MAX_MD_SIZE];
835                 const EVP_MD *digest = EVP_md5();
836
837                 user->Extend("ssl_cert",certinfo);
838
839                 cert = SSL_get_peer_certificate((SSL*)session->sess);
840
841                 if (!cert)
842                 {
843                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
844                         return certinfo;
845                 }
846
847                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
848
849                 if (SelfSigned)
850                 {
851                         certinfo->unknownsigner = false;
852                         certinfo->trusted = true;
853                 }
854                 else
855                 {
856                         certinfo->unknownsigner = true;
857                         certinfo->trusted = false;
858                 }
859
860                 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
861                 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
862
863                 if (!X509_digest(cert, digest, md, &n))
864                 {
865                         certinfo->error = "Out of memory generating fingerprint";
866                 }
867                 else
868                 {
869                         certinfo->fingerprint = irc::hex(md, n);
870                 }
871
872                 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))
873                 {
874                         certinfo->error = "Not activated, or expired certificate";
875                 }
876
877                 X509_free(cert);
878                 return certinfo;
879         }
880
881         void Prioritize()
882         {
883                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
884                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
885         }
886
887 };
888
889 static int error_callback(const char *str, size_t len, void *u)
890 {
891         ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
892         mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
893
894         //
895         // XXX: Remove this line, it causes valgrind warnings...
896         //
897         // MD_update(&m, buf, j);
898         //
899         //
900         // ... ONLY JOKING! :-)
901         //
902
903         return 0;
904 }
905
906 MODULE_INIT(ModuleSSLOpenSSL)