gpgv.cc 12 KB

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