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