]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
Insert massive change here.
[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 "ssl_cert.h"
18
19 /* $ModDesc: Provides SSL support for clients */
20 /* $CompileFlags: -I/usr/include -I/usr/local/include */
21 /* $LinkerFlags: -L/usr/local/lib -Wl,--rpath -Wl,/usr/local/lib -L/usr/lib -Wl,--rpath -Wl,/usr/lib -lssl */
22
23
24
25 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
26 enum issl_io_status { ISSL_WRITE, ISSL_READ };
27
28 static bool SelfSigned = false;
29
30 bool isin(int port, const std::vector<int> &portlist)
31 {
32         for(unsigned int i = 0; i < portlist.size(); i++)
33                 if(portlist[i] == port)
34                         return true;
35                         
36         return false;
37 }
38
39 char* get_error()
40 {
41         return ERR_error_string(ERR_get_error(), NULL);
42 }
43
44 /** Represents an SSL user's extra data
45  */
46 class issl_session : public classbase
47 {
48 public:
49         SSL* sess;
50         issl_status status;
51         issl_io_status rstat;
52         issl_io_status wstat;
53
54         unsigned int inbufoffset;
55         char* inbuf;                    // Buffer OpenSSL reads into.
56         std::string outbuf;     // Buffer for outgoing data that OpenSSL will not take.
57         int fd;
58         
59         issl_session()
60         {
61                 rstat = ISSL_READ;
62                 wstat = ISSL_WRITE;
63         }
64 };
65
66 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
67 {
68         /* XXX: This will allow self signed certificates.
69          * In the future if we want an option to not allow this,
70          * we can just return preverify_ok here, and openssl
71          * will boot off self-signed and invalid peer certs.
72          */
73         int ve = X509_STORE_CTX_get_error(ctx);
74
75         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
76
77         return 1;
78 }
79         
80 class ModuleSSLOpenSSL : public Module
81 {
82         
83         ConfigReader* Conf;
84         
85         CullList* culllist;
86         
87         std::vector<int> listenports;
88         
89         int inbufsize;
90         issl_session sessions[MAX_DESCRIPTORS];
91         
92         SSL_CTX* ctx;
93         
94         char* dummy;
95         
96         std::string keyfile;
97         std::string certfile;
98         std::string cafile;
99         // std::string crlfile;
100         std::string dhfile;
101         
102  public:
103         
104         ModuleSSLOpenSSL(InspIRCd* Me)
105                 : Module::Module(Me)
106         {
107                 culllist = new CullList(ServerInstance);
108                 
109                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
110                 inbufsize = ServerInstance->Config->NetBufferSize;
111                 
112                 /* Global SSL library initialization*/
113                 SSL_library_init();
114                 SSL_load_error_strings();
115                 
116                 /* Build our SSL context*/
117                 ctx = SSL_CTX_new( SSLv23_server_method() );
118
119                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
120
121                 // Needs the flag as it ignores a plain /rehash
122                 OnRehash("ssl");
123         }
124         
125         virtual void OnRehash(const std::string &param)
126         {
127                 if(param != "ssl")
128                         return;
129         
130                 Conf = new ConfigReader(ServerInstance);
131                         
132                 for(unsigned int i = 0; i < listenports.size(); i++)
133                 {
134                         ServerInstance->Config->DelIOHook(listenports[i]);
135                 }
136                 
137                 listenports.clear();
138                 
139                 for(int i = 0; i < Conf->Enumerate("bind"); i++)
140                 {
141                         // For each <bind> tag
142                         if(((Conf->ReadValue("bind", "type", i) == "") || (Conf->ReadValue("bind", "type", i) == "clients")) && (Conf->ReadValue("bind", "ssl", i) == "openssl"))
143                         {
144                                 // Get the port we're meant to be listening on with SSL
145                                 unsigned int port = Conf->ReadInteger("bind", "port", i, true);
146                                 if (ServerInstance->Config->AddIOHook(port, this))
147                                 {
148                                         // We keep a record of which ports we're listening on with SSL
149                                         listenports.push_back(port);
150                                 
151                                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", port);
152                                 }
153                                 else
154                                 {
155                                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", port);
156                                 }
157                         }
158                 }
159                 
160                 std::string confdir(CONFIG_FILE);
161                 // +1 so we the path ends with a /
162                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
163                 
164                 cafile  = Conf->ReadValue("openssl", "cafile", 0);
165                 // crlfile      = Conf->ReadValue("openssl", "crlfile", 0);
166                 certfile        = Conf->ReadValue("openssl", "certfile", 0);
167                 keyfile = Conf->ReadValue("openssl", "keyfile", 0);
168                 dhfile  = Conf->ReadValue("openssl", "dhfile", 0);
169                 
170                 // Set all the default values needed.
171                 if(cafile == "")
172                         cafile = "ca.pem";
173                         
174                 //if(crlfile == "")
175                 //      crlfile = "crl.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();
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_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
292                 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
293         }
294
295         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
296         {
297                 issl_session* session = &sessions[fd];
298         
299                 session->fd = fd;
300                 session->inbuf = new char[inbufsize];
301                 session->inbufoffset = 0;               
302                 session->sess = SSL_new(ctx);
303                 session->status = ISSL_NONE;
304         
305                 if(session->sess == NULL)
306                 {
307                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
308                         return;
309                 }
310                 
311                 if(SSL_set_fd(session->sess, fd) == 0)
312                 {
313                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
314                         return;
315                 }
316
317                 Handshake(session);
318         }
319
320         virtual void OnRawSocketClose(int fd)
321         {
322                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
323                 CloseSession(&sessions[fd]);
324
325                 EventHandler* user = ServerInstance->SE->GetRef(fd);
326
327                 if ((user) && (user->GetExt("ssl_cert", dummy)))
328                 {
329                         ssl_cert* tofree;
330                         user->GetExt("ssl_cert", tofree);
331                         delete tofree;
332                         user->Shrink("ssl_cert");
333                 }
334         }
335
336         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
337         {
338                 issl_session* session = &sessions[fd];
339                 
340                 if(!session->sess)
341                 {
342                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
343                         readresult = 0;
344                         CloseSession(session);
345                         return 1;
346                 }
347                 
348                 if(session->status == ISSL_HANDSHAKING)
349                 {
350                         if(session->rstat == ISSL_READ || session->wstat == ISSL_READ)
351                         {
352                                 // The handshake isn't finished and it wants to read, try to finish it.
353                                 if(Handshake(session))
354                                 {
355                                         // Handshake successfully resumed.
356                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
357                                 }
358                                 else
359                                 {
360                                         // Couldn't resume handshake.   
361                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
362                                         return -1;
363                                 }
364                         }
365                         else
366                         {
367                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
368                                 return -1;                      
369                         }
370                 }
371
372                 // If we resumed the handshake then session->status will be ISSL_OPEN
373                                 
374                 if(session->status == ISSL_OPEN)
375                 {
376                         if(session->wstat == ISSL_READ)
377                         {
378                                 if(DoWrite(session) == 0)
379                                         return 0;
380                         }
381                         
382                         if(session->rstat == ISSL_READ)
383                         {
384                                 int ret = DoRead(session);
385                         
386                                 if(ret > 0)
387                                 {
388                                         if(count <= session->inbufoffset)
389                                         {
390                                                 memcpy(buffer, session->inbuf, count);
391                                                 // Move the stuff left in inbuf to the beginning of it
392                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
393                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
394                                                 session->inbufoffset -= count;
395                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
396                                                 readresult = count;
397                                         }
398                                         else
399                                         {
400                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
401                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
402                                                 
403                                                 readresult = session->inbufoffset;
404                                                 // Zero the offset, as there's nothing there..
405                                                 session->inbufoffset = 0;
406                                         }
407                                 
408                                         return 1;
409                                 }
410                                 else
411                                 {
412                                         return ret;
413                                 }
414                         }
415                 }
416                 
417                 return -1;
418         }
419         
420         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
421         {               
422                 issl_session* session = &sessions[fd];
423
424                 if(!session->sess)
425                 {
426                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
427                         CloseSession(session);
428                         return 1;
429                 }
430
431                 session->outbuf.append(buffer, count);
432                 
433                 if(session->status == ISSL_HANDSHAKING)
434                 {
435                         // The handshake isn't finished, try to finish it.
436                         if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
437                         {
438                                 if(Handshake(session))
439                                 {
440                                         // Handshake successfully resumed.
441                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
442                                 }
443                                 else
444                                 {
445                                         // Couldn't resume handshake.   
446                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
447                                 }
448                         }
449                         else
450                         {
451                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
452                         }
453                 }
454                 
455                 if(session->status == ISSL_OPEN)
456                 {
457                         if(session->rstat == ISSL_WRITE)
458                         {
459                                 DoRead(session);
460                         }
461                         
462                         if(session->wstat == ISSL_WRITE)
463                         {
464                                 return DoWrite(session);
465                         }
466                 }
467                 
468                 return 1;
469         }
470         
471         int DoWrite(issl_session* session)
472         {
473                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
474                 
475                 if(ret == 0)
476                 {
477                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
478                         CloseSession(session);
479                         return 0;
480                 }
481                 else if(ret < 0)
482                 {
483                         int err = SSL_get_error(session->sess, ret);
484                         
485                         if(err == SSL_ERROR_WANT_WRITE)
486                         {
487                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
488                                 session->wstat = ISSL_WRITE;
489                                 return -1;
490                         }
491                         else if(err == SSL_ERROR_WANT_READ)
492                         {
493                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
494                                 session->wstat = ISSL_READ;
495                                 return -1;
496                         }
497                         else
498                         {
499                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
500                                 CloseSession(session);
501                                 return 0;
502                         }
503                 }
504                 else
505                 {
506                         session->outbuf = session->outbuf.substr(ret);
507                         return ret;
508                 }
509         }
510         
511         int DoRead(issl_session* session)
512         {
513                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
514                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
515                         
516                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
517
518                 if(ret == 0)
519                 {
520                         // Client closed connection.
521                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
522                         CloseSession(session);
523                         return 0;
524                 }
525                 else if(ret < 0)
526                 {
527                         int err = SSL_get_error(session->sess, ret);
528                                 
529                         if(err == SSL_ERROR_WANT_READ)
530                         {
531                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
532                                 session->rstat = ISSL_READ;
533                                 return -1;
534                         }
535                         else if(err == SSL_ERROR_WANT_WRITE)
536                         {
537                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
538                                 session->rstat = ISSL_WRITE;
539                                 return -1;
540                         }
541                         else
542                         {
543                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
544                                 CloseSession(session);
545                                 return 0;
546                         }
547                 }
548                 else
549                 {
550                         // Read successfully 'ret' bytes into inbuf + inbufoffset
551                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
552                         // 'buffer' is 'count' long
553
554                         session->inbufoffset += ret;
555
556                         return ret;
557                 }
558         }
559         
560         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
561         virtual void OnWhois(userrec* source, userrec* dest)
562         {
563                 // Bugfix, only send this numeric for *our* SSL users
564                 if(dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
565                 {
566                         source->WriteServ("320 %s %s :is using a secure connection", source->nick, dest->nick);
567                 }
568         }
569         
570         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
571         {
572                 // check if the linking module wants to know about OUR metadata
573                 if(extname == "ssl")
574                 {
575                         // check if this user has an swhois field to send
576                         if(user->GetExt(extname, dummy))
577                         {
578                                 // call this function in the linking module, let it format the data how it
579                                 // sees fit, and send it on its way. We dont need or want to know how.
580                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
581                         }
582                 }
583         }
584         
585         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
586         {
587                 // check if its our metadata key, and its associated with a user
588                 if ((target_type == TYPE_USER) && (extname == "ssl"))
589                 {
590                         userrec* dest = (userrec*)target;
591                         // if they dont already have an ssl flag, accept the remote server's
592                         if (!dest->GetExt(extname, dummy))
593                         {
594                                 dest->Extend(extname, "ON");
595                         }
596                 }
597         }
598         
599         bool Handshake(issl_session* session)
600         {               
601                 int ret = SSL_accept(session->sess);
602       
603                 if(ret < 0)
604                 {
605                         int err = SSL_get_error(session->sess, ret);
606                                 
607                         if(err == SSL_ERROR_WANT_READ)
608                         {
609                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
610                                 session->rstat = ISSL_READ;
611                                 session->status = ISSL_HANDSHAKING;
612                         }
613                         else if(err == SSL_ERROR_WANT_WRITE)
614                         {
615                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
616                                 session->wstat = ISSL_WRITE;
617                                 session->status = ISSL_HANDSHAKING;
618                                 MakePollWrite(session);
619                         }
620                         else
621                         {
622                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
623                                 CloseSession(session);
624                         }
625
626                         return false;
627                 }
628                 else
629                 {
630                         // Handshake complete.
631                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
632                         
633                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
634                         userrec* u = ServerInstance->FindDescriptor(session->fd);
635                         if (u)
636                         {
637                                 if (!u->GetExt("ssl", dummy))
638                                         u->Extend("ssl", "ON");
639                         }
640                         
641                         session->status = ISSL_OPEN;
642                         
643                         MakePollWrite(session);
644                         
645                         return true;
646                 }
647         }
648         
649         virtual void OnPostConnect(userrec* user)
650         {
651                 // This occurs AFTER OnUserConnect so we can be sure the
652                 // protocol module has propogated the NICK message.
653                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
654                 {
655                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
656                         std::deque<std::string>* metadata = new std::deque<std::string>;
657                         metadata->push_back(user->nick);
658                         metadata->push_back("ssl");             // The metadata id
659                         metadata->push_back("ON");              // The value to send
660                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
661                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
662                         DELETE(event);
663                         DELETE(metadata);
664
665                         VerifyCertificate(&sessions[user->GetFd()], user);
666                 }
667         }
668         
669         void MakePollWrite(issl_session* session)
670         {
671                 OnRawSocketWrite(session->fd, NULL, 0);
672         }
673         
674         void CloseSession(issl_session* session)
675         {
676                 if(session->sess)
677                 {
678                         SSL_shutdown(session->sess);
679                         SSL_free(session->sess);
680                 }
681                 
682                 if(session->inbuf)
683                 {
684                         delete[] session->inbuf;
685                 }
686                 
687                 session->outbuf.clear();
688                 session->inbuf = NULL;
689                 session->sess = NULL;
690                 session->status = ISSL_NONE;
691         }
692
693         void VerifyCertificate(issl_session* session, userrec* user)
694         {
695                 X509* cert;
696                 ssl_cert* certinfo = new ssl_cert;
697                 unsigned int n;
698                 unsigned char md[EVP_MAX_MD_SIZE];
699                 const EVP_MD *digest = EVP_md5();
700
701                 user->Extend("ssl_cert",certinfo);
702
703                 cert = SSL_get_peer_certificate((SSL*)session->sess);
704
705                 if (!cert)
706                 {
707                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
708                         return;
709                 }
710
711                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
712
713                 if (SelfSigned)
714                 {
715                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
716                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
717                 }
718                 else
719                 {
720                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
721                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
722                 }
723
724                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
725                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
726
727                 if (!X509_digest(cert, digest, md, &n))
728                 {
729                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
730                 }
731                 else
732                 {
733                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
734                 }
735
736                 user->WriteServ("NOTICE %s :*** Your SSL Certificate fingerprint is: %s", user->nick, irc::hex(md, n).c_str());
737
738                 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))
739                 {
740                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
741                 }
742
743                 X509_free(cert);
744         }
745 };
746
747 class ModuleSSLOpenSSLFactory : public ModuleFactory
748 {
749  public:
750         ModuleSSLOpenSSLFactory()
751         {
752         }
753         
754         ~ModuleSSLOpenSSLFactory()
755         {
756         }
757         
758         virtual Module * CreateModule(InspIRCd* Me)
759         {
760                 return new ModuleSSLOpenSSL(Me);
761         }
762 };
763
764
765 extern "C" void * init_module( void )
766 {
767         return new ModuleSSLOpenSSLFactory;
768 }