]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
More classbase cleanup, hold ConfigTag reference in Autoconnect/Link
[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-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include <openssl/ssl.h>
16 #include <openssl/err.h>
17 #include "ssl.h"
18
19 #ifdef WINDOWS
20 #pragma comment(lib, "libeay32MTd")
21 #pragma comment(lib, "ssleay32MTd")
22 #undef MAX_DESCRIPTORS
23 #define MAX_DESCRIPTORS 10000
24 #endif
25
26 /* $ModDesc: Provides SSL support for clients */
27
28 /* $LinkerFlags: if("USE_FREEBSD_BASE_SSL") -lssl -lcrypto */
29 /* $CompileFlags: if(!"USE_FREEBSD_BASE_SSL") pkgconfversion("openssl","0.9.7") pkgconfincludes("openssl","/openssl/ssl.h","") */
30 /* $LinkerFlags: if(!"USE_FREEBSD_BASE_SSL") rpath("pkg-config --libs openssl") pkgconflibs("openssl","/libssl.so","-lssl -lcrypto -ldl") */
31
32 /* $ModDep: transport.h */
33 /* $NoPedantic */
34 /* $CopyInstall: conf/key.pem $(CONPATH) */
35 /* $CopyInstall: conf/cert.pem $(CONPATH) */
36
37
38 enum issl_status { ISSL_NONE, ISSL_HANDSHAKING, ISSL_OPEN };
39
40 static bool SelfSigned = false;
41
42 char* get_error()
43 {
44         return ERR_error_string(ERR_get_error(), NULL);
45 }
46
47 static int error_callback(const char *str, size_t len, void *u);
48
49 /** Represents an SSL user's extra data
50  */
51 class issl_session
52 {
53 public:
54         SSL* sess;
55         issl_status status;
56
57         int fd;
58         bool outbound;
59         bool data_to_write;
60
61         issl_session()
62         {
63                 outbound = false;
64                 data_to_write = false;
65         }
66 };
67
68 static int OnVerify(int preverify_ok, X509_STORE_CTX *ctx)
69 {
70         /* XXX: This will allow self signed certificates.
71          * In the future if we want an option to not allow this,
72          * we can just return preverify_ok here, and openssl
73          * will boot off self-signed and invalid peer certs.
74          */
75         int ve = X509_STORE_CTX_get_error(ctx);
76
77         SelfSigned = (ve == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
78
79         return 1;
80 }
81
82 class ModuleSSLOpenSSL : public Module
83 {
84         int inbufsize;
85         issl_session* sessions;
86
87         SSL_CTX* ctx;
88         SSL_CTX* clictx;
89
90         char cipher[MAXBUF];
91
92         std::string keyfile;
93         std::string certfile;
94         std::string cafile;
95         // std::string crlfile;
96         std::string dhfile;
97         std::string sslports;
98
99  public:
100
101         ModuleSSLOpenSSL()
102         {
103                 ServerInstance->Modules->PublishInterface("BufferedSocketHook", this);
104
105                 sessions = new issl_session[ServerInstance->SE->GetMaxFds()];
106
107                 // Not rehashable...because I cba to reduce all the sizes of existing buffers.
108                 inbufsize = ServerInstance->Config->NetBufferSize;
109
110                 /* Global SSL library initialization*/
111                 SSL_library_init();
112                 SSL_load_error_strings();
113
114                 /* Build our SSL contexts:
115                  * NOTE: OpenSSL makes us have two contexts, one for servers and one for clients. ICK.
116                  */
117                 ctx = SSL_CTX_new( SSLv23_server_method() );
118                 clictx = SSL_CTX_new( SSLv23_client_method() );
119
120                 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
121                 SSL_CTX_set_mode(clictx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
122
123                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
124                 SSL_CTX_set_verify(clictx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);
125
126                 // Needs the flag as it ignores a plain /rehash
127                 OnModuleRehash(NULL,"ssl");
128                 Implementation eventlist[] = {
129                         I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnPostConnect,
130                         I_OnHookIO };
131                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
132         }
133
134         void OnHookIO(StreamSocket* user, ListenSocketBase* lsb)
135         {
136                 if (!user->GetIOHook() && lsb->hook == "openssl")
137                 {
138                         /* Hook the user with our module */
139                         user->AddIOHook(this);
140                 }
141         }
142
143         void OnRehash(User* user)
144         {
145                 ConfigReader Conf;
146
147                 sslports.clear();
148
149                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
150                 {
151                         ListenSocketBase* port = ServerInstance->ports[i];
152                         if (port->hook != "openssl")
153                                 continue;
154
155                         std::string portid = port->GetBindDesc();
156                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
157                         if (port->type == "clients" && port->GetIP() != "127.0.0.1")
158                                 sslports.append(portid).append(";");
159                 }
160
161                 if (!sslports.empty())
162                         sslports.erase(sslports.end() - 1);
163         }
164
165         void OnModuleRehash(User* user, const std::string &param)
166         {
167                 if (param != "ssl")
168                         return;
169
170                 OnRehash(user);
171
172                 ConfigReader Conf;
173
174                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
175                 certfile = Conf.ReadValue("openssl", "certfile", 0);
176                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
177                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
178
179                 // Set all the default values needed.
180                 if (cafile.empty())
181                         cafile = "conf/ca.pem";
182
183                 if (certfile.empty())
184                         certfile = "conf/cert.pem";
185
186                 if (keyfile.empty())
187                         keyfile = "conf/key.pem";
188
189                 if (dhfile.empty())
190                         dhfile = "conf/dhparams.pem";
191
192                 /* Load our keys and certificates
193                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
194                  */
195                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
196                 {
197                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
198                         ERR_print_errors_cb(error_callback, this);
199                 }
200
201                 if (((!SSL_CTX_use_PrivateKey_file(ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) || (!SSL_CTX_use_PrivateKey_file(clictx, keyfile.c_str(), SSL_FILETYPE_PEM)))
202                 {
203                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
204                         ERR_print_errors_cb(error_callback, this);
205                 }
206
207                 /* Load the CAs we trust*/
208                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
209                 {
210                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
211                         ERR_print_errors_cb(error_callback, this);
212                 }
213
214                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
215                 DH* ret;
216
217                 if (dhpfile == NULL)
218                 {
219                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
220                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
221                 }
222                 else
223                 {
224                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
225                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
226                         {
227                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
228                                 ERR_print_errors_cb(error_callback, this);
229                         }
230                 }
231
232                 fclose(dhpfile);
233         }
234
235         void On005Numeric(std::string &output)
236         {
237                 if (!sslports.empty())
238                         output.append(" SSL=" + sslports);
239         }
240
241         ~ModuleSSLOpenSSL()
242         {
243                 SSL_CTX_free(ctx);
244                 SSL_CTX_free(clictx);
245                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
246                 delete[] sessions;
247         }
248
249         void OnCleanup(int target_type, void* item)
250         {
251                 if (target_type == TYPE_USER)
252                 {
253                         User* user = (User*)item;
254
255                         if (user->GetIOHook() == this)
256                         {
257                                 // User is using SSL, they're a local user, and they're using one of *our* SSL ports.
258                                 // Potentially there could be multiple SSL modules loaded at once on different ports.
259                                 ServerInstance->Users->QuitUser(user, "SSL module unloading");
260                                 user->DelIOHook();
261                         }
262                 }
263         }
264
265         Version GetVersion()
266         {
267                 return Version("Provides SSL support for clients", VF_VENDOR);
268         }
269
270
271         void OnRequest(Request& request)
272         {
273                 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
274                 if (sslinfo)
275                         sslinfo->OnRequest(request);
276         }
277
278
279         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
280         {
281                 int fd = user->GetFd();
282
283                 issl_session* session = &sessions[fd];
284
285                 session->fd = fd;
286                 session->sess = SSL_new(ctx);
287                 session->status = ISSL_NONE;
288                 session->outbound = false;
289
290                 if (session->sess == NULL)
291                         return;
292
293                 if (SSL_set_fd(session->sess, fd) == 0)
294                 {
295                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
296                         return;
297                 }
298
299                 Handshake(user, session);
300         }
301
302         void OnStreamSocketConnect(StreamSocket* user)
303         {
304                 int fd = user->GetFd();
305                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
306                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
307                         return;
308
309                 issl_session* session = &sessions[fd];
310
311                 session->fd = fd;
312                 session->sess = SSL_new(clictx);
313                 session->status = ISSL_NONE;
314                 session->outbound = true;
315
316                 if (session->sess == NULL)
317                         return;
318
319                 if (SSL_set_fd(session->sess, fd) == 0)
320                 {
321                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
322                         return;
323                 }
324
325                 Handshake(user, session);
326         }
327
328         void OnStreamSocketClose(StreamSocket* user)
329         {
330                 int fd = user->GetFd();
331                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
332                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
333                         return;
334
335                 CloseSession(&sessions[fd]);
336         }
337
338         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
339         {
340                 int fd = user->GetFd();
341                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
342                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
343                         return -1;
344
345                 issl_session* session = &sessions[fd];
346
347                 if (!session->sess)
348                 {
349                         CloseSession(session);
350                         return -1;
351                 }
352
353                 if (session->status == ISSL_HANDSHAKING)
354                 {
355                         // The handshake isn't finished and it wants to read, try to finish it.
356                         if (!Handshake(user, session))
357                         {
358                                 // Couldn't resume handshake.
359                                 if (session->status == ISSL_NONE)
360                                         return -1;
361                                 return 0;
362                         }
363                 }
364
365                 // If we resumed the handshake then session->status will be ISSL_OPEN
366
367                 if (session->status == ISSL_OPEN)
368                 {
369                         char* buffer = ServerInstance->GetReadBuffer();
370                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
371                         int ret = SSL_read(session->sess, buffer, bufsiz);
372                         
373                         if (ret > 0)
374                         {
375                                 recvq.append(buffer, ret);
376                                 return 1;
377                         }
378                         else if (ret == 0)
379                         {
380                                 // Client closed connection.
381                                 CloseSession(session);
382                                 return -1;
383                         }
384                         else if (ret < 0)
385                         {
386                                 int err = SSL_get_error(session->sess, ret);
387
388                                 if (err == SSL_ERROR_WANT_READ)
389                                 {
390                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
391                                         return 0;
392                                 }
393                                 else if (err == SSL_ERROR_WANT_WRITE)
394                                 {
395                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
396                                         return 0;
397                                 }
398                                 else
399                                 {
400                                         CloseSession(session);
401                                         return -1;
402                                 }
403                         }
404                 }
405
406                 return 0;
407         }
408
409         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
410         {
411                 int fd = user->GetFd();
412
413                 issl_session* session = &sessions[fd];
414
415                 if (!session->sess)
416                 {
417                         CloseSession(session);
418                         return -1;
419                 }
420
421                 session->data_to_write = true;
422
423                 if (session->status == ISSL_HANDSHAKING)
424                 {
425                         if (!Handshake(user, session))
426                         {
427                                 // Couldn't resume handshake.
428                                 if (session->status == ISSL_NONE)
429                                         return -1;
430                                 return 0;
431                         }
432                 }
433
434                 if (session->status == ISSL_OPEN)
435                 {
436                         int ret = SSL_write(session->sess, buffer.data(), buffer.size());
437                         if (ret == (int)buffer.length())
438                         {
439                                 session->data_to_write = false;
440                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
441                                 return 1;
442                         }
443                         else if (ret > 0)
444                         {
445                                 buffer = buffer.substr(ret);
446                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
447                                 return 0;
448                         }
449                         else if (ret == 0)
450                         {
451                                 CloseSession(session);
452                                 return -1;
453                         }
454                         else if (ret < 0)
455                         {
456                                 int err = SSL_get_error(session->sess, ret);
457
458                                 if (err == SSL_ERROR_WANT_WRITE)
459                                 {
460                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
461                                         return 0;
462                                 }
463                                 else if (err == SSL_ERROR_WANT_READ)
464                                 {
465                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
466                                         return 0;
467                                 }
468                                 else
469                                 {
470                                         CloseSession(session);
471                                         return -1;
472                                 }
473                         }
474                 }
475                 return 0;
476         }
477
478         bool Handshake(EventHandler* user, issl_session* session)
479         {
480                 int ret;
481
482                 if (session->outbound)
483                         ret = SSL_connect(session->sess);
484                 else
485                         ret = SSL_accept(session->sess);
486
487                 if (ret < 0)
488                 {
489                         int err = SSL_get_error(session->sess, ret);
490
491                         if (err == SSL_ERROR_WANT_READ)
492                         {
493                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
494                                 session->status = ISSL_HANDSHAKING;
495                                 return true;
496                         }
497                         else if (err == SSL_ERROR_WANT_WRITE)
498                         {
499                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
500                                 session->status = ISSL_HANDSHAKING;
501                                 return true;
502                         }
503                         else
504                         {
505                                 CloseSession(session);
506                         }
507
508                         return false;
509                 }
510                 else if (ret > 0)
511                 {
512                         // Handshake complete.
513                         VerifyCertificate(session, user);
514
515                         session->status = ISSL_OPEN;
516
517                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
518
519                         return true;
520                 }
521                 else if (ret == 0)
522                 {
523                         CloseSession(session);
524                         return true;
525                 }
526
527                 return true;
528         }
529
530         void CloseSession(issl_session* session)
531         {
532                 if (session->sess)
533                 {
534                         SSL_shutdown(session->sess);
535                         SSL_free(session->sess);
536                 }
537
538                 session->sess = NULL;
539                 session->status = ISSL_NONE;
540                 errno = EIO;
541         }
542
543         void VerifyCertificate(issl_session* session, Extensible* user)
544         {
545                 if (!session->sess || !user)
546                         return;
547
548                 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
549                 if (!sslinfo)
550                         return;
551
552                 X509* cert;
553                 ssl_cert* certinfo = new ssl_cert;
554                 unsigned int n;
555                 unsigned char md[EVP_MAX_MD_SIZE];
556                 const EVP_MD *digest = EVP_md5();
557
558                 cert = SSL_get_peer_certificate((SSL*)session->sess);
559
560                 if (!cert)
561                 {
562                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
563                         SSLCertSubmission(user, this, sslinfo, certinfo);
564                         return;
565                 }
566
567                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
568
569                 if (SelfSigned)
570                 {
571                         certinfo->unknownsigner = false;
572                         certinfo->trusted = true;
573                 }
574                 else
575                 {
576                         certinfo->unknownsigner = true;
577                         certinfo->trusted = false;
578                 }
579
580                 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
581                 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
582
583                 if (!X509_digest(cert, digest, md, &n))
584                 {
585                         certinfo->error = "Out of memory generating fingerprint";
586                 }
587                 else
588                 {
589                         certinfo->fingerprint = irc::hex(md, n);
590                 }
591
592                 if ((ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(cert), ServerInstance->Time()) == -1) || (ASN1_UTCTIME_cmp_time_t(X509_get_notBefore(cert), ServerInstance->Time()) == 0))
593                 {
594                         certinfo->error = "Not activated, or expired certificate";
595                 }
596
597                 X509_free(cert);
598                 SSLCertSubmission(user, this, sslinfo, certinfo);
599         }
600
601         void Prioritize()
602         {
603                 Module* server = ServerInstance->Modules->Find("m_spanningtree.so");
604                 ServerInstance->Modules->SetPriority(this, I_OnPostConnect, PRIORITY_AFTER, &server);
605         }
606
607 };
608
609 static int error_callback(const char *str, size_t len, void *u)
610 {
611         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
612
613         //
614         // XXX: Remove this line, it causes valgrind warnings...
615         //
616         // MD_update(&m, buf, j);
617         //
618         //
619         // ... ONLY JOKING! :-)
620         //
621
622         return 0;
623 }
624
625 MODULE_INIT(ModuleSSLOpenSSL)