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