]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Added SQLQuery::GetError() and removed a lot of space indenting
[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
16 /* $ModDesc: Provides SSL support for clients */
17 /* $CompileFlags: -I/usr/include -I/usr/local/include */
18 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
19
20 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
21 enum issl_io_status { ISSL_WRITE, ISSL_READ };
22
23 bool isin(int port, const std::vector<int> &portlist)
24 {
25         for(unsigned int i = 0; i < portlist.size(); i++)
26                 if(portlist[i] == port)
27                         return true;
28                         
29         return false;
30 }
31
32 char* get_error()
33 {
34         return ERR_error_string(ERR_get_error(), NULL);
35 }
36
37 class issl_session
38 {
39 public:
40         SSL* sess;
41         issl_status status;
42         issl_io_status rstat;
43         issl_io_status wstat;
44
45         unsigned int inbufoffset;
46         char* inbuf;                    // Buffer OpenSSL reads into.
47         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
48         int fd;
49         
50         issl_session()
51         {
52                 rstat = ISSL_READ;
53                 wstat = ISSL_WRITE;
54         }
55 };
56
57 class ModuleSSLOpenSSL : public Module
58 {
59         Server* Srv;
60         ServerConfig* SrvConf;
61         ConfigReader* Conf;
62         
63         CullList culllist;
64         
65         std::vector<int> listenports;
66         
67         int inbufsize;
68         issl_session sessions[MAX_DESCRIPTORS];
69         
70         SSL_CTX* ctx;
71         
72         std::string keyfile;
73         std::string certfile;
74         std::string cafile;
75         // std::string crlfile;
76         std::string dhfile;
77         
78  public:
79         
80         ModuleSSLOpenSSL(Server* Me)
81                 : Module::Module(Me)
82         {
83                 Srv = Me;
84                 SrvConf = Srv->GetConfig();
85                 
86                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
87                 inbufsize = SrvConf->NetBufferSize;
88                 
89                 /* Global SSL library initialization*/
90                 SSL_library_init();
91                 SSL_load_error_strings();
92                 
93                 /* Build our SSL context*/
94                 ctx = SSL_CTX_new( SSLv23_server_method() );
95
96                 // Needs the flag as it ignores a plain /rehash
97                 OnRehash("ssl");
98         }
99         
100         virtual void OnRehash(const std::string &param)
101         {
102                 if(param != "ssl")
103                         return;
104         
105                 Conf = new ConfigReader;
106                         
107                 for(unsigned int i = 0; i < listenports.size(); i++)
108                 {
109                         SrvConf->DelIOHook(listenports[i]);
110                 }
111                 
112                 listenports.clear();
113                 
114                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
115                 {
116                         // For each <bind> tag
117                         if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
118                         {
119                                 // Get the port we're meant to be listening on with SSL
120                                 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
121                                 if(SrvConf->AddIOHook(port, this))
122                                 {
123                                         // We keep a record of which ports we're listening on with SSL
124                                         listenports.push_back(port);
125                                 
126                                         log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
127                                 }
128                                 else
129                                 {
130                                         log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
131                                 }
132                         }
133                 }
134                 
135                 std::string confdir(CONFIG_FILE);
136                 // +1 so we the path ends with a /
137                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
138                 
139                 cafile  = Conf->ReadValue("openssl", "cafile", 0);
140                 // crlfile      = Conf->ReadValue("openssl", "crlfile", 0);
141                 certfile        = Conf->ReadValue("openssl", "certfile", 0);
142                 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
143                 dhfile  = Conf->ReadValue("openssl", "dhfile", 0);
144                 
145                 // Set all the default values needed.
146                 if(cafile == "")
147                         cafile = "ca.pem";
148                         
149                 //if(crlfile == "")
150                 //      crlfile = "crl.pem";
151                         
152                 if(certfile == "")
153                         certfile = "cert.pem";
154                         
155                 if(keyfile == "")
156                         keyfile = "key.pem";
157                         
158                 if(dhfile == "")
159                         dhfile = "dhparams.pem";
160                         
161                 // Prepend relative paths with the path to the config directory.        
162                 if(cafile[0] != '/')
163                         cafile = confdir + cafile;
164                 
165                 //if(crlfile[0] != '/')
166                 //      crlfile = confdir + crlfile;
167                         
168                 if(certfile[0] != '/')
169                         certfile = confdir + certfile;
170                         
171                 if(keyfile[0] != '/')
172                         keyfile = confdir + keyfile;
173                         
174                 if(dhfile[0] != '/')
175                         dhfile = confdir + dhfile;
176
177                 /* Load our keys and certificates*/
178                 if(!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
179                 {
180                         log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
181                 }
182
183                 if(!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
184                 {
185                         log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
186                 }
187
188                 /* Load the CAs we trust*/
189                 if(!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
190                 {
191                         log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
192                 }
193
194                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
195                 DH* ret;
196
197                 if(dhpfile == NULL)
198                 {
199                         log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
200                         throw ModuleException();
201                 }
202                 else
203                 {
204                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
205                 
206                         if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
207                         {
208                                 log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
209                         }
210                 }
211                 
212                 fclose(dhpfile);
213
214                 DELETE(Conf);
215         }
216
217         virtual ~ModuleSSLOpenSSL()
218         {
219                 SSL_CTX_free(ctx);
220         }
221         
222         virtual void OnCleanup(int target_type, void* item)
223         {
224                 if(target_type == TYPE_USER)
225                 {
226                         userrec* user = (userrec*)item;
227                         
228                         if(user->GetExt("ssl") && IS_LOCAL(user) && isin(user->port, listenports))
229                         {
230                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
231                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
232                                 log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
233                                 culllist.AddItem(user, "SSL module unloading");
234                         }
235                 }
236         }
237         
238         virtual void OnUnloadModule(Module* mod, const std::string &name)
239         {
240                 if(mod == this)
241                 {
242                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
243                         int numusers = culllist.Apply();
244                         log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
245                         
246                         for(unsigned int i = 0; i < listenports.size(); i++)
247                                 SrvConf->DelIOHook(listenports[i]);
248                 }
249         }
250         
251         virtual Version GetVersion()
252         {
253                 return Version(1, 0, 0, 0, VF_VENDOR);
254         }
255
256         void Implements(char* List)
257         {
258                 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
259                 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnGlobalConnect] = 1;
260         }
261
262         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
263         {
264                 issl_session* session = &sessions[fd];
265         
266                 session->fd = fd;
267                 session->inbuf = new char[inbufsize];
268                 session->inbufoffset = 0;               
269                 session->sess = SSL_new(ctx);
270                 session->status = ISSL_NONE;
271         
272                 if(session->sess == NULL)
273                 {
274                         log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
275                         return;
276                 }
277                 
278                 if(SSL_set_fd(session->sess, fd) == 0)
279                 {
280                         log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
281                         return;
282                 }
283
284                 Handshake(session);
285         }
286
287         virtual void OnRawSocketClose(int fd)
288         {
289                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
290                 CloseSession(&sessions[fd]);
291         }
292         
293         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
294         {
295                 issl_session* session = &sessions[fd];
296                 
297                 if(!session->sess)
298                 {
299                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
300                         readresult = 0;
301                         CloseSession(session);
302                         return 1;
303                 }
304                 
305                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead(%d, buffer, %u, %d)", fd, count, readresult);
306                 
307                 if(session->status == ISSL_HANDSHAKING)
308                 {
309                         if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
310                         {
311                                 // The handshake isn't finished and it wants to read, try to finish it.
312                                 if(Handshake(session))
313                                 {
314                                         // Handshake successfully resumed.
315                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
316                                 }
317                                 else
318                                 {
319                                         // Couldn't resume handshake.   
320                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
321                                         return -1;
322                                 }
323                         }
324                         else
325                         {
326                                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
327                                 return -1;                      
328                         }
329                 }
330                 
331                 // If we resumed the handshake then session->status will be ISSL_OPEN
332                                 
333                 if(session->status == ISSL_OPEN)
334                 {
335                         if(session->wstat == ISSL_READ)
336                         {
337                                 if(DoWrite(session) == 0)
338                                         return 0;
339                         }
340                         
341                         if(session->rstat == ISSL_READ)
342                         {
343                                 int ret = DoRead(session);
344                         
345                                 if(ret > 0)
346                                 {
347                                         if(count <= session->inbufoffset)
348                                         {
349                                                 memcpy(buffer, session->inbuf, count);
350                                                 // Move the stuff left in inbuf to the beginning of it
351                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
352                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
353                                                 session->inbufoffset -= count;
354                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
355                                                 readresult = count;
356                                         }
357                                         else
358                                         {
359                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
360                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
361                                                 
362                                                 readresult = session->inbufoffset;
363                                                 // Zero the offset, as there's nothing there..
364                                                 session->inbufoffset = 0;
365                                         }
366                                 
367                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: Passing %d bytes up to insp:", count);
368                                         Srv->Log(DEBUG, std::string(buffer, readresult));
369                                 
370                                         return 1;
371                                 }
372                                 else
373                                 {
374                                         return ret;
375                                 }
376                         }
377                 }
378                 
379                 return -1;
380         }
381         
382         virtual int OnRawSocketWrite(int fd, char* buffer, int count)
383         {               
384                 issl_session* session = &sessions[fd];
385
386                 if(!session->sess)
387                 {
388                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
389                         CloseSession(session);
390                         return 1;
391                 }
392                 
393                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);                
394                 session->outbuf.append(buffer, count);
395                 
396                 if(session->status == ISSL_HANDSHAKING)
397                 {
398                         // The handshake isn't finished, try to finish it.
399                         if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
400                         {
401                                 if(Handshake(session))
402                                 {
403                                         // Handshake successfully resumed.
404                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
405                                 }
406                                 else
407                                 {
408                                         // Couldn't resume handshake.   
409                                         log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
410                                 }
411                         }
412                         else
413                         {
414                                 log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
415                         }
416                 }
417                 
418                 if(session->status == ISSL_OPEN)
419                 {
420                         if(session->rstat == ISSL_WRITE)
421                         {
422                                 DoRead(session);
423                         }
424                         
425                         if(session->wstat == ISSL_WRITE)
426                         {
427                                 return DoWrite(session);
428                         }
429                 }
430                 
431                 return 1;
432         }
433         
434         int DoWrite(issl_session* session)
435         {
436                 log(DEBUG, "m_ssl_openssl.so: DoWrite: Trying to write %d bytes:", session->outbuf.size());
437                 Srv->Log(DEBUG, session->outbuf);
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") || (IS_LOCAL(dest) &&  isin(dest->port, listenports)))
535                 {
536                         WriteServ(source->fd, "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))
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))
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"))
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")) && (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(Server* Me)
674         {
675                 return new ModuleSSLOpenSSL(Me);
676         }
677 };
678
679
680 extern "C" void * init_module( void )
681 {
682         return new ModuleSSLOpenSSLFactory;
683 }