gpgv.cc 11 KB

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