gpgv.cc 12 KB

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