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