]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/gpgv.cc
warn if clearsigned file has ignored content parts
[apt.git] / apt-pkg / contrib / gpgv.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Include Files /*{{{*/
3 #include<config.h>
4
5 #include<apt-pkg/configuration.h>
6 #include<apt-pkg/error.h>
7 #include<apt-pkg/strutl.h>
8 #include<apt-pkg/fileutl.h>
9 #include<apt-pkg/gpgv.h>
10
11 #include <errno.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <fcntl.h>
16 #include <sys/wait.h>
17 #include <unistd.h>
18 #include <stddef.h>
19
20 #include <algorithm>
21 #include <fstream>
22 #include <iostream>
23 #include <sstream>
24 #include <string>
25 #include <vector>
26
27 #include <apti18n.h>
28 /*}}}*/
29 static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
30 {
31 std::string out;
32 std::string tmpdir = GetTempDir();
33 strprintf(out, "%s/%s.XXXXXX", tmpdir.c_str(), basename);
34 return strdup(out.c_str());
35 }
36 /*}}}*/
37 // ExecGPGV - returns the command needed for verify /*{{{*/
38 // ---------------------------------------------------------------------
39 /* Generating the commandline for calling gpg is somehow complicated as
40 we need to add multiple keyrings and user supplied options.
41 Also, as gpg has no options to enforce a certain reduced style of
42 clear-signed files (=the complete content of the file is signed and
43 the content isn't encoded) we do a divide and conquer approach here
44 and split up the clear-signed file in message and signature for gpg.
45 And as a cherry on the cake, we use our apt-key wrapper to do part
46 of the lifting in regards to merging keyrings. Fun for the whole family.
47 */
48 static bool iovprintf(std::ostream &out, const char *format,
49 va_list &args, ssize_t &size) {
50 char *S = (char*)malloc(size);
51 ssize_t const n = vsnprintf(S, size, format, args);
52 if (n > -1 && n < size) {
53 out << S;
54 free(S);
55 return true;
56 } else {
57 if (n > -1)
58 size = n + 1;
59 else
60 size *= 2;
61 }
62 free(S);
63 return false;
64 }
65 static void APT_PRINTF(4) apt_error(std::ostream &outterm, int const statusfd, int fd[2], const char *format, ...)
66 {
67 std::ostringstream outstr;
68 std::ostream &out = (statusfd == -1) ? outterm : outstr;
69 va_list args;
70 ssize_t size = 400;
71 while (true) {
72 bool ret;
73 va_start(args,format);
74 ret = iovprintf(out, format, args, size);
75 va_end(args);
76 if (ret == true)
77 break;
78 }
79 if (statusfd != -1)
80 {
81 auto const errtag = "[APTKEY:] ERROR ";
82 outstr << '\n';
83 auto const errtext = outstr.str();
84 if (FileFd::Write(fd[1], errtag, strlen(errtag)) == false ||
85 FileFd::Write(fd[1], errtext.data(), errtext.size()) == false)
86 outterm << errtext << std::flush;
87 }
88 }
89 void ExecGPGV(std::string const &File, std::string const &FileGPG,
90 int const &statusfd, int fd[2], std::string const &key)
91 {
92 #define EINTERNAL 111
93 std::string const aptkey = _config->Find("Dir::Bin::apt-key", CMAKE_INSTALL_FULL_BINDIR "/apt-key");
94
95 bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
96 struct exiter {
97 std::vector<const char *> files;
98 void operator ()(int code) APT_NORETURN {
99 std::for_each(files.begin(), files.end(), unlink);
100 exit(code);
101 }
102 } local_exit;
103
104
105 std::vector<const char *> Args;
106 Args.reserve(10);
107
108 Args.push_back(aptkey.c_str());
109 Args.push_back("--quiet");
110 Args.push_back("--readonly");
111 if (key.empty() == false)
112 {
113 if (key[0] == '/')
114 {
115 Args.push_back("--keyring");
116 Args.push_back(key.c_str());
117 }
118 else
119 {
120 Args.push_back("--keyid");
121 Args.push_back(key.c_str());
122 }
123 }
124 Args.push_back("verify");
125
126 char statusfdstr[10];
127 if (statusfd != -1)
128 {
129 Args.push_back("--status-fd");
130 snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
131 Args.push_back(statusfdstr);
132 }
133
134 Configuration::Item const *Opts;
135 Opts = _config->Tree("Acquire::gpgv::Options");
136 if (Opts != 0)
137 {
138 Opts = Opts->Child;
139 for (; Opts != 0; Opts = Opts->Next)
140 {
141 if (Opts->Value.empty() == true)
142 continue;
143 Args.push_back(Opts->Value.c_str());
144 }
145 }
146
147 enum { DETACHED, CLEARSIGNED } releaseSignature = (FileGPG != File) ? DETACHED : CLEARSIGNED;
148 char * sig = NULL;
149 char * data = NULL;
150 char * conf = nullptr;
151
152 // Dump the configuration so apt-key picks up the correct Dir values
153 {
154 conf = GenerateTemporaryFileTemplate("apt.conf");
155 if (conf == nullptr) {
156 apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for passing config to apt-key");
157 local_exit(EINTERNAL);
158 }
159 int confFd = mkstemp(conf);
160 if (confFd == -1) {
161 apt_error(std::cerr, statusfd, fd, "Couldn't create temporary file %s for passing config to apt-key", conf);
162 local_exit(EINTERNAL);
163 }
164 local_exit.files.push_back(conf);
165
166 std::ofstream confStream(conf);
167 close(confFd);
168 _config->Dump(confStream);
169 confStream.close();
170 setenv("APT_CONFIG", conf, 1);
171 }
172
173 if (releaseSignature == DETACHED)
174 {
175 Args.push_back(FileGPG.c_str());
176 Args.push_back(File.c_str());
177 }
178 else // clear-signed file
179 {
180 sig = GenerateTemporaryFileTemplate("apt.sig");
181 data = GenerateTemporaryFileTemplate("apt.data");
182 if (sig == NULL || data == NULL)
183 {
184 apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for splitting up %s", File.c_str());
185 local_exit(EINTERNAL);
186 }
187
188 int const sigFd = mkstemp(sig);
189 int const dataFd = mkstemp(data);
190 if (dataFd != -1)
191 local_exit.files.push_back(data);
192 if (sigFd != -1)
193 local_exit.files.push_back(sig);
194 if (sigFd == -1 || dataFd == -1)
195 {
196 apt_error(std::cerr, statusfd, fd, "Couldn't create tempfiles for splitting up %s", File.c_str());
197 local_exit(EINTERNAL);
198 }
199
200 FileFd signature;
201 signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
202 FileFd message;
203 message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
204
205 if (signature.Failed() == true || message.Failed() == true ||
206 SplitClearSignedFile(File, &message, nullptr, &signature) == false)
207 {
208 apt_error(std::cerr, statusfd, fd, "Splitting up %s into data and signature failed", File.c_str());
209 local_exit(112);
210 }
211 Args.push_back(sig);
212 Args.push_back(data);
213 }
214
215 Args.push_back(NULL);
216
217 if (Debug == true)
218 {
219 std::clog << "Preparing to exec: ";
220 for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
221 std::clog << " " << *a;
222 std::clog << std::endl;
223 }
224
225 if (statusfd != -1)
226 {
227 int const nullfd = open("/dev/null", O_WRONLY);
228 close(fd[0]);
229 // Redirect output to /dev/null; we read from the status fd
230 if (statusfd != STDOUT_FILENO)
231 dup2(nullfd, STDOUT_FILENO);
232 if (statusfd != STDERR_FILENO)
233 dup2(nullfd, STDERR_FILENO);
234 // Redirect the pipe to the status fd (3)
235 dup2(fd[1], statusfd);
236
237 putenv((char *)"LANG=");
238 putenv((char *)"LC_ALL=");
239 putenv((char *)"LC_MESSAGES=");
240 }
241
242
243 // We have created tempfiles we have to clean up
244 // and we do an additional check, so fork yet another time …
245 pid_t pid = ExecFork();
246 if(pid < 0) {
247 apt_error(std::cerr, statusfd, fd, "Fork failed for %s to check %s", Args[0], File.c_str());
248 local_exit(EINTERNAL);
249 }
250 if(pid == 0)
251 {
252 if (statusfd != -1)
253 dup2(fd[1], statusfd);
254 execvp(Args[0], (char **) &Args[0]);
255 apt_error(std::cerr, statusfd, fd, "Couldn't execute %s to check %s", Args[0], File.c_str());
256 local_exit(EINTERNAL);
257 }
258
259 // Wait and collect the error code - taken from WaitPid as we need the exact Status
260 int Status;
261 while (waitpid(pid,&Status,0) != pid)
262 {
263 if (errno == EINTR)
264 continue;
265 apt_error(std::cerr, statusfd, fd, _("Waited for %s but it wasn't there"), "apt-key");
266 local_exit(EINTERNAL);
267 }
268
269 // check if it exit'ed normally …
270 if (WIFEXITED(Status) == false)
271 {
272 apt_error(std::cerr, statusfd, fd, _("Sub-process %s exited unexpectedly"), "apt-key");
273 local_exit(EINTERNAL);
274 }
275
276 // … and with a good exit code
277 if (WEXITSTATUS(Status) != 0)
278 {
279 // we forward the statuscode, so don't generate a message on the fd in this case
280 apt_error(std::cerr, -1, fd, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
281 local_exit(WEXITSTATUS(Status));
282 }
283
284 // everything fine
285 local_exit(0);
286 }
287 /*}}}*/
288 // SplitClearSignedFile - split message into data/signature /*{{{*/
289 static int GetLineErrno(char **lineptr, size_t *n, FILE *stream, std::string const &InFile)
290 {
291 int result;
292
293 errno = 0;
294 result = getline(lineptr, n, stream);
295 if (errno != 0)
296 {
297 _error->Errno("getline", "Could not read from %s", InFile.c_str());
298 return -1;
299 }
300
301 return result;
302 }
303 bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
304 std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
305 {
306 FILE *in = fopen(InFile.c_str(), "r");
307 if (in == NULL)
308 return _error->Errno("fopen", "can not open %s", InFile.c_str());
309
310 bool found_message_start = false;
311 bool found_message_end = false;
312 bool skip_until_empty_line = false;
313 bool found_signature = false;
314 bool first_line = true;
315 bool signed_message_not_on_first_line = false;
316 bool found_garbage = false;
317
318 char *buf = NULL;
319 size_t buf_size = 0;
320 _error->PushToStack();
321 while (GetLineErrno(&buf, &buf_size, in, InFile) != -1)
322 {
323 _strrstrip(buf);
324 if (found_message_start == false)
325 {
326 if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
327 {
328 found_message_start = true;
329 skip_until_empty_line = true;
330 }
331 else
332 signed_message_not_on_first_line = found_garbage = true;
333 }
334 else if (skip_until_empty_line == true)
335 {
336 if (strlen(buf) == 0)
337 skip_until_empty_line = false;
338 // save "Hash" Armor Headers, others aren't allowed
339 else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
340 ContentHeader->push_back(buf);
341 }
342 else if (found_signature == false)
343 {
344 if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
345 {
346 found_signature = true;
347 found_message_end = true;
348 if (SignatureFile != NULL)
349 {
350 SignatureFile->Write(buf, strlen(buf));
351 SignatureFile->Write("\n", 1);
352 }
353 }
354 else if (found_message_end == false) // we are in the message block
355 {
356 // we don't have any fields which need dash-escaped,
357 // but implementations are free to encode all lines …
358 char const * dashfree = buf;
359 if (strncmp(dashfree, "- ", 2) == 0)
360 dashfree += 2;
361 if(first_line == true) // first line does not need a newline
362 first_line = false;
363 else if (ContentFile != NULL)
364 ContentFile->Write("\n", 1);
365 else
366 continue;
367 if (ContentFile != NULL)
368 ContentFile->Write(dashfree, strlen(dashfree));
369 }
370 else
371 found_garbage = true;
372 }
373 else if (found_signature == true)
374 {
375 if (SignatureFile != NULL)
376 {
377 SignatureFile->Write(buf, strlen(buf));
378 SignatureFile->Write("\n", 1);
379 }
380 if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
381 found_signature = false; // look for other signatures
382 }
383 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
384 else
385 found_garbage = true;
386 }
387 fclose(in);
388 if (buf != NULL)
389 free(buf);
390
391 // Flush the files. Errors will be checked below.
392 if (SignatureFile != nullptr)
393 SignatureFile->Flush();
394 if (ContentFile != nullptr)
395 ContentFile->Flush();
396
397 if (found_message_start)
398 {
399 if (signed_message_not_on_first_line)
400 _error->Warning("Clearsigned file '%s' does not start with a signed message block.", InFile.c_str());
401 else if (found_garbage)
402 _error->Warning("Clearsigned file '%s' contains unsigned lines.", InFile.c_str());
403 }
404
405 // An error occured during reading - propagate it up
406 bool const hasErrored = _error->PendingError();
407 _error->MergeWithStack();
408 if (hasErrored)
409 return false;
410
411 if (found_signature == true)
412 return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
413
414 // if we haven't found any of them, this an unsigned file,
415 // so don't generate an error, but splitting was unsuccessful none-the-less
416 if (first_line == true && found_message_start == false && found_message_end == false)
417 return false;
418 // otherwise one missing indicates a syntax error
419 else if (first_line == true || found_message_start == false || found_message_end == false)
420 return _error->Error("Splitting of file %s failed as it doesn't contain all expected parts %i %i %i", InFile.c_str(), first_line, found_message_start, found_message_end);
421
422 return true;
423 }
424 /*}}}*/
425 bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
426 {
427 char * const message = GenerateTemporaryFileTemplate("fileutl.message");
428 int const messageFd = mkstemp(message);
429 if (messageFd == -1)
430 {
431 free(message);
432 return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
433 }
434 // we have the fd, thats enough for us
435 unlink(message);
436 free(message);
437
438 MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
439 if (MessageFile.Failed() == true)
440 return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
441
442 _error->PushToStack();
443 bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
444 bool const errorDone = _error->PendingError();
445 _error->MergeWithStack();
446 if (splitDone == false)
447 {
448 MessageFile.Close();
449
450 if (errorDone == true)
451 return false;
452
453 // we deal with an unsigned file
454 MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
455 }
456 else // clear-signed
457 {
458 if (MessageFile.Seek(0) == false)
459 return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
460 }
461
462 return MessageFile.Failed() == false;
463 }
464 /*}}}*/