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