helper.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 #include "squid.h"
10 #include "../helper.h"
11 #include "anyp/PortCfg.h"
12 #include "base/AsyncCallbacks.h"
13 #include "cache_cf.h"
14 #include "fs_io.h"
15 #include "helper/Reply.h"
16 #include "Parsing.h"
17 #include "sbuf/Stream.h"
18 #include "SquidConfig.h"
20 #include "ssl/Config.h"
21 #include "ssl/helper.h"
22 #include "wordlist.h"
23 
24 #include <limits>
25 
27 
28 #if USE_SSL_CRTD
29 
30 namespace Ssl {
31 
34 public:
35  GeneratorRequestor(HLPCB *aCallback, void *aData): callback(aCallback), data(aData) {}
38 };
39 
43 
44 public:
46  void emplace(HLPCB *callback, void *data) { requestors.emplace_back(callback, data); }
47 
49 
51  typedef std::vector<GeneratorRequestor> GeneratorRequestors;
53 };
54 
56 typedef std::unordered_map<SBuf, GeneratorRequest*> GeneratorRequests;
57 
58 static void HandleGeneratorReply(void *data, const ::Helper::Reply &reply);
59 
60 } // namespace Ssl
61 
62 CBDATA_NAMESPACED_CLASS_INIT(Ssl, GeneratorRequest);
63 
65 static std::ostream &
66 operator <<(std::ostream &os, const Ssl::GeneratorRequest &gr)
67 {
68  return os << "crtGenRq" << gr.query.id.value << "/" << gr.requestors.size();
69 }
70 
73 
75 
77 {
78  assert(ssl_crtd == nullptr);
79 
80  // we need to start ssl_crtd only if some port(s) need to bump SSL *and* generate certificates
81  // TODO: generate host certificates for SNI enabled accel ports
82  bool found = false;
83  for (AnyP::PortCfgPointer s = HttpPortList; !found && s != nullptr; s = s->next)
84  found = s->flags.tunnelSslBumping && s->secure.generateHostCertificates;
85  if (!found)
86  return;
87 
88  ssl_crtd = ::Helper::Client::Make("sslcrtd_program");
89  ssl_crtd->childs.updateLimits(Ssl::TheConfig.ssl_crtdChildren);
90  ssl_crtd->ipc_type = IPC_STREAM;
91  // The crtd messages may contain the eol ('\n') character. We are
92  // going to use the '\1' char as the end-of-message mark.
93  ssl_crtd->eom = '\1';
94  assert(ssl_crtd->cmdline == nullptr);
95  {
96  char *tmp = xstrdup(Ssl::TheConfig.ssl_crtd);
97  char *tmp_begin = tmp;
98  char *token = nullptr;
99  while ((token = strwordtok(nullptr, &tmp))) {
100  wordlistAdd(&ssl_crtd->cmdline, token);
101  }
102  safe_free(tmp_begin);
103  }
104  ssl_crtd->openSessions();
105 }
106 
108 {
109  if (!ssl_crtd)
110  return;
111  helperShutdown(ssl_crtd);
112  wordlistDestroy(&ssl_crtd->cmdline);
113  ssl_crtd = nullptr;
114 }
115 
116 void
118 {
119  Shutdown();
120  Init();
121 }
122 
123 void Ssl::Helper::Submit(CrtdMessage const & message, HLPCB * callback, void * data)
124 {
125  SBuf rawMessage(message.compose().c_str()); // XXX: helpers cannot use SBuf
126  rawMessage.append("\n", 1);
127 
128  const auto pending = TheGeneratorRequests.find(rawMessage);
129  if (pending != TheGeneratorRequests.end()) {
130  pending->second->emplace(callback, data);
131  debugs(83, 5, "collapsed request from " << data << " onto " << *pending->second);
132  return;
133  }
134 
135  GeneratorRequest *request = new GeneratorRequest;
136  request->query = rawMessage;
137  request->emplace(callback, data);
138  TheGeneratorRequests.emplace(request->query, request);
139  debugs(83, 5, "request from " << data << " as " << *request);
140  // ssl_crtd becomes nil if Squid is reconfigured without SslBump or
141  // certificate generation disabled in the new configuration
142  if (ssl_crtd && ssl_crtd->trySubmit(request->query.c_str(), HandleGeneratorReply, request))
143  return;
144 
146  failReply.notes.add("message", "error 45 Temporary network problem, please retry later");
147  HandleGeneratorReply(request, failReply);
148 }
149 
151 static void
152 Ssl::HandleGeneratorReply(void *data, const ::Helper::Reply &reply)
153 {
154  const std::unique_ptr<Ssl::GeneratorRequest> request(static_cast<Ssl::GeneratorRequest*>(data));
155  assert(request);
156  const auto erased = TheGeneratorRequests.erase(request->query);
157  assert(erased);
158 
159  for (auto &requestor: request->requestors) {
160  if (void *cbdata = requestor.data.validDone()) {
161  debugs(83, 5, "to " << cbdata << " in " << *request);
162  requestor.callback(cbdata, reply);
163  }
164  }
165 }
166 #endif //USE_SSL_CRTD
167 
169 
171 {
172  if (!Ssl::TheConfig.ssl_crt_validator)
173  return;
174 
175  assert(ssl_crt_validator == nullptr);
176 
177  // we need to start ssl_crtd only if some port(s) need to bump SSL
178  bool found = false;
179  for (AnyP::PortCfgPointer s = HttpPortList; !found && s != nullptr; s = s->next)
180  found = s->flags.tunnelSslBumping;
181  if (!found)
182  return;
183 
184  ssl_crt_validator = ::Helper::Client::Make("ssl_crt_validator");
185  ssl_crt_validator->childs.updateLimits(Ssl::TheConfig.ssl_crt_validator_Children);
186  ssl_crt_validator->ipc_type = IPC_STREAM;
187  // The crtd messages may contain the eol ('\n') character. We are
188  // going to use the '\1' char as the end-of-message mark.
189  ssl_crt_validator->eom = '\1';
190  assert(ssl_crt_validator->cmdline == nullptr);
191 
192  /* defaults */
193  int ttl = 3600; // 1 hour
194  size_t cache = 64*1024*1024; // 64 MB
195  {
196  // TODO: Do this during parseConfigFile() for proper parsing, error handling
197  char *tmp = xstrdup(Ssl::TheConfig.ssl_crt_validator);
198  char *tmp_begin = tmp;
199  char * token = nullptr;
200  bool parseParams = true;
201  while ((token = strwordtok(nullptr, &tmp))) {
202  if (parseParams) {
203  if (strcmp(token, "ttl=infinity") == 0) {
205  continue;
206  } else if (strncmp(token, "ttl=", 4) == 0) {
207  ttl = xatoi(token + 4);
208  if (ttl < 0) {
209  throw TextException(ToSBuf("Negative TTL in sslcrtvalidator_program ", Ssl::TheConfig.ssl_crt_validator,
210  Debug::Extra, "For unlimited TTL, use ttl=infinity"),
211  Here());
212  }
213  continue;
214  } else if (strncmp(token, "cache=", 6) == 0) {
215  cache = xatoi(token + 6);
216  continue;
217  } else
218  parseParams = false;
219  }
220  wordlistAdd(&ssl_crt_validator->cmdline, token);
221  }
222  xfree(tmp_begin);
223  }
224  ssl_crt_validator->openSessions();
225 
226  //WARNING: initializing static member in an object initialization method
227  assert(HelperCache == nullptr);
228  HelperCache = new CacheType(cache, ttl);
229 }
230 
232 {
233  if (!ssl_crt_validator)
234  return;
235  helperShutdown(ssl_crt_validator);
236  wordlistDestroy(&ssl_crt_validator->cmdline);
237  ssl_crt_validator = nullptr;
238 
239  // CertValidationHelper::HelperCache is a static member, it is not good policy to
240  // reset it here. Will work because the current Ssl::CertValidationHelper is
241  // always the same static object.
242  delete HelperCache;
243  HelperCache = nullptr;
244 }
245 
246 void
248 {
249  Shutdown();
250  Init();
251 }
252 
254 {
256 
257 public:
258  SBuf query;
261 };
263 
264 static void
265 sslCrtvdHandleReplyWrapper(void *data, const ::Helper::Reply &reply)
266 {
268 
269  submitData *crtdvdData = static_cast<submitData *>(data);
270  assert(crtdvdData->ssl.get());
271  Ssl::CertValidationResponse::Pointer validationResponse = new Ssl::CertValidationResponse(crtdvdData->ssl);
272  if (reply.result == ::Helper::BrokenHelper) {
273  debugs(83, DBG_IMPORTANT, "ERROR: \"ssl_crtvd\" helper error response: " << reply.other().content());
274  validationResponse->resultCode = ::Helper::BrokenHelper;
275  } else if (!reply.other().hasContent()) {
276  debugs(83, DBG_IMPORTANT, "\"ssl_crtvd\" helper returned NULL response");
277  validationResponse->resultCode = ::Helper::BrokenHelper;
278  } else if (replyMsg.parse(reply.other().content(), reply.other().contentSize()) != Ssl::CrtdMessage::OK ||
279  !replyMsg.parseResponse(*validationResponse) ) {
280  debugs(83, DBG_IMPORTANT, "WARNING: Reply from ssl_crtvd for " << " is incorrect");
281  debugs(83, DBG_IMPORTANT, "ERROR: Certificate cannot be validated. ssl_crtvd response: " << replyMsg.getBody());
282  validationResponse->resultCode = ::Helper::BrokenHelper;
283  } else
284  validationResponse->resultCode = reply.result;
285 
286  crtdvdData->callback.answer() = validationResponse;
287  ScheduleCallHere(crtdvdData->callback.release());
288 
290  (validationResponse->resultCode == ::Helper::Okay || validationResponse->resultCode == ::Helper::Error)) {
291  (void)Ssl::CertValidationHelper::HelperCache->add(crtdvdData->query, validationResponse);
292  }
293 
294  delete crtdvdData;
295 }
296 
297 void
299 {
302  message.composeRequest(request);
303  debugs(83, 5, "SSL crtvd request: " << message.compose().c_str());
304 
305  submitData *crtdvdData = new submitData;
306  crtdvdData->query.assign(message.compose().c_str());
307  crtdvdData->query.append('\n');
308  crtdvdData->callback = callback;
309  crtdvdData->ssl = request.ssl;
310  Ssl::CertValidationResponse::Pointer const*validationResponse;
311 
313  (validationResponse = CertValidationHelper::HelperCache->get(crtdvdData->query))) {
314 
315  crtdvdData->callback.answer() = *validationResponse;
316  ScheduleCallHere(crtdvdData->callback.release());
317  delete crtdvdData;
318  return;
319  }
320 
321  // ssl_crt_validator becomes nil if Squid is reconfigured with cert
322  // validator disabled in the new configuration
323  if (ssl_crt_validator && ssl_crt_validator->trySubmit(crtdvdData->query.c_str(), sslCrtvdHandleReplyWrapper, crtdvdData))
324  return;
325 
327  resp->resultCode = ::Helper::BrokenHelper;
328  crtdvdData->callback.answer() = resp;
329  ScheduleCallHere(crtdvdData->callback.release());
330  delete crtdvdData;
331  return;
332 }
333 
an old-style void* callback parameter
Definition: cbdata.h:383
AsyncCallback< Answer > Callback
Definition: helper.h:47
Value value
instance identifier
Definition: InstanceId.h:70
std::vector< GeneratorRequestor > GeneratorRequestors
Ssl::Helper request initiators waiting for the same answer (FIFO).
Definition: helper.cc:51
#define Here()
source code location of the caller
Definition: Here.h:15
void wordlistDestroy(wordlist **list)
destroy a wordlist
Definition: wordlist.cc:16
Security::SessionPointer ssl
static void HandleGeneratorReply(void *data, const ::Helper::Reply &reply)
receives helper response
Definition: helper.cc:152
static Ssl::GeneratorRequests TheGeneratorRequests
pending Ssl::Helper requests (to all certificate generator helpers combined)
Definition: helper.cc:72
SBuf & assign(const SBuf &S)
Definition: SBuf.cc:83
@ Error
Definition: ResultCode.h:19
AnyP::PortCfgPointer HttpPortList
list of Squid http(s)_port configured
Definition: PortCfg.cc:22
Security::SessionPointer ssl
Definition: helper.cc:260
#define CBDATA_NAMESPACED_CLASS_INIT(namespace, type)
Definition: cbdata.h:333
static const std::string code_cert_validate
String code for "cert_validate" messages.
Initiator of an Ssl::Helper query.
Definition: helper.cc:33
void composeRequest(CertValidationRequest const &vcert)
GeneratorRequestors requestors
Definition: helper.cc:52
#define ScheduleCallHere(call)
Definition: AsyncCall.h:166
static void Submit(CrtdMessage const &message, HLPCB *callback, void *data)
Submit crtd message to external crtd server.
Definition: helper.cc:123
#define CBDATA_CLASS(type)
Definition: cbdata.h:289
Definition: SBuf.h:93
static void sslCrtvdHandleReplyWrapper(void *data, const ::Helper::Reply &reply)
Definition: helper.cc:265
static void Shutdown()
Shutdown helper structure.
Definition: helper.cc:231
#define xstrdup
static void Submit(const Ssl::CertValidationRequest &, const Callback &)
Submit crtd request message to external crtd server.
Definition: helper.cc:298
const A & max(A const &lhs, A const &rhs)
Definition: cbdata.cc:37
static Pointer Make(const char *name)
Definition: helper.cc:757
SBuf query
Ssl::Helper request message (GeneratorRequests key)
Definition: helper.cc:48
void helperShutdown(const Helper::Client::Pointer &hlp)
Definition: helper.cc:769
static void Reconfigure()
Definition: helper.cc:247
static void Init()
Init helper structure.
Definition: helper.cc:76
static void Init()
Init helper structure.
Definition: helper.cc:170
void * data
Definition: cbdata.cc:78
static void Shutdown()
Shutdown helper structure.
Definition: helper.cc:107
std::string compose() const
char * strwordtok(char *buf, char **t)
Definition: String.cc:314
Definition: ClpMap.h:40
Definition: Xaction.cc:39
NotePairs notes
Definition: Reply.h:62
::Helper::ClientPointer ssl_crt_validator
helper for management of ssl_crtd.
Definition: helper.h:56
int xatoi(const char *token)
Definition: Parsing.cc:44
#define safe_free(x)
Definition: xalloc.h:73
static std::ostream & operator<<(std::ostream &os, const Ssl::GeneratorRequest &gr)
prints Ssl::GeneratorRequest for debugging
Definition: helper.cc:66
Config TheConfig
Definition: Config.cc:12
#define assert(EX)
Definition: assert.h:17
@ Okay
Definition: ResultCode.h:18
static void Reconfigure()
Definition: helper.cc:117
const char * c_str()
Definition: SBuf.cc:516
#define CBDATA_CLASS_INIT(type)
Definition: cbdata.h:325
::Helper::ClientPointer ssl_crtd
helper for management of ssl_crtd.
Definition: helper.h:37
static std::ostream & Extra(std::ostream &)
Definition: debug.cc:1316
SBuf & append(const SBuf &S)
Definition: SBuf.cc:185
#define xfree
void setCode(std::string const &aCode)
Set new request/reply code to compose.
bool parseResponse(CertValidationResponse &resp)
Parse a response message and fill the resp object with parsed information.
std::shared_ptr< SSL > SessionPointer
Definition: Session.h:53
ParseResult parse(const char *buffer, size_t len)
Definition: crtd_message.cc:23
CallbackData data
Definition: helper.cc:37
SBuf query
Definition: helper.cc:255
an std::runtime_error with thrower location info
Definition: TextException.h:20
SBuf ToSBuf(Args &&... args)
slowly stream-prints all arguments into a freshly allocated SBuf
Definition: Stream.h:63
A pending Ssl::Helper request, combining the original and collapsed queries.
Definition: helper.cc:41
#define DBG_IMPORTANT
Definition: Stream.h:38
Ssl::CertValidationHelper::Callback callback
Definition: helper.cc:259
void add(const SBuf &key, const SBuf &value)
Definition: Notes.cc:317
@ BrokenHelper
Definition: ResultCode.h:20
GeneratorRequestor(HLPCB *aCallback, void *aData)
Definition: helper.cc:35
std::unordered_map< SBuf, GeneratorRequest * > GeneratorRequests
Ssl::Helper query:GeneratorRequest map.
Definition: helper.cc:56
void HLPCB(void *, const Helper::Reply &)
Definition: forward.h:33
static CacheType * HelperCache
cache for cert validation helper
Definition: helper.h:59
const char * wordlistAdd(wordlist **list, const char *key)
Definition: wordlist.cc:25
const InstanceId< SBuf > id
Definition: SBuf.h:608
#define IPC_STREAM
Definition: defines.h:104
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Stream.h:192
void Init(void)
prepares to parse ACLs configuration
Definition: AclRegs.cc:189
void emplace(HLPCB *callback, void *data)
adds a GeneratorRequestor
Definition: helper.cc:46
const std::string & getBody() const
Current body. If parsing is not finished the method returns incompleted body.

 

Introduction

Documentation

Support

Miscellaneous