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