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