]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Fix ModuleManager failing when:
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_gnutls.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
6  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
8  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "inspircd.h"
25 #include <gnutls/gnutls.h>
26 #include <gnutls/x509.h>
27 #include <gcrypt.h>
28 #include "ssl.h"
29 #include "m_cap.h"
30
31 #ifdef _WIN32
32 # pragma comment(lib, "libgnutls.lib")
33 # pragma comment(lib, "libgcrypt.lib")
34 # pragma comment(lib, "libgpg-error.lib")
35 # pragma comment(lib, "user32.lib")
36 # pragma comment(lib, "advapi32.lib")
37 # pragma comment(lib, "libgcc.lib")
38 # pragma comment(lib, "libmingwex.lib")
39 # pragma comment(lib, "gdi32.lib")
40 #endif
41
42 /* $ModDesc: Provides SSL support for clients */
43 /* $CompileFlags: pkgconfincludes("gnutls","/gnutls/gnutls.h","") */
44 /* $LinkerFlags: rpath("pkg-config --libs gnutls") pkgconflibs("gnutls","/libgnutls.so","-lgnutls") -lgcrypt */
45
46 // These don't exist in older GnuTLS versions
47 #if(GNUTLS_VERSION_MAJOR < 2)
48 typedef gnutls_certificate_credentials_t gnutls_certificate_credentials;
49 typedef gnutls_dh_params_t gnutls_dh_params;
50 #endif
51
52 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
53
54 static std::vector<gnutls_x509_crt_t> x509_certs;
55 static gnutls_x509_privkey_t x509_key;
56 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
57 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
58         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr_st * st) {
59
60         st->type = GNUTLS_CRT_X509;
61 #else
62 static int cert_callback (gnutls_session_t session, const gnutls_datum_t * req_ca_rdn, int nreqs,
63         const gnutls_pk_algorithm_t * sign_algos, int sign_algos_length, gnutls_retr2_st * st) {
64         st->cert_type = GNUTLS_CRT_X509;
65         st->key_type = GNUTLS_PRIVKEY_X509;
66 #endif
67         st->ncerts = x509_certs.size();
68         st->cert.x509 = &x509_certs[0];
69         st->key.x509 = x509_key;
70         st->deinit_all = 0;
71
72         return 0;
73 }
74
75 static ssize_t gnutls_pull_wrapper(gnutls_transport_ptr_t user_wrap, void* buffer, size_t size)
76 {
77         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
78         if (user->GetEventMask() & FD_READ_WILL_BLOCK)
79         {
80                 errno = EAGAIN;
81                 return -1;
82         }
83         int rv = ServerInstance->SE->Recv(user, reinterpret_cast<char *>(buffer), size, 0);
84         if (rv < (int)size)
85                 ServerInstance->SE->ChangeEventMask(user, FD_READ_WILL_BLOCK);
86         return rv;
87 }
88
89 static ssize_t gnutls_push_wrapper(gnutls_transport_ptr_t user_wrap, const void* buffer, size_t size)
90 {
91         StreamSocket* user = reinterpret_cast<StreamSocket*>(user_wrap);
92         if (user->GetEventMask() & FD_WRITE_WILL_BLOCK)
93         {
94                 errno = EAGAIN;
95                 return -1;
96         }
97         int rv = ServerInstance->SE->Send(user, reinterpret_cast<const char *>(buffer), size, 0);
98         if (rv < (int)size)
99                 ServerInstance->SE->ChangeEventMask(user, FD_WRITE_WILL_BLOCK);
100         return rv;
101 }
102
103 class RandGen : public HandlerBase2<void, char*, size_t>
104 {
105  public:
106         RandGen() {}
107         void Call(char* buffer, size_t len)
108         {
109                 gcry_randomize(buffer, len, GCRY_STRONG_RANDOM);
110         }
111 };
112
113 /** Represents an SSL user's extra data
114  */
115 class issl_session
116 {
117 public:
118         gnutls_session_t sess;
119         issl_status status;
120         reference<ssl_cert> cert;
121         issl_session() : sess(NULL) {}
122 };
123
124 class CommandStartTLS : public SplitCommand
125 {
126  public:
127         bool enabled;
128         CommandStartTLS (Module* mod) : SplitCommand(mod, "STARTTLS")
129         {
130                 enabled = true;
131                 works_before_reg = true;
132         }
133
134         CmdResult HandleLocal(const std::vector<std::string> &parameters, LocalUser *user)
135         {
136                 if (!enabled)
137                 {
138                         user->WriteNumeric(691, "%s :STARTTLS is not enabled", user->nick.c_str());
139                         return CMD_FAILURE;
140                 }
141
142                 if (user->registered == REG_ALL)
143                 {
144                         user->WriteNumeric(691, "%s :STARTTLS is not permitted after client registration is complete", user->nick.c_str());
145                 }
146                 else
147                 {
148                         if (!user->eh.GetIOHook())
149                         {
150                                 user->WriteNumeric(670, "%s :STARTTLS successful, go ahead with TLS handshake", user->nick.c_str());
151                                 /* We need to flush the write buffer prior to adding the IOHook,
152                                  * otherwise we'll be sending this line inside the SSL session - which
153                                  * won't start its handshake until the client gets this line. Currently,
154                                  * we assume the write will not block here; this is usually safe, as
155                                  * STARTTLS is sent very early on in the registration phase, where the
156                                  * user hasn't built up much sendq. Handling a blocked write here would
157                                  * be very annoying.
158                                  */
159                                 user->eh.DoWrite();
160                                 user->eh.AddIOHook(creator);
161                                 creator->OnStreamSocketAccept(&user->eh, NULL, NULL);
162                         }
163                         else
164                                 user->WriteNumeric(691, "%s :STARTTLS failure", user->nick.c_str());
165                 }
166
167                 return CMD_FAILURE;
168         }
169 };
170
171 class ModuleSSLGnuTLS : public Module
172 {
173         issl_session* sessions;
174
175         gnutls_certificate_credentials_t x509_cred;
176         gnutls_dh_params_t dh_params;
177         gnutls_digest_algorithm_t hash;
178         gnutls_priority_t priority;
179
180         std::string sslports;
181         int dh_bits;
182
183         bool cred_alloc;
184         bool dh_alloc;
185
186         RandGen randhandler;
187         CommandStartTLS starttls;
188
189         GenericCap capHandler;
190         ServiceProvider iohook;
191  public:
192
193         ModuleSSLGnuTLS()
194                 : starttls(this), capHandler(this, "tls"), iohook(this, "ssl/gnutls", SERVICE_IOHOOK)
195         {
196                 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
197
198                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
199
200                 gnutls_global_init(); // This must be called once in the program
201                 gnutls_x509_privkey_init(&x509_key);
202                 // Init this here so it's always initialized, avoids an extra boolean
203                 gnutls_priority_init(&priority, "NORMAL", NULL);
204
205                 cred_alloc = false;
206                 dh_alloc = false;
207         }
208
209         void init()
210         {
211                 // Needs the flag as it ignores a plain /rehash
212                 OnModuleRehash(NULL,"ssl");
213
214                 ServerInstance->GenRandom = &randhandler;
215
216                 // Void return, guess we assume success
217                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
218                 Implementation eventlist[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnUserConnect,
219                         I_OnEvent, I_OnHookIO };
220                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
221
222                 ServerInstance->Modules->AddService(iohook);
223                 ServerInstance->AddCommand(&starttls);
224         }
225
226         void OnRehash(User* user)
227         {
228                 sslports.clear();
229
230                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
231                 starttls.enabled = Conf->getBool("starttls", true);
232
233                 if (Conf->getBool("showports", true))
234                 {
235                         sslports = Conf->getString("advertisedports");
236                         if (!sslports.empty())
237                                 return;
238
239                         for (size_t i = 0; i < ServerInstance->ports.size(); i++)
240                         {
241                                 ListenSocket* port = ServerInstance->ports[i];
242                                 if (port->bind_tag->getString("ssl") != "gnutls")
243                                         continue;
244
245                                 const std::string& portid = port->bind_desc;
246                                 ServerInstance->Logs->Log("m_ssl_gnutls", DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %s", portid.c_str());
247
248                                 if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
249                                 {
250                                         /*
251                                          * Found an SSL port for clients that is not bound to 127.0.0.1 and handled by us, display
252                                          * the IP:port in ISUPPORT.
253                                          *
254                                          * We used to advertise all ports seperated by a ';' char that matched the above criteria,
255                                          * but this resulted in too long ISUPPORT lines if there were lots of ports to be displayed.
256                                          * To solve this by default we now only display the first IP:port found and let the user
257                                          * configure the exact value for the 005 token, if necessary.
258                                          */
259                                         sslports = portid;
260                                         break;
261                                 }
262                         }
263                 }
264         }
265
266         void OnModuleRehash(User* user, const std::string &param)
267         {
268                 if(param != "ssl")
269                         return;
270
271                 std::string keyfile;
272                 std::string certfile;
273                 std::string cafile;
274                 std::string crlfile;
275                 OnRehash(user);
276
277                 ConfigTag* Conf = ServerInstance->Config->ConfValue("gnutls");
278
279                 cafile = Conf->getString("cafile", CONFIG_PATH "/ca.pem");
280                 crlfile = Conf->getString("crlfile", CONFIG_PATH "/crl.pem");
281                 certfile = Conf->getString("certfile", CONFIG_PATH "/cert.pem");
282                 keyfile = Conf->getString("keyfile", CONFIG_PATH "/key.pem");
283                 dh_bits = Conf->getInt("dhbits");
284                 std::string hashname = Conf->getString("hash", "md5");
285
286                 // The GnuTLS manual states that the gnutls_set_default_priority()
287                 // call we used previously when initializing the session is the same
288                 // as setting the "NORMAL" priority string.
289                 // Thus if the setting below is not in the config we will behave exactly
290                 // the same as before, when the priority setting wasn't available.
291                 std::string priorities = Conf->getString("priority", "NORMAL");
292
293                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
294                         dh_bits = 1024;
295
296                 if (hashname == "md5")
297                         hash = GNUTLS_DIG_MD5;
298                 else if (hashname == "sha1")
299                         hash = GNUTLS_DIG_SHA1;
300                 else
301                         throw ModuleException("Unknown hash type " + hashname);
302
303
304                 int ret;
305
306                 if (dh_alloc)
307                 {
308                         gnutls_dh_params_deinit(dh_params);
309                         dh_alloc = false;
310                 }
311
312                 if (cred_alloc)
313                 {
314                         // Deallocate the old credentials
315                         gnutls_certificate_free_credentials(x509_cred);
316
317                         for(unsigned int i=0; i < x509_certs.size(); i++)
318                                 gnutls_x509_crt_deinit(x509_certs[i]);
319                         x509_certs.clear();
320                 }
321
322                 ret = gnutls_certificate_allocate_credentials(&x509_cred);
323                 cred_alloc = (ret >= 0);
324                 if (!cred_alloc)
325                         ServerInstance->Logs->Log("m_ssl_gnutls",DEBUG, "m_ssl_gnutls.so: Failed to allocate certificate credentials: %s", gnutls_strerror(ret));
326
327                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
328                         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));
329
330                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
331                         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));
332
333                 FileReader reader;
334
335                 reader.LoadFile(certfile);
336                 std::string cert_string = reader.Contents();
337                 gnutls_datum_t cert_datum = { (unsigned char*)cert_string.data(), static_cast<unsigned int>(cert_string.length()) };
338
339                 reader.LoadFile(keyfile);
340                 std::string key_string = reader.Contents();
341                 gnutls_datum_t key_datum = { (unsigned char*)key_string.data(), static_cast<unsigned int>(key_string.length()) };
342
343                 // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
344                 unsigned int certcount = Conf->getInt("certcount", 3);
345                 x509_certs.resize(certcount);
346                 ret = gnutls_x509_crt_list_import(&x509_certs[0], &certcount, &cert_datum, GNUTLS_X509_FMT_PEM, GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED);
347                 if (ret < 0)
348                         throw ModuleException("Unable to load GnuTLS server certificate (" + certfile + "): " + std::string(gnutls_strerror(ret)));
349                 x509_certs.resize(certcount);
350
351                 if((ret = gnutls_x509_privkey_import(x509_key, &key_datum, GNUTLS_X509_FMT_PEM)) < 0)
352                         throw ModuleException("Unable to load GnuTLS server private key (" + keyfile + "): " + std::string(gnutls_strerror(ret)));
353
354                 if((ret = gnutls_certificate_set_x509_key(x509_cred, &x509_certs[0], certcount, x509_key)) < 0)
355                         throw ModuleException("Unable to set GnuTLS cert/key pair: " + std::string(gnutls_strerror(ret)));
356
357                 // It's safe to call this every time as we cannot have this uninitialized, see constructor and below.
358                 gnutls_priority_deinit(priority);
359
360                 // Try to set the priorities for ciphers, kex methods etc. to the user supplied string
361                 // If the user did not supply anything then the string is already set to "NORMAL"
362                 const char* priocstr = priorities.c_str();
363                 const char* prioerror;
364
365                 if ((ret = gnutls_priority_init(&priority, priocstr, &prioerror)) < 0)
366                 {
367                         // gnutls did not understand the user supplied string, log and fall back to the default priorities
368                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to set priorities to \"%s\": %s Syntax error at position %u, falling back to default (NORMAL)", priorities.c_str(), gnutls_strerror(ret), (unsigned int) (prioerror - priocstr));
369                         gnutls_priority_init(&priority, "NORMAL", NULL);
370                 }
371
372                 #if(GNUTLS_VERSION_MAJOR < 2 || ( GNUTLS_VERSION_MAJOR == 2 && GNUTLS_VERSION_MINOR < 12 ) )
373                 gnutls_certificate_client_set_retrieve_function (x509_cred, cert_callback);
374                 #else
375                 gnutls_certificate_set_retrieve_function (x509_cred, cert_callback);
376                 #endif
377                 ret = gnutls_dh_params_init(&dh_params);
378                 dh_alloc = (ret >= 0);
379                 if (!dh_alloc)
380                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters: %s", gnutls_strerror(ret));
381
382                 // This may be on a large (once a day or week) timer eventually.
383                 GenerateDHParams();
384         }
385
386         void GenerateDHParams()
387         {
388                 // Generate Diffie Hellman parameters - for use with DHE
389                 // kx algorithms. These should be discarded and regenerated
390                 // once a day, once a week or once a month. Depending on the
391                 // security requirements.
392
393                 if (!dh_alloc)
394                         return;
395
396                 int ret;
397
398                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
399                         ServerInstance->Logs->Log("m_ssl_gnutls",DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
400         }
401
402         ~ModuleSSLGnuTLS()
403         {
404                 for(unsigned int i=0; i < x509_certs.size(); i++)
405                         gnutls_x509_crt_deinit(x509_certs[i]);
406
407                 gnutls_x509_privkey_deinit(x509_key);
408                 gnutls_priority_deinit(priority);
409
410                 if (dh_alloc)
411                         gnutls_dh_params_deinit(dh_params);
412                 if (cred_alloc)
413                         gnutls_certificate_free_credentials(x509_cred);
414
415                 gnutls_global_deinit();
416                 delete[] sessions;
417                 ServerInstance->GenRandom = &ServerInstance->HandleGenRandom;
418         }
419
420         void OnCleanup(int target_type, void* item)
421         {
422                 if(target_type == TYPE_USER)
423                 {
424                         LocalUser* user = IS_LOCAL(static_cast<User*>(item));
425
426                         if (user && user->eh.GetIOHook() == this)
427                         {
428                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
429                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
430                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
431                         }
432                 }
433         }
434
435         Version GetVersion()
436         {
437                 return Version("Provides SSL support for clients", VF_VENDOR);
438         }
439
440
441         void On005Numeric(std::string &output)
442         {
443                 if (!sslports.empty())
444                         output.append(" SSL=" + sslports);
445                 if (starttls.enabled)
446                         output.append(" STARTTLS");
447         }
448
449         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
450         {
451                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "gnutls")
452                 {
453                         /* Hook the user with our module */
454                         user->AddIOHook(this);
455                 }
456         }
457
458         void OnRequest(Request& request)
459         {
460                 if (strcmp("GET_SSL_CERT", request.id) == 0)
461                 {
462                         SocketCertificateRequest& req = static_cast<SocketCertificateRequest&>(request);
463                         int fd = req.sock->GetFd();
464                         issl_session* session = &sessions[fd];
465
466                         req.cert = session->cert;
467                 }
468         }
469
470         void InitSession(StreamSocket* user, bool me_server)
471         {
472                 issl_session* session = &sessions[user->GetFd()];
473
474                 gnutls_init(&session->sess, me_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
475
476                 gnutls_priority_set(session->sess, priority);
477                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
478                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
479                 gnutls_transport_set_ptr(session->sess, reinterpret_cast<gnutls_transport_ptr_t>(user));
480                 gnutls_transport_set_push_function(session->sess, gnutls_push_wrapper);
481                 gnutls_transport_set_pull_function(session->sess, gnutls_pull_wrapper);
482
483                 if (me_server)
484                         gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
485
486                 Handshake(session, user);
487         }
488
489         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
490         {
491                 issl_session* session = &sessions[user->GetFd()];
492
493                 /* For STARTTLS: Don't try and init a session on a socket that already has a session */
494                 if (session->sess)
495                         return;
496
497                 InitSession(user, true);
498         }
499
500         void OnStreamSocketConnect(StreamSocket* user)
501         {
502                 InitSession(user, false);
503         }
504
505         void OnStreamSocketClose(StreamSocket* user)
506         {
507                 CloseSession(&sessions[user->GetFd()]);
508         }
509
510         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
511         {
512                 issl_session* session = &sessions[user->GetFd()];
513
514                 if (!session->sess)
515                 {
516                         CloseSession(session);
517                         user->SetError("No SSL session");
518                         return -1;
519                 }
520
521                 if (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE)
522                 {
523                         // The handshake isn't finished, try to finish it.
524
525                         if(!Handshake(session, user))
526                         {
527                                 if (session->status != ISSL_CLOSING)
528                                         return 0;
529                                 return -1;
530                         }
531                 }
532
533                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
534
535                 if (session->status == ISSL_HANDSHAKEN)
536                 {
537                         char* buffer = ServerInstance->GetReadBuffer();
538                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
539                         int ret = gnutls_record_recv(session->sess, buffer, bufsiz);
540                         if (ret > 0)
541                         {
542                                 recvq.append(buffer, ret);
543                                 return 1;
544                         }
545                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
546                         {
547                                 return 0;
548                         }
549                         else if (ret == 0)
550                         {
551                                 user->SetError("SSL Connection closed");
552                                 CloseSession(session);
553                                 return -1;
554                         }
555                         else
556                         {
557                                 user->SetError(gnutls_strerror(ret));
558                                 CloseSession(session);
559                                 return -1;
560                         }
561                 }
562                 else if (session->status == ISSL_CLOSING)
563                         return -1;
564
565                 return 0;
566         }
567
568         int OnStreamSocketWrite(StreamSocket* user, std::string& sendq)
569         {
570                 issl_session* session = &sessions[user->GetFd()];
571
572                 if (!session->sess)
573                 {
574                         CloseSession(session);
575                         user->SetError("No SSL session");
576                         return -1;
577                 }
578
579                 if (session->status == ISSL_HANDSHAKING_WRITE || session->status == ISSL_HANDSHAKING_READ)
580                 {
581                         // The handshake isn't finished, try to finish it.
582                         Handshake(session, user);
583                         if (session->status != ISSL_CLOSING)
584                                 return 0;
585                         return -1;
586                 }
587
588                 int ret = 0;
589
590                 if (session->status == ISSL_HANDSHAKEN)
591                 {
592                         ret = gnutls_record_send(session->sess, sendq.data(), sendq.length());
593
594                         if (ret == (int)sendq.length())
595                         {
596                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_WRITE);
597                                 return 1;
598                         }
599                         else if (ret > 0)
600                         {
601                                 sendq = sendq.substr(ret);
602                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
603                                 return 0;
604                         }
605                         else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
606                         {
607                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
608                                 return 0;
609                         }
610                         else // (ret < 0)
611                         {
612                                 user->SetError(gnutls_strerror(ret));
613                                 CloseSession(session);
614                                 return -1;
615                         }
616                 }
617
618                 return 0;
619         }
620
621         bool Handshake(issl_session* session, StreamSocket* user)
622         {
623                 int ret = gnutls_handshake(session->sess);
624
625                 if (ret < 0)
626                 {
627                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
628                         {
629                                 // Handshake needs resuming later, read() or write() would have blocked.
630
631                                 if(gnutls_record_get_direction(session->sess) == 0)
632                                 {
633                                         // gnutls_handshake() wants to read() again.
634                                         session->status = ISSL_HANDSHAKING_READ;
635                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
636                                 }
637                                 else
638                                 {
639                                         // gnutls_handshake() wants to write() again.
640                                         session->status = ISSL_HANDSHAKING_WRITE;
641                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
642                                 }
643                         }
644                         else
645                         {
646                                 user->SetError("Handshake Failed - " + std::string(gnutls_strerror(ret)));
647                                 CloseSession(session);
648                                 session->status = ISSL_CLOSING;
649                         }
650
651                         return false;
652                 }
653                 else
654                 {
655                         // Change the seesion state
656                         session->status = ISSL_HANDSHAKEN;
657
658                         VerifyCertificate(session,user);
659
660                         // Finish writing, if any left
661                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
662
663                         return true;
664                 }
665         }
666
667         void OnUserConnect(LocalUser* user)
668         {
669                 if (user->eh.GetIOHook() == this)
670                 {
671                         if (sessions[user->eh.GetFd()].sess)
672                         {
673                                 ssl_cert* cert = sessions[user->eh.GetFd()].cert;
674                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->eh.GetFd()].sess));
675                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->eh.GetFd()].sess))).append("-");
676                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->eh.GetFd()].sess)));
677                                 if (cert->fingerprint.empty())
678                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick.c_str(), cipher.c_str());
679                                 else
680                                         user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\""
681                                                 " and your SSL fingerprint is %s", user->nick.c_str(), cipher.c_str(), cert->fingerprint.c_str());
682                         }
683                 }
684         }
685
686         void CloseSession(issl_session* session)
687         {
688                 if (session->sess)
689                 {
690                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
691                         gnutls_deinit(session->sess);
692                 }
693                 session->sess = NULL;
694                 session->cert = NULL;
695                 session->status = ISSL_NONE;
696         }
697
698         void VerifyCertificate(issl_session* session, StreamSocket* user)
699         {
700                 if (!session->sess || !user)
701                         return;
702
703                 unsigned int status;
704                 const gnutls_datum_t* cert_list;
705                 int ret;
706                 unsigned int cert_list_size;
707                 gnutls_x509_crt_t cert;
708                 char name[MAXBUF];
709                 unsigned char digest[MAXBUF];
710                 size_t digest_size = sizeof(digest);
711                 size_t name_size = sizeof(name);
712                 ssl_cert* certinfo = new ssl_cert;
713                 session->cert = certinfo;
714
715                 /* This verification function uses the trusted CAs in the credentials
716                  * structure. So you must have installed one or more CA certificates.
717                  */
718                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
719
720                 if (ret < 0)
721                 {
722                         certinfo->error = std::string(gnutls_strerror(ret));
723                         return;
724                 }
725
726                 certinfo->invalid = (status & GNUTLS_CERT_INVALID);
727                 certinfo->unknownsigner = (status & GNUTLS_CERT_SIGNER_NOT_FOUND);
728                 certinfo->revoked = (status & GNUTLS_CERT_REVOKED);
729                 certinfo->trusted = !(status & GNUTLS_CERT_SIGNER_NOT_CA);
730
731                 /* Up to here the process is the same for X.509 certificates and
732                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
733                  * be easily extended to work with openpgp keys as well.
734                  */
735                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
736                 {
737                         certinfo->error = "No X509 keys sent";
738                         return;
739                 }
740
741                 ret = gnutls_x509_crt_init(&cert);
742                 if (ret < 0)
743                 {
744                         certinfo->error = gnutls_strerror(ret);
745                         return;
746                 }
747
748                 cert_list_size = 0;
749                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
750                 if (cert_list == NULL)
751                 {
752                         certinfo->error = "No certificate was found";
753                         goto info_done_dealloc;
754                 }
755
756                 /* This is not a real world example, since we only check the first
757                  * certificate in the given chain.
758                  */
759
760                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
761                 if (ret < 0)
762                 {
763                         certinfo->error = gnutls_strerror(ret);
764                         goto info_done_dealloc;
765                 }
766
767                 gnutls_x509_crt_get_dn(cert, name, &name_size);
768                 certinfo->dn = name;
769
770                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
771                 certinfo->issuer = name;
772
773                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, hash, digest, &digest_size)) < 0)
774                 {
775                         certinfo->error = gnutls_strerror(ret);
776                 }
777                 else
778                 {
779                         certinfo->fingerprint = irc::hex(digest, digest_size);
780                 }
781
782                 /* Beware here we do not check for errors.
783                  */
784                 if ((gnutls_x509_crt_get_expiration_time(cert) < ServerInstance->Time()) || (gnutls_x509_crt_get_activation_time(cert) > ServerInstance->Time()))
785                 {
786                         certinfo->error = "Not activated, or expired certificate";
787                 }
788
789 info_done_dealloc:
790                 gnutls_x509_crt_deinit(cert);
791         }
792
793         void OnEvent(Event& ev)
794         {
795                 if (starttls.enabled)
796                         capHandler.HandleEvent(ev);
797         }
798 };
799
800 MODULE_INIT(ModuleSSLGnuTLS)