]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
760b4c35ad18ea76e7cb73f71f9a2090abb25590
[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: `perl extra/openssl_config.pl compile` */
21 /* $LinkerFlags: `perl extra/openssl_config.pl link` */
22 /* $ModDep: ssl_cert.h */
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                                 std::string port = Conf->ReadValue("bind", "port", i);
146                                 irc::portparser portrange(port, false);
147                                 long portno = -1;
148                                 while ((portno = portrange.GetToken()))
149                                 {
150                                         if (ServerInstance->Config->AddIOHook(portno, this))
151                                         {
152                                                 listenports.push_back(portno);
153                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %d", portno);
154                                         }
155                                         else
156                                         {
157                                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: FAILED to enable SSL on port %d, maybe you have another ssl or similar module loaded?", portno);
158                                         }
159                                 }
160                         }
161                 }
162                 
163                 std::string confdir(CONFIG_FILE);
164                 // +1 so we the path ends with a /
165                 confdir = confdir.substr(0, confdir.find_last_of('/') + 1);
166                 
167                 cafile   = Conf->ReadValue("openssl", "cafile", 0);
168                 certfile = Conf->ReadValue("openssl", "certfile", 0);
169                 keyfile  = Conf->ReadValue("openssl", "keyfile", 0);
170                 dhfile   = Conf->ReadValue("openssl", "dhfile", 0);
171                 
172                 // Set all the default values needed.
173                 if (cafile == "")
174                         cafile = "ca.pem";
175                         
176                 if (certfile == "")
177                         certfile = "cert.pem";
178                         
179                 if (keyfile == "")
180                         keyfile = "key.pem";
181                         
182                 if (dhfile == "")
183                         dhfile = "dhparams.pem";
184                         
185                 // Prepend relative paths with the path to the config directory.        
186                 if (cafile[0] != '/')
187                         cafile = confdir + cafile;
188                 
189                 //if(crlfile[0] != '/')
190                 //      crlfile = confdir + crlfile;
191                         
192                 if (certfile[0] != '/')
193                         certfile = confdir + certfile;
194                         
195                 if (keyfile[0] != '/')
196                         keyfile = confdir + keyfile;
197                         
198                 if (dhfile[0] != '/')
199                         dhfile = confdir + dhfile;
200
201                 /* Load our keys and certificates*/
202                 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str()))
203                 {
204                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s", certfile.c_str());
205                 }
206
207                 if (!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))
208                 {
209                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read key file %s", keyfile.c_str());
210                 }
211
212                 /* Load the CAs we trust*/
213                 if (!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))
214                 {
215                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Can't read CA list from ", cafile.c_str());
216                 }
217
218                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
219                 DH* ret;
220
221                 if (dhpfile == NULL)
222                 {
223                         ServerInstance->Log(DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
224                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
225                 }
226                 else
227                 {
228                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
229                 
230                         if(SSL_CTX_set_tmp_dh(ctx, ret) < 0)
231                         {
232                                 ServerInstance->Log(DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters");
233                         }
234                 }
235                 
236                 fclose(dhpfile);
237
238                 DELETE(Conf);
239         }
240
241         virtual ~ModuleSSLOpenSSL()
242         {
243                 SSL_CTX_free(ctx);
244                 delete culllist;
245         }
246         
247         virtual void OnCleanup(int target_type, void* item)
248         {
249                 if (target_type == TYPE_USER)
250                 {
251                         userrec* user = (userrec*)item;
252                         
253                         if (user->GetExt("ssl", dummy) && IS_LOCAL(user) && isin(user->GetPort(), listenports))
254                         {
255                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
256                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
257                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Adding user %s to cull list", user->nick);
258                                 culllist->AddItem(user, "SSL module unloading");
259                         }
260                         if (user->GetExt("ssl_cert", dummy) && isin(user->GetPort(), listenports))
261                         {
262                                 ssl_cert* tofree;
263                                 user->GetExt("ssl_cert", tofree);
264                                 delete tofree;
265                                 user->Shrink("ssl_cert");
266                         }
267                 }
268         }
269         
270         virtual void OnUnloadModule(Module* mod, const std::string &name)
271         {
272                 if (mod == this)
273                 {
274                         // We're being unloaded, kill all the users added to the cull list in OnCleanup
275                         int numusers = culllist->Apply();
276                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Killed %d users for unload of OpenSSL SSL module", numusers);
277                         
278                         for(unsigned int i = 0; i < listenports.size(); i++)
279                                 ServerInstance->Config->DelIOHook(listenports[i]);
280                 }
281         }
282         
283         virtual Version GetVersion()
284         {
285                 return Version(1, 1, 0, 0, VF_VENDOR, API_VERSION);
286         }
287
288         void Implements(char* List)
289         {
290                 List[I_OnRawSocketAccept] = List[I_OnRawSocketClose] = List[I_OnRawSocketRead] = List[I_OnRawSocketWrite] = List[I_OnCleanup] = 1;
291                 List[I_OnSyncUserMetaData] = List[I_OnDecodeMetaData] = List[I_OnUnloadModule] = List[I_OnRehash] = List[I_OnWhois] = List[I_OnPostConnect] = 1;
292         }
293
294         virtual void OnRawSocketAccept(int fd, const std::string &ip, int localport)
295         {
296                 issl_session* session = &sessions[fd];
297         
298                 session->fd = fd;
299                 session->inbuf = new char[inbufsize];
300                 session->inbufoffset = 0;               
301                 session->sess = SSL_new(ctx);
302                 session->status = ISSL_NONE;
303         
304                 if (session->sess == NULL)
305                 {
306                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
307                         return;
308                 }
309                 
310                 if (SSL_set_fd(session->sess, fd) == 0)
311                 {
312                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
313                         return;
314                 }
315
316                 Handshake(session);
317         }
318
319         virtual void OnRawSocketClose(int fd)
320         {
321                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
322                 CloseSession(&sessions[fd]);
323
324                 EventHandler* user = ServerInstance->SE->GetRef(fd);
325
326                 if ((user) && (user->GetExt("ssl_cert", dummy)))
327                 {
328                         ssl_cert* tofree;
329                         user->GetExt("ssl_cert", tofree);
330                         delete tofree;
331                         user->Shrink("ssl_cert");
332                 }
333         }
334
335         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
336         {
337                 issl_session* session = &sessions[fd];
338                 
339                 if (!session->sess)
340                 {
341                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
342                         readresult = 0;
343                         CloseSession(session);
344                         return 1;
345                 }
346                 
347                 if (session->status == ISSL_HANDSHAKING)
348                 {
349                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
350                         {
351                                 // The handshake isn't finished and it wants to read, try to finish it.
352                                 if (Handshake(session))
353                                 {
354                                         // Handshake successfully resumed.
355                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
356                                 }
357                                 else
358                                 {
359                                         // Couldn't resume handshake.   
360                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
361                                         return -1;
362                                 }
363                         }
364                         else
365                         {
366                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
367                                 return -1;                      
368                         }
369                 }
370
371                 // If we resumed the handshake then session->status will be ISSL_OPEN
372                                 
373                 if (session->status == ISSL_OPEN)
374                 {
375                         if (session->wstat == ISSL_READ)
376                         {
377                                 if(DoWrite(session) == 0)
378                                         return 0;
379                         }
380                         
381                         if (session->rstat == ISSL_READ)
382                         {
383                                 int ret = DoRead(session);
384                         
385                                 if (ret > 0)
386                                 {
387                                         if (count <= session->inbufoffset)
388                                         {
389                                                 memcpy(buffer, session->inbuf, count);
390                                                 // Move the stuff left in inbuf to the beginning of it
391                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
392                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
393                                                 session->inbufoffset -= count;
394                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
395                                                 readresult = count;
396                                         }
397                                         else
398                                         {
399                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
400                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
401                                                 
402                                                 readresult = session->inbufoffset;
403                                                 // Zero the offset, as there's nothing there..
404                                                 session->inbufoffset = 0;
405                                         }
406                                 
407                                         return 1;
408                                 }
409                                 else
410                                 {
411                                         return ret;
412                                 }
413                         }
414                 }
415                 
416                 return -1;
417         }
418         
419         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
420         {               
421                 issl_session* session = &sessions[fd];
422
423                 if (!session->sess)
424                 {
425                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
426                         CloseSession(session);
427                         return 1;
428                 }
429
430                 session->outbuf.append(buffer, count);
431                 
432                 if (session->status == ISSL_HANDSHAKING)
433                 {
434                         // The handshake isn't finished, try to finish it.
435                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
436                         {
437                                 if (Handshake(session))
438                                 {
439                                         // Handshake successfully resumed.
440                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
441                                 }
442                                 else
443                                 {
444                                         // Couldn't resume handshake.   
445                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
446                                 }
447                         }
448                         else
449                         {
450                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
451                         }
452                 }
453                 
454                 if (session->status == ISSL_OPEN)
455                 {
456                         if (session->rstat == ISSL_WRITE)
457                         {
458                                 DoRead(session);
459                         }
460                         
461                         if (session->wstat == ISSL_WRITE)
462                         {
463                                 return DoWrite(session);
464                         }
465                 }
466                 
467                 return 1;
468         }
469         
470         int DoWrite(issl_session* session)
471         {
472                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
473                 
474                 if (ret == 0)
475                 {
476                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
477                         CloseSession(session);
478                         return 0;
479                 }
480                 else if (ret < 0)
481                 {
482                         int err = SSL_get_error(session->sess, ret);
483                         
484                         if (err == SSL_ERROR_WANT_WRITE)
485                         {
486                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
487                                 session->wstat = ISSL_WRITE;
488                                 return -1;
489                         }
490                         else if (err == SSL_ERROR_WANT_READ)
491                         {
492                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
493                                 session->wstat = ISSL_READ;
494                                 return -1;
495                         }
496                         else
497                         {
498                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
499                                 CloseSession(session);
500                                 return 0;
501                         }
502                 }
503                 else
504                 {
505                         session->outbuf = session->outbuf.substr(ret);
506                         return ret;
507                 }
508         }
509         
510         int DoRead(issl_session* session)
511         {
512                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
513                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
514                         
515                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
516
517                 if (ret == 0)
518                 {
519                         // Client closed connection.
520                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
521                         CloseSession(session);
522                         return 0;
523                 }
524                 else if (ret < 0)
525                 {
526                         int err = SSL_get_error(session->sess, ret);
527                                 
528                         if (err == SSL_ERROR_WANT_READ)
529                         {
530                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
531                                 session->rstat = ISSL_READ;
532                                 return -1;
533                         }
534                         else if (err == SSL_ERROR_WANT_WRITE)
535                         {
536                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
537                                 session->rstat = ISSL_WRITE;
538                                 return -1;
539                         }
540                         else
541                         {
542                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
543                                 CloseSession(session);
544                                 return 0;
545                         }
546                 }
547                 else
548                 {
549                         // Read successfully 'ret' bytes into inbuf + inbufoffset
550                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
551                         // 'buffer' is 'count' long
552
553                         session->inbufoffset += ret;
554
555                         return ret;
556                 }
557         }
558         
559         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
560         virtual void OnWhois(userrec* source, userrec* dest)
561         {
562                 // Bugfix, only send this numeric for *our* SSL users
563                 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
564                 {
565                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
566                 }
567         }
568         
569         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
570         {
571                 // check if the linking module wants to know about OUR metadata
572                 if (extname == "ssl")
573                 {
574                         // check if this user has an swhois field to send
575                         if(user->GetExt(extname, dummy))
576                         {
577                                 // call this function in the linking module, let it format the data how it
578                                 // sees fit, and send it on its way. We dont need or want to know how.
579                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
580                         }
581                 }
582         }
583         
584         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
585         {
586                 // check if its our metadata key, and its associated with a user
587                 if ((target_type == TYPE_USER) && (extname == "ssl"))
588                 {
589                         userrec* dest = (userrec*)target;
590                         // if they dont already have an ssl flag, accept the remote server's
591                         if (!dest->GetExt(extname, dummy))
592                         {
593                                 dest->Extend(extname, "ON");
594                         }
595                 }
596         }
597         
598         bool Handshake(issl_session* session)
599         {               
600                 int ret = SSL_accept(session->sess);
601       
602                 if (ret < 0)
603                 {
604                         int err = SSL_get_error(session->sess, ret);
605                                 
606                         if (err == SSL_ERROR_WANT_READ)
607                         {
608                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
609                                 session->rstat = ISSL_READ;
610                                 session->status = ISSL_HANDSHAKING;
611                         }
612                         else if (err == SSL_ERROR_WANT_WRITE)
613                         {
614                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
615                                 session->wstat = ISSL_WRITE;
616                                 session->status = ISSL_HANDSHAKING;
617                                 MakePollWrite(session);
618                         }
619                         else
620                         {
621                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
622                                 CloseSession(session);
623                         }
624
625                         return false;
626                 }
627                 else
628                 {
629                         // Handshake complete.
630                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
631                         
632                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
633                         userrec* u = ServerInstance->FindDescriptor(session->fd);
634                         if (u)
635                         {
636                                 if (!u->GetExt("ssl", dummy))
637                                         u->Extend("ssl", "ON");
638                         }
639                         
640                         session->status = ISSL_OPEN;
641                         
642                         MakePollWrite(session);
643                         
644                         return true;
645                 }
646         }
647         
648         virtual void OnPostConnect(userrec* user)
649         {
650                 // This occurs AFTER OnUserConnect so we can be sure the
651                 // protocol module has propogated the NICK message.
652                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
653                 {
654                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
655                         std::deque<std::string>* metadata = new std::deque<std::string>;
656                         metadata->push_back(user->nick);
657                         metadata->push_back("ssl");             // The metadata id
658                         metadata->push_back("ON");              // The value to send
659                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
660                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
661                         DELETE(event);
662                         DELETE(metadata);
663
664                         VerifyCertificate(&sessions[user->GetFd()], user);
665                 }
666         }
667         
668         void MakePollWrite(issl_session* session)
669         {
670                 OnRawSocketWrite(session->fd, NULL, 0);
671         }
672         
673         void CloseSession(issl_session* session)
674         {
675                 if (session->sess)
676                 {
677                         SSL_shutdown(session->sess);
678                         SSL_free(session->sess);
679                 }
680                 
681                 if (session->inbuf)
682                 {
683                         delete[] session->inbuf;
684                 }
685                 
686                 session->outbuf.clear();
687                 session->inbuf = NULL;
688                 session->sess = NULL;
689                 session->status = ISSL_NONE;
690         }
691
692         void VerifyCertificate(issl_session* session, userrec* user)
693         {
694                 X509* cert;
695                 ssl_cert* certinfo = new ssl_cert;
696                 unsigned int n;
697                 unsigned char md[EVP_MAX_MD_SIZE];
698                 const EVP_MD *digest = EVP_md5();
699
700                 user->Extend("ssl_cert",certinfo);
701
702                 cert = SSL_get_peer_certificate((SSL*)session->sess);
703
704                 if (!cert)
705                 {
706                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
707                         return;
708                 }
709
710                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
711
712                 if (SelfSigned)
713                 {
714                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
715                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
716                 }
717                 else
718                 {
719                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
720                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
721                 }
722
723                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
724                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
725
726                 if (!X509_digest(cert, digest, md, &n))
727                 {
728                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
729                 }
730                 else
731                 {
732                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
733                 }
734
735                 user->WriteServ("NOTICE %s :*** Your SSL Certificate fingerprint is: %s", user->nick, irc::hex(md, n).c_str());
736
737                 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))
738                 {
739                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
740                 }
741
742                 X509_free(cert);
743         }
744 };
745
746 class ModuleSSLOpenSSLFactory : public ModuleFactory
747 {
748  public:
749         ModuleSSLOpenSSLFactory()
750         {
751         }
752         
753         ~ModuleSSLOpenSSLFactory()
754         {
755         }
756         
757         virtual Module * CreateModule(InspIRCd* Me)
758         {
759                 return new ModuleSSLOpenSSL(Me);
760         }
761 };
762
763
764 extern "C" void * init_module( void )
765 {
766         return new ModuleSSLOpenSSLFactory;
767 }