]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/gpgv.cc
8f619fee2ce67d7b54da98742cd4ebeaf203b9a9
[apt.git] / apt-pkg / contrib / gpgv.cc
1 // -*- mode: cpp; mode: fold -*-
2 // Include Files /*{{{*/
3 #include<config.h>
4
5 #include <errno.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <fcntl.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <unistd.h>
14
15 #include<apt-pkg/configuration.h>
16 #include<apt-pkg/error.h>
17 #include<apt-pkg/strutl.h>
18 #include<apt-pkg/fileutl.h>
19 #include<apt-pkg/gpgv.h>
20
21 #include <apti18n.h>
22 /*}}}*/
23 static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
24 {
25 const char *tmpdir = getenv("TMPDIR");
26
27 #ifdef P_tmpdir
28 if (!tmpdir)
29 tmpdir = P_tmpdir;
30 #endif
31
32 // check that tmpdir is set and exists
33 struct stat st;
34 if (!tmpdir || stat(tmpdir, &st) != 0)
35 tmpdir = "/tmp";
36
37 std::string out;
38 strprintf(out, "%s/%s.XXXXXX", tmpdir, basename);
39 return strdup(out.c_str());
40 }
41 /*}}}*/
42 // ExecGPGV - returns the command needed for verify /*{{{*/
43 // ---------------------------------------------------------------------
44 /* Generating the commandline for calling gpgv is somehow complicated as
45 we need to add multiple keyrings and user supplied options.
46 Also, as gpgv has no options to enforce a certain reduced style of
47 clear-signed files (=the complete content of the file is signed and
48 the content isn't encoded) we do a divide and conquer approach here
49 and split up the clear-signed file in message and signature for gpgv
50 */
51 void ExecGPGV(std::string const &File, std::string const &FileGPG,
52 int const &statusfd, int fd[2])
53 {
54 #define EINTERNAL 111
55 std::string const gpgvpath = _config->Find("Dir::Bin::gpg", "/usr/bin/gpgv");
56 // FIXME: remove support for deprecated APT::GPGV setting
57 std::string const trustedFile = _config->Find("APT::GPGV::TrustedKeyring", _config->FindFile("Dir::Etc::Trusted"));
58 std::string const trustedPath = _config->FindDir("Dir::Etc::TrustedParts");
59
60 bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
61
62 if (Debug == true)
63 {
64 std::clog << "gpgv path: " << gpgvpath << std::endl;
65 std::clog << "Keyring file: " << trustedFile << std::endl;
66 std::clog << "Keyring path: " << trustedPath << std::endl;
67 }
68
69 std::vector<std::string> keyrings;
70 if (DirectoryExists(trustedPath))
71 keyrings = GetListOfFilesInDir(trustedPath, "gpg", false, true);
72 if (RealFileExists(trustedFile) == true)
73 keyrings.push_back(trustedFile);
74
75 std::vector<const char *> Args;
76 Args.reserve(30);
77
78 if (keyrings.empty() == true)
79 {
80 // TRANSLATOR: %s is the trusted keyring parts directory
81 ioprintf(std::cerr, _("No keyring installed in %s."),
82 _config->FindDir("Dir::Etc::TrustedParts").c_str());
83 exit(EINTERNAL);
84 }
85
86 Args.push_back(gpgvpath.c_str());
87 Args.push_back("--ignore-time-conflict");
88
89 char statusfdstr[10];
90 if (statusfd != -1)
91 {
92 Args.push_back("--status-fd");
93 snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
94 Args.push_back(statusfdstr);
95 }
96
97 for (std::vector<std::string>::const_iterator K = keyrings.begin();
98 K != keyrings.end(); ++K)
99 {
100 Args.push_back("--keyring");
101 Args.push_back(K->c_str());
102 }
103
104 Configuration::Item const *Opts;
105 Opts = _config->Tree("Acquire::gpgv::Options");
106 if (Opts != 0)
107 {
108 Opts = Opts->Child;
109 for (; Opts != 0; Opts = Opts->Next)
110 {
111 if (Opts->Value.empty() == true)
112 continue;
113 Args.push_back(Opts->Value.c_str());
114 }
115 }
116
117 std::vector<std::string> dataHeader;
118 char * sig = NULL;
119 char * data = NULL;
120
121 // file with detached signature
122 if (FileGPG != File)
123 {
124 Args.push_back(FileGPG.c_str());
125 Args.push_back(File.c_str());
126 }
127 else // clear-signed file
128 {
129 sig = GenerateTemporaryFileTemplate("apt.sig");
130 data = GenerateTemporaryFileTemplate("apt.data");
131 if (sig == NULL || data == NULL)
132 {
133 ioprintf(std::cerr, "Couldn't create tempfile names for splitting up %s", File.c_str());
134 exit(EINTERNAL);
135 }
136
137 int const sigFd = mkstemp(sig);
138 int const dataFd = mkstemp(data);
139 if (sigFd == -1 || dataFd == -1)
140 {
141 if (dataFd != -1)
142 unlink(sig);
143 if (sigFd != -1)
144 unlink(data);
145 ioprintf(std::cerr, "Couldn't create tempfiles for splitting up %s", File.c_str());
146 exit(EINTERNAL);
147 }
148
149 FileFd signature;
150 signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
151 FileFd message;
152 message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
153
154 if (signature.Failed() == true || message.Failed() == true ||
155 SplitClearSignedFile(File, &message, &dataHeader, &signature) == false)
156 {
157 if (dataFd != -1)
158 unlink(sig);
159 if (sigFd != -1)
160 unlink(data);
161 ioprintf(std::cerr, "Splitting up %s into data and signature failed", File.c_str());
162 exit(112);
163 }
164 Args.push_back(sig);
165 Args.push_back(data);
166 }
167
168 Args.push_back(NULL);
169
170 if (Debug == true)
171 {
172 std::clog << "Preparing to exec: " << gpgvpath;
173 for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
174 std::clog << " " << *a;
175 std::clog << std::endl;
176 }
177
178 if (statusfd != -1)
179 {
180 int const nullfd = open("/dev/null", O_RDONLY);
181 close(fd[0]);
182 // Redirect output to /dev/null; we read from the status fd
183 if (statusfd != STDOUT_FILENO)
184 dup2(nullfd, STDOUT_FILENO);
185 if (statusfd != STDERR_FILENO)
186 dup2(nullfd, STDERR_FILENO);
187 // Redirect the pipe to the status fd (3)
188 dup2(fd[1], statusfd);
189
190 putenv((char *)"LANG=");
191 putenv((char *)"LC_ALL=");
192 putenv((char *)"LC_MESSAGES=");
193 }
194
195 if (FileGPG != File)
196 {
197 execvp(gpgvpath.c_str(), (char **) &Args[0]);
198 ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
199 exit(EINTERNAL);
200 }
201 else
202 {
203 //#define UNLINK_EXIT(X) exit(X)
204 #define UNLINK_EXIT(X) unlink(sig);unlink(data);exit(X)
205
206 // for clear-signed files we have created tempfiles we have to clean up
207 // and we do an additional check, so fork yet another time …
208 pid_t pid = ExecFork();
209 if(pid < 0) {
210 ioprintf(std::cerr, "Fork failed for %s to check %s", Args[0], File.c_str());
211 UNLINK_EXIT(EINTERNAL);
212 }
213 if(pid == 0)
214 {
215 if (statusfd != -1)
216 dup2(fd[1], statusfd);
217 execvp(gpgvpath.c_str(), (char **) &Args[0]);
218 ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
219 UNLINK_EXIT(EINTERNAL);
220 }
221
222 // Wait and collect the error code - taken from WaitPid as we need the exact Status
223 int Status;
224 while (waitpid(pid,&Status,0) != pid)
225 {
226 if (errno == EINTR)
227 continue;
228 ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "gpgv");
229 UNLINK_EXIT(EINTERNAL);
230 }
231 #undef UNLINK_EXIT
232 // we don't need the files any longer
233 unlink(sig);
234 unlink(data);
235 free(sig);
236 free(data);
237
238 // check if it exit'ed normally …
239 if (WIFEXITED(Status) == false)
240 {
241 ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "gpgv");
242 exit(EINTERNAL);
243 }
244
245 // … and with a good exit code
246 if (WEXITSTATUS(Status) != 0)
247 {
248 ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "gpgv", WEXITSTATUS(Status));
249 exit(WEXITSTATUS(Status));
250 }
251
252 // everything fine
253 exit(0);
254 }
255 exit(EINTERNAL); // unreachable safe-guard
256 }
257 /*}}}*/
258 // SplitClearSignedFile - split message into data/signature /*{{{*/
259 bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
260 std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
261 {
262 FILE *in = fopen(InFile.c_str(), "r");
263 if (in == NULL)
264 return _error->Errno("fopen", "can not open %s", InFile.c_str());
265
266 bool found_message_start = false;
267 bool found_message_end = false;
268 bool skip_until_empty_line = false;
269 bool found_signature = false;
270 bool first_line = true;
271
272 char *buf = NULL;
273 size_t buf_size = 0;
274 ssize_t line_len = 0;
275 while ((line_len = getline(&buf, &buf_size, in)) != -1)
276 {
277 _strrstrip(buf);
278 if (found_message_start == false)
279 {
280 if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
281 {
282 found_message_start = true;
283 skip_until_empty_line = true;
284 }
285 }
286 else if (skip_until_empty_line == true)
287 {
288 if (strlen(buf) == 0)
289 skip_until_empty_line = false;
290 // save "Hash" Armor Headers, others aren't allowed
291 else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
292 ContentHeader->push_back(buf);
293 }
294 else if (found_signature == false)
295 {
296 if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
297 {
298 found_signature = true;
299 found_message_end = true;
300 if (SignatureFile != NULL)
301 {
302 SignatureFile->Write(buf, strlen(buf));
303 SignatureFile->Write("\n", 1);
304 }
305 }
306 else if (found_message_end == false) // we are in the message block
307 {
308 // we don't have any fields which need dash-escaped,
309 // but implementations are free to encode all lines …
310 char const * dashfree = buf;
311 if (strncmp(dashfree, "- ", 2) == 0)
312 dashfree += 2;
313 if(first_line == true) // first line does not need a newline
314 first_line = false;
315 else if (ContentFile != NULL)
316 ContentFile->Write("\n", 1);
317 else
318 continue;
319 if (ContentFile != NULL)
320 ContentFile->Write(dashfree, strlen(dashfree));
321 }
322 }
323 else if (found_signature == true)
324 {
325 if (SignatureFile != NULL)
326 {
327 SignatureFile->Write(buf, strlen(buf));
328 SignatureFile->Write("\n", 1);
329 }
330 if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
331 found_signature = false; // look for other signatures
332 }
333 // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
334 }
335 fclose(in);
336
337 if (found_signature == true)
338 return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
339
340 // if we haven't found any of them, this an unsigned file,
341 // so don't generate an error, but splitting was unsuccessful none-the-less
342 if (first_line == true && found_message_start == false && found_message_end == false)
343 return false;
344 // otherwise one missing indicates a syntax error
345 else if (first_line == true || found_message_start == false || found_message_end == false)
346 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);
347
348 return true;
349 }
350 /*}}}*/
351 bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
352 {
353 char * const message = GenerateTemporaryFileTemplate("fileutl.message");
354 int const messageFd = mkstemp(message);
355 if (messageFd == -1)
356 {
357 free(message);
358 return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
359 }
360 // we have the fd, thats enough for us
361 unlink(message);
362 free(message);
363
364 MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite, true);
365 if (MessageFile.Failed() == true)
366 return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
367
368 _error->PushToStack();
369 bool const splitDone = SplitClearSignedFile(ClearSignedFileName.c_str(), &MessageFile, NULL, NULL);
370 bool const errorDone = _error->PendingError();
371 _error->MergeWithStack();
372 if (splitDone == false)
373 {
374 MessageFile.Close();
375
376 if (errorDone == true)
377 return false;
378
379 // we deal with an unsigned file
380 MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
381 }
382 else // clear-signed
383 {
384 if (MessageFile.Seek(0) == false)
385 return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
386 }
387
388 return MessageFile.Failed() == false;
389 }
390 /*}}}*/