]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ssl_openssl.cpp
5eac93af602f7698e69ea77a629c55745765e41d
[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[] = { I_On005Numeric, I_OnRehash, I_OnModuleRehash, I_OnHookIO };
129                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
130         }
131
132         void OnHookIO(StreamSocket* user, ListenSocket* lsb)
133         {
134                 if (!user->GetIOHook() && lsb->bind_tag->getString("ssl") == "openssl")
135                 {
136                         /* Hook the user with our module */
137                         user->AddIOHook(this);
138                 }
139         }
140
141         void OnRehash(User* user)
142         {
143                 ConfigReader Conf;
144
145                 sslports.clear();
146
147                 for (size_t i = 0; i < ServerInstance->ports.size(); i++)
148                 {
149                         ListenSocket* port = ServerInstance->ports[i];
150                         if (port->bind_tag->getString("ssl") != "openssl")
151                                 continue;
152
153                         std::string portid = port->bind_desc;
154                         ServerInstance->Logs->Log("m_ssl_openssl", DEFAULT, "m_ssl_openssl.so: Enabling SSL for port %s", portid.c_str());
155                         if (port->bind_tag->getString("type", "clients") == "clients" && port->bind_addr != "127.0.0.1")
156                                 sslports.append(portid).append(";");
157                 }
158
159                 if (!sslports.empty())
160                         sslports.erase(sslports.end() - 1);
161         }
162
163         void OnModuleRehash(User* user, const std::string &param)
164         {
165                 if (param != "ssl")
166                         return;
167
168                 OnRehash(user);
169
170                 ConfigReader Conf;
171
172                 cafile   = Conf.ReadValue("openssl", "cafile", 0);
173                 certfile = Conf.ReadValue("openssl", "certfile", 0);
174                 keyfile  = Conf.ReadValue("openssl", "keyfile", 0);
175                 dhfile   = Conf.ReadValue("openssl", "dhfile", 0);
176
177                 // Set all the default values needed.
178                 if (cafile.empty())
179                         cafile = "conf/ca.pem";
180
181                 if (certfile.empty())
182                         certfile = "conf/cert.pem";
183
184                 if (keyfile.empty())
185                         keyfile = "conf/key.pem";
186
187                 if (dhfile.empty())
188                         dhfile = "conf/dhparams.pem";
189
190                 /* Load our keys and certificates
191                  * NOTE: OpenSSL's error logging API sucks, don't blame us for this clusterfuck.
192                  */
193                 if ((!SSL_CTX_use_certificate_chain_file(ctx, certfile.c_str())) || (!SSL_CTX_use_certificate_chain_file(clictx, certfile.c_str())))
194                 {
195                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read certificate file %s. %s", certfile.c_str(), strerror(errno));
196                         ERR_print_errors_cb(error_callback, this);
197                 }
198
199                 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)))
200                 {
201                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read key file %s. %s", keyfile.c_str(), strerror(errno));
202                         ERR_print_errors_cb(error_callback, this);
203                 }
204
205                 /* Load the CAs we trust*/
206                 if (((!SSL_CTX_load_verify_locations(ctx, cafile.c_str(), 0))) || (!SSL_CTX_load_verify_locations(clictx, cafile.c_str(), 0)))
207                 {
208                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Can't read CA list from %s. %s", cafile.c_str(), strerror(errno));
209                         ERR_print_errors_cb(error_callback, this);
210                 }
211
212                 FILE* dhpfile = fopen(dhfile.c_str(), "r");
213                 DH* ret;
214
215                 if (dhpfile == NULL)
216                 {
217                         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so Couldn't open DH file %s: %s", dhfile.c_str(), strerror(errno));
218                         throw ModuleException("Couldn't open DH file " + dhfile + ": " + strerror(errno));
219                 }
220                 else
221                 {
222                         ret = PEM_read_DHparams(dhpfile, NULL, NULL, NULL);
223                         if ((SSL_CTX_set_tmp_dh(ctx, ret) < 0) || (SSL_CTX_set_tmp_dh(clictx, ret) < 0))
224                         {
225                                 ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "m_ssl_openssl.so: Couldn't set DH parameters %s. SSL errors follow:", dhfile.c_str());
226                                 ERR_print_errors_cb(error_callback, this);
227                         }
228                 }
229
230                 fclose(dhpfile);
231         }
232
233         void On005Numeric(std::string &output)
234         {
235                 if (!sslports.empty())
236                         output.append(" SSL=" + sslports);
237         }
238
239         ~ModuleSSLOpenSSL()
240         {
241                 SSL_CTX_free(ctx);
242                 SSL_CTX_free(clictx);
243                 ServerInstance->Modules->UnpublishInterface("BufferedSocketHook", this);
244                 delete[] sessions;
245         }
246
247         void OnCleanup(int target_type, void* item)
248         {
249                 if (target_type == TYPE_USER)
250                 {
251                         LocalUser* user = IS_LOCAL((User*)item);
252
253                         if (user && user->eh.GetIOHook() == this)
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->Users->QuitUser(user, "SSL module unloading");
258                         }
259                 }
260         }
261
262         Version GetVersion()
263         {
264                 return Version("Provides SSL support for clients", VF_VENDOR);
265         }
266
267
268         void OnRequest(Request& request)
269         {
270                 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
271                 if (sslinfo)
272                         sslinfo->OnRequest(request);
273         }
274
275
276         void OnStreamSocketAccept(StreamSocket* user, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
277         {
278                 int fd = user->GetFd();
279
280                 issl_session* session = &sessions[fd];
281
282                 session->fd = fd;
283                 session->sess = SSL_new(ctx);
284                 session->status = ISSL_NONE;
285                 session->outbound = false;
286
287                 if (session->sess == NULL)
288                         return;
289
290                 if (SSL_set_fd(session->sess, fd) == 0)
291                 {
292                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
293                         return;
294                 }
295
296                 Handshake(user, session);
297         }
298
299         void OnStreamSocketConnect(StreamSocket* user)
300         {
301                 int fd = user->GetFd();
302                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
303                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() -1))
304                         return;
305
306                 issl_session* session = &sessions[fd];
307
308                 session->fd = fd;
309                 session->sess = SSL_new(clictx);
310                 session->status = ISSL_NONE;
311                 session->outbound = true;
312
313                 if (session->sess == NULL)
314                         return;
315
316                 if (SSL_set_fd(session->sess, fd) == 0)
317                 {
318                         ServerInstance->Logs->Log("m_ssl_openssl",DEBUG,"BUG: Can't set fd with SSL_set_fd: %d", fd);
319                         return;
320                 }
321
322                 Handshake(user, session);
323         }
324
325         void OnStreamSocketClose(StreamSocket* user)
326         {
327                 int fd = user->GetFd();
328                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
329                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
330                         return;
331
332                 CloseSession(&sessions[fd]);
333         }
334
335         int OnStreamSocketRead(StreamSocket* user, std::string& recvq)
336         {
337                 int fd = user->GetFd();
338                 /* Are there any possibilities of an out of range fd? Hope not, but lets be paranoid */
339                 if ((fd < 0) || (fd > ServerInstance->SE->GetMaxFds() - 1))
340                         return -1;
341
342                 issl_session* session = &sessions[fd];
343
344                 if (!session->sess)
345                 {
346                         CloseSession(session);
347                         return -1;
348                 }
349
350                 if (session->status == ISSL_HANDSHAKING)
351                 {
352                         // The handshake isn't finished and it wants to read, try to finish it.
353                         if (!Handshake(user, session))
354                         {
355                                 // Couldn't resume handshake.
356                                 if (session->status == ISSL_NONE)
357                                         return -1;
358                                 return 0;
359                         }
360                 }
361
362                 // If we resumed the handshake then session->status will be ISSL_OPEN
363
364                 if (session->status == ISSL_OPEN)
365                 {
366                         char* buffer = ServerInstance->GetReadBuffer();
367                         size_t bufsiz = ServerInstance->Config->NetBufferSize;
368                         int ret = SSL_read(session->sess, buffer, bufsiz);
369                         
370                         if (ret > 0)
371                         {
372                                 recvq.append(buffer, ret);
373                                 return 1;
374                         }
375                         else if (ret == 0)
376                         {
377                                 // Client closed connection.
378                                 CloseSession(session);
379                                 return -1;
380                         }
381                         else if (ret < 0)
382                         {
383                                 int err = SSL_get_error(session->sess, ret);
384
385                                 if (err == SSL_ERROR_WANT_READ)
386                                 {
387                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ);
388                                         return 0;
389                                 }
390                                 else if (err == SSL_ERROR_WANT_WRITE)
391                                 {
392                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
393                                         return 0;
394                                 }
395                                 else
396                                 {
397                                         CloseSession(session);
398                                         return -1;
399                                 }
400                         }
401                 }
402
403                 return 0;
404         }
405
406         int OnStreamSocketWrite(StreamSocket* user, std::string& buffer)
407         {
408                 int fd = user->GetFd();
409
410                 issl_session* session = &sessions[fd];
411
412                 if (!session->sess)
413                 {
414                         CloseSession(session);
415                         return -1;
416                 }
417
418                 session->data_to_write = true;
419
420                 if (session->status == ISSL_HANDSHAKING)
421                 {
422                         if (!Handshake(user, session))
423                         {
424                                 // Couldn't resume handshake.
425                                 if (session->status == ISSL_NONE)
426                                         return -1;
427                                 return 0;
428                         }
429                 }
430
431                 if (session->status == ISSL_OPEN)
432                 {
433                         int ret = SSL_write(session->sess, buffer.data(), buffer.size());
434                         if (ret == (int)buffer.length())
435                         {
436                                 session->data_to_write = false;
437                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
438                                 return 1;
439                         }
440                         else if (ret > 0)
441                         {
442                                 buffer = buffer.substr(ret);
443                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
444                                 return 0;
445                         }
446                         else if (ret == 0)
447                         {
448                                 CloseSession(session);
449                                 return -1;
450                         }
451                         else if (ret < 0)
452                         {
453                                 int err = SSL_get_error(session->sess, ret);
454
455                                 if (err == SSL_ERROR_WANT_WRITE)
456                                 {
457                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_SINGLE_WRITE);
458                                         return 0;
459                                 }
460                                 else if (err == SSL_ERROR_WANT_READ)
461                                 {
462                                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
463                                         return 0;
464                                 }
465                                 else
466                                 {
467                                         CloseSession(session);
468                                         return -1;
469                                 }
470                         }
471                 }
472                 return 0;
473         }
474
475         bool Handshake(EventHandler* user, issl_session* session)
476         {
477                 int ret;
478
479                 if (session->outbound)
480                         ret = SSL_connect(session->sess);
481                 else
482                         ret = SSL_accept(session->sess);
483
484                 if (ret < 0)
485                 {
486                         int err = SSL_get_error(session->sess, ret);
487
488                         if (err == SSL_ERROR_WANT_READ)
489                         {
490                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
491                                 session->status = ISSL_HANDSHAKING;
492                                 return true;
493                         }
494                         else if (err == SSL_ERROR_WANT_WRITE)
495                         {
496                                 ServerInstance->SE->ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
497                                 session->status = ISSL_HANDSHAKING;
498                                 return true;
499                         }
500                         else
501                         {
502                                 CloseSession(session);
503                         }
504
505                         return false;
506                 }
507                 else if (ret > 0)
508                 {
509                         // Handshake complete.
510                         VerifyCertificate(session, user);
511
512                         session->status = ISSL_OPEN;
513
514                         ServerInstance->SE->ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);
515
516                         return true;
517                 }
518                 else if (ret == 0)
519                 {
520                         CloseSession(session);
521                         return true;
522                 }
523
524                 return true;
525         }
526
527         void CloseSession(issl_session* session)
528         {
529                 if (session->sess)
530                 {
531                         SSL_shutdown(session->sess);
532                         SSL_free(session->sess);
533                 }
534
535                 session->sess = NULL;
536                 session->status = ISSL_NONE;
537                 errno = EIO;
538         }
539
540         void VerifyCertificate(issl_session* session, Extensible* user)
541         {
542                 if (!session->sess || !user)
543                         return;
544
545                 Module* sslinfo = ServerInstance->Modules->Find("m_sslinfo.so");
546                 if (!sslinfo)
547                         return;
548
549                 X509* cert;
550                 ssl_cert* certinfo = new ssl_cert;
551                 unsigned int n;
552                 unsigned char md[EVP_MAX_MD_SIZE];
553                 const EVP_MD *digest = EVP_md5();
554
555                 cert = SSL_get_peer_certificate((SSL*)session->sess);
556
557                 if (!cert)
558                 {
559                         certinfo->error = "Could not get peer certificate: "+std::string(get_error());
560                         SSLCertSubmission(user, this, sslinfo, certinfo);
561                         return;
562                 }
563
564                 certinfo->invalid = (SSL_get_verify_result(session->sess) != X509_V_OK);
565
566                 if (SelfSigned)
567                 {
568                         certinfo->unknownsigner = false;
569                         certinfo->trusted = true;
570                 }
571                 else
572                 {
573                         certinfo->unknownsigner = true;
574                         certinfo->trusted = false;
575                 }
576
577                 certinfo->dn = X509_NAME_oneline(X509_get_subject_name(cert),0,0);
578                 certinfo->issuer = X509_NAME_oneline(X509_get_issuer_name(cert),0,0);
579
580                 if (!X509_digest(cert, digest, md, &n))
581                 {
582                         certinfo->error = "Out of memory generating fingerprint";
583                 }
584                 else
585                 {
586                         certinfo->fingerprint = irc::hex(md, n);
587                 }
588
589                 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))
590                 {
591                         certinfo->error = "Not activated, or expired certificate";
592                 }
593
594                 X509_free(cert);
595                 SSLCertSubmission(user, this, sslinfo, certinfo);
596         }
597 };
598
599 static int error_callback(const char *str, size_t len, void *u)
600 {
601         ServerInstance->Logs->Log("m_ssl_openssl",DEFAULT, "SSL error: " + std::string(str, len - 1));
602
603         //
604         // XXX: Remove this line, it causes valgrind warnings...
605         //
606         // MD_update(&m, buf, j);
607         //
608         //
609         // ... ONLY JOKING! :-)
610         //
611
612         return 0;
613 }
614
615 MODULE_INIT(ModuleSSLOpenSSL)