]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Header update: 2007 -> 2008
[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-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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
16 #include <gnutls/gnutls.h>
17 #include <gnutls/x509.h>
18
19 #include "inspircd_config.h"
20 #include "configreader.h"
21 #include "users.h"
22 #include "channels.h"
23 #include "modules.h"
24 #include "socket.h"
25 #include "hashcomp.h"
26 #include "transport.h"
27
28 #ifdef WINDOWS
29 #pragma comment(lib, "libgnutls-13.lib")
30 #undef MAX_DESCRIPTORS
31 #define MAX_DESCRIPTORS 10000
32 #endif
33
34 /* $ModDesc: Provides SSL support for clients */
35 /* $CompileFlags: exec("libgnutls-config --cflags") */
36 /* $LinkerFlags: rpath("libgnutls-config --libs") exec("libgnutls-config --libs") */
37 /* $ModDep: transport.h */
38 /* $CopyInstall: conf/key.pem $(CONPATH) */
39 /* $CopyInstall: conf/cert.pem $(CONPATH) */
40
41 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
42
43 bool isin(int port, const std::vector<int> &portlist)
44 {
45         for(unsigned int i = 0; i < portlist.size(); i++)
46                 if(portlist[i] == port)
47                         return true;
48
49         return false;
50 }
51
52 /** Represents an SSL user's extra data
53  */
54 class issl_session : public classbase
55 {
56 public:
57         gnutls_session_t sess;
58         issl_status status;
59         std::string outbuf;
60         int inbufoffset;
61         char* inbuf;
62         int fd;
63 };
64
65 class ModuleSSLGnuTLS : public Module
66 {
67
68         ConfigReader* Conf;
69
70         char* dummy;
71
72         std::vector<int> listenports;
73
74         int inbufsize;
75         issl_session sessions[MAX_DESCRIPTORS];
76
77         gnutls_certificate_credentials x509_cred;
78         gnutls_dh_params dh_params;
79
80         std::string keyfile;
81         std::string certfile;
82         std::string cafile;
83         std::string crlfile;
84         std::string sslports;
85         int dh_bits;
86
87         int clientactive;
88
89  public:
90
91         ModuleSSLGnuTLS(InspIRCd* Me)
92                 : Module(Me)
93         {
94                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
95
96                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
97                 inbufsize = ServerInstance->Config->NetBufferSize;
98
99                 gnutls_global_init(); // This must be called once in the program
100
101                 if(gnutls_certificate_allocate_credentials(&x509_cred) != 0)
102                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to allocate certificate credentials");
103
104                 // Guessing return meaning
105                 if(gnutls_dh_params_init(&dh_params) < 0)
106                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to initialise DH parameters");
107
108                 // Needs the flag as it ignores a plain /rehash
109                 OnRehash(NULL,"ssl");
110
111                 // Void return, guess we assume success
112                 gnutls_certificate_set_dh_params(x509_cred, dh_params);
113                 Implementation eventlist[] = { I_On005Numeric, I_OnRawSocketConnect, I_OnRawSocketAccept, I_OnRawSocketClose, I_OnRawSocketRead, I_OnRawSocketWrite, I_OnCleanup,
114                         I_OnBufferFlushed, I_OnRequest, I_OnSyncUserMetaData, I_OnDecodeMetaData, I_OnUnloadModule, I_OnRehash, I_OnWhois, I_OnPostConnect };
115                 ServerInstance->Modules->Attach(eventlist, this, 15);
116         }
117
118         virtual void OnRehash(User* user, const std::string &param)
119         {
120                 if(param != "ssl")
121                         return;
122
123                 Conf = new ConfigReader(ServerInstance);
124
125                 for(unsigned int i = 0; i < listenports.size(); i++)
126                 {
127                         ServerInstance->Config->DelIOHook(listenports[i]);
128                 }
129
130                 listenports.clear();
131                 clientactive = 0;
132                 sslports.clear();
133
134                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
135                 {
136                         // For each <bind> tag
137                         std::string x = Conf->ReadValue("bind", "type", i);
138                         if(((x.empty()) || (x == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
139                         {
140                                 // Get the port we're meant to be listening on with SSL
141                                 std::string port = Conf->ReadValue("bind", "port", i);
142                                 irc::portparser portrange(port, false);
143                                 long portno = -1;
144                                 while ((portno = portrange.GetToken()))
145                                 {
146                                         clientactive++;
147                                         try
148                                         {
149                                                 if (ServerInstance->Config->AddIOHook(portno, this))
150                                                 {
151                                                         listenports.push_back(portno);
152                                                         for (size_t i = 0; i < ServerInstance->Config->ports.size(); i++)
153                                                                 if (ServerInstance->Config->ports[i]->GetPort() == portno)
154                                                                         ServerInstance->Config->ports[i]->SetDescription("ssl");
155                                                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Enabling SSL for port %d", portno);
156                                                         sslports.append("*:").append(ConvToStr(portno)).append(";");
157                                                 }
158                                                 else
159                                                 {
160                                                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
161                                                 }
162                                         }
163                                         catch (ModuleException &e)
164                                         {
165                                                 ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: FAILED to enable SSL on port %d: %s. Maybe it's already hooked by the same port on a different IP, or you have an other SSL or similar module loaded?", portno, e.GetReason());
166                                         }
167                                 }
168                         }
169                 }
170
171                 std::string confdir(ServerInstance->ConfigFileName);
172                 // +1 so we the path ends with a /
173                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
174
175                 cafile  = Conf->ReadValue("gnutls", "cafile", 0);
176                 crlfile = Conf->ReadValue("gnutls", "crlfile", 0);
177                 certfile        = Conf->ReadValue("gnutls", "certfile", 0);
178                 keyfile = Conf->ReadValue("gnutls", "keyfile", 0);
179                 dh_bits = Conf->ReadInteger("gnutls", "dhbits", 0, false);
180
181                 // Set all the default values needed.
182                 if (cafile.empty())
183                         cafile = "ca.pem";
184
185                 if (crlfile.empty())
186                         crlfile = "crl.pem";
187
188                 if (certfile.empty())
189                         certfile = "cert.pem";
190
191                 if (keyfile.empty())
192                         keyfile = "key.pem";
193
194                 if((dh_bits != 768) && (dh_bits != 1024) && (dh_bits != 2048) && (dh_bits != 3072) && (dh_bits != 4096))
195                         dh_bits = 1024;
196
197                 // Prepend relative paths with the path to the config directory.
198                 if(cafile[0] != '/')
199                         cafile = confdir + cafile;
200
201                 if(crlfile[0] != '/')
202                         crlfile = confdir + crlfile;
203
204                 if(certfile[0] != '/')
205                         certfile = confdir + certfile;
206
207                 if(keyfile[0] != '/')
208                         keyfile = confdir + keyfile;
209
210                 int ret;
211
212                 if((ret =gnutls_certificate_set_x509_trust_file(x509_cred, cafile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
213                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 trust file '%s': %s", cafile.c_str(), gnutls_strerror(ret));
214
215                 if((ret = gnutls_certificate_set_x509_crl_file (x509_cred, crlfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
216                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to set X.509 CRL file '%s': %s", crlfile.c_str(), gnutls_strerror(ret));
217
218                 if((ret = gnutls_certificate_set_x509_key_file (x509_cred, certfile.c_str(), keyfile.c_str(), GNUTLS_X509_FMT_PEM)) < 0)
219                 {
220                         // If this fails, no SSL port will work. At all. So, do the smart thing - throw a ModuleException
221                         throw ModuleException("Unable to load GnuTLS server certificate: " + std::string(gnutls_strerror(ret)));
222                 }
223
224                 // This may be on a large (once a day or week) timer eventually.
225                 GenerateDHParams();
226
227                 delete Conf;
228         }
229
230         void GenerateDHParams()
231         {
232                 // Generate Diffie Hellman parameters - for use with DHE
233                 // kx algorithms. These should be discarded and regenerated
234                 // once a day, once a week or once a month. Depending on the
235                 // security requirements.
236
237                 int ret;
238
239                 if((ret = gnutls_dh_params_generate2(dh_params, dh_bits)) < 0)
240                         ServerInstance->Log(DEFAULT, "m_ssl_gnutls.so: Failed to generate DH parameters (%d bits): %s", dh_bits, gnutls_strerror(ret));
241         }
242
243         virtual ~ModuleSSLGnuTLS()
244         {
245                 gnutls_dh_params_deinit(dh_params);
246                 gnutls_certificate_free_credentials(x509_cred);
247                 gnutls_global_deinit();
248         }
249
250         virtual void OnCleanup(int target_type, void* item)
251         {
252                 if(target_type == TYPE_USER)
253                 {
254                         User* user = (User*)item;
255
256                         if(user->GetExt("ssl", dummy) && isin(user->GetPort(), listenports))
257                         {
258                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
259                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
260                                 User::QuitUser(ServerInstance, user, "SSL module unloading");
261                         }
262                         if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
263                         {
264                                 ssl_cert* tofree;
265                                 user->GetExt("ssl_cert", tofree);
266                                 delete tofree;
267                                 user->Shrink("ssl_cert");
268                         }
269                 }
270         }
271
272         virtual void OnUnloadModule(Module* mod, const std::string &name)
273         {
274                 if(mod == this)
275                 {
276                         for(unsigned int i = 0; i < listenports.size(); i++)
277                         {
278                                 ServerInstance->Config->DelIOHook(listenports[i]);
279                                 for (size_t j = 0; j < ServerInstance->Config->ports.size(); j++)
280                                         if (ServerInstance->Config->ports[j]->GetPort() == listenports[i])
281                                                 ServerInstance->Config->ports[j]->SetDescription("plaintext");
282                         }
283                 }
284         }
285
286         virtual Version GetVersion()
287         {
288                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
289         }
290
291
292         virtual void On005Numeric(std::string &output)
293         {
294                 output.append(" SSL=" + sslports);
295         }
296
297         virtual char* OnRequest(Request* request)
298         {
299                 ISHRequest* ISR = (ISHRequest*)request;
300                 if (strcmp("IS_NAME", request->GetId()) == 0)
301                 {
302                         return "gnutls";
303                 }
304                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
305                 {
306                         char* ret = "OK";
307                         try
308                         {
309                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
310                         }
311                         catch (ModuleException &e)
312                         {
313                                 return NULL;
314                         }
315                         return ret;
316                 }
317                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
318                 {
319                         return ServerInstance->Config->DelIOHook((BufferedSocket*)ISR->Sock) ? (char*)"OK" : NULL;
320                 }
321                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
322                 {
323                         if (ISR->Sock->GetFd() < 0)
324                                 return (char*)"OK";
325
326                         issl_session* session = &sessions[ISR->Sock->GetFd()];
327                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : (char*)"OK";
328                 }
329                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
330                 {
331                         if (ISR->Sock->GetFd() > -1)
332                         {
333                                 issl_session* session = &sessions[ISR->Sock->GetFd()];
334                                 if (session->sess)
335                                 {
336                                         if ((Extensible*)ServerInstance->FindDescriptor(ISR->Sock->GetFd()) == (Extensible*)(ISR->Sock))
337                                         {
338                                                 VerifyCertificate(session, (BufferedSocket*)ISR->Sock);
339                                                 return "OK";
340                                         }
341                                 }
342                         }
343                 }
344                 return NULL;
345         }
346
347
348         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
349         {
350                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
351                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
352                         return;
353
354                 issl_session* session = &sessions[fd];
355
356                 session->fd = fd;
357                 session->inbuf = new char[inbufsize];
358                 session->inbufoffset = 0;
359
360                 gnutls_init(&session->sess, GNUTLS_SERVER);
361
362                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
363                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
364                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
365
366                 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
367                  * This needs testing, but it's easy enough to rollback if need be
368                  * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
369                  * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
370                  *
371                  * With testing this seems to...not work :/
372                  */
373
374                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
375
376                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
377
378                 Handshake(session);
379         }
380
381         virtual void OnRawSocketConnect(int fd)
382         {
383                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
384                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
385                         return;
386
387                 issl_session* session = &sessions[fd];
388
389                 session->fd = fd;
390                 session->inbuf = new char[inbufsize];
391                 session->inbufoffset = 0;
392
393                 gnutls_init(&session->sess, GNUTLS_CLIENT);
394
395                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
396                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
397                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
398                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
399
400                 Handshake(session);
401         }
402
403         virtual void OnRawSocketClose(int fd)
404         {
405                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
406                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
407                         return;
408
409                 CloseSession(&sessions[fd]);
410
411                 EventHandler* user = ServerInstance->SE->GetRef(fd);
412
413                 if ((user) && (user->GetExt("ssl_cert", dummy)))
414                 {
415                         ssl_cert* tofree;
416                         user->GetExt("ssl_cert", tofree);
417                         delete tofree;
418                         user->Shrink("ssl_cert");
419                 }
420         }
421
422         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
423         {
424                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
425                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
426                         return 0;
427
428                 issl_session* session = &sessions[fd];
429
430                 if (!session->sess)
431                 {
432                         readresult = 0;
433                         CloseSession(session);
434                         return 1;
435                 }
436
437                 if (session->status == ISSL_HANDSHAKING_READ)
438                 {
439                         // The handshake isn't finished, try to finish it.
440
441                         if(!Handshake(session))
442                         {
443                                 // Couldn't resume handshake.
444                                 return -1;
445                         }
446                 }
447                 else if (session->status == ISSL_HANDSHAKING_WRITE)
448                 {
449                         errno = EAGAIN;
450                         MakePollWrite(session);
451                         return -1;
452                 }
453
454                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
455
456                 if (session->status == ISSL_HANDSHAKEN)
457                 {
458                         // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
459                         // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
460                         int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
461
462                         if (ret == 0)
463                         {
464                                 // Client closed connection.
465                                 readresult = 0;
466                                 CloseSession(session);
467                                 return 1;
468                         }
469                         else if (ret < 0)
470                         {
471                                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
472                                 {
473                                         errno = EAGAIN;
474                                         return -1;
475                                 }
476                                 else
477                                 {
478                                         readresult = 0;
479                                         CloseSession(session);
480                                 }
481                         }
482                         else
483                         {
484                                 // Read successfully 'ret' bytes into inbuf + inbufoffset
485                                 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
486                                 // 'buffer' is 'count' long
487
488                                 unsigned int length = ret + session->inbufoffset;
489
490                                 if(count <= length)
491                                 {
492                                         memcpy(buffer, session->inbuf, count);
493                                         // Move the stuff left in inbuf to the beginning of it
494                                         memcpy(session->inbuf, session->inbuf + count, (length - count));
495                                         // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
496                                         session->inbufoffset = length - count;
497                                         // Insp uses readresult as the count of how much data there is in buffer, so:
498                                         readresult = count;
499                                 }
500                                 else
501                                 {
502                                         // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
503                                         memcpy(buffer, session->inbuf, length);
504                                         // Zero the offset, as there's nothing there..
505                                         session->inbufoffset = 0;
506                                         // As above
507                                         readresult = length;
508                                 }
509                         }
510                 }
511                 else if(session->status == ISSL_CLOSING)
512                         readresult = 0;
513
514                 return 1;
515         }
516
517         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
518         {
519                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
520                 if ((fd < 0) || (fd > MAX_DESCRIPTORS))
521                         return 0;
522
523                 issl_session* session = &sessions[fd];
524                 const char* sendbuffer = buffer;
525
526                 if (!session->sess)
527                 {
528                         CloseSession(session);
529                         return 1;
530                 }
531
532                 session->outbuf.append(sendbuffer, count);
533                 sendbuffer = session->outbuf.c_str();
534                 count = session->outbuf.size();
535
536                 if (session->status == ISSL_HANDSHAKING_WRITE)
537                 {
538                         // The handshake isn't finished, try to finish it.
539                         Handshake(session);
540                         errno = EAGAIN;
541                         return -1;
542                 }
543
544                 int ret = 0;
545
546                 if (session->status == ISSL_HANDSHAKEN)
547                 {
548                         ret = gnutls_record_send(session->sess, sendbuffer, count);
549
550                         if (ret == 0)
551                         {
552                                 CloseSession(session);
553                         }
554                         else if (ret < 0)
555                         {
556                                 if(ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED)
557                                 {
558                                         CloseSession(session);
559                                 }
560                                 else
561                                 {
562                                         errno = EAGAIN;
563                                 }
564                         }
565                         else
566                         {
567                                 session->outbuf = session->outbuf.substr(ret);
568                         }
569                 }
570
571                 MakePollWrite(session);
572
573                 /* Who's smart idea was it to return 1 when we havent written anything?
574                  * This fucks the buffer up in BufferedSocket :p
575                  */
576                 return ret < 1 ? 0 : ret;
577         }
578
579         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
580         virtual void OnWhois(User* source, User* dest)
581         {
582                 if (!clientactive)
583                         return;
584
585                 // Bugfix, only send this numeric for *our* SSL users
586                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
587                 {
588                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
589                 }
590         }
591
592         virtual void OnSyncUserMetaData(User* user, Module* proto, void* opaque, const std::string &extname, bool displayable)
593         {
594                 // check if the linking module wants to know about OUR metadata
595                 if(extname == "ssl")
596                 {
597                         // check if this user has an swhois field to send
598                         if(user->GetExt(extname, dummy))
599                         {
600                                 // call this function in the linking module, let it format the data how it
601                                 // sees fit, and send it on its way. We dont need or want to know how.
602                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, displayable ? "Enabled" : "ON");
603                         }
604                 }
605         }
606
607         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
608         {
609                 // check if its our metadata key, and its associated with a user
610                 if ((target_type == TYPE_USER) && (extname == "ssl"))
611                 {
612                         User* dest = (User*)target;
613                         // if they dont already have an ssl flag, accept the remote server's
614                         if (!dest->GetExt(extname, dummy))
615                         {
616                                 dest->Extend(extname, "ON");
617                         }
618                 }
619         }
620
621         bool Handshake(issl_session* session)
622         {
623                 int ret = gnutls_handshake(session->sess);
624
625                 if (ret < 0)
626                 {
627                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
628                         {
629                                 // Handshake needs resuming later, read() or write() would have blocked.
630
631                                 if(gnutls_record_get_direction(session->sess) == 0)
632                                 {
633                                         // gnutls_handshake() wants to read() again.
634                                         session->status = ISSL_HANDSHAKING_READ;
635                                 }
636                                 else
637                                 {
638                                         // gnutls_handshake() wants to write() again.
639                                         session->status = ISSL_HANDSHAKING_WRITE;
640                                         MakePollWrite(session);
641                                 }
642                         }
643                         else
644                         {
645                                 // Handshake failed.
646                                 CloseSession(session);
647                                 session->status = ISSL_CLOSING;
648                         }
649
650                         return false;
651                 }
652                 else
653                 {
654                         // Handshake complete.
655                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
656                         User* extendme = ServerInstance->FindDescriptor(session->fd);
657                         if (extendme)
658                         {
659                                 if (!extendme->GetExt("ssl", dummy))
660                                         extendme->Extend("ssl", "ON");
661                         }
662
663                         // Change the seesion state
664                         session->status = ISSL_HANDSHAKEN;
665
666                         // Finish writing, if any left
667                         MakePollWrite(session);
668
669                         return true;
670                 }
671         }
672
673         virtual void OnPostConnect(User* user)
674         {
675                 // This occurs AFTER OnUserConnect so we can be sure the
676                 // protocol module has propagated the NICK message.
677                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
678                 {
679                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
680                         std::deque<std::string>* metadata = new std::deque<std::string>;
681                         metadata->push_back(user->nick);
682                         metadata->push_back("ssl");             // The metadata id
683                         metadata->push_back("ON");              // The value to send
684                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
685                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
686                         delete event;
687                         delete metadata;
688
689                         VerifyCertificate(&sessions[user->GetFd()],user);
690                         if (sessions[user->GetFd()].sess)
691                         {
692                                 std::string cipher = gnutls_kx_get_name(gnutls_kx_get(sessions[user->GetFd()].sess));
693                                 cipher.append("-").append(gnutls_cipher_get_name(gnutls_cipher_get(sessions[user->GetFd()].sess))).append("-");
694                                 cipher.append(gnutls_mac_get_name(gnutls_mac_get(sessions[user->GetFd()].sess)));
695                                 user->WriteServ("NOTICE %s :*** You are connected using SSL cipher \"%s\"", user->nick, cipher.c_str());
696                         }
697                 }
698         }
699
700         void MakePollWrite(issl_session* session)
701         {
702                 //OnRawSocketWrite(session->fd, NULL, 0);
703                 EventHandler* eh = ServerInstance->FindDescriptor(session->fd);
704                 if (eh)
705                         ServerInstance->SE->WantWrite(eh);
706         }
707
708         virtual void OnBufferFlushed(User* user)
709         {
710                 if (user->GetExt("ssl"))
711                 {
712                         issl_session* session = &sessions[user->GetFd()];
713                         if (session && session->outbuf.size())
714                                 OnRawSocketWrite(user->GetFd(), NULL, 0);
715                 }
716         }
717
718         void CloseSession(issl_session* session)
719         {
720                 if(session->sess)
721                 {
722                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
723                         gnutls_deinit(session->sess);
724                 }
725
726                 if(session->inbuf)
727                 {
728                         delete[] session->inbuf;
729                 }
730
731                 session->outbuf.clear();
732                 session->inbuf = NULL;
733                 session->sess = NULL;
734                 session->status = ISSL_NONE;
735         }
736
737         void VerifyCertificate(issl_session* session, Extensible* user)
738         {
739                 if (!session->sess || !user)
740                         return;
741
742                 unsigned int status;
743                 const gnutls_datum_t* cert_list;
744                 int ret;
745                 unsigned int cert_list_size;
746                 gnutls_x509_crt_t cert;
747                 char name[MAXBUF];
748                 unsigned char digest[MAXBUF];
749                 size_t digest_size = sizeof(digest);
750                 size_t name_size = sizeof(name);
751                 ssl_cert* certinfo = new ssl_cert;
752
753                 user->Extend("ssl_cert",certinfo);
754
755                 /* This verification function uses the trusted CAs in the credentials
756                  * structure. So you must have installed one or more CA certificates.
757                  */
758                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
759
760                 if (ret < 0)
761                 {
762                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
763                         return;
764                 }
765
766                 if (status & GNUTLS_CERT_INVALID)
767                 {
768                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
769                 }
770                 else
771                 {
772                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
773                 }
774                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
775                 {
776                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
777                 }
778                 else
779                 {
780                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
781                 }
782                 if (status & GNUTLS_CERT_REVOKED)
783                 {
784                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
785                 }
786                 else
787                 {
788                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
789                 }
790                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
791                 {
792                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
793                 }
794                 else
795                 {
796                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
797                 }
798
799                 /* Up to here the process is the same for X.509 certificates and
800                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
801                  * be easily extended to work with openpgp keys as well.
802                  */
803                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
804                 {
805                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
806                         return;
807                 }
808
809                 ret = gnutls_x509_crt_init(&cert);
810                 if (ret < 0)
811                 {
812                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
813                         return;
814                 }
815
816                 cert_list_size = 0;
817                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
818                 if (cert_list == NULL)
819                 {
820                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
821                         return;
822                 }
823
824                 /* This is not a real world example, since we only check the first
825                  * certificate in the given chain.
826                  */
827
828                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
829                 if (ret < 0)
830                 {
831                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
832                         return;
833                 }
834
835                 gnutls_x509_crt_get_dn(cert, name, &name_size);
836
837                 certinfo->data.insert(std::make_pair("dn",name));
838
839                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
840
841                 certinfo->data.insert(std::make_pair("issuer",name));
842
843                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
844                 {
845                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
846                 }
847                 else
848                 {
849                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
850                 }
851
852                 /* Beware here we do not check for errors.
853                  */
854                 if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0)))
855                 {
856                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
857                 }
858
859                 gnutls_x509_crt_deinit(cert);
860
861                 return;
862         }
863
864 };
865
866 MODULE_INIT(ModuleSSLGnuTLS)