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