]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Make end of netburst SNOMASK REMOTELINK unless servers are directly linked [jackmcbarn]
[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://wiki.inspircd.org/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: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
26 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") */
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 static gnutls_x509_crt_t x509_cert;
34 static gnutls_x509_privkey_t x509_key;
35 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
36         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
37
38         st->type = GNUTLS_CRT_X509;
39         st->ncerts = 1;
40         st->cert.x509 = &x509_cert;
41         st->key.x509 = x509_key;
42         st->deinit_all = 0;
43
44         return 0;
45 }
46
47 /** Represents an SSL user's extra data
48  */
49 class issl_session : public classbase
50 {
51 public:
52         issl_session()
53         {
54                 sess = NULL;
55         }
56
57         gnutls_session_t sess;
58         issl_status status;
59         std::string outbuf;
60 };
61
62 class CommandStartTLS : public Command
63 {
64  public:
65         CommandStartTLS (Module* mod) : Command(mod, "STARTTLS")
66         {
67                 works_before_reg = true;
68         }
69
70         CmdResult Handle (const std::vector<std::string> &parameters, User *user)
71         {
72                 /* changed from == REG_ALL to catch clients sending STARTTLS
73                  * after NICK and USER but before OnUserConnect completes and
74                  * give a proper error message (see bug #645) - dz
75                  */
76                 if (user->registered != REG_NONE)
77                 {
78                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration has started", user->nick.c_str());
79                 }
80                 else
81                 {
82                         if (!user->GetIOHook())
83                         {
84                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
85                                 user->AddIOHook(creator);
86                                 creator->OnRawSocketAccept(user->GetFd(), NULL, NULL);
87                         }
88                         else
89                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
90                 }
91
92                 return CMD_FAILURE;
93         }
94 };
95
96 class ModuleSSLGnuTLS : public Module
97 {
98         std::set<ListenSocketBase*> listenports;
99
100         issl_session* sessions;
101
102         gnutls_certificate_credentials x509_cred;
103         gnutls_dh_params dh_params;
104
105         std::string keyfile;
106         std::string certfile;
107         std::string cafile;
108         std::string crlfile;
109         std::string sslports;
110         int dh_bits;
111
112         bool cred_alloc;
113
114         CommandStartTLS starttls;
115
116         GenericCap capHandler;
117  public:
118
119         ModuleSSLGnuTLS(InspIRCd* Me)
120                 : Module(Me), starttls(this), capHandler(this, "tls")
121         {
122                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
123
124                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
125
126                 gnutls_global_init(); // This must be called once in the program
127                 gnutls_x509_crt_init(&x509_cert);
128                 gnutls_x509_privkey_init(&x509_key);
129
130                 cred_alloc = false;
131                 // Needs the flag as it ignores a plain /rehash
132                 OnModuleRehash(NULL,"ssl");
133
134                 // Void return, guess we assume success
135                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
136                 Implementation eventlist[] = { I_On005Numeric, I_OnRawSocketConnect, I_OnRawSocketAccept,
137                         I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup,
138                         I_OnBufferFlushed, I_OnRequest, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
139                         I_OnEvent, I_OnHookIO };
140                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
141
142                 ServerInstance->AddCommand(&starttls);
143         }
144
145         virtual void OnRehash(User* user)
146         {
147                 ConfigReader Conf(ServerInstance);
148
149                 listenports.clear();
150                 sslports.clear();
151
152                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
153                 {
154                         ListenSocketBase* port = ServerInstance->ports[i];
155                         std::string desc = port->GetDescription();
156                         if (desc != "gnutls")
157                                 continue;
158
159                         listenports.insert(port);
160                         std::string portid = port->GetBindDesc();
161
162                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
163                         if (port->GetIP() != "127.0.0.1")
164                                 sslports.append(portid).append(";");
165                 }
166
167                 if (!sslports.empty())
168                         sslports.erase(sslports.end() - 1);
169         }
170
171         virtual void OnModuleRehash(User* user, const std::string &param)
172         {
173                 if(param != "ssl")
174                         return;
175
176                 OnRehash(user);
177
178                 ConfigReader Conf(ServerInstance);
179
180                 std::string confdir(ServerInstance->ConfigFileName);
181                 // +1 so we the path ends with a /
182                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
183
184                 cafile = Conf.ReadValue("gnutls", "cafile", 0);
185                 crlfile = Conf.ReadValue("gnutls", "crlfile", 0);
186                 certfile = Conf.ReadValue("gnutls", "certfile", 0);
187                 keyfile = Conf.ReadValue("gnutls", "keyfile", 0);
188                 dh_bits = Conf.ReadInteger("gnutls", "dhbits", 0, false);
189
190                 // Set all the default values needed.
191                 if (cafile.empty())
192                         cafile = "ca.pem";
193
194                 if (crlfile.empty())
195                         crlfile = "crl.pem";
196
197                 if (certfile.empty())
198                         certfile = "cert.pem";
199
200                 if (keyfile.empty())
201                         keyfile = "key.pem";
202
203                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
204                         dh_bits = 1024;
205
206                 // Prepend relative paths with the path to the config directory.
207                 if ((cafile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(cafile)))
208                         cafile = confdir + cafile;
209
210                 if ((crlfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(crlfile)))
211                         crlfile = confdir + crlfile;
212
213                 if ((certfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(certfile)))
214                         certfile = confdir + certfile;
215
216                 if ((keyfile[0] != '/') && (!ServerInstance->Config->StartsWithWindowsDriveLetter(keyfile)))
217                         keyfile = confdir + keyfile;
218
219                 int ret;
220
221                 if (cred_alloc)
222                 {
223                         // Deallocate the old credentials
224                         gnutls_dh_params_deinit(dh_params);
225                         gnutls_certificate_free_credentials(x509_cred);
226                 }
227                 else
228                         cred_alloc = true;
229
230                 if((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0)
231                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
232
233                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
234                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
235
236                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
237                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
238
239                 FileReader reader(ServerInstance);
240
241                 reader.LoadFile(certfile);
242                 std::string cert_string = reader.Contents();
243                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), cert_string.length() };
244
245                 reader.LoadFile(keyfile);
246                 std::string key_string = reader.Contents();
247                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), key_string.length() };
248
249                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
250                 if((ret = gnutls_x509_crt_import(x509_cert, &cert_datum, GNUTLS_X509_FMT_PEM)) < 0)
251                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
252
253                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
254                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
255
256                 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_cert, 1, x509_key)) < 0)
257                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
258
259                 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
260
261                 if((ret = gnutls_dh_params_init(&dh_params)) < 0)
262                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
263
264                 // This may be on a large (once a day or week) timer eventually.
265                 GenerateDHParams();
266         }
267
268         void GenerateDHParams()
269         {
270                 // Generate Diffie Hellman parameters - for use with DHE
271                 // kx algorithms. These should be discarded and regenerated
272                 // once a day, once a week or once a month. Depending on the
273                 // security requirements.
274
275                 int ret;
276
277                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
278                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
279         }
280
281         virtual ~ModuleSSLGnuTLS()
282         {
283                 gnutls_x509_crt_deinit(x509_cert);
284                 gnutls_x509_privkey_deinit(x509_key);
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 = static_cast<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                 }
306         }
307
308         virtual Version GetVersion()
309         {
310                 return Version("$Id$", VF_VENDOR, API_VERSION);
311         }
312
313
314         virtual void On005Numeric(std::string &output)
315         {
316                 if (!sslports.empty())
317                         output.append(" SSL=" + sslports);
318                 output.append(" STARTTLS");
319         }
320
321         virtual void OnHookIO(EventHandler* user, ListenSocketBase* lsb)
322         {
323                 if (!user->GetIOHook() && listenports.find(lsb) != listenports.end())
324                 {
325                         /* Hook the user with our module */
326                         user->AddIOHook(this);
327                 }
328         }
329
330         virtual const char* OnRequest(Request* request)
331         {
332                 ISHRequest* ISR = static_cast<ISHRequest*>(request);
333                 if (strcmp("IS_NAME", request->GetId()) == 0)
334                 {
335                         return "gnutls";
336                 }
337                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
338                 {
339                         const char* ret = "OK";
340                         try
341                         {
342                                 ret = ISR->Sock->AddIOHook(this) ? "OK" : NULL;
343                         }
344                         catch (ModuleException &e)
345                         {
346                                 return NULL;
347                         }
348                         return ret;
349                 }
350                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
351                 {
352                         return ISR->Sock->DelIOHook() ? "OK" : NULL;
353                 }
354                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
355                 {
356                         if (ISR->Sock->GetFd() < 0)
357                                 return "OK";
358
359                         issl_session* session = &sessions[ISR->Sock->GetFd()];
360                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : "OK";
361                 }
362                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
363                 {
364                         if (ISR->Sock->GetFd() > -1)
365                         {
366                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
367                                 if (session->sess)
368                                 {
369                                         if (static_cast<Extensible*>(ServerInstance->SE->GetRef(ISR->Sock->GetFd())) == static_cast<Extensible*>(ISR->Sock))
370                                         {
371                                                 return "OK";
372                                         }
373                                 }
374                         }
375                 }
376                 else if (strcmp("GET_CERT", request->GetId()) == 0)
377                 {
378                         Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
379                         if (sslinfo)
380                                 return sslinfo->OnRequest(request);
381                 }
382                 return NULL;
383         }
384
385
386         virtual void OnRawSocketAccept(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
387         {
388                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
389                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
390                         return;
391
392                 issl_session* session = &sessions[fd];
393
394                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
395                 if (session->sess)
396                         return;
397
398                 gnutls_init(&session->sess, GNUTLS_SERVER);
399
400                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
401                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
402                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
403
404                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(fd)); // Give gnutls the fd for the socket.
405
406                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
407
408                 Handshake(session, fd);
409         }
410
411         virtual void OnRawSocketConnect(int fd)
412         {
413                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
414                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
415                         return;
416
417                 issl_session* session = &sessions[fd];
418
419                 gnutls_init(&session->sess, GNUTLS_CLIENT);
420
421                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
422                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
423                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
424                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(fd)); // Give gnutls the fd for the socket.
425
426                 Handshake(session, fd);
427         }
428
429         virtual void OnRawSocketClose(int fd)
430         {
431                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
432                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds()))
433                         return;
434
435                 CloseSession(&sessions[fd]);
436         }
437
438         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
439         {
440                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
441                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
442                         return 0;
443
444                 issl_session* session = &sessions[fd];
445
446                 if (!session->sess)
447                 {
448                         readresult = 0;
449                         CloseSession(session);
450                         return 1;
451                 }
452
453                 if (session->status == ISSL_HANDSHAKING_READ)
454                 {
455                         // The handshake isn't finished, try to finish it.
456
457                         if(!Handshake(session, fd))
458                         {
459                                 errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
460                                 // Couldn't resume handshake.
461                                 return -1;
462                         }
463                 }
464                 else if (session->status == ISSL_HANDSHAKING_WRITE)
465                 {
466                         errno = EAGAIN;
467                         MakePollWrite(fd);
468                         return -1;
469                 }
470
471                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
472
473                 if (session->status == ISSL_HANDSHAKEN)
474                 {
475                         unsigned int len = 0;
476                         while (len < count)
477                         {
478                                 int ret = gnutls_record_recv(session->sess, buffer + len, count - len);
479                                 if (ret > 0)
480                                 {
481                                         len += ret;
482                                 }
483                                 else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
484                                 {
485                                         break;
486                                 }
487                                 else
488                                 {
489                                         if (ret != 0)
490                                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
491                                                         "m_ssl_gnutls.so: Error while reading on fd %d: %s",
492                                                         fd, gnutls_strerror(ret));
493
494                                         // if ret == 0, client closed connection.
495                                         readresult = 0;
496                                         CloseSession(session);
497                                         return 1;
498                                 }
499                         }
500                         readresult = len;
501                         if (len)
502                         {
503                                 return 1;
504                         }
505                         else
506                         {
507                                 errno = EAGAIN;
508                                 return -1;
509                         }
510                 }
511                 else if (session->status == ISSL_CLOSING)
512                         readresult = 0;
513
514                 return 1;
515         }
516
517         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
518         {
519                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
520                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
521                         return 0;
522
523                 issl_session* session = &sessions[fd];
524                 const char* sendbuffer = buffer;
525
526                 if (!session->sess)
527                 {
528                         CloseSession(session);
529                         return 1;
530                 }
531
532                 session->outbuf.append(sendbuffer, count);
533                 sendbuffer = session->outbuf.c_str();
534                 count = session->outbuf.size();
535
536                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
537                 {
538                         // The handshake isn't finished, try to finish it.
539                         Handshake(session, fd);
540                         errno = session->status == ISSL_CLOSING ? EIO : EAGAIN;
541                         return -1;
542                 }
543
544                 int ret = 0;
545
546                 if (session->status == ISSL_HANDSHAKEN)
547                 {
548                         ret = gnutls_record_send(session->sess, sendbuffer, count);
549
550                         if (ret == 0)
551                         {
552                                 CloseSession(session);
553                         }
554                         else if (ret < 0)
555                         {
556                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
557                                 {
558                                         ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
559                                                         "m_ssl_gnutls.so: Error while writing to fd %d: %s",
560                                                         fd, gnutls_strerror(ret));
561                                         CloseSession(session);
562                                 }
563                                 else
564                                 {
565                                         errno = EAGAIN;
566                                 }
567                         }
568                         else
569                         {
570                                 session->outbuf = session->outbuf.substr(ret);
571                         }
572                 }
573
574                 if (!session->outbuf.empty())
575                         MakePollWrite(fd);
576
577                 /* Who's smart idea was it to return 1 when we havent written anything?
578                  * This fucks the buffer up in BufferedSocket :p
579                  */
580                 return ret < 1 ? 0 : ret;
581         }
582
583         bool Handshake(issl_session* session, int fd)
584         {
585                 int ret = gnutls_handshake(session->sess);
586
587                 if (ret < 0)
588                 {
589                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
590                         {
591                                 // Handshake needs resuming later, read() or write() would have blocked.
592
593                                 if(gnutls_record_get_direction(session->sess) == 0)
594                                 {
595                                         // gnutls_handshake() wants to read() again.
596                                         session->status = ISSL_HANDSHAKING_READ;
597                                 }
598                                 else
599                                 {
600                                         // gnutls_handshake() wants to write() again.
601                                         session->status = ISSL_HANDSHAKING_WRITE;
602                                         MakePollWrite(fd);
603                                 }
604                         }
605                         else
606                         {
607                                 // Handshake failed.
608                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT,
609                                                 "m_ssl_gnutls.so: Handshake failed on fd %d: %s",
610                                                 fd, gnutls_strerror(ret));
611                                 CloseSession(session);
612                                 session->status = ISSL_CLOSING;
613                         }
614
615                         return false;
616                 }
617                 else
618                 {
619                         // Change the seesion state
620                         session->status = ISSL_HANDSHAKEN;
621
622                         EventHandler* user = ServerInstance->SE->GetRef(fd);
623
624                         VerifyCertificate(session,user);
625
626                         // Finish writing, if any left
627                         MakePollWrite(fd);
628
629                         return true;
630                 }
631         }
632
633         virtual void OnPostConnect(User* user)
634         {
635                 // This occurs AFTER OnUserConnect so we can be sure the
636                 // protocol module has propagated the NICK message.
637                 if (user->GetIOHook() == this && (IS_LOCAL(user)))
638                 {
639                         if (sessions[user->GetFd()].sess)
640                         {
641                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
642                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
643                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
644                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
645                         }
646                 }
647         }
648
649         void MakePollWrite(int fd)
650         {
651                 //OnRawSocketWrite(fd, NULL, 0);
652                 EventHandler* eh = ServerInstance->SE->GetRef(fd);
653                 if (eh)
654                         ServerInstance->SE->WantWrite(eh);
655         }
656
657         virtual void OnBufferFlushed(User* user)
658         {
659                 if (user->GetIOHook() == this)
660                 {
661                         issl_session* session = &sessions[user->GetFd()];
662                         if (session && session->outbuf.size())
663                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
664                 }
665         }
666
667         void CloseSession(issl_session* session)
668         {
669                 if(session->sess)
670                 {
671                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
672                         gnutls_deinit(session->sess);
673                 }
674
675                 session->outbuf.clear();
676                 session->sess = NULL;
677                 session->status = ISSL_NONE;
678         }
679
680         void VerifyCertificate(issl_session* session, Extensible* user)
681         {
682                 if (!session->sess || !user)
683                         return;
684
685                 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
686                 if (!sslinfo)
687                         return;
688
689                 unsigned int status;
690                 const gnutls_datum_t* cert_list;
691                 int ret;
692                 unsigned int cert_list_size;
693                 gnutls_x509_crt_t cert;
694                 char name[MAXBUF];
695                 unsigned char digest[MAXBUF];
696                 size_t digest_size = sizeof(digest);
697                 size_t name_size = sizeof(name);
698                 ssl_cert* certinfo = new ssl_cert;
699
700                 /* This verification function uses the trusted CAs in the credentials
701                  * structure. So you must have installed one or more CA certificates.
702                  */
703                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
704
705                 if (ret < 0)
706                 {
707                         certinfo->error = std::string(gnutls_strerror(ret));
708                         goto info_done;
709                 }
710
711                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
712                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
713                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
714                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
715
716                 /* Up to here the process is the same for X.509 certificates and
717                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
718                  * be easily extended to work with openpgp keys as well.
719                  */
720                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
721                 {
722                         certinfo->error = "No X509 keys sent";
723                         goto info_done;
724                 }
725
726                 ret = gnutls_x509_crt_init(&cert);
727                 if (ret < 0)
728                 {
729                         certinfo->error = gnutls_strerror(ret);
730                         goto info_done;
731                 }
732
733                 cert_list_size = 0;
734                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
735                 if (cert_list == NULL)
736                 {
737                         certinfo->error = "No certificate was found";
738                         goto info_done_dealloc;
739                 }
740
741                 /* This is not a real world example, since we only check the first
742                  * certificate in the given chain.
743                  */
744
745                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
746                 if (ret < 0)
747                 {
748                         certinfo->error = gnutls_strerror(ret);
749                         goto info_done_dealloc;
750                 }
751
752                 gnutls_x509_crt_get_dn(cert, name, &name_size);
753                 certinfo->dn = name;
754
755                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
756                 certinfo->issuer = name;
757
758                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
759                 {
760                         certinfo->error = gnutls_strerror(ret);
761                 }
762                 else
763                 {
764                         certinfo->fingerprint = irc::hex(digest, digest_size);
765                 }
766
767                 /* Beware here we do not check for errors.
768                  */
769                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
770                 {
771                         certinfo->error = "Not activated, or expired certificate";
772                 }
773
774 info_done_dealloc:
775                 gnutls_x509_crt_deinit(cert);
776 info_done:
777                 BufferedSocketFingerprintSubmission(user, this, sslinfo, certinfo).Send();
778         }
779
780         void OnEvent(Event* ev)
781         {
782                 capHandler.HandleEvent(ev);
783         }
784 };
785
786 MODULE_INIT(ModuleSSLGnuTLS)