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