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