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