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