]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Allow SSL fingerprint-based server authentication
[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_OnSyncUserMetaData, I_OnDecodeMetaData,
156                         I_OnUnloadModule, I_OnRehash, I_OnModuleRehash, I_OnWhois, I_OnPostConnect,
157                         I_OnHookUserIO };
158                 ServerInstance->Modules->Attach(eventlist, this, 17);
159         }
160
161         virtual void OnHookUserIO(User* user, const std::string &targetip)
162         {
163                 if (!user->GetIOHook() && isin(targetip,user->GetPort(), listenports))
164                 {
165                         /* Hook the user with our module */
166                         user->AddIOHook(this);
167                 }
168         }
169
170         virtual void OnRehash(User* user)
171         {
172                 ConfigReader Conf(ServerInstance);
173
174                 listenports.clear();
175                 clientactive = 0;
176                 sslports.clear();
177
178                 for(int index = 0; index < Conf.Enumerate("bind"); index++)
179                 {
180                         // For each <bind> tag
181                         std::string x = Conf.ReadValue("bind", "type", index);
182                         if(((x.empty()) || (x == "clients")) && (Conf.ReadValue("bind", "ssl", index) == "openssl"))
183                         {
184                                 // Get the port we're meant to be listening on with SSL
185                                 std::string port = Conf.ReadValue("bind", "port", index);
186                                 std::string addr = Conf.ReadValue("bind", "address", index);
187
188                                 if (!addr.empty())
189                                 {
190                                         // normalize address, important for IPv6
191                                         int portint = 0;
192                                         irc::sockets::sockaddrs bin;
193                                         if (irc::sockets::aptosa(addr.c_str(), portint, &bin))
194                                                 irc::sockets::satoap(&bin, addr, portint);
195                                 }
196
197                                 irc::portparser portrange(port, false);
198                                 long portno = -1;
199                                 while ((portno = portrange.GetToken()))
200                                 {
201                                         clientactive++;
202                                         try
203                                         {
204                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
205
206                                                 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
207                                                         if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
208                                                                 ServerInstance->Config->ports[i]->SetDescription("ssl");
209                                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %ld", portno);
210
211                                                 if (addr != "127.0.0.1")
212                                                         sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
213                                         }
214                                         catch (ModuleException &e)
215                                         {
216                                                 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());
217                                         }
218                                 }
219                         }
220                 }
221
222                 if (!sslports.empty())
223                         sslports.erase(sslports.end() - 1);
224         }
225
226         virtual void OnModuleRehash(User* user, const std::string &param)
227         {
228                 if (param != "ssl")
229                         return;
230
231                 OnRehash(user);
232
233                 ConfigReader Conf(ServerInstance);
234
235                 std::string confdir(ServerInstance->ConfigFileName);
236                 // +1 so we the path ends with a /
237                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
238
239                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
240                 certfile = Conf.ReadValue("openssl", "certfile", 0);
241                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
242                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
243
244                 // Set all the default values needed.
245                 if (cafile.empty())
246                         cafile = "ca.pem";
247
248                 if (certfile.empty())
249                         certfile = "cert.pem";
250
251                 if (keyfile.empty())
252                         keyfile = "key.pem";
253
254                 if (dhfile.empty())
255                         dhfile = "dhparams.pem";
256
257                 // Prepend relative paths with the path to the config directory.
258                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
259                         cafile = confdir + cafile;
260
261                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
262                         certfile = confdir + certfile;
263
264                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
265                         keyfile = confdir + keyfile;
266
267                 if ((dhfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(dhfile)))
268                         dhfile = confdir + dhfile;
269
270                 /* Load our keys and certificates
271                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
272                  */
273                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
274                 {
275                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
276                         ERR_print_errors_cb(error_callback, this);
277                 }
278
279                 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)))
280                 {
281                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
282                         ERR_print_errors_cb(error_callback, this);
283                 }
284
285                 /* Load the CAs we trust*/
286                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
287                 {
288                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
289                         ERR_print_errors_cb(error_callback, this);
290                 }
291
292                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
293                 DH* ret;
294
295                 if (dhpfile == NULL)
296                 {
297                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
298                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
299                 }
300                 else
301                 {
302                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
303                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
304                         {
305                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
306                                 ERR_print_errors_cb(error_callback, this);
307                         }
308                 }
309
310                 fclose(dhpfile);
311         }
312
313         virtual void On005Numeric(std::string &output)
314         {
315                 output.append(" SSL=" + sslports);
316         }
317
318         virtual ~ModuleSSLOpenSSL()
319         {
320                 SSL_CTX_free(ctx);
321                 SSL_CTX_free(clictx);
322                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
323                 delete[] sessions;
324         }
325
326         virtual void OnCleanup(int target_type, void* item)
327         {
328                 if (target_type == TYPE_USER)
329                 {
330                         User* user = (User*)item;
331
332                         if (user->GetIOHook() == this)
333                         {
334                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
335                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
336                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
337                                 user->DelIOHook();
338                         }
339                         if (user->GetExt("ssl_cert", dummy))
340                         {
341                                 ssl_cert* tofree;
342                                 user->GetExt("ssl_cert", tofree);
343                                 delete tofree;
344                                 user->Shrink("ssl_cert");
345                         }
346                 }
347         }
348
349         virtual void OnUnloadModule(Module* mod, const std::string &name)
350         {
351                 if (mod == this)
352                 {
353                         for(unsigned int i = 0; i < listenports.size(); i++)
354                         {
355                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
356                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
357                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
358                         }
359                 }
360         }
361
362         virtual Version GetVersion()
363         {
364                 return Version("$Id$", VF_VENDOR, API_VERSION);
365         }
366
367
368         virtual const char* OnRequest(Request* request)
369         {
370                 ISHRequest* ISR = (ISHRequest*)request;
371                 if (strcmp("IS_NAME", request->GetId()) == 0)
372                 {
373                         return "openssl";
374                 }
375                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
376                 {
377                         const char* ret = "OK";
378                         try
379                         {
380                                 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
381                         }
382                         catch (ModuleException &e)
383                         {
384                                 return NULL;
385                         }
386
387                         return ret;
388                 }
389                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
390                 {
391                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
392                 }
393                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
394                 {
395                         if (ISR->Sock->GetFd() < 0)
396                                 return "OK";
397
398                         issl_session* session = &sessions[ISR->Sock->GetFd()];
399                         return (session->status == ISSL_HANDSHAKING) ? NULL : "OK";
400                 }
401                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
402                 {
403                         issl_session* session = &sessions[ISR->Sock->GetFd()];
404                         if (session->sess)
405                         {
406                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
407                                 return "OK";
408                         }
409                 }
410                 else if (strcmp("GET_FP", request->GetId()) == 0)
411                 {
412                         if (ISR->Sock->GetFd() > -1)
413                         {
414                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
415                                 if (session->sess)
416                                 {
417                                         Extensible* ext = ISR->Sock;
418                                         ssl_cert* certinfo;
419                                         if (ext->GetExt("ssl_cert",certinfo))
420                                                 return certinfo->GetFingerprint().c_str();
421                                 }
422                         }
423                 }
424                 return NULL;
425         }
426
427
428         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
429         {
430                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
431                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
432                         return;
433
434                 issl_session* session = &sessions[fd];
435
436                 session->fd = fd;
437                 session->inbuf = new char[inbufsize];
438                 session->inbufoffset = 0;
439                 session->sess = SSL_new(ctx);
440                 session->status = ISSL_NONE;
441                 session->outbound = false;
442
443                 if (session->sess == NULL)
444                         return;
445
446                 if (SSL_set_fd(session->sess, fd) == 0)
447                 {
448                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
449                         return;
450                 }
451
452                 Handshake(session);
453         }
454
455         virtual void OnRawSocketConnect(int fd)
456         {
457                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
458                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
459                         return;
460
461                 issl_session* session = &sessions[fd];
462
463                 session->fd = fd;
464                 session->inbuf = new char[inbufsize];
465                 session->inbufoffset = 0;
466                 session->sess = SSL_new(clictx);
467                 session->status = ISSL_NONE;
468                 session->outbound = true;
469
470                 if (session->sess == NULL)
471                         return;
472
473                 if (SSL_set_fd(session->sess, fd) == 0)
474                 {
475                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
476                         return;
477                 }
478
479                 Handshake(session);
480         }
481
482         virtual void OnRawSocketClose(int fd)
483         {
484                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
485                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
486                         return;
487
488                 CloseSession(&sessions[fd]);
489
490                 EventHandler* user = ServerInstance->SE->GetRef(fd);
491
492                 if ((user) && (user->GetExt("ssl_cert", dummy)))
493                 {
494                         ssl_cert* tofree;
495                         user->GetExt("ssl_cert", tofree);
496                         delete tofree;
497                         user->Shrink("ssl_cert");
498                 }
499         }
500
501         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
502         {
503                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
504                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
505                         return 0;
506
507                 issl_session* session = &sessions[fd];
508
509                 if (!session->sess)
510                 {
511                         readresult = 0;
512                         CloseSession(session);
513                         return 1;
514                 }
515
516                 if (session->status == ISSL_HANDSHAKING)
517                 {
518                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
519                         {
520                                 // The handshake isn't finished and it wants to read, try to finish it.
521                                 if (!Handshake(session))
522                                 {
523                                         // Couldn't resume handshake.
524                                         errno = session->status == ISSL_NONE ? EIO : EAGAIN;
525                                         return -1;
526                                 }
527                         }
528                         else
529                         {
530                                 errno = EAGAIN;
531                                 return -1;
532                         }
533                 }
534
535                 // If we resumed the handshake then session->status will be ISSL_OPEN
536
537                 if (session->status == ISSL_OPEN)
538                 {
539                         if (session->wstat == ISSL_READ)
540                         {
541                                 if(DoWrite(session) == 0)
542                                         return 0;
543                         }
544
545                         if (session->rstat == ISSL_READ)
546                         {
547                                 int ret = DoRead(session);
548
549                                 if (ret > 0)
550                                 {
551                                         if (count <= session->inbufoffset)
552                                         {
553                                                 memcpy(buffer, session->inbuf, count);
554                                                 // Move the stuff left in inbuf to the beginning of it
555                                                 memmove(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
556                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
557                                                 session->inbufoffset -= count;
558                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
559                                                 readresult = count;
560                                         }
561                                         else
562                                         {
563                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
564                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
565
566                                                 readresult = session->inbufoffset;
567                                                 // Zero the offset, as there's nothing there..
568                                                 session->inbufoffset = 0;
569                                         }
570                                         return 1;
571                                 }
572                                 return ret;
573                         }
574                 }
575
576                 return -1;
577         }
578
579         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
580         {
581                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
582                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
583                         return 0;
584
585                 errno = EAGAIN;
586                 issl_session* session = &sessions[fd];
587
588                 if (!session->sess)
589                 {
590                         CloseSession(session);
591                         return -1;
592                 }
593
594                 session->outbuf.append(buffer, count);
595                 MakePollWrite(session);
596
597                 if (session->status == ISSL_HANDSHAKING)
598                 {
599                         // The handshake isn't finished, try to finish it.
600                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
601                         {
602                                 if (!Handshake(session))
603                                 {
604                                         // Couldn't resume handshake.
605                                         errno = session->status == ISSL_NONE ? EIO : EAGAIN;
606                                         return -1;
607                                 }
608                         }
609                 }
610
611                 if (session->status == ISSL_OPEN)
612                 {
613                         if (session->rstat == ISSL_WRITE)
614                         {
615                                 DoRead(session);
616                         }
617
618                         if (session->wstat == ISSL_WRITE)
619                         {
620                                 return DoWrite(session);
621                         }
622                 }
623
624                 return 1;
625         }
626
627         int DoWrite(issl_session* session)
628         {
629                 if (!session->outbuf.size())
630                         return -1;
631
632                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
633
634                 if (ret == 0)
635                 {
636                         CloseSession(session);
637                         return 0;
638                 }
639                 else if (ret < 0)
640                 {
641                         int err = SSL_get_error(session->sess, ret);
642
643                         if (err == SSL_ERROR_WANT_WRITE)
644                         {
645                                 session->wstat = ISSL_WRITE;
646                                 return -1;
647                         }
648                         else if (err == SSL_ERROR_WANT_READ)
649                         {
650                                 session->wstat = ISSL_READ;
651                                 return -1;
652                         }
653                         else
654                         {
655                                 CloseSession(session);
656                                 return 0;
657                         }
658                 }
659                 else
660                 {
661                         session->outbuf = session->outbuf.substr(ret);
662                         return ret;
663                 }
664         }
665
666         int DoRead(issl_session* session)
667         {
668                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
669                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
670
671                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
672
673                 if (ret == 0)
674                 {
675                         // Client closed connection.
676                         CloseSession(session);
677                         return 0;
678                 }
679                 else if (ret < 0)
680                 {
681                         int err = SSL_get_error(session->sess, ret);
682
683                         if (err == SSL_ERROR_WANT_READ)
684                         {
685                                 session->rstat = ISSL_READ;
686                                 return -1;
687                         }
688                         else if (err == SSL_ERROR_WANT_WRITE)
689                         {
690                                 session->rstat = ISSL_WRITE;
691                                 MakePollWrite(session);
692                                 return -1;
693                         }
694                         else
695                         {
696                                 CloseSession(session);
697                                 return 0;
698                         }
699                 }
700                 else
701                 {
702                         // Read successfully 'ret' bytes into inbuf + inbufoffset
703                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
704                         // 'buffer' is 'count' long
705
706                         session->inbufoffset += ret;
707
708                         return ret;
709                 }
710         }
711
712         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
713         virtual void OnWhois(User* source, User* dest)
714         {
715                 if (!clientactive)
716                         return;
717
718                 // Bugfix, only send this numeric for *our* SSL users
719                 if (dest->GetExt("ssl", dummy))
720                 {
721                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str());
722                 }
723         }
724
725         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
726         {
727                 // check if the linking module wants to know about OUR metadata
728                 if (extname == "ssl")
729                 {
730                         // check if this user has an swhois field to send
731                         if(user->GetExt(extname, dummy))
732                         {
733                                 // call this function in the linking module, let it format the data how it
734                                 // sees fit, and send it on its way. We dont need or want to know how.
735                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
736                         }
737                 }
738         }
739
740         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
741         {
742                 // check if its our metadata key, and its associated with a user
743                 if ((target_type == TYPE_USER) && (extname == "ssl"))
744                 {
745                         User* dest = (User*)target;
746                         // if they dont already have an ssl flag, accept the remote server's
747                         if (!dest->GetExt(extname, dummy))
748                         {
749                                 dest->Extend(extname, "ON");
750                         }
751                 }
752         }
753
754         bool Handshake(issl_session* session)
755         {
756                 int ret;
757
758                 if (session->outbound)
759                         ret = SSL_connect(session->sess);
760                 else
761                         ret = SSL_accept(session->sess);
762
763                 if (ret < 0)
764                 {
765                         int err = SSL_get_error(session->sess, ret);
766
767                         if (err == SSL_ERROR_WANT_READ)
768                         {
769                                 session->rstat = ISSL_READ;
770                                 session->status = ISSL_HANDSHAKING;
771                                 return true;
772                         }
773                         else if (err == SSL_ERROR_WANT_WRITE)
774                         {
775                                 session->wstat = ISSL_WRITE;
776                                 session->status = ISSL_HANDSHAKING;
777                                 MakePollWrite(session);
778                                 return true;
779                         }
780                         else
781                         {
782                                 CloseSession(session);
783                         }
784
785                         return false;
786                 }
787                 else if (ret > 0)
788                 {
789                         // Handshake complete.
790                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
791                         EventHandler *u = ServerInstance->SE->GetRef(session->fd);
792                         if (u)
793                         {
794                                 if (!u->GetExt("ssl", dummy))
795                                         u->Extend("ssl", "ON");
796                         }
797
798                         session->status = ISSL_OPEN;
799
800                         MakePollWrite(session);
801
802                         return true;
803                 }
804                 else if (ret == 0)
805                 {
806                         CloseSession(session);
807                         return true;
808                 }
809
810                 return true;
811         }
812
813         virtual void OnPostConnect(User* user)
814         {
815                 // This occurs AFTER OnUserConnect so we can be sure the
816                 // protocol module has propagated the NICK message.
817                 if ((user->GetIOHook() == this) && (IS_LOCAL(user)))
818                 {
819                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
820                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "ssl", "on");
821
822                         VerifyCertificate(&sessions[user->GetFd()], user);
823                         if (sessions[user->GetFd()].sess)
824                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), SSL_get_cipher(sessions[user->GetFd()].sess));
825                 }
826         }
827
828         void MakePollWrite(issl_session* session)
829         {
830                 //OnRawSocketWrite(session->fd, NULL, 0);
831                 EventHandler* eh = ServerInstance->SE->GetRef(session->fd);
832                 if (eh)
833                 {
834                         ServerInstance->SE->WantWrite(eh);
835                 }
836         }
837
838         virtual void OnBufferFlushed(User* user)
839         {
840                 if (user->GetIOHook() == this)
841                 {
842                         issl_session* session = &sessions[user->GetFd()];
843                         if (session && session->outbuf.size())
844                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
845                 }
846         }
847
848         void CloseSession(issl_session* session)
849         {
850                 if (session->sess)
851                 {
852                         SSL_shutdown(session->sess);
853                         SSL_free(session->sess);
854                 }
855
856                 if (session->inbuf)
857                 {
858                         delete[] session->inbuf;
859                 }
860
861                 session->outbuf.clear();
862                 session->inbuf = NULL;
863                 session->sess = NULL;
864                 session->status = ISSL_NONE;
865                 errno = EIO;
866         }
867
868         void VerifyCertificate(issl_session* session, Extensible* user)
869         {
870                 if (!session->sess || !user)
871                         return;
872
873                 X509* cert;
874                 ssl_cert* certinfo = new ssl_cert;
875                 unsigned int n;
876                 unsigned char md[EVP_MAX_MD_SIZE];
877                 const EVP_MD *digest = EVP_md5();
878
879                 user->Extend("ssl_cert",certinfo);
880
881                 cert = SSL_get_peer_certificate((SSL*)session->sess);
882
883                 if (!cert)
884                 {
885                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
886                         return;
887                 }
888
889                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
890
891                 if (SelfSigned)
892                 {
893                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
894                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
895                 }
896                 else
897                 {
898                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
899                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
900                 }
901
902                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
903                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
904
905                 if (!X509_digest(cert, digest, md, &n))
906                 {
907                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
908                 }
909                 else
910                 {
911                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
912                 }
913
914                 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))
915                 {
916                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
917                 }
918
919                 X509_free(cert);
920         }
921
922         void Prioritize()
923         {
924                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
925                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
926         }
927
928 };
929
930 static int error_callback(const char *str, size_t len, void *u)
931 {
932         ModuleSSLOpenSSL* mssl = (ModuleSSLOpenSSL*)u;
933         mssl->PublicInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
934
935         //
936         // XXX: Remove this line, it causes valgrind warnings...
937         //
938         // MD_update(&m, buf, j);
939         //
940         //
941         // ... ONLY JOKING! :-)
942         //
943
944         return 0;
945 }
946
947 MODULE_INIT(ModuleSSLOpenSSL)