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