]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Record compression ratio stats for a /stats char (this isnt finished yet)
[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
13 #include "socket.h"
14 #include "hashcomp.h"
15 #include "inspircd.h"
16
17 #include "transport.h"
18
19 /* $ModDesc: Provides SSL support for clients */
20 /* $CompileFlags: `perl extra/openssl_config.pl compile` */
21 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
22 /* $ModDep: transport.h */
23
24 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
25 enum issl_io_status { ISSL_WRITE, ISSL_READ };
26
27 static bool SelfSigned = false;
28
29 bool isin(int port, const std::vector<int> &portlist)
30 {
31         for(unsigned int i = 0; i < portlist.size(); i++)
32                 if(portlist[i] == port)
33                         return true;
34                         
35         return false;
36 }
37
38 char* get_error()
39 {
40         return ERR_error_string(ERR_get_error(), NULL);
41 }
42
43 /** Represents an SSL user's extra data
44  */
45 class issl_session : public classbase
46 {
47 public:
48         SSL* sess;
49         issl_status status;
50         issl_io_status rstat;
51         issl_io_status wstat;
52
53         unsigned int inbufoffset;
54         char* inbuf;                    // Buffer OpenSSL reads into.
55         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
56         int fd;
57         
58         issl_session()
59         {
60                 rstat = ISSL_READ;
61                 wstat = ISSL_WRITE;
62         }
63 };
64
65 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
66 {
67         /* XXX: This will allow self signed certificates.
68          * In the future if we want an option to not allow this,
69          * we can just return preverify_ok here, and openssl
70          * will boot off self-signed and invalid peer certs.
71          */
72         int ve = X509_STORE_CTX_get_error(ctx);
73
74         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
75
76         return 1;
77 }
78         
79 class ModuleSSLOpenSSL : public Module
80 {
81         
82         ConfigReader* Conf;
83         
84         CullList* culllist;
85         
86         std::vector<int> listenports;
87         
88         int inbufsize;
89         issl_session sessions[MAX_DESCRIPTORS];
90         
91         SSL_CTX* ctx;
92         
93         char* dummy;
94         
95         std::string keyfile;
96         std::string certfile;
97         std::string cafile;
98         // std::string crlfile;
99         std::string dhfile;
100         
101  public:
102         
103         ModuleSSLOpenSSL(InspIRCd* Me)
104                 : Module::Module(Me)
105         {
106                 culllist = new CullList(ServerInstance);
107
108                 ServerInstance->PublishInterface("InspSocketHook", this);
109                 
110                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
111                 inbufsize = ServerInstance->Config->NetBufferSize;
112                 
113                 /* Global SSL library initialization*/
114                 SSL_library_init();
115                 SSL_load_error_strings();
116                 
117                 /* Build our SSL context*/
118                 ctx = SSL_CTX_new( SSLv23_server_method() );
119
120                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
121
122                 // Needs the flag as it ignores a plain /rehash
123                 OnRehash("ssl");
124         }
125         
126         virtual void OnRehash(const std::string &param)
127         {
128                 if (param != "ssl")
129                         return;
130         
131                 Conf = new ConfigReader(ServerInstance);
132                         
133                 for (unsigned int i = 0; i < listenports.size(); i++)
134                 {
135                         ServerInstance->Config->DelIOHook(listenports[i]);
136                 }
137                 
138                 listenports.clear();
139                 
140                 for (int i = 0; i < Conf->Enumerate("bind"); i++)
141                 {
142                         // For each <bind> tag
143                         if (((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
144                         {
145                                 // Get the port we're meant to be listening on with SSL
146                                 std::string port = Conf->ReadValue("bind", "port", i);
147                                 irc::portparser portrange(port, false);
148                                 long portno = -1;
149                                 while ((portno = portrange.GetToken()))
150                                 {
151                                         if (ServerInstance->Config->AddIOHook(portno, this))
152                                         {
153                                                 listenports.push_back(portno);
154                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
155                                         }
156                                         else
157                                         {
158                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
159                                         }
160                                 }
161                         }
162                 }
163                 
164                 std::string confdir(CONFIG_FILE);
165                 // +1 so we the path ends with a /
166                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
167                 
168                 cafile   = Conf->ReadValue("openssl", "cafile", 0);
169                 certfile = Conf->ReadValue("openssl", "certfile", 0);
170                 keyfile  = Conf->ReadValue("openssl", "keyfile", 0);
171                 dhfile   = Conf->ReadValue("openssl", "dhfile", 0);
172                 
173                 // Set all the default values needed.
174                 if (cafile == "")
175                         cafile = "ca.pem";
176                         
177                 if (certfile == "")
178                         certfile = "cert.pem";
179                         
180                 if (keyfile == "")
181                         keyfile = "key.pem";
182                         
183                 if (dhfile == "")
184                         dhfile = "dhparams.pem";
185                         
186                 // Prepend relative paths with the path to the config directory.        
187                 if (cafile[0] != '/')
188                         cafile = confdir + cafile;
189                 
190                 //if(crlfile[0] != '/')
191                 //      crlfile = confdir + crlfile;
192                         
193                 if (certfile[0] != '/')
194                         certfile = confdir + certfile;
195                         
196                 if (keyfile[0] != '/')
197                         keyfile = confdir + keyfile;
198                         
199                 if (dhfile[0] != '/')
200                         dhfile = confdir + dhfile;
201
202                 /* Load our keys and certificates*/
203                 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
204                 {
205                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
206                 }
207
208                 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
209                 {
210                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
211                 }
212
213                 /* Load the CAs we trust*/
214                 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
215                 {
216                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
217                 }
218
219                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
220                 DH* ret;
221
222                 if (dhpfile == NULL)
223                 {
224                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
225                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
226                 }
227                 else
228                 {
229                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
230                 
231                         if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
232                         {
233                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
234                         }
235                 }
236                 
237                 fclose(dhpfile);
238
239                 DELETE(Conf);
240         }
241
242         virtual ~ModuleSSLOpenSSL()
243         {
244                 SSL_CTX_free(ctx);
245                 delete culllist;
246         }
247         
248         virtual void OnCleanup(int target_type, void* item)
249         {
250                 if (target_type == TYPE_USER)
251                 {
252                         userrec* user = (userrec*)item;
253                         
254                         if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
255                         {
256                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
257                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
258                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
259                                 culllist->AddItem(user, "SSL module unloading");
260                         }
261                         if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
262                         {
263                                 ssl_cert* tofree;
264                                 user->GetExt("ssl_cert", tofree);
265                                 delete tofree;
266                                 user->Shrink("ssl_cert");
267                         }
268                 }
269         }
270         
271         virtual void OnUnloadModule(Module* mod, const std::string &name)
272         {
273                 if (mod == this)
274                 {
275                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
276                         int numusers = culllist->Apply();
277                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
278                         
279                         for(unsigned int i = 0; i < listenports.size(); i++)
280                                 ServerInstance->Config->DelIOHook(listenports[i]);
281                 }
282         }
283         
284         virtual Version GetVersion()
285         {
286                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
287         }
288
289         void Implements(char* List)
290         {
291                 List[I_OnRawSocketConnect] = List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
292                 List[I_OnRequest] = List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
293         }
294
295         virtual char* OnRequest(Request* request)
296         {
297                 ISHRequest* ISR = (ISHRequest*)request;
298                 ServerInstance->Log(DEBUG, "hook OnRequest");
299                 if (strcmp("IS_NAME", request->GetId()) == 0)
300                 {
301                         return "openssl";
302                 }
303                 else if (strcmp("IS_HOOK", request->GetId()) == 0)
304                 {
305                         ServerInstance->Log(DEBUG, "Hooking socket %08x", ISR->Sock);
306                         return ServerInstance->Config->AddIOHook((Module*)this, (InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
307                 }
308                 else if (strcmp("IS_UNHOOK", request->GetId()) == 0)
309                 {
310                         ServerInstance->Log(DEBUG, "Unhooking socket %08x", ISR->Sock);
311                         return ServerInstance->Config->DelIOHook((InspSocket*)ISR->Sock) ? (char*)"OK" : NULL;
312                 }
313                 else if (strcmp("IS_HSDONE", request->GetId()) == 0)
314                 {
315                         issl_session* session = &sessions[ISR->Sock->GetFd()];
316                         return (session->status == ISSL_HANDSHAKING) ? NULL : (char*)"OK";
317                 }
318                 else if (strcmp("IS_ATTACH", request->GetId()) == 0)
319                 {
320                         issl_session* session = &sessions[ISR->Sock->GetFd()];
321                         if (session)
322                         {
323                                 VerifyCertificate(session, (InspSocket*)ISR->Sock);
324                                 return "OK";
325                         }
326                 }
327                 return NULL;
328         }
329
330
331         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
332         {
333                 ServerInstance->Log(DEBUG, "Hook accept %d", fd);
334                 issl_session* session = &sessions[fd];
335         
336                 session->fd = fd;
337                 session->inbuf = new char[inbufsize];
338                 session->inbufoffset = 0;               
339                 session->sess = SSL_new(ctx);
340                 session->status = ISSL_NONE;
341         
342                 if (session->sess == NULL)
343                 {
344                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
345                         return;
346                 }
347                 
348                 if (SSL_set_fd(session->sess, fd) == 0)
349                 {
350                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
351                         return;
352                 }
353
354                 Handshake(session);
355         }
356
357         virtual void OnRawSocketConnect(int fd)
358         {
359                 issl_session* session = &sessions[fd];
360
361                 session->fd = fd;
362                 session->inbuf = new char[inbufsize];
363                 session->inbufoffset = 0;
364                 session->sess = SSL_new(ctx);
365                 session->status = ISSL_NONE;
366
367                 if (session->sess == NULL)
368                 {
369                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
370                         return;
371                 }
372
373                 if (SSL_set_fd(session->sess, fd) == 0)
374                 {
375                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
376                         return;
377                 }
378
379                 Handshake(session);
380         }
381
382         virtual void OnRawSocketClose(int fd)
383         {
384                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
385                 CloseSession(&sessions[fd]);
386
387                 EventHandler* user = ServerInstance->SE->GetRef(fd);
388
389                 if ((user) && (user->GetExt("ssl_cert", dummy)))
390                 {
391                         ssl_cert* tofree;
392                         user->GetExt("ssl_cert", tofree);
393                         delete tofree;
394                         user->Shrink("ssl_cert");
395                 }
396         }
397
398         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
399         {
400                 issl_session* session = &sessions[fd];
401                 
402                 if (!session->sess)
403                 {
404                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
405                         readresult = 0;
406                         CloseSession(session);
407                         return 1;
408                 }
409                 
410                 if (session->status == ISSL_HANDSHAKING)
411                 {
412                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
413                         {
414                                 // The handshake isn't finished and it wants to read, try to finish it.
415                                 if (Handshake(session))
416                                 {
417                                         // Handshake successfully resumed.
418                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
419                                 }
420                                 else
421                                 {
422                                         // Couldn't resume handshake.   
423                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
424                                         return -1;
425                                 }
426                         }
427                         else
428                         {
429                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
430                                 return -1;                      
431                         }
432                 }
433
434                 // If we resumed the handshake then session->status will be ISSL_OPEN
435                                 
436                 if (session->status == ISSL_OPEN)
437                 {
438                         if (session->wstat == ISSL_READ)
439                         {
440                                 if(DoWrite(session) == 0)
441                                         return 0;
442                         }
443                         
444                         if (session->rstat == ISSL_READ)
445                         {
446                                 int ret = DoRead(session);
447                         
448                                 if (ret > 0)
449                                 {
450                                         if (count <= session->inbufoffset)
451                                         {
452                                                 memcpy(buffer, session->inbuf, count);
453                                                 // Move the stuff left in inbuf to the beginning of it
454                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
455                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
456                                                 session->inbufoffset -= count;
457                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
458                                                 readresult = count;
459                                         }
460                                         else
461                                         {
462                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
463                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
464                                                 
465                                                 readresult = session->inbufoffset;
466                                                 // Zero the offset, as there's nothing there..
467                                                 session->inbufoffset = 0;
468                                         }
469                                 
470                                         return 1;
471                                 }
472                                 else
473                                 {
474                                         return ret;
475                                 }
476                         }
477                 }
478                 
479                 return -1;
480         }
481         
482         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
483         {               
484                 issl_session* session = &sessions[fd];
485
486                 if (!session->sess)
487                 {
488                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
489                         CloseSession(session);
490                         return 1;
491                 }
492
493                 session->outbuf.append(buffer, count);
494                 
495                 if (session->status == ISSL_HANDSHAKING)
496                 {
497                         // The handshake isn't finished, try to finish it.
498                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
499                         {
500                                 if (Handshake(session))
501                                 {
502                                         // Handshake successfully resumed.
503                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
504                                 }
505                                 else
506                                 {
507                                         // Couldn't resume handshake.   
508                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
509                                 }
510                         }
511                         else
512                         {
513                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
514                         }
515                 }
516                 
517                 if (session->status == ISSL_OPEN)
518                 {
519                         if (session->rstat == ISSL_WRITE)
520                         {
521                                 DoRead(session);
522                         }
523                         
524                         if (session->wstat == ISSL_WRITE)
525                         {
526                                 return DoWrite(session);
527                         }
528                 }
529                 
530                 return 1;
531         }
532         
533         int DoWrite(issl_session* session)
534         {
535                 if (!session->outbuf.size())
536                         return -1;
537
538                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: To write: %d", session->outbuf.size());
539                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
540                 
541                 if (ret == 0)
542                 {
543                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
544                         CloseSession(session);
545                         return 0;
546                 }
547                 else if (ret < 0)
548                 {
549                         int err = SSL_get_error(session->sess, ret);
550                         
551                         if (err == SSL_ERROR_WANT_WRITE)
552                         {
553                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
554                                 session->wstat = ISSL_WRITE;
555                                 return -1;
556                         }
557                         else if (err == SSL_ERROR_WANT_READ)
558                         {
559                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
560                                 session->wstat = ISSL_READ;
561                                 return -1;
562                         }
563                         else
564                         {
565                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
566                                 CloseSession(session);
567                                 return 0;
568                         }
569                 }
570                 else
571                 {
572                         session->outbuf = session->outbuf.substr(ret);
573                         return ret;
574                 }
575         }
576         
577         int DoRead(issl_session* session)
578         {
579                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
580                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
581                         
582                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
583
584                 if (ret == 0)
585                 {
586                         // Client closed connection.
587                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
588                         CloseSession(session);
589                         return 0;
590                 }
591                 else if (ret < 0)
592                 {
593                         int err = SSL_get_error(session->sess, ret);
594                                 
595                         if (err == SSL_ERROR_WANT_READ)
596                         {
597                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
598                                 session->rstat = ISSL_READ;
599                                 return -1;
600                         }
601                         else if (err == SSL_ERROR_WANT_WRITE)
602                         {
603                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
604                                 session->rstat = ISSL_WRITE;
605                                 return -1;
606                         }
607                         else
608                         {
609                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
610                                 CloseSession(session);
611                                 return 0;
612                         }
613                 }
614                 else
615                 {
616                         // Read successfully 'ret' bytes into inbuf + inbufoffset
617                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
618                         // 'buffer' is 'count' long
619
620                         session->inbufoffset += ret;
621
622                         return ret;
623                 }
624         }
625         
626         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
627         virtual void OnWhois(userrec* source, userrec* dest)
628         {
629                 // Bugfix, only send this numeric for *our* SSL users
630                 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
631                 {
632                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
633                 }
634         }
635         
636         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
637         {
638                 // check if the linking module wants to know about OUR metadata
639                 if (extname == "ssl")
640                 {
641                         // check if this user has an swhois field to send
642                         if(user->GetExt(extname, dummy))
643                         {
644                                 // call this function in the linking module, let it format the data how it
645                                 // sees fit, and send it on its way. We dont need or want to know how.
646                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
647                         }
648                 }
649         }
650         
651         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
652         {
653                 // check if its our metadata key, and its associated with a user
654                 if ((target_type == TYPE_USER) && (extname == "ssl"))
655                 {
656                         userrec* dest = (userrec*)target;
657                         // if they dont already have an ssl flag, accept the remote server's
658                         if (!dest->GetExt(extname, dummy))
659                         {
660                                 dest->Extend(extname, "ON");
661                         }
662                 }
663         }
664         
665         bool Handshake(issl_session* session)
666         {               
667                 int ret = SSL_accept(session->sess);
668       
669                 if (ret < 0)
670                 {
671                         int err = SSL_get_error(session->sess, ret);
672                                 
673                         if (err == SSL_ERROR_WANT_READ)
674                         {
675                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
676                                 session->rstat = ISSL_READ;
677                                 session->status = ISSL_HANDSHAKING;
678                         }
679                         else if (err == SSL_ERROR_WANT_WRITE)
680                         {
681                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
682                                 session->wstat = ISSL_WRITE;
683                                 session->status = ISSL_HANDSHAKING;
684                                 MakePollWrite(session);
685                         }
686                         else
687                         {
688                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
689                                 CloseSession(session);
690                         }
691
692                         return false;
693                 }
694                 else
695                 {
696                         // Handshake complete.
697                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
698                         
699                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
700                         userrec* u = ServerInstance->FindDescriptor(session->fd);
701                         if (u)
702                         {
703                                 if (!u->GetExt("ssl", dummy))
704                                         u->Extend("ssl", "ON");
705                         }
706                         
707                         session->status = ISSL_OPEN;
708                         
709                         MakePollWrite(session);
710                         
711                         return true;
712                 }
713         }
714         
715         virtual void OnPostConnect(userrec* user)
716         {
717                 // This occurs AFTER OnUserConnect so we can be sure the
718                 // protocol module has propogated the NICK message.
719                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
720                 {
721                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
722                         std::deque<std::string>* metadata = new std::deque<std::string>;
723                         metadata->push_back(user->nick);
724                         metadata->push_back("ssl");             // The metadata id
725                         metadata->push_back("ON");              // The value to send
726                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
727                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
728                         DELETE(event);
729                         DELETE(metadata);
730
731                         VerifyCertificate(&sessions[user->GetFd()], user);
732                 }
733         }
734         
735         void MakePollWrite(issl_session* session)
736         {
737                 OnRawSocketWrite(session->fd, NULL, 0);
738         }
739         
740         void CloseSession(issl_session* session)
741         {
742                 if (session->sess)
743                 {
744                         SSL_shutdown(session->sess);
745                         SSL_free(session->sess);
746                 }
747                 
748                 if (session->inbuf)
749                 {
750                         delete[] session->inbuf;
751                 }
752                 
753                 session->outbuf.clear();
754                 session->inbuf = NULL;
755                 session->sess = NULL;
756                 session->status = ISSL_NONE;
757         }
758
759         void VerifyCertificate(issl_session* session, Extensible* user)
760         {
761                 X509* cert;
762                 ssl_cert* certinfo = new ssl_cert;
763                 unsigned int n;
764                 unsigned char md[EVP_MAX_MD_SIZE];
765                 const EVP_MD *digest = EVP_md5();
766
767                 user->Extend("ssl_cert",certinfo);
768
769                 cert = SSL_get_peer_certificate((SSL*)session->sess);
770
771                 if (!cert)
772                 {
773                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
774                         return;
775                 }
776
777                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
778
779                 if (SelfSigned)
780                 {
781                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
782                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
783                 }
784                 else
785                 {
786                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
787                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
788                 }
789
790                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
791                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
792
793                 if (!X509_digest(cert, digest, md, &n))
794                 {
795                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
796                 }
797                 else
798                 {
799                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
800                 }
801
802                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), time(NULL)) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), time(NULL)) == 0))
803                 {
804                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
805                 }
806
807                 X509_free(cert);
808         }
809 };
810
811 class ModuleSSLOpenSSLFactory : public ModuleFactory
812 {
813  public:
814         ModuleSSLOpenSSLFactory()
815         {
816         }
817         
818         ~ModuleSSLOpenSSLFactory()
819         {
820         }
821         
822         virtual Module * CreateModule(InspIRCd* Me)
823         {
824                 return new ModuleSSLOpenSSL(Me);
825         }
826 };
827
828
829 extern "C" void * init_module( void )
830 {
831         return new ModuleSSLOpenSSLFactory;
832 }