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