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