File: sqv.cc

package info (click to toggle)
apt 3.1.13
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 22,764 kB
  • sloc: cpp: 71,085; sh: 31,750; xml: 5,553; perl: 217; python: 197; ansic: 191; makefile: 41
file content (418 lines) | stat: -rw-r--r-- 12,225 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#include <config.h>

#include "aptmethod.h"
#include <apt-pkg/gpgv.h>
#include <apt-pkg/strutl.h>
#include <iterator>
#include <optional>
#include <ostream>
#include <sstream>

using std::string;
using std::vector;

class SQVMethod : public aptMethod
{
   private:
   std::optional<std::string> policy{};
   void SetPolicy();
   bool VerifyGetSigners(const char *file, const char *outfile,
			 vector<string> keyFiles,
			 vector<string> &signers);
   bool ExecuteSqv(const std::vector<std::string> &args, std::vector<std::string> &signers);

   protected:
   bool URIAcquire(std::string const &Message, FetchItem *Itm) override;

   public:
   SQVMethod();
};

SQVMethod::SQVMethod() : aptMethod("sqv", "1.1", SingleInstance | SendConfig | SendURIEncoded)
{
}

void SQVMethod::SetPolicy()
{
   constexpr const char *policies[] = {
      // APT overrides
      "APT_SEQUOIA_CRYPTO_POLICY",
      "/etc/crypto-policies/back-ends/apt-sequoia.config",
      "/var/lib/crypto-config/profiles/current/apt-sequoia.config",
      // Sequoia overrides
      "SEQUOIA_CRYPTO_POLICY",
      "/etc/crypto-policies/back-ends/sequoia.config",
      "/var/lib/crypto-config/profiles/current/sequoia.config",
      // Fallback APT defaults
      "/usr/share/apt/default-sequoia.config",
   };

   if (policy)
      return;

   policy = "";

   for (auto policy : policies)
   {
      if (not strchr(policy, '/'))
      {
	 if (auto value = getenv(policy))
	 {
	    this->policy = value;
	    break;
	 }
      }
      else if (FileExists(policy))
      {
	 this->policy = policy;
	 break;
      }
   }

   if (not policy->empty())
   {
      if (DebugEnabled())
	 std::clog << "Setting SEQUOIA_CRYPTO_POLICY=" << *policy << std::endl;
      setenv("SEQUOIA_CRYPTO_POLICY", policy->c_str(), 1);
   }
}
bool SQVMethod::VerifyGetSigners(const char *file, const char *outfile,
				 vector<string> keyFiles,
				 vector<string> &signers)
{
   bool const Debug = DebugEnabled();

   std::vector<std::string> args;

   SetPolicy();

   args.push_back(SQV_EXECUTABLE);
   auto dearmorKeyOrCheckFormat = [&](std::string const &k) -> bool
   {
      _error->PushToStack();
      FileFd keyFd(k, FileFd::ReadOnly);
      _error->RevertToStack();
      if (not keyFd.IsOpen())
	 return _error->Warning("The key(s) in the keyring %s are ignored as the file is not readable by user executing gpgv.\n", k.c_str());
      else if (APT::String::Endswith(k, ".asc"))
      {
	 std::string b64msg;
	 int state = 0;
	 for (std::string line; keyFd.ReadLine(line);)
	 {
	    line = APT::String::Strip(line);
	    if (APT::String::Startswith(line, "-----BEGIN PGP PUBLIC KEY BLOCK-----"))
	       state = 1;
	    else if (state == 1 && line == "")
	       state = 2;
	    else if (state == 2 && line != "" && line[0] != '=' && line[0] != '-')
	       b64msg += line;
	    else if (APT::String::Startswith(line, "-----END"))
	       state = 3;
	 }
	 if (state != 3)
	    goto err;

	 return true;
      }
      else
      {
	 unsigned char c;
	 if (not keyFd.Read(&c, sizeof(c)))
	    goto err;
	 // Identify the leading byte of an OpenPGP public key packet
	 // 0x98 -- old-format OpenPGP public key packet, up to 255 octets
	 // 0x99 -- old-format OpenPGP public key packet, 256-65535 octets
	 // 0xc6 -- new-format OpenPGP public key packet, any length
	 if (c != 0x98 && c != 0x99 && c != 0xc6)
	    goto err;
	 return true;
      }
   err:
      return _error->Warning("The key(s) in the keyring %s are ignored as the file has an unsupported filetype.", k.c_str());
   };
   if (keyFiles.empty())
   {
      // Either trusted or trustedparts must exist
      _error->PushToStack();
      auto Parts = GetListOfFilesInDir(_config->FindDir("Dir::Etc::TrustedParts"), std::vector<std::string>{"gpg", "asc"}, true);
      if (auto trusted = _config->FindFile("Dir::Etc::Trusted"); not trusted.empty())
      {
	 std::string s;
	 strprintf(s, "Loading %s from deprecated option Dir::Etc::Trusted\n", trusted.c_str());
	 Warning(std::move(s));
	 Parts.push_back(trusted);
      }
      if (Parts.empty())
	 _error->MergeWithStack();
      else
	 _error->RevertToStack();
      for (auto &Part : Parts)
      {
	 if (Debug)
	    std::clog << "Trying TrustedPart: " << Part << std::endl;
	 if (struct stat st; stat(Part.c_str(), &st) != 0 || st.st_size == 0)
	    continue;
	 if (not dearmorKeyOrCheckFormat(Part))
	 {
	    std::string msg;
	    _error->PopMessage(msg);
	    if (not msg.empty())
	       Warning(std::move(msg));
	    continue;
	 }
	 keyFiles.push_back(Part);
      }
   }
   else
   {
      std::string buf;
      for (auto k : keyFiles)
      {
	 _error->PushToStack();
	 FileFd keyFd(k, FileFd::ReadOnly);
	 _error->RevertToStack();
	 if (keyFd.IsOpen())
	    continue;

	 strprintf(buf, "The key(s) in the keyring %s are ignored as the file is not readable by user executing gpgv.\n", k.c_str());
	 Warning(std::move(buf));
      }
   }

   if (keyFiles.empty())
      return _error->Error("The signatures couldn't be verified because no keyring is specified");

   for (auto const &keyring : keyFiles)
   {
      args.push_back("--keyring");
      args.push_back(keyring);
   }

   FileFd signatureFd;
   FileFd messageFd;
   DEFER([&]
	 {
	 if (signatureFd.IsOpen()) RemoveFile("RemoveSignature", signatureFd.Name());
	 if (messageFd.IsOpen()) RemoveFile("RemoveMessage", messageFd.Name()); });

   if (strcmp(file, outfile) == 0)
   {
      if (GetTempFile("apt.sig", false, &signatureFd) == nullptr)
	 return false;
      if (GetTempFile("apt.data", false, &messageFd) == nullptr)
	 return false;

      // FIXME: The test suite only expects the final message.
      _error->PushToStack();
      if (signatureFd.Failed() || messageFd.Failed() ||
	  not SplitClearSignedFile(file, &messageFd, nullptr, &signatureFd))
	 return _error->RevertToStack(), _error->Error("Splitting up %s into data and signature failed", file);
      _error->RevertToStack();

      args.push_back(signatureFd.Name());
      args.push_back(messageFd.Name());
   }
   else
   {
      if (not VerifyDetachedSignatureFile(file))
	 return false;
      args.push_back(file);
      args.push_back(outfile);
   }

   bool res = false;
   std::vector<std::string> aheadErrors;
   // Check the signature with a one-year-ahead policy first
   {
      _error->PushToStack();
      auto time = std::time(nullptr);
      auto tm = std::localtime(&time);
      std::string yearAheadDate;
      strprintf(yearAheadDate, "%d-%d-%d", tm->tm_year + 1900 + 1, tm->tm_mon + 1, tm->tm_mday);

      args.push_back("--policy-as-of");
      args.push_back(std::move(yearAheadDate));
      res = ExecuteSqv(args, signers);
      args.pop_back();
      args.pop_back();

      // Preserve any warnings or whatnot on success
      if (res)
	 _error->MergeWithStack();
      else
      {
	 while (not _error->empty())
	 {
	    std::string msg;
	    _error->PopMessage(msg);
	    aheadErrors.push_back(msg);
	 }
	 _error->RevertToStack();
      }
   }

   // The year-ahead-policy produced no valid signer, check if valid at current time.
   if (not res)
   {
      // clear signers, args have already been cleaned post-execution
      signers.clear();
      res = ExecuteSqv(args, signers);
      if (res)
      {
	 Warning(_("Policy will reject signature within a year, see --audit for details"));
	 for (auto &&msg : aheadErrors)
	    Audit(std::move(msg));
      }
   }
   return res;
}

bool SQVMethod::ExecuteSqv(const std::vector<std::string> &args, std::vector<std::string> &signers)
{
   bool const Debug = DebugEnabled();

   // FIXME: Use a select() loop
   FileFd sqvout;
   FileFd sqverr;
   if (GetTempFile("apt.sqvout", false, &sqvout) == nullptr)
      return "Internal error: Cannot create temporary file";

   DEFER([&]
	 { RemoveFile("CleanSQVOut", sqvout.Name()); });

   if (GetTempFile("apt.sqverr", false, &sqverr) == nullptr)
      return "Internal error: Cannot create temporary file";

   DEFER([&]
	 { RemoveFile("CleanSQVErr", sqverr.Name()); });

   // Translate the argument list to a C array. This should happen before
   // the fork so we don't allocate money between fork() and execvp().
   if (Debug)
      std::clog << "Executing " << APT::String::Join(args, " ") << std::endl;
   std::vector<const char *> cArgs;
   cArgs.reserve(args.size() + 1);
   for (auto const &arg : args)
      cArgs.push_back(arg.c_str());
   cArgs.push_back(nullptr);
   pid_t pid = ExecFork({sqvout.Fd(), sqverr.Fd()});
   if (pid < 0)
      return _error->Errno("VerifyGetSigners", "Couldn't spawn new process");
   else if (pid == 0)
   {
      dup2(sqvout.Fd(), STDOUT_FILENO);
      dup2(sqverr.Fd(), STDERR_FILENO);
      execvp(cArgs[0], (char **)&cArgs[0]);
      _exit(123);
   }

   int status;
   waitpid(pid, &status, 0);
   sqverr.Seek(0);
   sqvout.Seek(0);

   if (Debug == true)
      ioprintf(std::clog, "sqv exited with status %i\n", WEXITSTATUS(status));
   if (WEXITSTATUS(status) != 0)
   {
      std::string msg;
      for (std::string err; sqverr.ReadLine(err);)
	 msg.append(err).append("\n");
      return _error->Error(_("Sub-process %s returned an error code (%u), error message is:\n%s"), cArgs[0], WEXITSTATUS(status), msg.c_str());
   }

   for (std::string signer; sqvout.ReadLine(signer);)
   {
      if (Debug)
	 std::clog << "Got GOODSIG " << signer << std::endl;
      signers.push_back(signer);
   }

   return true;
}

static std::string GenerateKeyFile(std::string const key)
{
   FileFd fd;
   GetTempFile("apt-key.XXXXXX.asc", false, &fd);
   fd.Write(key.data(), key.size());
   return fd.Name();
}

bool SQVMethod::URIAcquire(std::string const &Message, FetchItem *Itm)
{
   // Quick safety check: do we have left-over errors from a previous URL?
   if (unlikely(_error->PendingError()))
      return _error->Error("Internal error: Error set at start of verification");

   URI const Get(Itm->Uri);
   std::string const Path = DecodeSendURI(Get.Host + Get.Path); // To account for relative paths

   std::vector<std::string> Signers, keyFpts, keyFiles;
   struct TemporaryFile
   {
      std::string name = "";
      ~TemporaryFile() { RemoveFile("~TemporaryFile", name); }
   } tmpKey;

   std::string SignedBy = DeQuoteString(LookupTag(Message, "Signed-By"));

   if (SignedBy.find("-----BEGIN PGP PUBLIC KEY BLOCK-----") != std::string::npos)
   {
      tmpKey.name = GenerateKeyFile(SignedBy);
      keyFiles.emplace_back(tmpKey.name);
   }
   else
   {
      for (auto &&key : VectorizeString(SignedBy, ','))
	 if (key.empty() == false && key[0] == '/')
	    keyFiles.emplace_back(std::move(key));
	 else
	    keyFpts.emplace_back(std::move(key));
   }

   // Nothing should have failed here in the setup, if it did, don't bother verifying
   if (_error->PendingError())
      return false;

   // Run sqv on file, extract contents and get the key ID of the signer
   VerifyGetSigners(Path.c_str(), Itm->DestFile.c_str(), keyFiles, Signers);
   if (Signers.empty())
      return _error->PendingError() ? false : _error->Error("No good signature");

   if (not keyFpts.empty())
   {
      Signers.erase(std::remove_if(Signers.begin(), Signers.end(), [&](std::string const &signer)
				   {
	 bool allowedSigner = std::find(keyFpts.begin(), keyFpts.end(), signer) != keyFpts.end();
	 if (not allowedSigner && DebugEnabled())
	       std::cerr << "NoPubKey: GOODSIG " << signer << "\n";
	 return not allowedSigner; }),
		    Signers.end());

      if (Signers.empty())
      {
	 if (keyFpts.size() > 1)
	    return _error->Error(_("No good signature from required signers: %s"), APT::String::Join(keyFpts, ", ").c_str());
	 return _error->Error(_("No good signature from required signer: %s"), APT::String::Join(keyFpts, ", ").c_str());
      }
   }
   std::unordered_map<std::string, std::string> fields;
   fields.emplace("URI", Itm->Uri);
   fields.emplace("Filename", Itm->DestFile);
   fields.emplace("Signed-By", APT::String::Join(Signers, "\n"));
   SendMessage("201 URI Done", std::move(fields));
   Dequeue();

   if (DebugEnabled())
      std::clog << "sqv succeeded\n";

   // If we have a pending error somehow, we should still fail here...
   return not _error->PendingError();
}

int main()
{
   return SQVMethod().Run();
}