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