]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
ca690fb8f5e976f64f0edf3951af9a0b7180787c
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.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 <openssl/ssl.h>
18 #include <openssl/err.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: `perl extra/openssl_config.pl compile` */
34 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
35 /* $ModDep: transport.h */
36
37 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
38 enum issl_io_status { ISSL_WRITE, ISSL_READ };
39
40 static bool SelfSigned = false;
41
42 bool isin(int port, const std::vector<int> &portlist)
43 {
44         for(unsigned int i = 0; i < portlist.size(); i++)
45                 if(portlist[i] == port)
46                         return true;
47                         
48         return false;
49 }
50
51 char* get_error()
52 {
53         return ERR_error_string(ERR_get_error(), NULL);
54 }
55
56 /** Represents an SSL user's extra data
57  */
58 class issl_session : public classbase
59 {
60 public:
61         SSL* sess;
62         issl_status status;
63         issl_io_status rstat;
64         issl_io_status wstat;
65
66         unsigned int inbufoffset;
67         char* inbuf;                    // Buffer OpenSSL reads into.
68         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
69         int fd;
70         
71         issl_session()
72         {
73                 rstat = ISSL_READ;
74                 wstat = ISSL_WRITE;
75         }
76 };
77
78 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
79 {
80         /* XXX: This will allow self signed certificates.
81          * In the future if we want an option to not allow this,
82          * we can just return preverify_ok here, and openssl
83          * will boot off self-signed and invalid peer certs.
84          */
85         int ve = X509_STORE_CTX_get_error(ctx);
86
87         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
88
89         return 1;
90 }
91         
92 class ModuleSSLOpenSSL : public Module
93 {
94         
95         ConfigReader* Conf;
96         
97         CullList* culllist;
98         
99         std::vector<int> listenports;
100         
101         int inbufsize;
102         issl_session sessions[MAX_DESCRIPTORS];
103         
104         SSL_CTX* ctx;
105         
106         char* dummy;
107         
108         std::string keyfile;
109         std::string certfile;
110         std::string cafile;
111         // std::string crlfile;
112         std::string dhfile;
113         
114  public:
115         
116         ModuleSSLOpenSSL(InspIRCd* Me)
117                 : Module::Module(Me)
118         {
119                 culllist = new CullList(ServerInstance);
120
121                 ServerInstance->PublishInterface("InspSocketHook", this);
122                 
123                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
124                 inbufsize = ServerInstance->Config->NetBufferSize;
125                 
126                 /* Global SSL library initialization*/
127                 SSL_library_init();
128                 SSL_load_error_strings();
129                 
130                 /* Build our SSL context*/
131                 ctx = SSL_CTX_new( SSLv23_server_method() );
132
133                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
134
135                 // Needs the flag as it ignores a plain /rehash
136                 OnRehash("ssl");
137         }
138         
139         virtual void OnRehash(const std::string &param)
140         {
141                 if (param != "ssl")
142                         return;
143         
144                 Conf = new ConfigReader(ServerInstance);
145                         
146                 for (unsigned int i = 0; i < listenports.size(); i++)
147                 {
148                         ServerInstance->Config->DelIOHook(listenports[i]);
149                 }
150                 
151                 listenports.clear();
152                 
153                 for (int i = 0; i < Conf->Enumerate("bind"); i++)
154                 {
155                         // For each <bind> tag
156                         if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
157                         {
158                                 // Get the port we're meant to be listening on with SSL
159                                 std::string port = Conf->ReadValue("bind", "port", i);
160                                 irc::portparser portrange(port, false);
161                                 long portno = -1;
162                                 while ((portno = portrange.GetToken()))
163                                 {
164                                         if (ServerInstance->Config->AddIOHook(portno, this))
165                                         {
166                                                 listenports.push_back(portno);
167                                                 for (unsigned int i = 0; i < ServerInstance->stats->BoundPortCount; i++)
168                                                         if (ServerInstance->Config->ports[i] == portno)
169                                                                 ServerInstance->Config->openSockfd[i]->SetDescription("ssl");
170                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
171                                         }
172                                         else
173                                         {
174                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
175                                         }
176                                 }
177                         }
178                 }
179                 
180                 std::string confdir(CONFIG_FILE);
181                 // +1 so we the path ends with a /
182                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
183                 
184                 cafile   = Conf->ReadValue("openssl", "cafile", 0);
185                 certfile = Conf->ReadValue("openssl", "certfile", 0);
186                 keyfile  = Conf->ReadValue("openssl", "keyfile", 0);
187                 dhfile   = Conf->ReadValue("openssl", "dhfile", 0);
188                 
189                 // Set all the default values needed.
190                 if (cafile == "")
191                         cafile = "ca.pem";
192                         
193                 if (certfile == "")
194                         certfile = "cert.pem";
195                         
196                 if (keyfile == "")
197                         keyfile = "key.pem";
198                         
199                 if (dhfile == "")
200                         dhfile = "dhparams.pem";
201                         
202                 // Prepend relative paths with the path to the config directory.        
203                 if (cafile[0] != '/')
204                         cafile = confdir + cafile;
205                 
206                 //if(crlfile[0] != '/')
207                 //      crlfile = confdir + crlfile;
208                         
209                 if (certfile[0] != '/')
210                         certfile = confdir + certfile;
211                         
212                 if (keyfile[0] != '/')
213                         keyfile = confdir + keyfile;
214                         
215                 if (dhfile[0] != '/')
216                         dhfile = confdir + dhfile;
217
218                 /* Load our keys and certificates*/
219                 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
220                 {
221                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
222                 }
223
224                 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
225                 {
226                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
227                 }
228
229                 /* Load the CAs we trust*/
230                 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
231                 {
232                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
233                 }
234
235                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
236                 DH* ret;
237
238                 if (dhpfile == NULL)
239                 {
240                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
241                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
242                 }
243                 else
244                 {
245                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
246                 
247                         if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
248                         {
249                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
250                         }
251                 }
252                 
253                 fclose(dhpfile);
254
255                 DELETE(Conf);
256         }
257
258         virtual ~ModuleSSLOpenSSL()
259         {
260                 SSL_CTX_free(ctx);
261                 delete culllist;
262         }
263         
264         virtual void OnCleanup(int target_type, void* item)
265         {
266                 if (target_type == TYPE_USER)
267                 {
268                         userrec* user = (userrec*)item;
269                         
270                         if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
271                         {
272                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
273                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
274                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
275                                 culllist->AddItem(user, "SSL module unloading");
276                         }
277                         if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
278                         {
279                                 ssl_cert* tofree;
280                                 user->GetExt("ssl_cert", tofree);
281                                 delete tofree;
282                                 user->Shrink("ssl_cert");
283                         }
284                 }
285         }
286         
287         virtual void OnUnloadModule(Module* mod, const std::string &name)
288         {
289                 if (mod == this)
290                 {
291                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
292                         int numusers = culllist->Apply();
293                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
294                         
295                         for(unsigned int i = 0; i < listenports.size(); i++)
296                         {
297                                 ServerInstance->Config->DelIOHook(listenports[i]);
298                                 for (unsigned int j = 0; j < ServerInstance->stats->BoundPortCount; j++)
299                                         if (ServerInstance->Config->ports[j] == listenports[i])
300                                                 ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
301                         }
302                 }
303         }
304         
305         virtual Version GetVersion()
306         {
307                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
308         }
309
310         void Implements(char* List)
311         {
312                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
313                 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
314         }
315
316         virtual char* OnRequest(Request* request)
317         {
318                 ISHRequest* ISR = (ISHRequest*)request;
319                 ServerInstance->Log(DEBUG, "hook OnRequest");
320                 if (strcmp("IS_NAME", request->GetId()) == 0)
321                 {
322                         return "openssl";
323                 }
324                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
325                 {
326                         char* ret = "OK";
327                         try
328                         {
329                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
330                         }
331                         catch (ModuleException &e)
332                         {
333                                 return NULL;
334                         }
335
336                         return ret;
337                 }
338                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
339                 {
340                         ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
341                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
342                 }
343                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
344                 {
345                         issl_session* session = &sessions[ISR->Sock->GetFd()];
346                         return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
347                 }
348                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
349                 {
350                         issl_session* session = &sessions[ISR->Sock->GetFd()];
351                         if (session)
352                         {
353                                 VerifyCertificate(session, (InspSocket*)ISR->Sock);
354                                 return "OK";
355                         }
356                 }
357                 return NULL;
358         }
359
360
361         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
362         {
363                 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
364                 issl_session* session = &sessions[fd];
365         
366                 session->fd = fd;
367                 session->inbuf = new char[inbufsize];
368                 session->inbufoffset = 0;               
369                 session->sess = SSL_new(ctx);
370                 session->status = ISSL_NONE;
371         
372                 if (session->sess == NULL)
373                 {
374                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
375                         return;
376                 }
377                 
378                 if (SSL_set_fd(session->sess, fd) == 0)
379                 {
380                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
381                         return;
382                 }
383
384                 Handshake(session);
385         }
386
387         virtual void OnRawSocketConnect(int fd)
388         {
389                 issl_session* session = &sessions[fd];
390
391                 session->fd = fd;
392                 session->inbuf = new char[inbufsize];
393                 session->inbufoffset = 0;
394                 session->sess = SSL_new(ctx);
395                 session->status = ISSL_NONE;
396
397                 if (session->sess == NULL)
398                 {
399                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
400                         return;
401                 }
402
403                 if (SSL_set_fd(session->sess, fd) == 0)
404                 {
405                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
406                         return;
407                 }
408
409                 Handshake(session);
410         }
411
412         virtual void OnRawSocketClose(int fd)
413         {
414                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
415                 CloseSession(&sessions[fd]);
416
417                 EventHandler* user = ServerInstance->SE->GetRef(fd);
418
419                 if ((user) && (user->GetExt("ssl_cert", dummy)))
420                 {
421                         ssl_cert* tofree;
422                         user->GetExt("ssl_cert", tofree);
423                         delete tofree;
424                         user->Shrink("ssl_cert");
425                 }
426         }
427
428         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
429         {
430                 issl_session* session = &sessions[fd];
431                 
432                 if (!session->sess)
433                 {
434                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
435                         readresult = 0;
436                         CloseSession(session);
437                         return 1;
438                 }
439                 
440                 if (session->status == ISSL_HANDSHAKING)
441                 {
442                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
443                         {
444                                 // The handshake isn't finished and it wants to read, try to finish it.
445                                 if (Handshake(session))
446                                 {
447                                         // Handshake successfully resumed.
448                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
449                                 }
450                                 else
451                                 {
452                                         // Couldn't resume handshake.   
453                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
454                                         return -1;
455                                 }
456                         }
457                         else
458                         {
459                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
460                                 return -1;                      
461                         }
462                 }
463
464                 // If we resumed the handshake then session->status will be ISSL_OPEN
465                                 
466                 if (session->status == ISSL_OPEN)
467                 {
468                         if (session->wstat == ISSL_READ)
469                         {
470                                 if(DoWrite(session) == 0)
471                                         return 0;
472                         }
473                         
474                         if (session->rstat == ISSL_READ)
475                         {
476                                 int ret = DoRead(session);
477                         
478                                 if (ret > 0)
479                                 {
480                                         if (count <= session->inbufoffset)
481                                         {
482                                                 memcpy(buffer, session->inbuf, count);
483                                                 // Move the stuff left in inbuf to the beginning of it
484                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
485                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
486                                                 session->inbufoffset -= count;
487                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
488                                                 readresult = count;
489                                         }
490                                         else
491                                         {
492                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
493                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
494                                                 
495                                                 readresult = session->inbufoffset;
496                                                 // Zero the offset, as there's nothing there..
497                                                 session->inbufoffset = 0;
498                                         }
499                                 
500                                         return 1;
501                                 }
502                                 else
503                                 {
504                                         return ret;
505                                 }
506                         }
507                 }
508                 
509                 return -1;
510         }
511         
512         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
513         {               
514                 issl_session* session = &sessions[fd];
515
516                 if (!session->sess)
517                 {
518                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
519                         CloseSession(session);
520                         return 1;
521                 }
522
523                 session->outbuf.append(buffer, count);
524                 
525                 if (session->status == ISSL_HANDSHAKING)
526                 {
527                         // The handshake isn't finished, try to finish it.
528                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
529                         {
530                                 if (Handshake(session))
531                                 {
532                                         // Handshake successfully resumed.
533                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
534                                 }
535                                 else
536                                 {
537                                         // Couldn't resume handshake.   
538                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
539                                 }
540                         }
541                         else
542                         {
543                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
544                         }
545                 }
546                 
547                 if (session->status == ISSL_OPEN)
548                 {
549                         if (session->rstat == ISSL_WRITE)
550                         {
551                                 DoRead(session);
552                         }
553                         
554                         if (session->wstat == ISSL_WRITE)
555                         {
556                                 return DoWrite(session);
557                         }
558                 }
559                 
560                 return 1;
561         }
562         
563         int DoWrite(issl_session* session)
564         {
565                 if (!session->outbuf.size())
566                         return -1;
567
568                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
569                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
570                 
571                 if (ret == 0)
572                 {
573                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
574                         CloseSession(session);
575                         return 0;
576                 }
577                 else if (ret < 0)
578                 {
579                         int err = SSL_get_error(session->sess, ret);
580                         
581                         if (err == SSL_ERROR_WANT_WRITE)
582                         {
583                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
584                                 session->wstat = ISSL_WRITE;
585                                 return -1;
586                         }
587                         else if (err == SSL_ERROR_WANT_READ)
588                         {
589                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
590                                 session->wstat = ISSL_READ;
591                                 return -1;
592                         }
593                         else
594                         {
595                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
596                                 CloseSession(session);
597                                 return 0;
598                         }
599                 }
600                 else
601                 {
602                         session->outbuf = session->outbuf.substr(ret);
603                         return ret;
604                 }
605         }
606         
607         int DoRead(issl_session* session)
608         {
609                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
610                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
611                         
612                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
613
614                 if (ret == 0)
615                 {
616                         // Client closed connection.
617                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
618                         CloseSession(session);
619                         return 0;
620                 }
621                 else if (ret < 0)
622                 {
623                         int err = SSL_get_error(session->sess, ret);
624                                 
625                         if (err == SSL_ERROR_WANT_READ)
626                         {
627                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
628                                 session->rstat = ISSL_READ;
629                                 return -1;
630                         }
631                         else if (err == SSL_ERROR_WANT_WRITE)
632                         {
633                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
634                                 session->rstat = ISSL_WRITE;
635                                 return -1;
636                         }
637                         else
638                         {
639                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
640                                 CloseSession(session);
641                                 return 0;
642                         }
643                 }
644                 else
645                 {
646                         // Read successfully 'ret' bytes into inbuf + inbufoffset
647                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
648                         // 'buffer' is 'count' long
649
650                         session->inbufoffset += ret;
651
652                         return ret;
653                 }
654         }
655         
656         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
657         virtual void OnWhois(userrec* source, userrec* dest)
658         {
659                 // Bugfix, only send this numeric for *our* SSL users
660                 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
661                 {
662                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
663                 }
664         }
665         
666         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
667         {
668                 // check if the linking module wants to know about OUR metadata
669                 if (extname == "ssl")
670                 {
671                         // check if this user has an swhois field to send
672                         if(user->GetExt(extname, dummy))
673                         {
674                                 // call this function in the linking module, let it format the data how it
675                                 // sees fit, and send it on its way. We dont need or want to know how.
676                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
677                         }
678                 }
679         }
680         
681         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
682         {
683                 // check if its our metadata key, and its associated with a user
684                 if ((target_type == TYPE_USER) && (extname == "ssl"))
685                 {
686                         userrec* dest = (userrec*)target;
687                         // if they dont already have an ssl flag, accept the remote server's
688                         if (!dest->GetExt(extname, dummy))
689                         {
690                                 dest->Extend(extname, "ON");
691                         }
692                 }
693         }
694         
695         bool Handshake(issl_session* session)
696         {               
697                 int ret = SSL_accept(session->sess);
698       
699                 if (ret < 0)
700                 {
701                         int err = SSL_get_error(session->sess, ret);
702                                 
703                         if (err == SSL_ERROR_WANT_READ)
704                         {
705                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
706                                 session->rstat = ISSL_READ;
707                                 session->status = ISSL_HANDSHAKING;
708                         }
709                         else if (err == SSL_ERROR_WANT_WRITE)
710                         {
711                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
712                                 session->wstat = ISSL_WRITE;
713                                 session->status = ISSL_HANDSHAKING;
714                                 MakePollWrite(session);
715                         }
716                         else
717                         {
718                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
719                                 CloseSession(session);
720                         }
721
722                         return false;
723                 }
724                 else
725                 {
726                         // Handshake complete.
727                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
728                         
729                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
730                         userrec* u = ServerInstance->FindDescriptor(session->fd);
731                         if (u)
732                         {
733                                 if (!u->GetExt("ssl", dummy))
734                                         u->Extend("ssl", "ON");
735                         }
736                         
737                         session->status = ISSL_OPEN;
738                         
739                         MakePollWrite(session);
740                         
741                         return true;
742                 }
743         }
744         
745         virtual void OnPostConnect(userrec* user)
746         {
747                 // This occurs AFTER OnUserConnect so we can be sure the
748                 // protocol module has propogated the NICK message.
749                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
750                 {
751                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
752                         std::deque<std::string>* metadata = new std::deque<std::string>;
753                         metadata->push_back(user->nick);
754                         metadata->push_back("ssl");             // The metadata id
755                         metadata->push_back("ON");              // The value to send
756                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
757                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
758                         DELETE(event);
759                         DELETE(metadata);
760
761                         VerifyCertificate(&sessions[user->GetFd()], user);
762                 }
763         }
764         
765         void MakePollWrite(issl_session* session)
766         {
767                 OnRawSocketWrite(session->fd, NULL, 0);
768         }
769         
770         void CloseSession(issl_session* session)
771         {
772                 if (session->sess)
773                 {
774                         SSL_shutdown(session->sess);
775                         SSL_free(session->sess);
776                 }
777                 
778                 if (session->inbuf)
779                 {
780                         delete[] session->inbuf;
781                 }
782                 
783                 session->outbuf.clear();
784                 session->inbuf = NULL;
785                 session->sess = NULL;
786                 session->status = ISSL_NONE;
787         }
788
789         void VerifyCertificate(issl_session* session, Extensible* user)
790         {
791                 X509* cert;
792                 ssl_cert* certinfo = new ssl_cert;
793                 unsigned int n;
794                 unsigned char md[EVP_MAX_MD_SIZE];
795                 const EVP_MD *digest = EVP_md5();
796
797                 user->Extend("ssl_cert",certinfo);
798
799                 cert = SSL_get_peer_certificate((SSL*)session->sess);
800
801                 if (!cert)
802                 {
803                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
804                         return;
805                 }
806
807                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
808
809                 if (SelfSigned)
810                 {
811                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
812                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
813                 }
814                 else
815                 {
816                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
817                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
818                 }
819
820                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
821                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
822
823                 if (!X509_digest(cert, digest, md, &n))
824                 {
825                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
826                 }
827                 else
828                 {
829                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
830                 }
831
832                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0))
833                 {
834                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
835                 }
836
837                 X509_free(cert);
838         }
839 };
840
841 class ModuleSSLOpenSSLFactory : public ModuleFactory
842 {
843  public:
844         ModuleSSLOpenSSLFactory()
845         {
846         }
847         
848         ~ModuleSSLOpenSSLFactory()
849         {
850         }
851         
852         virtual Module * CreateModule(InspIRCd* Me)
853         {
854                 return new ModuleSSLOpenSSL(Me);
855         }
856 };
857
858
859 extern "C" void * init_module( void )
860 {
861         return new ModuleSSLOpenSSLFactory;
862 }