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