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