]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
9dea711f8d00d059b2c2a17a99309bda36751fab
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 #include <gnutls/gnutls.h>
16 #include <gnutls/x509.h>
17 #include "transport.h"
18 #include "m_cap.h"
19
20 #ifdef WINDOWS
21 #pragma comment(lib, "libgnutls-13.lib")
22 #endif
23
24 /* $ModDesc: Provides SSL support for clients */
25 /* $CompileFlags: exec("libgnutls-config --cflags") */
26 /* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */
27 /* $ModDep: transport.h */
28 /* $CopyInstall: conf/key.pem $(CONPATH) */
29 /* $CopyInstall: conf/cert.pem $(CONPATH) */
30
31 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
32
33 bool isin(const std::string &host, int port, const std::vector<std::string> &portlist)
34 {
35         if (std::find(portlist.begin(), portlist.end(), "*:" + ConvToStr(port)) != portlist.end())
36                 return true;
37
38         if (std::find(portlist.begin(), portlist.end(), ":" + ConvToStr(port)) != portlist.end())
39                 return true;
40
41         return std::find(portlist.begin(), portlist.end(), host + ":" + ConvToStr(port)) != portlist.end();
42 }
43
44 /** Represents an SSL user's extra data
45  */
46 class issl_session : public classbase
47 {
48 public:
49         issl_session()
50         {
51                 sess = NULL;
52         }
53
54         gnutls_session_t sess;
55         issl_status status;
56         std::string outbuf;
57         int fd;
58 };
59
60 class CommandStartTLS : public Command
61 {
62         Module* Caller;
63  public:
64         CommandStartTLS (InspIRCd* Instance, Module* mod) : Command(Instance,"STARTTLS", 0, 0, true), Caller(mod)
65         {
66                 this->source = "m_ssl_gnutls.so";
67         }
68
69         CmdResult Handle (const std::vector<std::string> &parameters, User *user)
70         {
71                 /* changed from == REG_ALL to catch clients sending STARTTLS
72                  * after NICK and USER but before OnUserConnect completes and
73                  * give a proper error message (see bug #645) - dz
74                  */
75                 if (user->registered != REG_NONE)
76                 {
77                         ServerInstance->Users->QuitUser(user, "STARTTLS is not permitted after client registration has started");
78                 }
79                 else
80                 {
81                         if (!user->GetIOHook())
82                         {
83                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
84                                 user->AddIOHook(Caller);
85                                 Caller->OnRawSocketAccept(user->GetFd(), user->GetIPString(), user->GetPort());
86                         }
87                         else
88                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
89                 }
90
91                 return CMD_FAILURE;
92         }
93 };
94
95 class ModuleSSLGnuTLS : public Module
96 {
97
98         ConfigReader* Conf;
99
100         char* dummy;
101
102         std::vector<std::string> listenports;
103
104         issl_session* sessions;
105
106         gnutls_certificate_credentials x509_cred;
107         gnutls_dh_params dh_params;
108
109         std::string keyfile;
110         std::string certfile;
111         std::string cafile;
112         std::string crlfile;
113         std::string sslports;
114         int dh_bits;
115
116         int clientactive;
117         bool cred_alloc;
118
119         CommandStartTLS* starttls;
120
121  public:
122
123         ModuleSSLGnuTLS(InspIRCd* Me)
124                 : Module(Me)
125         {
126                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
127
128                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
129
130                 gnutls_global_init(); // This must be called once in the program
131
132                 cred_alloc = false;
133                 // Needs the flag as it ignores a plain /rehash
134                 OnRehash(NULL,"ssl");
135
136                 // Void return, guess we assume success
137                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
138                 Implementation eventlist[] = { I_On005Numeric, I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup,
139                         I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect, I_OnEvent, I_OnHookUserIO };
140                 ServerInstance->Modules->Attach(eventlist, this, 17);
141
142                 starttls = new CommandStartTLS(ServerInstance, this);
143                 ServerInstance->AddCommand(starttls);
144         }
145
146         virtual void OnRehash(User* user, const std::string &param)
147         {
148                 Conf = new ConfigReader(ServerInstance);
149
150                 listenports.clear();
151                 clientactive = 0;
152                 sslports.clear();
153
154                 for(int index = 0; index < Conf->Enumerate("bind"); index++)
155                 {
156                         // For each <bind> tag
157                         std::string x = Conf->ReadValue("bind", "type", index);
158                         if(((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", index) == "gnutls"))
159                         {
160                                 // Get the port we're meant to be listening on with SSL
161                                 std::string port = Conf->ReadValue("bind", "port", index);
162                                 std::string addr = Conf->ReadValue("bind", "address", index);
163
164                                 irc::portparser portrange(port, false);
165                                 long portno = -1;
166                                 while ((portno = portrange.GetToken()))
167                                 {
168                                         clientactive++;
169                                         try
170                                         {
171                                                 listenports.push_back(addr + ":" + ConvToStr(portno));
172
173                                                 for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
174                                                         if ((ServerInstance->Config->ports[i]->GetPort() == portno) && (ServerInstance->Config->ports[i]->GetIP() == addr))
175                                                                 ServerInstance->Config->ports[i]->SetDescription("ssl");
176                                                 ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %ld", portno);
177
178                                                 sslports.append((addr.empty() ? "*" : addr)).append(":").append(ConvToStr(portno)).append(";");
179                                         }
180                                         catch (ModuleException &e)
181                                         {
182                                                 ServerInstance->Logs->Log("m_ssl_gnutls",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());
183                                         }
184                                 }
185                         }
186                 }
187
188                 if (!sslports.empty())
189                         sslports.erase(sslports.end() - 1);
190
191                 if(param != "ssl")
192                 {
193                         delete Conf;
194                         return;
195                 }
196
197                 std::string confdir(ServerInstance->ConfigFileName);
198                 // +1 so we the path ends with a /
199                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
200
201                 cafile  = Conf->ReadValue("gnutls", "cafile", 0);
202                 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
203                 certfile        = Conf->ReadValue("gnutls", "certfile", 0);
204                 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
205                 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
206
207                 // Set all the default values needed.
208                 if (cafile.empty())
209                         cafile = "ca.pem";
210
211                 if (crlfile.empty())
212                         crlfile = "crl.pem";
213
214                 if (certfile.empty())
215                         certfile = "cert.pem";
216
217                 if (keyfile.empty())
218                         keyfile = "key.pem";
219
220                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
221                         dh_bits = 1024;
222
223                 // Prepend relative paths with the path to the config directory.
224                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
225                         cafile = confdir + cafile;
226
227                 if ((crlfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(crlfile)))
228                         crlfile = confdir + crlfile;
229
230                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
231                         certfile = confdir + certfile;
232
233                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
234                         keyfile = confdir + keyfile;
235
236                 int ret;
237
238                 if (cred_alloc)
239                 {
240                         // Deallocate the old credentials
241                         gnutls_dh_params_deinit(dh_params);
242                         gnutls_certificate_free_credentials(x509_cred);
243                 }
244                 else
245                         cred_alloc = true;
246
247                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
248                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
249
250                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
251                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
252
253                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
254                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
255
256                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
257                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
258
259                 if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
260                 {
261                         // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
262                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + ", key: " + keyfile + "): " + std::string(gnutls_strerror(ret)));
263                 }
264
265                 // This may be on a large (once a day or week) timer eventually.
266                 GenerateDHParams();
267
268                 delete Conf;
269         }
270
271         void GenerateDHParams()
272         {
273                 // Generate Diffie Hellman parameters - for use with DHE
274                 // kx algorithms. These should be discarded and regenerated
275                 // once a day, once a week or once a month. Depending on the
276                 // security requirements.
277
278                 int ret;
279
280                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
281                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
282         }
283
284         virtual ~ModuleSSLGnuTLS()
285         {
286                 gnutls_dh_params_deinit(dh_params);
287                 gnutls_certificate_free_credentials(x509_cred);
288                 gnutls_global_deinit();
289                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
290                 delete[] sessions;
291         }
292
293         virtual void OnCleanup(int target_type, void* item)
294         {
295                 if(target_type == TYPE_USER)
296                 {
297                         User* user = (User*)item;
298
299                         if (user->GetIOHook() == this)
300                         {
301                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
302                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
303                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
304                                 user->DelIOHook();
305                         }
306                         if (user->GetExt("ssl_cert", dummy))
307                         {
308                                 ssl_cert* tofree;
309                                 user->GetExt("ssl_cert", tofree);
310                                 delete tofree;
311                                 user->Shrink("ssl_cert");
312                         }
313                 }
314         }
315
316         virtual void OnUnloadModule(Module* mod, const std::string &name)
317         {
318                 if(mod == this)
319                 {
320                         for(unsigned int i = 0; i < listenports.size(); i++)
321                         {
322                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
323                                         if (listenports[i] == (ServerInstance->Config->ports[j]->GetIP()+":"+ConvToStr(ServerInstance->Config->ports[j]->GetPort())))
324                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
325                         }
326                 }
327         }
328
329         virtual Version GetVersion()
330         {
331                 return Version("$Id$", VF_VENDOR, API_VERSION);
332         }
333
334
335         virtual void On005Numeric(std::string &output)
336         {
337                 output.append(" SSL=" + sslports);
338         }
339
340         virtual void OnHookUserIO(User* user, const std::string &targetip)
341         {
342                 if (!user->GetIOHook() && isin(targetip,user->GetPort(),listenports))
343                 {
344                         /* Hook the user with our module */
345                         user->AddIOHook(this);
346                 }
347         }
348
349         virtual const char* OnRequest(Request* request)
350         {
351                 ISHRequest* ISR = (ISHRequest*)request;
352                 if (strcmp("IS_NAME", request->GetId()) == 0)
353                 {
354                         return "gnutls";
355                 }
356                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
357                 {
358                         const char* ret = "OK";
359                         try
360                         {
361                                 ret = ISR->Sock->AddIOHook((Module*)this) ? "OK" : NULL;
362                         }
363                         catch (ModuleException &e)
364                         {
365                                 return NULL;
366                         }
367                         return ret;
368                 }
369                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
370                 {
371                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
372                 }
373                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
374                 {
375                         if (ISR->Sock->GetFd() < 0)
376                                 return "OK";
377
378                         issl_session* session = &sessions[ISR->Sock->GetFd()];
379                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : "OK";
380                 }
381                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
382                 {
383                         if (ISR->Sock->GetFd() > -1)
384                         {
385                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
386                                 if (session->sess)
387                                 {
388                                         if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock))
389                                         {
390                                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
391                                                 return "OK";
392                                         }
393                                 }
394                         }
395                 }
396                 return NULL;
397         }
398
399
400         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
401         {
402                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
403                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
404                         return;
405
406                 issl_session* session = &sessions[fd];
407
408                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
409                 if (session->sess)
410                         return;
411
412                 session->fd = fd;
413
414                 gnutls_init(&session->sess, GNUTLS_SERVER);
415
416                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
417                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
418                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
419
420                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
421
422                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
423
424                 Handshake(session);
425         }
426
427         virtual void OnRawSocketConnect(int fd)
428         {
429                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
430                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
431                         return;
432
433                 issl_session* session = &sessions[fd];
434
435                 session->fd = fd;
436
437                 gnutls_init(&session->sess, GNUTLS_CLIENT);
438
439                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
440                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
441                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
442                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
443
444                 Handshake(session);
445         }
446
447         virtual void OnRawSocketClose(int fd)
448         {
449                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
450                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds()))
451                         return;
452
453                 CloseSession(&sessions[fd]);
454
455                 EventHandler* user = ServerInstance->SE->GetRef(fd);
456
457                 if ((user) && (user->GetExt("ssl_cert", dummy)))
458                 {
459                         ssl_cert* tofree;
460                         user->GetExt("ssl_cert", tofree);
461                         delete tofree;
462                         user->Shrink("ssl_cert");
463                 }
464         }
465
466         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
467         {
468                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
469                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
470                         return 0;
471
472                 issl_session* session = &sessions[fd];
473
474                 if (!session->sess)
475                 {
476                         readresult = 0;
477                         CloseSession(session);
478                         return 1;
479                 }
480
481                 if (session->status == ISSL_HANDSHAKING_READ)
482                 {
483                         // The handshake isn't finished, try to finish it.
484
485                         if(!Handshake(session))
486                         {
487                                 // Couldn't resume handshake.
488                                 return -1;
489                         }
490                 }
491                 else if (session->status == ISSL_HANDSHAKING_WRITE)
492                 {
493                         errno = EAGAIN;
494                         MakePollWrite(session);
495                         return -1;
496                 }
497
498                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
499
500                 if (session->status == ISSL_HANDSHAKEN)
501                 {
502                         int ret = gnutls_record_recv(session->sess, buffer, count);
503
504                         if (ret > 0)
505                         {
506                                 readresult = ret;
507                         }
508                         else if (ret == 0)
509                         {
510                                 // Client closed connection.
511                                 readresult = 0;
512                                 CloseSession(session);
513                                 return 1;
514                         }
515                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
516                         {
517                                 errno = EAGAIN;
518                                 return -1;
519                         }
520                         else
521                         {
522                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
523                                                 "m_ssl_gnutls.so: Error while reading on fd %d: %s",
524                                                 session->fd, gnutls_strerror(ret));
525                                 readresult = 0;
526                                 CloseSession(session);
527                         }
528                 }
529                 else if(session->status == ISSL_CLOSING)
530                         readresult = 0;
531
532                 return 1;
533         }
534
535         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
536         {
537                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
538                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
539                         return 0;
540
541                 issl_session* session = &sessions[fd];
542                 const char* sendbuffer = buffer;
543
544                 if (!session->sess)
545                 {
546                         CloseSession(session);
547                         return 1;
548                 }
549
550                 session->outbuf.append(sendbuffer, count);
551                 sendbuffer = session->outbuf.c_str();
552                 count = session->outbuf.size();
553
554                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
555                 {
556                         // The handshake isn't finished, try to finish it.
557                         Handshake(session);
558                         errno = EAGAIN;
559                         return -1;
560                 }
561
562                 int ret = 0;
563
564                 if (session->status == ISSL_HANDSHAKEN)
565                 {
566                         ret = gnutls_record_send(session->sess, sendbuffer, count);
567
568                         if (ret == 0)
569                         {
570                                 CloseSession(session);
571                         }
572                         else if (ret < 0)
573                         {
574                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
575                                 {
576                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
577                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
578                                                         session->fd, gnutls_strerror(ret));
579                                         CloseSession(session);
580                                 }
581                                 else
582                                 {
583                                         errno = EAGAIN;
584                                 }
585                         }
586                         else
587                         {
588                                 session->outbuf = session->outbuf.substr(ret);
589                         }
590                 }
591
592                 MakePollWrite(session);
593
594                 /* Who's smart idea was it to return 1 when we havent written anything?
595                  * This fucks the buffer up in BufferedSocket :p
596                  */
597                 return ret < 1 ? 0 : ret;
598         }
599
600         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
601         virtual void OnWhois(User* source, User* dest)
602         {
603                 if (!clientactive)
604                         return;
605
606                 // Bugfix, only send this numeric for *our* SSL users
607                 if (dest->GetExt("ssl", dummy))
608                 {
609                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick.c_str(), dest->nick.c_str());
610                 }
611         }
612
613         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
614         {
615                 // check if the linking module wants to know about OUR metadata
616                 if(extname == "ssl")
617                 {
618                         // check if this user has an swhois field to send
619                         if(user->GetExt(extname, dummy))
620                         {
621                                 // call this function in the linking module, let it format the data how it
622                                 // sees fit, and send it on its way. We dont need or want to know how.
623                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
624                         }
625                 }
626         }
627
628         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
629         {
630                 // check if its our metadata key, and its associated with a user
631                 if ((target_type == TYPE_USER) && (extname == "ssl"))
632                 {
633                         User* dest = (User*)target;
634                         // if they dont already have an ssl flag, accept the remote server's
635                         if (!dest->GetExt(extname, dummy))
636                         {
637                                 dest->Extend(extname, "ON");
638                         }
639                 }
640         }
641
642         bool Handshake(issl_session* session)
643         {
644                 int ret = gnutls_handshake(session->sess);
645
646                 if (ret < 0)
647                 {
648                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
649                         {
650                                 // Handshake needs resuming later, read() or write() would have blocked.
651
652                                 if(gnutls_record_get_direction(session->sess) == 0)
653                                 {
654                                         // gnutls_handshake() wants to read() again.
655                                         session->status = ISSL_HANDSHAKING_READ;
656                                 }
657                                 else
658                                 {
659                                         // gnutls_handshake() wants to write() again.
660                                         session->status = ISSL_HANDSHAKING_WRITE;
661                                         MakePollWrite(session);
662                                 }
663                         }
664                         else
665                         {
666                                 // Handshake failed.
667                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
668                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
669                                                 session->fd, gnutls_strerror(ret));
670                                 CloseSession(session);
671                                 session->status = ISSL_CLOSING;
672                         }
673
674                         return false;
675                 }
676                 else
677                 {
678                         // Handshake complete.
679                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
680                         User* extendme = ServerInstance->FindDescriptor(session->fd);
681                         if (extendme)
682                         {
683                                 if (!extendme->GetExt("ssl", dummy))
684                                         extendme->Extend("ssl", "ON");
685                         }
686
687                         // Change the seesion state
688                         session->status = ISSL_HANDSHAKEN;
689
690                         // Finish writing, if any left
691                         MakePollWrite(session);
692
693                         return true;
694                 }
695         }
696
697         virtual void OnPostConnect(User* user)
698         {
699                 // This occurs AFTER OnUserConnect so we can be sure the
700                 // protocol module has propagated the NICK message.
701                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
702                 {
703                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
704                         ServerInstance->PI->SendMetaData(user, TYPE_USER, "SSL", "on");
705
706                         VerifyCertificate(&sessions[user->GetFd()],user);
707                         if (sessions[user->GetFd()].sess)
708                         {
709                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
710                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
711                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
712                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
713                         }
714                 }
715         }
716
717         void MakePollWrite(issl_session* session)
718         {
719                 //OnRawSocketWrite(session->fd, NULL, 0);
720                 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
721                 if (eh)
722                         ServerInstance->SE->WantWrite(eh);
723         }
724
725         virtual void OnBufferFlushed(User* user)
726         {
727                 if (user->GetIOHook() == this)
728                 {
729                         issl_session* session = &sessions[user->GetFd()];
730                         if (session && session->outbuf.size())
731                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
732                 }
733         }
734
735         void CloseSession(issl_session* session)
736         {
737                 if(session->sess)
738                 {
739                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
740                         gnutls_deinit(session->sess);
741                 }
742
743                 session->outbuf.clear();
744                 session->sess = NULL;
745                 session->status = ISSL_NONE;
746         }
747
748         void VerifyCertificate(issl_session* session, Extensible* user)
749         {
750                 if (!session->sess || !user)
751                         return;
752
753                 unsigned int status;
754                 const gnutls_datum_t* cert_list;
755                 int ret;
756                 unsigned int cert_list_size;
757                 gnutls_x509_crt_t cert;
758                 char name[MAXBUF];
759                 unsigned char digest[MAXBUF];
760                 size_t digest_size = sizeof(digest);
761                 size_t name_size = sizeof(name);
762                 ssl_cert* certinfo = new ssl_cert;
763
764                 user->Extend("ssl_cert",certinfo);
765
766                 /* This verification function uses the trusted CAs in the credentials
767                  * structure. So you must have installed one or more CA certificates.
768                  */
769                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
770
771                 if (ret < 0)
772                 {
773                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
774                         return;
775                 }
776
777                 if (status & GNUTLS_CERT_INVALID)
778                 {
779                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
780                 }
781                 else
782                 {
783                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
784                 }
785                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
786                 {
787                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
788                 }
789                 else
790                 {
791                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
792                 }
793                 if (status & GNUTLS_CERT_REVOKED)
794                 {
795                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
796                 }
797                 else
798                 {
799                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
800                 }
801                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
802                 {
803                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
804                 }
805                 else
806                 {
807                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
808                 }
809
810                 /* Up to here the process is the same for X.509 certificates and
811                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
812                  * be easily extended to work with openpgp keys as well.
813                  */
814                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
815                 {
816                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
817                         return;
818                 }
819
820                 ret = gnutls_x509_crt_init(&cert);
821                 if (ret < 0)
822                 {
823                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
824                         return;
825                 }
826
827                 cert_list_size = 0;
828                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
829                 if (cert_list == NULL)
830                 {
831                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
832                         return;
833                 }
834
835                 /* This is not a real world example, since we only check the first
836                  * certificate in the given chain.
837                  */
838
839                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
840                 if (ret < 0)
841                 {
842                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
843                         return;
844                 }
845
846                 gnutls_x509_crt_get_dn(cert, name, &name_size);
847
848                 certinfo->data.insert(std::make_pair("dn",name));
849
850                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
851
852                 certinfo->data.insert(std::make_pair("issuer",name));
853
854                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
855                 {
856                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
857                 }
858                 else
859                 {
860                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
861                 }
862
863                 /* Beware here we do not check for errors.
864                  */
865                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
866                 {
867                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
868                 }
869
870                 gnutls_x509_crt_deinit(cert);
871
872                 return;
873         }
874
875         void OnEvent(Event* ev)
876         {
877                 GenericCapHandler(ev, "tls", "tls");
878         }
879
880         void Prioritize()
881         {
882                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
883                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
884         }
885 };
886
887 MODULE_INIT(ModuleSSLGnuTLS)