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