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