]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Note: FOR THE MOMENT, this is BROKEN. It wont run right until im done.
[user/henk/code/inspircd.git] / src / modules / extra / m_ssl_openssl.cpp
1 #include <string>
2 #include <vector>
3
4 #include <openssl/ssl.h>
5 #include <openssl/err.h>
6
7 #include "inspircd_config.h"
8 #include "configreader.h"
9 #include "users.h"
10 #include "channels.h"
11 #include "modules.h"
12 #include "helperfuncs.h"
13 #include "socket.h"
14 #include "hashcomp.h"
15 #include "inspircd.h"
16
17 /* $ModDesc: Provides SSL support for clients */
18 /* $CompileFlags: -I/usr/include -I/usr/local/include */
19 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
20
21 extern InspIRCd* ServerInstance;
22
23 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
24 enum issl_io_status { ISSL_WRITE, ISSL_READ };
25
26 bool isin(int port, const std::vector<int> &portlist)
27 {
28         for(unsigned int i = 0; i < portlist.size(); i++)
29                 if(portlist[i] == port)
30                         return true;
31                         
32         return false;
33 }
34
35 char* get_error()
36 {
37         return ERR_error_string(ERR_get_error(), NULL);
38 }
39
40 class issl_session : public classbase
41 {
42 public:
43         SSL* sess;
44         issl_status status;
45         issl_io_status rstat;
46         issl_io_status wstat;
47
48         unsigned int inbufoffset;
49         char* inbuf;                    // Buffer OpenSSL reads into.
50         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
51         int fd;
52         
53         issl_session()
54         {
55                 rstat = ISSL_READ;
56                 wstat = ISSL_WRITE;
57         }
58 };
59
60 class ModuleSSLOpenSSL : public Module
61 {
62         Server* Srv;
63         ConfigReader* Conf;
64         
65         CullList* culllist;
66         
67         std::vector<int> listenports;
68         
69         int inbufsize;
70         issl_session sessions[MAX_DESCRIPTORS];
71         
72         SSL_CTX* ctx;
73         
74         char* dummy;
75         
76         std::string keyfile;
77         std::string certfile;
78         std::string cafile;
79         // std::string crlfile;
80         std::string dhfile;
81         
82  public:
83         
84         ModuleSSLOpenSSL(InspIRCd* Me)
85                 : Module::Module(Me)
86         {
87                 
88
89                 culllist = new CullList(ServerInstance);
90                 
91                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
92                 inbufsize = ServerInstance->Config->NetBufferSize;
93                 
94                 /* Global SSL library initialization*/
95                 SSL_library_init();
96                 SSL_load_error_strings();
97                 
98                 /* Build our SSL context*/
99                 ctx = SSL_CTX_new( SSLv23_server_method() );
100
101                 // Needs the flag as it ignores a plain /rehash
102                 OnRehash("ssl");
103         }
104         
105         virtual void OnRehash(const std::string &param)
106         {
107                 if(param != "ssl")
108                         return;
109         
110                 Conf = new ConfigReader;
111                         
112                 for(unsigned int i = 0; i < listenports.size(); i++)
113                 {
114                         ServerInstance->Config->DelIOHook(listenports[i]);
115                 }
116                 
117                 listenports.clear();
118                 
119                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
120                 {
121                         // For each <bind> tag
122                         if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
123                         {
124                                 // Get the port we're meant to be listening on with SSL
125                                 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
126                                 if (ServerInstance->Config->AddIOHook(port, this))
127                                 {
128                                         // We keep a record of which ports we're listening on with SSL
129                                         listenports.push_back(port);
130                                 
131                                         log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
132                                 }
133                                 else
134                                 {
135                                         log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
136                                 }
137                         }
138                 }
139                 
140                 std::string confdir(CONFIG_FILE);
141                 // +1 so we the path ends with a /
142                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
143                 
144                 cafile  = Conf->ReadValue("openssl", "cafile", 0);
145                 // crlfile      = Conf->ReadValue("openssl", "crlfile", 0);
146                 certfile        = Conf->ReadValue("openssl", "certfile", 0);
147                 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
148                 dhfile  = Conf->ReadValue("openssl", "dhfile", 0);
149                 
150                 // Set all the default values needed.
151                 if(cafile == "")
152                         cafile = "ca.pem";
153                         
154                 //if(crlfile == "")
155                 //      crlfile = "crl.pem";
156                         
157                 if(certfile == "")
158                         certfile = "cert.pem";
159                         
160                 if(keyfile == "")
161                         keyfile = "key.pem";
162                         
163                 if(dhfile == "")
164                         dhfile = "dhparams.pem";
165                         
166                 // Prepend relative paths with the path to the config directory.        
167                 if(cafile[0] != '/')
168                         cafile = confdir + cafile;
169                 
170                 //if(crlfile[0] != '/')
171                 //      crlfile = confdir + crlfile;
172                         
173                 if(certfile[0] != '/')
174                         certfile = confdir + certfile;
175                         
176                 if(keyfile[0] != '/')
177                         keyfile = confdir + keyfile;
178                         
179                 if(dhfile[0] != '/')
180                         dhfile = confdir + dhfile;
181
182                 /* Load our keys and certificates*/
183                 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
184                 {
185                         log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
186                 }
187
188                 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
189                 {
190                         log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
191                 }
192
193                 /* Load the CAs we trust*/
194                 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
195                 {
196                         log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
197                 }
198
199                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
200                 DH* ret;
201
202                 if(dhpfile == NULL)
203                 {
204                         log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
205                         throw ModuleException();
206                 }
207                 else
208                 {
209                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
210                 
211                         if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
212                         {
213                                 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
214                         }
215                 }
216                 
217                 fclose(dhpfile);
218
219                 DELETE(Conf);
220         }
221
222         virtual ~ModuleSSLOpenSSL()
223         {
224                 SSL_CTX_free(ctx);
225                 delete culllist;
226         }
227         
228         virtual void OnCleanup(int target_type, void* item)
229         {
230                 if(target_type == TYPE_USER)
231                 {
232                         userrec* user = (userrec*)item;
233                         
234                         if(user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
235                         {
236                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
237                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
238                                 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
239                                 culllist->AddItem(user, "SSL module unloading");
240                         }
241                 }
242         }
243         
244         virtual void OnUnloadModule(Module* mod, const std::string &name)
245         {
246                 if(mod == this)
247                 {
248                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
249                         int numusers = culllist->Apply();
250                         log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
251                         
252                         for(unsigned int i = 0; i < listenports.size(); i++)
253                                 ServerInstance->Config->DelIOHook(listenports[i]);
254                 }
255         }
256         
257         virtual Version GetVersion()
258         {
259                 return Version(1, 0, 0, 0, VF_VENDOR);
260         }
261
262         void Implements(char* List)
263         {
264                 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
265                 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
266         }
267
268         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
269         {
270                 issl_session* session = &sessions[fd];
271         
272                 session->fd = fd;
273                 session->inbuf = new char[inbufsize];
274                 session->inbufoffset = 0;               
275                 session->sess = SSL_new(ctx);
276                 session->status = ISSL_NONE;
277         
278                 if(session->sess == NULL)
279                 {
280                         log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
281                         return;
282                 }
283                 
284                 if(SSL_set_fd(session->sess, fd) == 0)
285                 {
286                         log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
287                         return;
288                 }
289
290                 Handshake(session);
291         }
292
293         virtual void OnRawSocketClose(int fd)
294         {
295                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
296                 CloseSession(&sessions[fd]);
297         }
298         
299         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
300         {
301                 issl_session* session = &sessions[fd];
302                 
303                 if(!session->sess)
304                 {
305                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
306                         readresult = 0;
307                         CloseSession(session);
308                         return 1;
309                 }
310                 
311                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
312                 
313                 if(session->status == ISSL_HANDSHAKING)
314                 {
315                         if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
316                         {
317                                 // The handshake isn't finished and it wants to read, try to finish it.
318                                 if(Handshake(session))
319                                 {
320                                         // Handshake successfully resumed.
321                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
322                                 }
323                                 else
324                                 {
325                                         // Couldn't resume handshake.   
326                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
327                                         return -1;
328                                 }
329                         }
330                         else
331                         {
332                                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
333                                 return -1;                      
334                         }
335                 }
336                 
337                 // If we resumed the handshake then session->status will be ISSL_OPEN
338                                 
339                 if(session->status == ISSL_OPEN)
340                 {
341                         if(session->wstat == ISSL_READ)
342                         {
343                                 if(DoWrite(session) == 0)
344                                         return 0;
345                         }
346                         
347                         if(session->rstat == ISSL_READ)
348                         {
349                                 int ret = DoRead(session);
350                         
351                                 if(ret > 0)
352                                 {
353                                         if(count <= session->inbufoffset)
354                                         {
355                                                 memcpy(buffer, session->inbuf, count);
356                                                 // Move the stuff left in inbuf to the beginning of it
357                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
358                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
359                                                 session->inbufoffset -= count;
360                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
361                                                 readresult = count;
362                                         }
363                                         else
364                                         {
365                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
366                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
367                                                 
368                                                 readresult = session->inbufoffset;
369                                                 // Zero the offset, as there's nothing there..
370                                                 session->inbufoffset = 0;
371                                         }
372                                 
373                                         return 1;
374                                 }
375                                 else
376                                 {
377                                         return ret;
378                                 }
379                         }
380                 }
381                 
382                 return -1;
383         }
384         
385         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
386         {               
387                 issl_session* session = &sessions[fd];
388
389                 if(!session->sess)
390                 {
391                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
392                         CloseSession(session);
393                         return 1;
394                 }
395                 
396                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);                
397                 session->outbuf.append(buffer, count);
398                 
399                 if(session->status == ISSL_HANDSHAKING)
400                 {
401                         // The handshake isn't finished, try to finish it.
402                         if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
403                         {
404                                 if(Handshake(session))
405                                 {
406                                         // Handshake successfully resumed.
407                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
408                                 }
409                                 else
410                                 {
411                                         // Couldn't resume handshake.   
412                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
413                                 }
414                         }
415                         else
416                         {
417                                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
418                         }
419                 }
420                 
421                 if(session->status == ISSL_OPEN)
422                 {
423                         if(session->rstat == ISSL_WRITE)
424                         {
425                                 DoRead(session);
426                         }
427                         
428                         if(session->wstat == ISSL_WRITE)
429                         {
430                                 return DoWrite(session);
431                         }
432                 }
433                 
434                 return 1;
435         }
436         
437         int DoWrite(issl_session* session)
438         {
439                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
440                 
441                 if(ret == 0)
442                 {
443                         log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
444                         CloseSession(session);
445                         return 0;
446                 }
447                 else if(ret < 0)
448                 {
449                         int err = SSL_get_error(session->sess, ret);
450                         
451                         if(err == SSL_ERROR_WANT_WRITE)
452                         {
453                                 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
454                                 session->wstat = ISSL_WRITE;
455                                 return -1;
456                         }
457                         else if(err == SSL_ERROR_WANT_READ)
458                         {
459                                 log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
460                                 session->wstat = ISSL_READ;
461                                 return -1;
462                         }
463                         else
464                         {
465                                 log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
466                                 CloseSession(session);
467                                 return 0;
468                         }
469                 }
470                 else
471                 {
472                         log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
473                         session->outbuf = session->outbuf.substr(ret);
474                         return ret;
475                 }
476         }
477         
478         int DoRead(issl_session* session)
479         {
480                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
481                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
482                 log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
483                         
484                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
485
486                 if(ret == 0)
487                 {
488                         // Client closed connection.
489                         log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
490                         CloseSession(session);
491                         return 0;
492                 }
493                 else if(ret < 0)
494                 {
495                         int err = SSL_get_error(session->sess, ret);
496                                 
497                         if(err == SSL_ERROR_WANT_READ)
498                         {
499                                 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
500                                 session->rstat = ISSL_READ;
501                                 return -1;
502                         }
503                         else if(err == SSL_ERROR_WANT_WRITE)
504                         {
505                                 log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
506                                 session->rstat = ISSL_WRITE;
507                                 return -1;
508                         }
509                         else
510                         {
511                                 log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
512                                 CloseSession(session);
513                                 return 0;
514                         }
515                 }
516                 else
517                 {
518                         // Read successfully 'ret' bytes into inbuf + inbufoffset
519                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
520                         // 'buffer' is 'count' long
521                         
522                         log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);
523
524                         session->inbufoffset += ret;
525
526                         return ret;
527                 }
528         }
529         
530         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
531         virtual void OnWhois(userrec* source, userrec* dest)
532         {
533                 // Bugfix, only send this numeric for *our* SSL users
534                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
535                 {
536                         source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
537                 }
538         }
539         
540         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
541         {
542                 // check if the linking module wants to know about OUR metadata
543                 if(extname == "ssl")
544                 {
545                         // check if this user has an swhois field to send
546                         if(user->GetExt(extname, dummy))
547                         {
548                                 // call this function in the linking module, let it format the data how it
549                                 // sees fit, and send it on its way. We dont need or want to know how.
550                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
551                         }
552                 }
553         }
554         
555         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
556         {
557                 // check if its our metadata key, and its associated with a user
558                 if ((target_type == TYPE_USER) && (extname == "ssl"))
559                 {
560                         userrec* dest = (userrec*)target;
561                         // if they dont already have an ssl flag, accept the remote server's
562                         if (!dest->GetExt(extname, dummy))
563                         {
564                                 dest->Extend(extname, "ON");
565                         }
566                 }
567         }
568         
569         bool Handshake(issl_session* session)
570         {               
571                 int ret = SSL_accept(session->sess);
572       
573                 if(ret < 0)
574                 {
575                         int err = SSL_get_error(session->sess, ret);
576                                 
577                         if(err == SSL_ERROR_WANT_READ)
578                         {
579                                 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
580                                 session->rstat = ISSL_READ;
581                                 session->status = ISSL_HANDSHAKING;
582                         }
583                         else if(err == SSL_ERROR_WANT_WRITE)
584                         {
585                                 log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
586                                 session->wstat = ISSL_WRITE;
587                                 session->status = ISSL_HANDSHAKING;
588                                 MakePollWrite(session);
589                         }
590                         else
591                         {
592                                 log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
593                                 CloseSession(session);
594                         }
595
596                         return false;
597                 }
598                 else
599                 {
600                         // Handshake complete.
601                         log(DEBUG, "m_ssl_openssl.so: Handshake completed");
602                         
603                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
604                         userrec* u = Srv->FindDescriptor(session->fd);
605                         if (u)
606                         {
607                                 if (!u->GetExt("ssl", dummy))
608                                         u->Extend("ssl", "ON");
609                         }
610                         
611                         session->status = ISSL_OPEN;
612                         
613                         MakePollWrite(session);
614                         
615                         return true;
616                 }
617         }
618         
619         virtual void OnGlobalConnect(userrec* user)
620         {
621                 // This occurs AFTER OnUserConnect so we can be sure the
622                 // protocol module has propogated the NICK message.
623                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
624                 {
625                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
626                         std::deque<std::string>* metadata = new std::deque<std::string>;
627                         metadata->push_back(user->nick);
628                         metadata->push_back("ssl");             // The metadata id
629                         metadata->push_back("ON");              // The value to send
630                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
631                         event->Send();                          // Trigger the event. We don't care what module picks it up.
632                         DELETE(event);
633                         DELETE(metadata);
634                 }
635         }
636         
637         void MakePollWrite(issl_session* session)
638         {
639                 OnRawSocketWrite(session->fd, NULL, 0);
640         }
641         
642         void CloseSession(issl_session* session)
643         {
644                 if(session->sess)
645                 {
646                         SSL_shutdown(session->sess);
647                         SSL_free(session->sess);
648                 }
649                 
650                 if(session->inbuf)
651                 {
652                         delete[] session->inbuf;
653                 }
654                 
655                 session->outbuf.clear();
656                 session->inbuf = NULL;
657                 session->sess = NULL;
658                 session->status = ISSL_NONE;
659         }
660 };
661
662 class ModuleSSLOpenSSLFactory : public ModuleFactory
663 {
664  public:
665         ModuleSSLOpenSSLFactory()
666         {
667         }
668         
669         ~ModuleSSLOpenSSLFactory()
670         {
671         }
672         
673         virtual Module * CreateModule(InspIRCd* Me)
674         {
675                 return new ModuleSSLOpenSSL(Me);
676         }
677 };
678
679
680 extern "C" void * init_module( void )
681 {
682         return new ModuleSSLOpenSSLFactory;
683 }