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