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