]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
pgsql should now work thx to added posibility to force a fd out of the socketengine...
[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(NULL,"ssl");
137         }
138         
139         virtual void OnRehash(userrec* user, 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                                                 if (ServerInstance->Config->openSockfd[j])
301                                                         ServerInstance->Config->openSockfd[j]->SetDescription("plaintext");
302                         }
303                 }
304         }
305         
306         virtual Version GetVersion()
307         {
308                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
309         }
310
311         void Implements(char* List)
312         {
313                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
314                 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
315         }
316
317         virtual char* OnRequest(Request* request)
318         {
319                 ISHRequest* ISR = (ISHRequest*)request;
320                 ServerInstance->Log(DEBUG, "hook OnRequest");
321                 if (strcmp("IS_NAME", request->GetId()) == 0)
322                 {
323                         return "openssl";
324                 }
325                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
326                 {
327                         char* ret = "OK";
328                         try
329                         {
330                                 ret = ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
331                         }
332                         catch (ModuleException &e)
333                         {
334                                 return NULL;
335                         }
336
337                         return ret;
338                 }
339                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
340                 {
341                         ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
342                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
343                 }
344                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
345                 {
346                         issl_session* session = &sessions[ISR->Sock->GetFd()];
347                         return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
348                 }
349                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
350                 {
351                         issl_session* session = &sessions[ISR->Sock->GetFd()];
352                         if (session)
353                         {
354                                 VerifyCertificate(session, (InspSocket*)ISR->Sock);
355                                 return "OK";
356                         }
357                 }
358                 return NULL;
359         }
360
361
362         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
363         {
364                 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
365                 issl_session* session = &sessions[fd];
366         
367                 session->fd = fd;
368                 session->inbuf = new char[inbufsize];
369                 session->inbufoffset = 0;               
370                 session->sess = SSL_new(ctx);
371                 session->status = ISSL_NONE;
372         
373                 if (session->sess == NULL)
374                 {
375                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
376                         return;
377                 }
378                 
379                 if (SSL_set_fd(session->sess, fd) == 0)
380                 {
381                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
382                         return;
383                 }
384
385                 Handshake(session);
386         }
387
388         virtual void OnRawSocketConnect(int fd)
389         {
390                 issl_session* session = &sessions[fd];
391
392                 session->fd = fd;
393                 session->inbuf = new char[inbufsize];
394                 session->inbufoffset = 0;
395                 session->sess = SSL_new(ctx);
396                 session->status = ISSL_NONE;
397
398                 if (session->sess == NULL)
399                 {
400                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
401                         return;
402                 }
403
404                 if (SSL_set_fd(session->sess, fd) == 0)
405                 {
406                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
407                         return;
408                 }
409
410                 Handshake(session);
411         }
412
413         virtual void OnRawSocketClose(int fd)
414         {
415                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
416                 CloseSession(&sessions[fd]);
417
418                 EventHandler* user = ServerInstance->SE->GetRef(fd);
419
420                 if ((user) && (user->GetExt("ssl_cert", dummy)))
421                 {
422                         ssl_cert* tofree;
423                         user->GetExt("ssl_cert", tofree);
424                         delete tofree;
425                         user->Shrink("ssl_cert");
426                 }
427         }
428
429         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
430         {
431                 issl_session* session = &sessions[fd];
432                 
433                 if (!session->sess)
434                 {
435                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
436                         readresult = 0;
437                         CloseSession(session);
438                         return 1;
439                 }
440                 
441                 if (session->status == ISSL_HANDSHAKING)
442                 {
443                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
444                         {
445                                 // The handshake isn't finished and it wants to read, try to finish it.
446                                 if (Handshake(session))
447                                 {
448                                         // Handshake successfully resumed.
449                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
450                                 }
451                                 else
452                                 {
453                                         // Couldn't resume handshake.   
454                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
455                                         return -1;
456                                 }
457                         }
458                         else
459                         {
460                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
461                                 return -1;                      
462                         }
463                 }
464
465                 // If we resumed the handshake then session->status will be ISSL_OPEN
466                                 
467                 if (session->status == ISSL_OPEN)
468                 {
469                         if (session->wstat == ISSL_READ)
470                         {
471                                 if(DoWrite(session) == 0)
472                                         return 0;
473                         }
474                         
475                         if (session->rstat == ISSL_READ)
476                         {
477                                 int ret = DoRead(session);
478                         
479                                 if (ret > 0)
480                                 {
481                                         if (count <= session->inbufoffset)
482                                         {
483                                                 memcpy(buffer, session->inbuf, count);
484                                                 // Move the stuff left in inbuf to the beginning of it
485                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
486                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
487                                                 session->inbufoffset -= count;
488                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
489                                                 readresult = count;
490                                         }
491                                         else
492                                         {
493                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
494                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
495                                                 
496                                                 readresult = session->inbufoffset;
497                                                 // Zero the offset, as there's nothing there..
498                                                 session->inbufoffset = 0;
499                                         }
500                                 
501                                         return 1;
502                                 }
503                                 else
504                                 {
505                                         return ret;
506                                 }
507                         }
508                 }
509                 
510                 return -1;
511         }
512         
513         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
514         {               
515                 issl_session* session = &sessions[fd];
516
517                 if (!session->sess)
518                 {
519                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
520                         CloseSession(session);
521                         return 1;
522                 }
523
524                 session->outbuf.append(buffer, count);
525                 
526                 if (session->status == ISSL_HANDSHAKING)
527                 {
528                         // The handshake isn't finished, try to finish it.
529                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
530                         {
531                                 if (Handshake(session))
532                                 {
533                                         // Handshake successfully resumed.
534                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
535                                 }
536                                 else
537                                 {
538                                         // Couldn't resume handshake.   
539                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
540                                 }
541                         }
542                         else
543                         {
544                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
545                         }
546                 }
547                 
548                 if (session->status == ISSL_OPEN)
549                 {
550                         if (session->rstat == ISSL_WRITE)
551                         {
552                                 DoRead(session);
553                         }
554                         
555                         if (session->wstat == ISSL_WRITE)
556                         {
557                                 return DoWrite(session);
558                         }
559                 }
560                 
561                 return 1;
562         }
563         
564         int DoWrite(issl_session* session)
565         {
566                 if (!session->outbuf.size())
567                         return -1;
568
569                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
570                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
571                 
572                 if (ret == 0)
573                 {
574                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
575                         CloseSession(session);
576                         return 0;
577                 }
578                 else if (ret < 0)
579                 {
580                         int err = SSL_get_error(session->sess, ret);
581                         
582                         if (err == SSL_ERROR_WANT_WRITE)
583                         {
584                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
585                                 session->wstat = ISSL_WRITE;
586                                 return -1;
587                         }
588                         else if (err == SSL_ERROR_WANT_READ)
589                         {
590                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
591                                 session->wstat = ISSL_READ;
592                                 return -1;
593                         }
594                         else
595                         {
596                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
597                                 CloseSession(session);
598                                 return 0;
599                         }
600                 }
601                 else
602                 {
603                         session->outbuf = session->outbuf.substr(ret);
604                         return ret;
605                 }
606         }
607         
608         int DoRead(issl_session* session)
609         {
610                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
611                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
612                         
613                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
614
615                 if (ret == 0)
616                 {
617                         // Client closed connection.
618                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
619                         CloseSession(session);
620                         return 0;
621                 }
622                 else if (ret < 0)
623                 {
624                         int err = SSL_get_error(session->sess, ret);
625                                 
626                         if (err == SSL_ERROR_WANT_READ)
627                         {
628                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
629                                 session->rstat = ISSL_READ;
630                                 return -1;
631                         }
632                         else if (err == SSL_ERROR_WANT_WRITE)
633                         {
634                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
635                                 session->rstat = ISSL_WRITE;
636                                 return -1;
637                         }
638                         else
639                         {
640                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
641                                 CloseSession(session);
642                                 return 0;
643                         }
644                 }
645                 else
646                 {
647                         // Read successfully 'ret' bytes into inbuf + inbufoffset
648                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
649                         // 'buffer' is 'count' long
650
651                         session->inbufoffset += ret;
652
653                         return ret;
654                 }
655         }
656         
657         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
658         virtual void OnWhois(userrec* source, userrec* dest)
659         {
660                 // Bugfix, only send this numeric for *our* SSL users
661                 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
662                 {
663                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
664                 }
665         }
666         
667         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
668         {
669                 // check if the linking module wants to know about OUR metadata
670                 if (extname == "ssl")
671                 {
672                         // check if this user has an swhois field to send
673                         if(user->GetExt(extname, dummy))
674                         {
675                                 // call this function in the linking module, let it format the data how it
676                                 // sees fit, and send it on its way. We dont need or want to know how.
677                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
678                         }
679                 }
680         }
681         
682         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
683         {
684                 // check if its our metadata key, and its associated with a user
685                 if ((target_type == TYPE_USER) && (extname == "ssl"))
686                 {
687                         userrec* dest = (userrec*)target;
688                         // if they dont already have an ssl flag, accept the remote server's
689                         if (!dest->GetExt(extname, dummy))
690                         {
691                                 dest->Extend(extname, "ON");
692                         }
693                 }
694         }
695         
696         bool Handshake(issl_session* session)
697         {               
698                 int ret = SSL_accept(session->sess);
699       
700                 if (ret < 0)
701                 {
702                         int err = SSL_get_error(session->sess, ret);
703                                 
704                         if (err == SSL_ERROR_WANT_READ)
705                         {
706                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
707                                 session->rstat = ISSL_READ;
708                                 session->status = ISSL_HANDSHAKING;
709                         }
710                         else if (err == SSL_ERROR_WANT_WRITE)
711                         {
712                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
713                                 session->wstat = ISSL_WRITE;
714                                 session->status = ISSL_HANDSHAKING;
715                                 MakePollWrite(session);
716                         }
717                         else
718                         {
719                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
720                                 CloseSession(session);
721                         }
722
723                         return false;
724                 }
725                 else
726                 {
727                         // Handshake complete.
728                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
729                         
730                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
731                         userrec* u = ServerInstance->FindDescriptor(session->fd);
732                         if (u)
733                         {
734                                 if (!u->GetExt("ssl", dummy))
735                                         u->Extend("ssl", "ON");
736                         }
737                         
738                         session->status = ISSL_OPEN;
739                         
740                         MakePollWrite(session);
741                         
742                         return true;
743                 }
744         }
745         
746         virtual void OnPostConnect(userrec* user)
747         {
748                 // This occurs AFTER OnUserConnect so we can be sure the
749                 // protocol module has propogated the NICK message.
750                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
751                 {
752                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
753                         std::deque<std::string>* metadata = new std::deque<std::string>;
754                         metadata->push_back(user->nick);
755                         metadata->push_back("ssl");             // The metadata id
756                         metadata->push_back("ON");              // The value to send
757                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
758                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
759                         DELETE(event);
760                         DELETE(metadata);
761
762                         VerifyCertificate(&sessions[user->GetFd()], user);
763                 }
764         }
765         
766         void MakePollWrite(issl_session* session)
767         {
768                 OnRawSocketWrite(session->fd, NULL, 0);
769         }
770         
771         void CloseSession(issl_session* session)
772         {
773                 if (session->sess)
774                 {
775                         SSL_shutdown(session->sess);
776                         SSL_free(session->sess);
777                 }
778                 
779                 if (session->inbuf)
780                 {
781                         delete[] session->inbuf;
782                 }
783                 
784                 session->outbuf.clear();
785                 session->inbuf = NULL;
786                 session->sess = NULL;
787                 session->status = ISSL_NONE;
788         }
789
790         void VerifyCertificate(issl_session* session, Extensible* user)
791         {
792                 X509* cert;
793                 ssl_cert* certinfo = new ssl_cert;
794                 unsigned int n;
795                 unsigned char md[EVP_MAX_MD_SIZE];
796                 const EVP_MD *digest = EVP_md5();
797
798                 user->Extend("ssl_cert",certinfo);
799
800                 cert = SSL_get_peer_certificate((SSL*)session->sess);
801
802                 if (!cert)
803                 {
804                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
805                         return;
806                 }
807
808                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
809
810                 if (SelfSigned)
811                 {
812                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
813                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
814                 }
815                 else
816                 {
817                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
818                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
819                 }
820
821                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
822                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
823
824                 if (!X509_digest(cert, digest, md, &n))
825                 {
826                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
827                 }
828                 else
829                 {
830                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
831                 }
832
833                 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))
834                 {
835                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
836                 }
837
838                 X509_free(cert);
839         }
840 };
841
842 class ModuleSSLOpenSSLFactory : public ModuleFactory
843 {
844  public:
845         ModuleSSLOpenSSLFactory()
846         {
847         }
848         
849         ~ModuleSSLOpenSSLFactory()
850         {
851         }
852         
853         virtual Module * CreateModule(InspIRCd* Me)
854         {
855                 return new ModuleSSLOpenSSL(Me);
856         }
857 };
858
859
860 extern "C" void * init_module( void )
861 {
862         return new ModuleSSLOpenSSLFactory;
863 }