]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_sslinfo.cpp
2c84c114bfd9e152e0d896c99a9f1f80cf4336db
[user/henk/code/inspircd.git] / src / modules / m_sslinfo.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5  *   Copyright (C) 2013, 2017-2019 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2013 Christopher 'm4z' Holm <them4z@gmail.com>
7  *   Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2010 Adam <Adam@anope.org>
10  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
12  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13  *   Copyright (C) 2006-2007, 2009-2010 Craig Edwards <brain@inspircd.org>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #include "inspircd.h"
30 #include "modules/ssl.h"
31 #include "modules/webirc.h"
32 #include "modules/whois.h"
33 #include "modules/who.h"
34
35 enum
36 {
37         // From oftc-hybrid.
38         RPL_WHOISCERTFP = 276,
39
40         // From UnrealIRCd.
41         RPL_WHOISSECURE = 671
42 };
43
44 class SSLCertExt : public ExtensionItem
45 {
46  public:
47         SSLCertExt(Module* parent)
48                 : ExtensionItem("ssl_cert", ExtensionItem::EXT_USER, parent)
49         {
50         }
51
52         ssl_cert* get(const Extensible* item) const
53         {
54                 return static_cast<ssl_cert*>(get_raw(item));
55         }
56
57         void set(Extensible* item, ssl_cert* value)
58         {
59                 value->refcount_inc();
60                 ssl_cert* old = static_cast<ssl_cert*>(set_raw(item, value));
61                 if (old && old->refcount_dec())
62                         delete old;
63         }
64
65         void unset(Extensible* container)
66         {
67                 free(container, unset_raw(container));
68         }
69
70         std::string ToNetwork(const Extensible* container, void* item) const CXX11_OVERRIDE
71         {
72                 return static_cast<ssl_cert*>(item)->GetMetaLine();
73         }
74
75         void FromNetwork(Extensible* container, const std::string& value) CXX11_OVERRIDE
76         {
77                 ssl_cert* cert = new ssl_cert;
78                 set(container, cert);
79
80                 std::stringstream s(value);
81                 std::string v;
82                 getline(s,v,' ');
83
84                 cert->invalid = (v.find('v') != std::string::npos);
85                 cert->trusted = (v.find('T') != std::string::npos);
86                 cert->revoked = (v.find('R') != std::string::npos);
87                 cert->unknownsigner = (v.find('s') != std::string::npos);
88                 if (v.find('E') != std::string::npos)
89                 {
90                         getline(s,cert->error,'\n');
91                 }
92                 else
93                 {
94                         getline(s,cert->fingerprint,' ');
95                         getline(s,cert->dn,' ');
96                         getline(s,cert->issuer,'\n');
97                 }
98         }
99
100         void free(Extensible* container, void* item) CXX11_OVERRIDE
101         {
102                 ssl_cert* old = static_cast<ssl_cert*>(item);
103                 if (old && old->refcount_dec())
104                         delete old;
105         }
106 };
107
108 class UserCertificateAPIImpl : public UserCertificateAPIBase
109 {
110  public:
111         LocalIntExt nosslext;
112         SSLCertExt sslext;
113
114         UserCertificateAPIImpl(Module* mod)
115                 : UserCertificateAPIBase(mod)
116                 , nosslext("no_ssl_cert", ExtensionItem::EXT_USER, mod)
117                 , sslext(mod)
118         {
119         }
120
121         ssl_cert* GetCertificate(User* user) CXX11_OVERRIDE
122         {
123                 ssl_cert* cert = sslext.get(user);
124                 if (cert)
125                         return cert;
126
127                 LocalUser* luser = IS_LOCAL(user);
128                 if (!luser || nosslext.get(luser))
129                         return NULL;
130
131                 cert = SSLClientCert::GetCertificate(&luser->eh);
132                 if (!cert)
133                         return NULL;
134
135                 SetCertificate(user, cert);
136                 return cert;
137         }
138
139         void SetCertificate(User* user, ssl_cert* cert) CXX11_OVERRIDE
140         {
141                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Setting SSL certificate for %s: %s",
142                         user->GetFullHost().c_str(), cert->GetMetaLine().c_str());
143                 sslext.set(user, cert);
144         }
145 };
146
147 class CommandSSLInfo : public Command
148 {
149  public:
150         UserCertificateAPIImpl sslapi;
151
152         CommandSSLInfo(Module* Creator)
153                 : Command(Creator, "SSLINFO", 1)
154                 , sslapi(Creator)
155         {
156                 this->syntax = "<nick>";
157         }
158
159         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
160         {
161                 User* target = ServerInstance->FindNickOnly(parameters[0]);
162
163                 if ((!target) || (target->registered != REG_ALL))
164                 {
165                         user->WriteNumeric(Numerics::NoSuchNick(parameters[0]));
166                         return CMD_FAILURE;
167                 }
168                 bool operonlyfp = ServerInstance->Config->ConfValue("sslinfo")->getBool("operonly");
169                 if (operonlyfp && !user->IsOper() && target != user)
170                 {
171                         user->WriteNotice("*** You cannot view SSL certificate information for other users");
172                         return CMD_FAILURE;
173                 }
174                 ssl_cert* cert = sslapi.GetCertificate(target);
175                 if (!cert)
176                 {
177                         user->WriteNotice("*** No SSL certificate for this user");
178                 }
179                 else if (cert->GetError().length())
180                 {
181                         user->WriteNotice("*** No SSL certificate information for this user (" + cert->GetError() + ").");
182                 }
183                 else
184                 {
185                         user->WriteNotice("*** Distinguished Name: " + cert->GetDN());
186                         user->WriteNotice("*** Issuer:             " + cert->GetIssuer());
187                         user->WriteNotice("*** Key Fingerprint:    " + cert->GetFingerprint());
188                 }
189                 return CMD_SUCCESS;
190         }
191 };
192
193 class ModuleSSLInfo
194         : public Module
195         , public WebIRC::EventListener
196         , public Whois::EventListener
197         , public Who::EventListener
198 {
199  private:
200         CommandSSLInfo cmd;
201
202         bool MatchFP(ssl_cert* const cert, const std::string& fp) const
203         {
204                 return irc::spacesepstream(fp).Contains(cert->GetFingerprint());
205         }
206
207  public:
208         ModuleSSLInfo()
209                 : WebIRC::EventListener(this)
210                 , Whois::EventListener(this)
211                 , Who::EventListener(this)
212                 , cmd(this)
213         {
214         }
215
216         Version GetVersion() CXX11_OVERRIDE
217         {
218                 return Version("Adds user facing SSL information, various SSL configuration options, and the /SSLINFO command to look up SSL certificate information for other users.", VF_VENDOR);
219         }
220
221         void OnWhois(Whois::Context& whois) CXX11_OVERRIDE
222         {
223                 ssl_cert* cert = cmd.sslapi.GetCertificate(whois.GetTarget());
224                 if (cert)
225                 {
226                         whois.SendLine(RPL_WHOISSECURE, "is using a secure connection");
227                         bool operonlyfp = ServerInstance->Config->ConfValue("sslinfo")->getBool("operonly");
228                         if ((!operonlyfp || whois.IsSelfWhois() || whois.GetSource()->IsOper()) && !cert->fingerprint.empty())
229                                 whois.SendLine(RPL_WHOISCERTFP, InspIRCd::Format("has client certificate fingerprint %s", cert->fingerprint.c_str()));
230                 }
231         }
232
233         ModResult OnWhoLine(const Who::Request& request, LocalUser* source, User* user, Membership* memb, Numeric::Numeric& numeric) CXX11_OVERRIDE
234         {
235                 size_t flag_index;
236                 if (!request.GetFieldIndex('f', flag_index))
237                         return MOD_RES_PASSTHRU;
238
239                 ssl_cert* cert = cmd.sslapi.GetCertificate(user);
240                 if (cert)
241                         numeric.GetParams()[flag_index].push_back('s');
242
243                 return MOD_RES_PASSTHRU;
244         }
245
246         ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE
247         {
248                 if ((command == "OPER") && (validated))
249                 {
250                         ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->oper_blocks.find(parameters[0]);
251                         if (i != ServerInstance->Config->oper_blocks.end())
252                         {
253                                 OperInfo* ifo = i->second;
254                                 ssl_cert* cert = cmd.sslapi.GetCertificate(user);
255
256                                 if (ifo->oper_block->getBool("sslonly") && !cert)
257                                 {
258                                         user->WriteNumeric(ERR_NOOPERHOST, "This oper login requires an SSL connection.");
259                                         user->CommandFloodPenalty += 10000;
260                                         ServerInstance->SNO->WriteGlobalSno('o', "WARNING! Failed oper attempt by %s using login '%s': secure connection required.", user->GetFullRealHost().c_str(), parameters[0].c_str());
261                                         return MOD_RES_DENY;
262                                 }
263
264                                 std::string fingerprint;
265                                 if (ifo->oper_block->readString("fingerprint", fingerprint) && (!cert || !MatchFP(cert, fingerprint)))
266                                 {
267                                         user->WriteNumeric(ERR_NOOPERHOST, "This oper login requires a matching SSL certificate fingerprint.");
268                                         user->CommandFloodPenalty += 10000;
269                                         ServerInstance->SNO->WriteGlobalSno('o', "WARNING! Failed oper attempt by %s using login '%s': client certificate fingerprint does not match.", user->GetFullRealHost().c_str(), parameters[0].c_str());
270                                         return MOD_RES_DENY;
271                                 }
272                         }
273                 }
274
275                 // Let core handle it for extra stuff
276                 return MOD_RES_PASSTHRU;
277         }
278
279         void OnPostConnect(User* user) CXX11_OVERRIDE
280         {
281                 LocalUser* const localuser = IS_LOCAL(user);
282                 if (!localuser)
283                         return;
284
285                 const SSLIOHook* const ssliohook = SSLIOHook::IsSSL(&localuser->eh);
286                 if (!ssliohook || cmd.sslapi.nosslext.get(localuser))
287                         return;
288
289                 ssl_cert* const cert = ssliohook->GetCertificate();
290
291                 {
292                         std::string text = "*** You are connected to ";
293                         if (!ssliohook->GetServerName(text))
294                                 text.append(ServerInstance->Config->ServerName);
295                         text.append(" using SSL cipher '");
296                         ssliohook->GetCiphersuite(text);
297                         text.push_back('\'');
298                         if ((cert) && (!cert->GetFingerprint().empty()))
299                                 text.append(" and your SSL certificate fingerprint is ").append(cert->GetFingerprint());
300                         user->WriteNotice(text);
301                 }
302
303                 if (!cert)
304                         return;
305                 // find an auto-oper block for this user
306                 for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->oper_blocks.begin(); i != ServerInstance->Config->oper_blocks.end(); ++i)
307                 {
308                         OperInfo* ifo = i->second;
309                         std::string fp = ifo->oper_block->getString("fingerprint");
310                         if (MatchFP(cert, fp) && ifo->oper_block->getBool("autologin"))
311                                 user->Oper(ifo);
312                 }
313         }
314
315         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
316         {
317                 ssl_cert* cert = cmd.sslapi.GetCertificate(user);
318                 bool ok = true;
319                 const std::string requiressl = myclass->config->getString("requiressl");
320                 if (stdalgo::string::equalsci(requiressl, "trusted"))
321                 {
322                         ok = (cert && cert->IsCAVerified());
323                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class requires a trusted SSL cert. Client %s one.", (ok ? "has" : "does not have"));
324                 }
325                 else if (myclass->config->getBool("requiressl"))
326                 {
327                         ok = (cert != NULL);
328                         ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class requires SSL. Client %s using SSL.", (ok ? "is" : "is not"));
329                 }
330
331                 if (!ok)
332                         return MOD_RES_DENY;
333                 return MOD_RES_PASSTHRU;
334         }
335
336         void OnWebIRCAuth(LocalUser* user, const WebIRC::FlagMap* flags) CXX11_OVERRIDE
337         {
338                 // We are only interested in connection flags. If none have been
339                 // given then we have nothing to do.
340                 if (!flags)
341                         return;
342
343                 // We only care about the tls connection flag if the connection
344                 // between the gateway and the server is secure.
345                 if (!cmd.sslapi.GetCertificate(user))
346                         return;
347
348                 WebIRC::FlagMap::const_iterator iter = flags->find("secure");
349                 if (iter == flags->end())
350                 {
351                         // If this is not set then the connection between the client and
352                         // the gateway is not secure.
353                         cmd.sslapi.nosslext.set(user, 1);
354                         cmd.sslapi.sslext.unset(user);
355                         return;
356                 }
357
358                 // Create a fake ssl_cert for the user.
359                 ssl_cert* cert = new ssl_cert;
360                 cert->error = "WebIRC users can not specify valid certs yet";
361                 cert->invalid = true;
362                 cert->revoked = true;
363                 cert->trusted = false;
364                 cert->unknownsigner = true;
365                 cmd.sslapi.SetCertificate(user, cert);
366         }
367 };
368
369 MODULE_INIT(ModuleSSLInfo)