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