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