]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_gnutls.cpp
Now with SQLite3 support. Fully functional and (hopefully) working.
[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-2007 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 <string>
15 #include <vector>
16
17 #include <gnutls/gnutls.h>
18 #include <gnutls/x509.h>
19
20 #include "inspircd_config.h"
21 #include "configreader.h"
22 #include "users.h"
23 #include "channels.h"
24 #include "modules.h"
25
26 #include "socket.h"
27 #include "hashcomp.h"
28 #include "inspircd.h"
29
30 #include "transport.h"
31
32 /* $ModDesc: Provides SSL support for clients */
33 /* $CompileFlags: exec("libgnutls-config --cflags") */
34 /* $LinkerFlags: rpath("libgnutls-config --libs") */
35 /* $ModDep: transport.h */
36
37
38 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING_READ, ISSL_HANDSHAKING_WRITE, ISSL_HANDSHAKEN, ISSL_CLOSING, ISSL_CLOSED };
39
40 bool isin(int port, const std::vector<int> &portlist)
41 {
42         for(unsigned int i = 0; i < portlist.size(); i++)
43                 if(portlist[i] == port)
44                         return true;
45                         
46         return false;
47 }
48
49 /** Represents an SSL user's extra data
50  */
51 class issl_session : public classbase
52 {
53 public:
54         gnutls_session_t sess;
55         issl_status status;
56         std::string outbuf;
57         int inbufoffset;
58         char* inbuf;
59         int fd;
60 };
61
62 class ModuleSSLGnuTLS : public Module
63 {
64         
65         ConfigReader* Conf;
66
67         char* dummy;
68         
69         CullList* culllist;
70         
71         std::vector<int> listenports;
72         
73         int inbufsize;
74         issl_session sessions[MAX_DESCRIPTORS];
75         
76         gnutls_certificate_credentials x509_cred;
77         gnutls_dh_params dh_params;
78         
79         std::string keyfile;
80         std::string certfile;
81         std::string cafile;
82         std::string crlfile;
83         int dh_bits;
84         
85  public:
86         
87         ModuleSSLGnuTLS(InspIRCd* Me)
88                 : Module::Module(Me)
89         {
90                 
91
92                 culllist = new CullList(ServerInstance);
93
94                 ServerInstance->PublishInterface("InspSocketHook", 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         }
114         
115         virtual void OnRehash(userrec* user, const std::string &param)
116         {
117                 if(param != "ssl")
118                         return;
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                 
129                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
130                 {
131                         // For each <bind> tag
132                         if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "gnutls"))
133                         {
134                                 // Get the port we're meant to be listening on with SSL
135                                 std::string port = Conf->ReadValue("bind", "port", i);
136                                 irc::portparser portrange(port, false);
137                                 long portno = -1;
138                                 while ((portno = portrange.GetToken()))
139                                 {
140                                         if (ServerInstance->Config->AddIOHook(portno, this))
141                                         {
142                                                 listenports.push_back(portno);
143                                                 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
144                                                         if (ServerInstance->Config->ports[i] == portno)
145                                                                 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
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                         {
263                                 ServerInstance->Config->DelIOHook(listenports[i]);
264                                 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
265                                         if (ServerInstance->Config->ports[j] == listenports[i])
266                                                 if (ServerInstance->Config->openSockfd[j])
267                                                         ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
268                         }
269                 }
270         }
271         
272         virtual Version GetVersion()
273         {
274                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
275         }
276
277         void Implements(char* List)
278         {
279                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
280                 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
281         }
282
283         virtual char* OnRequest(Request* request)
284         {
285                 ISHRequest* ISR = (ISHRequest*)request;
286                 if (strcmp("IS_NAME", request->GetId()) == 0)
287                 {
288                         return "gnutls";
289                 }
290                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
291                 {
292                         char* ret = "OK";
293                         try
294                         {
295                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
296                         }
297                         catch (ModuleException &e)
298                         {
299                                 return NULL;
300                         }
301                         return ret;
302                 }
303                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
304                 {
305                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
306                 }
307                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
308                 {
309                         issl_session* session = &sessions[ISR->Sock->GetFd()];
310                         return (session->status == ISSL_HANDSHAKING_READ || session->status == ISSL_HANDSHAKING_WRITE) ? NULL : (char*)"OK";
311                 }
312                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
313                 {
314                         issl_session* session = &sessions[ISR->Sock->GetFd()];
315                         if (session)
316                         {
317                                 VerifyCertificate(session, (InspSocket*)ISR->Sock);
318                                 return "OK";
319                         }
320                 }
321                 return NULL;
322         }
323
324
325         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
326         {
327                 issl_session* session = &sessions[fd];
328         
329                 session->fd = fd;
330                 session->inbuf = new char[inbufsize];
331                 session->inbufoffset = 0;
332         
333                 gnutls_init(&session->sess, GNUTLS_SERVER);
334
335                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
336                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
337                 gnutls_certificate_server_set_request(session->sess, GNUTLS_CERT_REQUEST); // Request client certificate if any.
338                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
339                 
340                 /* This is an experimental change to avoid a warning on 64bit systems about casting between integer and pointer of different sizes
341                  * This needs testing, but it's easy enough to rollback if need be
342                  * Old: gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
343                  * New: gnutls_transport_set_ptr(session->sess, &fd); // Give gnutls the fd for the socket.
344                  *
345                  * With testing this seems to...not work :/
346                  */
347                 
348                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
349
350                 Handshake(session);
351         }
352
353         virtual void OnRawSocketConnect(int fd)
354         {
355                 issl_session* session = &sessions[fd];
356
357                 session->fd = fd;
358                 session->inbuf = new char[inbufsize];
359                 session->inbufoffset = 0;
360
361                 gnutls_init(&session->sess, GNUTLS_SERVER);
362
363                 gnutls_set_default_priority(session->sess); // Avoid calling all the priority functions, defaults are adequate.
364                 gnutls_credentials_set(session->sess, GNUTLS_CRD_CERTIFICATE, x509_cred);
365                 gnutls_dh_set_prime_bits(session->sess, dh_bits);
366
367                 gnutls_transport_set_ptr(session->sess, (gnutls_transport_ptr_t) fd); // Give gnutls the fd for the socket.
368
369                 Handshake(session);
370         }
371
372         virtual void OnRawSocketClose(int fd)
373         {
374                 ServerInstance->Log(DEBUG, "OnRawSocketClose: %d", fd);
375                 CloseSession(&sessions[fd]);
376
377                 EventHandler* user = ServerInstance->SE->GetRef(fd);
378
379                 if ((user) && (user->GetExt("ssl_cert", dummy)))
380                 {
381                         ssl_cert* tofree;
382                         user->GetExt("ssl_cert", tofree);
383                         delete tofree;
384                         user->Shrink("ssl_cert");
385                 }
386         }
387         
388         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
389         {
390                 issl_session* session = &sessions[fd];
391                 
392                 if (!session->sess)
393                 {
394                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: No session to read from");
395                         readresult = 0;
396                         CloseSession(session);
397                         return 1;
398                 }
399
400                 if (session->status == ISSL_HANDSHAKING_READ)
401                 {
402                         // The handshake isn't finished, try to finish it.
403                         
404                         if(Handshake(session))
405                         {
406                                 // Handshake successfully resumed.
407                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: successfully resumed handshake");
408                         }
409                         else
410                         {
411                                 // Couldn't resume handshake.   
412                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: failed to resume handshake");
413                                 return -1;
414                         }
415                 }
416                 else if (session->status == ISSL_HANDSHAKING_WRITE)
417                 {
418                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
419                         return -1;
420                 }
421                 
422                 // If we resumed the handshake then session->status will be ISSL_HANDSHAKEN.
423                 
424                 if (session->status == ISSL_HANDSHAKEN)
425                 {
426                         // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
427                         // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
428                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: gnutls_record_recv(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
429                         
430                         int ret = gnutls_record_recv(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
431
432                         if (ret == 0)
433                         {
434                                 // Client closed connection.
435                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: Client closed the connection");
436                                 readresult = 0;
437                                 CloseSession(session);
438                                 return 1;
439                         }
440                         else if (ret < 0)
441                         {
442                                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
443                                 {
444                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Not all SSL data read: %s", gnutls_strerror(ret));
445                                         return -1;
446                                 }
447                                 else
448                                 {
449                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: Error reading SSL data: %s", gnutls_strerror(ret));
450                                         readresult = 0;
451                                         CloseSession(session);
452                                 }
453                         }
454                         else
455                         {
456                                 // Read successfully 'ret' bytes into inbuf + inbufoffset
457                                 // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
458                                 // 'buffer' is 'count' long
459                                 
460                                 unsigned int length = ret + session->inbufoffset;
461                                                 
462                                 if(count <= length)
463                                 {
464                                         memcpy(buffer, session->inbuf, count);
465                                         // Move the stuff left in inbuf to the beginning of it
466                                         memcpy(session->inbuf, session->inbuf + count, (length - count));
467                                         // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
468                                         session->inbufoffset = length - count;
469                                         // Insp uses readresult as the count of how much data there is in buffer, so:
470                                         readresult = count;
471                                 }
472                                 else
473                                 {
474                                         // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
475                                         memcpy(buffer, session->inbuf, length);
476                                         // Zero the offset, as there's nothing there..
477                                         session->inbufoffset = 0;
478                                         // As above
479                                         readresult = length;
480                                 }
481                         }
482                 }
483                 else if(session->status == ISSL_CLOSING)
484                 {
485                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketRead: session closing...");
486                         readresult = 0;
487                 }
488                 
489                 return 1;
490         }
491         
492         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
493         {
494                 if (!count)
495                         return 0;
496
497                 issl_session* session = &sessions[fd];
498                 const char* sendbuffer = buffer;
499
500                 if(!session->sess)
501                 {
502                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: No session to write to");
503                         CloseSession(session);
504                         return 1;
505                 }
506                 
507                 if(session->status == ISSL_HANDSHAKING_WRITE)
508                 {
509                         // The handshake isn't finished, try to finish it.
510                         
511                         if(Handshake(session))
512                         {
513                                 // Handshake successfully resumed.
514                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: successfully resumed handshake");
515                         }
516                         else
517                         {
518                                 // Couldn't resume handshake.   
519                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: failed to resume handshake"); 
520                         }
521                 }
522                 else if(session->status == ISSL_HANDSHAKING_READ)
523                 {
524                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");
525                 }
526
527                 session->outbuf.append(sendbuffer, count);
528                 sendbuffer = session->outbuf.c_str();
529                 count = session->outbuf.size();
530
531                 if(session->status == ISSL_HANDSHAKEN)
532                 {       
533                         int ret = gnutls_record_send(session->sess, sendbuffer, count);
534                 
535                         if(ret == 0)
536                         {
537                                 ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Client closed the connection");
538                                 CloseSession(session);
539                         }
540                         else if(ret < 0)
541                         {
542                                 if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
543                                 {
544                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Not all SSL data written: %s", gnutls_strerror(ret));
545                                 }
546                                 else
547                                 {
548                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: Error writing SSL data: %s", gnutls_strerror(ret));
549                                         CloseSession(session);                                  
550                                 }
551                         }
552                         else
553                         {
554                                 session->outbuf = session->outbuf.substr(ret);
555                         }
556                 }
557                 else if(session->status == ISSL_CLOSING)
558                 {
559                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: OnRawSocketWrite: session closing...");
560                 }
561                 
562                 return 1;
563         }
564         
565         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
566         virtual void OnWhois(userrec* source, userrec* dest)
567         {
568                 // Bugfix, only send this numeric for *our* SSL users
569                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
570                 {
571                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
572                 }
573         }
574         
575         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
576         {
577                 // check if the linking module wants to know about OUR metadata
578                 if(extname == "ssl")
579                 {
580                         // check if this user has an swhois field to send
581                         if(user->GetExt(extname, dummy))
582                         {
583                                 // call this function in the linking module, let it format the data how it
584                                 // sees fit, and send it on its way. We dont need or want to know how.
585                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
586                         }
587                 }
588         }
589         
590         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
591         {
592                 // check if its our metadata key, and its associated with a user
593                 if ((target_type == TYPE_USER) && (extname == "ssl"))
594                 {
595                         userrec* dest = (userrec*)target;
596                         // if they dont already have an ssl flag, accept the remote server's
597                         if (!dest->GetExt(extname, dummy))
598                         {
599                                 dest->Extend(extname, "ON");
600                         }
601                 }
602         }
603         
604         bool Handshake(issl_session* session)
605         {               
606                 int ret = gnutls_handshake(session->sess);
607       
608                 if(ret < 0)
609                 {
610                         if(ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
611                         {
612                                 // Handshake needs resuming later, read() or write() would have blocked.
613                                 
614                                 if(gnutls_record_get_direction(session->sess) == 0)
615                                 {
616                                         // gnutls_handshake() wants to read() again.
617                                         session->status = ISSL_HANDSHAKING_READ;
618                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (reading) later, error string: %s", gnutls_strerror(ret));
619                                 }
620                                 else
621                                 {
622                                         // gnutls_handshake() wants to write() again.
623                                         session->status = ISSL_HANDSHAKING_WRITE;
624                                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: Handshake needs resuming (writing) later, error string: %s", gnutls_strerror(ret));
625                                         MakePollWrite(session); 
626                                 }
627                         }
628                         else
629                         {
630                                 // Handshake failed.
631                                 CloseSession(session);
632                            ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: Handshake failed, error string: %s", gnutls_strerror(ret));
633                            session->status = ISSL_CLOSING;
634                         }
635                         
636                         return false;
637                 }
638                 else
639                 {
640                         // Handshake complete.
641                         ServerInstance->Log(DEBUG, "m_ssl_gnutls.so: Handshake completed");
642                         
643                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
644                         userrec* extendme = ServerInstance->FindDescriptor(session->fd);
645                         if (extendme)
646                         {
647                                 if (!extendme->GetExt("ssl", dummy))
648                                         extendme->Extend("ssl", "ON");
649                         }
650
651                         // Change the seesion state
652                         session->status = ISSL_HANDSHAKEN;
653                         
654                         // Finish writing, if any left
655                         MakePollWrite(session);
656                         
657                         return true;
658                 }
659         }
660
661         virtual void OnPostConnect(userrec* user)
662         {
663                 // This occurs AFTER OnUserConnect so we can be sure the
664                 // protocol module has propogated the NICK message.
665                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
666                 {
667                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
668                         std::deque<std::string>* metadata = new std::deque<std::string>;
669                         metadata->push_back(user->nick);
670                         metadata->push_back("ssl");             // The metadata id
671                         metadata->push_back("ON");              // The value to send
672                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
673                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
674                         DELETE(event);
675                         DELETE(metadata);
676
677                         VerifyCertificate(&sessions[user->GetFd()],user);
678                 }
679         }
680         
681         void MakePollWrite(issl_session* session)
682         {
683                 OnRawSocketWrite(session->fd, NULL, 0);
684         }
685         
686         void CloseSession(issl_session* session)
687         {
688                 if(session->sess)
689                 {
690                         gnutls_bye(session->sess, GNUTLS_SHUT_WR);
691                         gnutls_deinit(session->sess);
692                 }
693                 
694                 if(session->inbuf)
695                 {
696                         delete[] session->inbuf;
697                 }
698                 
699                 session->outbuf.clear();
700                 session->inbuf = NULL;
701                 session->sess = NULL;
702                 session->status = ISSL_NONE;
703         }
704
705         void VerifyCertificate(issl_session* session, Extensible* user)
706         {
707                 unsigned int status;
708                 const gnutls_datum_t* cert_list;
709                 int ret;
710                 unsigned int cert_list_size;
711                 gnutls_x509_crt_t cert;
712                 char name[MAXBUF];
713                 unsigned char digest[MAXBUF];
714                 size_t digest_size = sizeof(digest);
715                 size_t name_size = sizeof(name);
716                 ssl_cert* certinfo = new ssl_cert;
717
718                 user->Extend("ssl_cert",certinfo);
719
720                 /* This verification function uses the trusted CAs in the credentials
721                  * structure. So you must have installed one or more CA certificates.
722                  */
723                 ret = gnutls_certificate_verify_peers2(session->sess, &status);
724
725                 if (ret < 0)
726                 {
727                         certinfo->data.insert(std::make_pair("error",std::string(gnutls_strerror(ret))));
728                         return;
729                 }
730
731                 if (status & GNUTLS_CERT_INVALID)
732                 {
733                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(1)));
734                 }
735                 else
736                 {
737                         certinfo->data.insert(std::make_pair("invalid",ConvToStr(0)));
738                 }
739                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
740                 {
741                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
742                 }
743                 else
744                 {
745                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
746                 }
747                 if (status & GNUTLS_CERT_REVOKED)
748                 {
749                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(1)));
750                 }
751                 else
752                 {
753                         certinfo->data.insert(std::make_pair("revoked",ConvToStr(0)));
754                 }
755                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
756                 {
757                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
758                 }
759                 else
760                 {
761                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
762                 }
763         
764                 /* Up to here the process is the same for X.509 certificates and
765                  * OpenPGP keys. From now on X.509 certificates are assumed. This can
766                  * be easily extended to work with openpgp keys as well.
767                  */
768                 if (gnutls_certificate_type_get(session->sess) != GNUTLS_CRT_X509)
769                 {
770                         certinfo->data.insert(std::make_pair("error","No X509 keys sent"));
771                         return;
772                 }
773
774                 ret = gnutls_x509_crt_init(&cert);
775                 if (ret < 0)
776                 {
777                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
778                         return;
779                 }
780
781                 cert_list_size = 0;
782                 cert_list = gnutls_certificate_get_peers(session->sess, &cert_list_size);
783                 if (cert_list == NULL)
784                 {
785                         certinfo->data.insert(std::make_pair("error","No certificate was found"));
786                         return;
787                 }
788
789                 /* This is not a real world example, since we only check the first 
790                  * certificate in the given chain.
791                  */
792
793                 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
794                 if (ret < 0)
795                 {
796                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
797                         return;
798                 }
799
800                 gnutls_x509_crt_get_dn(cert, name, &name_size);
801
802                 certinfo->data.insert(std::make_pair("dn",name));
803
804                 gnutls_x509_crt_get_issuer_dn(cert, name, &name_size);
805
806                 certinfo->data.insert(std::make_pair("issuer",name));
807
808                 if ((ret = gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, digest, &digest_size)) < 0)
809                 {
810                         certinfo->data.insert(std::make_pair("error",gnutls_strerror(ret)));
811                 }
812                 else
813                 {
814                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(digest, digest_size)));
815                 }
816
817                 /* Beware here we do not check for errors.
818                  */
819                 if ((gnutls_x509_crt_get_expiration_time(cert) < time(0)) || (gnutls_x509_crt_get_activation_time(cert) > time(0)))
820                 {
821                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
822                 }
823
824                 gnutls_x509_crt_deinit(cert);
825
826                 return;
827         }
828
829 };
830
831 class ModuleSSLGnuTLSFactory : public ModuleFactory
832 {
833  public:
834         ModuleSSLGnuTLSFactory()
835         {
836         }
837         
838         ~ModuleSSLGnuTLSFactory()
839         {
840         }
841         
842         virtual Module * CreateModule(InspIRCd* Me)
843         {
844                 return new ModuleSSLGnuTLS(Me);
845         }
846 };
847
848
849 extern "C" void * init_module( void )
850 {
851         return new ModuleSSLGnuTLSFactory;
852 }