gpgv.cc 11 KB

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