]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
3e275f06e90da4f13b9c593846e1425f872efeec
[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 "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.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_OnRawSocketConnect] = 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 OnRawSocketConnect(int fd)
320         {
321                 issl_session* session = &sessions[fd];
322
323                 session->fd = fd;
324                 session->inbuf = new char[inbufsize];
325                 session->inbufoffset = 0;
326                 session->sess = SSL_new(ctx);
327                 session->status = ISSL_NONE;
328
329                 if (session->sess == NULL)
330                 {
331                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't create SSL object: %s", get_error());
332                         return;
333                 }
334
335                 if (SSL_set_fd(session->sess, fd) == 0)
336                 {
337                         ServerInstance->Log(DEBUG, "m_ssl.so: Couldn't set fd for SSL object: %s", get_error());
338                         return;
339                 }
340
341                 Handshake(session);
342         }
343
344         virtual void OnRawSocketClose(int fd)
345         {
346                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketClose: %d", fd);
347                 CloseSession(&sessions[fd]);
348
349                 EventHandler* user = ServerInstance->SE->GetRef(fd);
350
351                 if ((user) && (user->GetExt("ssl_cert", dummy)))
352                 {
353                         ssl_cert* tofree;
354                         user->GetExt("ssl_cert", tofree);
355                         delete tofree;
356                         user->Shrink("ssl_cert");
357                 }
358         }
359
360         virtual int OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult)
361         {
362                 issl_session* session = &sessions[fd];
363                 
364                 if (!session->sess)
365                 {
366                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: No session to read from");
367                         readresult = 0;
368                         CloseSession(session);
369                         return 1;
370                 }
371                 
372                 if (session->status == ISSL_HANDSHAKING)
373                 {
374                         if (session->rstat == ISSL_READ || session->wstat == ISSL_READ)
375                         {
376                                 // The handshake isn't finished and it wants to read, try to finish it.
377                                 if (Handshake(session))
378                                 {
379                                         // Handshake successfully resumed.
380                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: successfully resumed handshake");
381                                 }
382                                 else
383                                 {
384                                         // Couldn't resume handshake.   
385                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: failed to resume handshake");
386                                         return -1;
387                                 }
388                         }
389                         else
390                         {
391                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketRead: handshake wants to write data but we are currently reading");
392                                 return -1;                      
393                         }
394                 }
395
396                 // If we resumed the handshake then session->status will be ISSL_OPEN
397                                 
398                 if (session->status == ISSL_OPEN)
399                 {
400                         if (session->wstat == ISSL_READ)
401                         {
402                                 if(DoWrite(session) == 0)
403                                         return 0;
404                         }
405                         
406                         if (session->rstat == ISSL_READ)
407                         {
408                                 int ret = DoRead(session);
409                         
410                                 if (ret > 0)
411                                 {
412                                         if (count <= session->inbufoffset)
413                                         {
414                                                 memcpy(buffer, session->inbuf, count);
415                                                 // Move the stuff left in inbuf to the beginning of it
416                                                 memcpy(session->inbuf, session->inbuf + count, (session->inbufoffset - count));
417                                                 // Now we need to set session->inbufoffset to the amount of data still waiting to be handed to insp.
418                                                 session->inbufoffset -= count;
419                                                 // Insp uses readresult as the count of how much data there is in buffer, so:
420                                                 readresult = count;
421                                         }
422                                         else
423                                         {
424                                                 // There's not as much in the inbuf as there is space in the buffer, so just copy the whole thing.
425                                                 memcpy(buffer, session->inbuf, session->inbufoffset);
426                                                 
427                                                 readresult = session->inbufoffset;
428                                                 // Zero the offset, as there's nothing there..
429                                                 session->inbufoffset = 0;
430                                         }
431                                 
432                                         return 1;
433                                 }
434                                 else
435                                 {
436                                         return ret;
437                                 }
438                         }
439                 }
440                 
441                 return -1;
442         }
443         
444         virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
445         {               
446                 issl_session* session = &sessions[fd];
447
448                 if (!session->sess)
449                 {
450                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
451                         CloseSession(session);
452                         return 1;
453                 }
454
455                 session->outbuf.append(buffer, count);
456                 
457                 if (session->status == ISSL_HANDSHAKING)
458                 {
459                         // The handshake isn't finished, try to finish it.
460                         if (session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
461                         {
462                                 if (Handshake(session))
463                                 {
464                                         // Handshake successfully resumed.
465                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
466                                 }
467                                 else
468                                 {
469                                         // Couldn't resume handshake.   
470                                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
471                                 }
472                         }
473                         else
474                         {
475                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");                    
476                         }
477                 }
478                 
479                 if (session->status == ISSL_OPEN)
480                 {
481                         if (session->rstat == ISSL_WRITE)
482                         {
483                                 DoRead(session);
484                         }
485                         
486                         if (session->wstat == ISSL_WRITE)
487                         {
488                                 return DoWrite(session);
489                         }
490                 }
491                 
492                 return 1;
493         }
494         
495         int DoWrite(issl_session* session)
496         {
497                 int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
498                 
499                 if (ret == 0)
500                 {
501                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
502                         CloseSession(session);
503                         return 0;
504                 }
505                 else if (ret < 0)
506                 {
507                         int err = SSL_get_error(session->sess, ret);
508                         
509                         if (err == SSL_ERROR_WANT_WRITE)
510                         {
511                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
512                                 session->wstat = ISSL_WRITE;
513                                 return -1;
514                         }
515                         else if (err == SSL_ERROR_WANT_READ)
516                         {
517                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
518                                 session->wstat = ISSL_READ;
519                                 return -1;
520                         }
521                         else
522                         {
523                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
524                                 CloseSession(session);
525                                 return 0;
526                         }
527                 }
528                 else
529                 {
530                         session->outbuf = session->outbuf.substr(ret);
531                         return ret;
532                 }
533         }
534         
535         int DoRead(issl_session* session)
536         {
537                 // Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
538                 // Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
539                         
540                 int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);
541
542                 if (ret == 0)
543                 {
544                         // Client closed connection.
545                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
546                         CloseSession(session);
547                         return 0;
548                 }
549                 else if (ret < 0)
550                 {
551                         int err = SSL_get_error(session->sess, ret);
552                                 
553                         if (err == SSL_ERROR_WANT_READ)
554                         {
555                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
556                                 session->rstat = ISSL_READ;
557                                 return -1;
558                         }
559                         else if (err == SSL_ERROR_WANT_WRITE)
560                         {
561                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
562                                 session->rstat = ISSL_WRITE;
563                                 return -1;
564                         }
565                         else
566                         {
567                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
568                                 CloseSession(session);
569                                 return 0;
570                         }
571                 }
572                 else
573                 {
574                         // Read successfully 'ret' bytes into inbuf + inbufoffset
575                         // There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
576                         // 'buffer' is 'count' long
577
578                         session->inbufoffset += ret;
579
580                         return ret;
581                 }
582         }
583         
584         // :kenny.chatspike.net 320 Om Epy|AFK :is a Secure Connection
585         virtual void OnWhois(userrec* source, userrec* dest)
586         {
587                 // Bugfix, only send this numeric for *our* SSL users
588                 if (dest->GetExt("ssl", dummy) || (IS_LOCAL(dest) &&  isin(dest->GetPort(), listenports)))
589                 {
590                         ServerInstance->SendWhoisLine(source, dest, 320, "%s %s :is using a secure connection", source->nick, dest->nick);
591                 }
592         }
593         
594         virtual void OnSyncUserMetaData(userrec* user, Module* proto, void* opaque, const std::string &extname)
595         {
596                 // check if the linking module wants to know about OUR metadata
597                 if (extname == "ssl")
598                 {
599                         // check if this user has an swhois field to send
600                         if(user->GetExt(extname, dummy))
601                         {
602                                 // call this function in the linking module, let it format the data how it
603                                 // sees fit, and send it on its way. We dont need or want to know how.
604                                 proto->ProtoSendMetaData(opaque, TYPE_USER, user, extname, "ON");
605                         }
606                 }
607         }
608         
609         virtual void OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata)
610         {
611                 // check if its our metadata key, and its associated with a user
612                 if ((target_type == TYPE_USER) && (extname == "ssl"))
613                 {
614                         userrec* dest = (userrec*)target;
615                         // if they dont already have an ssl flag, accept the remote server's
616                         if (!dest->GetExt(extname, dummy))
617                         {
618                                 dest->Extend(extname, "ON");
619                         }
620                 }
621         }
622         
623         bool Handshake(issl_session* session)
624         {               
625                 int ret = SSL_accept(session->sess);
626       
627                 if (ret < 0)
628                 {
629                         int err = SSL_get_error(session->sess, ret);
630                                 
631                         if (err == SSL_ERROR_WANT_READ)
632                         {
633                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to read again: %s", get_error());
634                                 session->rstat = ISSL_READ;
635                                 session->status = ISSL_HANDSHAKING;
636                         }
637                         else if (err == SSL_ERROR_WANT_WRITE)
638                         {
639                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Not completed, need to write more data: %s", get_error());
640                                 session->wstat = ISSL_WRITE;
641                                 session->status = ISSL_HANDSHAKING;
642                                 MakePollWrite(session);
643                         }
644                         else
645                         {
646                                 ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake: Failed, bailing: %s", get_error());
647                                 CloseSession(session);
648                         }
649
650                         return false;
651                 }
652                 else
653                 {
654                         // Handshake complete.
655                         ServerInstance->Log(DEBUG, "m_ssl_openssl.so: Handshake completed");
656                         
657                         // This will do for setting the ssl flag...it could be done earlier if it's needed. But this seems neater.
658                         userrec* u = ServerInstance->FindDescriptor(session->fd);
659                         if (u)
660                         {
661                                 if (!u->GetExt("ssl", dummy))
662                                         u->Extend("ssl", "ON");
663                         }
664                         
665                         session->status = ISSL_OPEN;
666                         
667                         MakePollWrite(session);
668                         
669                         return true;
670                 }
671         }
672         
673         virtual void OnPostConnect(userrec* user)
674         {
675                 // This occurs AFTER OnUserConnect so we can be sure the
676                 // protocol module has propogated the NICK message.
677                 if ((user->GetExt("ssl", dummy)) && (IS_LOCAL(user)))
678                 {
679                         // Tell whatever protocol module we're using that we need to inform other servers of this metadata NOW.
680                         std::deque<std::string>* metadata = new std::deque<std::string>;
681                         metadata->push_back(user->nick);
682                         metadata->push_back("ssl");             // The metadata id
683                         metadata->push_back("ON");              // The value to send
684                         Event* event = new Event((char*)metadata,(Module*)this,"send_metadata");
685                         event->Send(ServerInstance);            // Trigger the event. We don't care what module picks it up.
686                         DELETE(event);
687                         DELETE(metadata);
688
689                         VerifyCertificate(&sessions[user->GetFd()], user);
690                 }
691         }
692         
693         void MakePollWrite(issl_session* session)
694         {
695                 OnRawSocketWrite(session->fd, NULL, 0);
696         }
697         
698         void CloseSession(issl_session* session)
699         {
700                 if (session->sess)
701                 {
702                         SSL_shutdown(session->sess);
703                         SSL_free(session->sess);
704                 }
705                 
706                 if (session->inbuf)
707                 {
708                         delete[] session->inbuf;
709                 }
710                 
711                 session->outbuf.clear();
712                 session->inbuf = NULL;
713                 session->sess = NULL;
714                 session->status = ISSL_NONE;
715         }
716
717         void VerifyCertificate(issl_session* session, userrec* user)
718         {
719                 X509* cert;
720                 ssl_cert* certinfo = new ssl_cert;
721                 unsigned int n;
722                 unsigned char md[EVP_MAX_MD_SIZE];
723                 const EVP_MD *digest = EVP_md5();
724
725                 user->Extend("ssl_cert",certinfo);
726
727                 cert = SSL_get_peer_certificate((SSL*)session->sess);
728
729                 if (!cert)
730                 {
731                         certinfo->data.insert(std::make_pair("error","Could not get peer certificate: "+std::string(get_error())));
732                         return;
733                 }
734
735                 certinfo->data.insert(std::make_pair("invalid", SSL_get_verify_result(session->sess) != X509_V_OK ? ConvToStr(1) : ConvToStr(0)));
736
737                 if (SelfSigned)
738                 {
739                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(0)));
740                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(1)));
741                 }
742                 else
743                 {
744                         certinfo->data.insert(std::make_pair("unknownsigner",ConvToStr(1)));
745                         certinfo->data.insert(std::make_pair("trusted",ConvToStr(0)));
746                 }
747
748                 certinfo->data.insert(std::make_pair("dn",std::string(X509_NAME_oneline(X509_get_subject_name(cert),0,0))));
749                 certinfo->data.insert(std::make_pair("issuer",std::string(X509_NAME_oneline(X509_get_issuer_name(cert),0,0))));
750
751                 if (!X509_digest(cert, digest, md, &n))
752                 {
753                         certinfo->data.insert(std::make_pair("error","Out of memory generating fingerprint"));
754                 }
755                 else
756                 {
757                         certinfo->data.insert(std::make_pair("fingerprint",irc::hex(md, n)));
758                 }
759
760                 user->WriteServ("NOTICE %s :*** Your SSL Certificate fingerprint is: %s", user->nick, irc::hex(md, n).c_str());
761
762                 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))
763                 {
764                         certinfo->data.insert(std::make_pair("error","Not activated, or expired certificate"));
765                 }
766
767                 X509_free(cert);
768         }
769 };
770
771 class ModuleSSLOpenSSLFactory : public ModuleFactory
772 {
773  public:
774         ModuleSSLOpenSSLFactory()
775         {
776         }
777         
778         ~ModuleSSLOpenSSLFactory()
779         {
780         }
781         
782         virtual Module * CreateModule(InspIRCd* Me)
783         {
784                 return new ModuleSSLOpenSSL(Me);
785         }
786 };
787
788
789 extern "C" void * init_module( void )
790 {
791         return new ModuleSSLOpenSSLFactory;
792 }