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