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