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