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