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