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