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