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