You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gpgv.cc 16 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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/fileutl.h>
  7. #include <apt-pkg/gpgv.h>
  8. #include <apt-pkg/strutl.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <stddef.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <sys/wait.h>
  16. #include <unistd.h>
  17. #include <algorithm>
  18. #include <fstream>
  19. #include <iostream>
  20. #include <memory>
  21. #include <sstream>
  22. #include <string>
  23. #include <vector>
  24. #include <apti18n.h>
  25. /*}}}*/
  26. static bool GetLineErrno(std::unique_ptr<char, decltype(&free)> &buffer, size_t *n, FILE *stream, std::string const &InFile, bool acceptEoF = false)/*{{{*/
  27. {
  28. errno = 0;
  29. auto lineptr = buffer.release();
  30. auto const result = getline(&lineptr, n, stream);
  31. buffer.reset(lineptr);
  32. if (errno != 0)
  33. return _error->Errno("getline", "Could not read from %s", InFile.c_str());
  34. if (result == -1)
  35. {
  36. if (acceptEoF)
  37. return false;
  38. return _error->Error("Splitting of clearsigned file %s failed as it doesn't contain all expected parts", InFile.c_str());
  39. }
  40. // We remove all whitespaces including newline here as
  41. // a) gpgv ignores them for signature
  42. // b) we can write out a \n in code later instead of dealing with \r\n or not
  43. _strrstrip(buffer.get());
  44. return true;
  45. }
  46. /*}}}*/
  47. static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
  48. {
  49. std::string out;
  50. std::string tmpdir = GetTempDir();
  51. strprintf(out, "%s/%s.XXXXXX", tmpdir.c_str(), basename);
  52. return strdup(out.c_str());
  53. }
  54. /*}}}*/
  55. // ExecGPGV - returns the command needed for verify /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* Generating the commandline for calling gpg is somehow complicated as
  58. we need to add multiple keyrings and user supplied options.
  59. Also, as gpg has no options to enforce a certain reduced style of
  60. clear-signed files (=the complete content of the file is signed and
  61. the content isn't encoded) we do a divide and conquer approach here
  62. and split up the clear-signed file in message and signature for gpg.
  63. And as a cherry on the cake, we use our apt-key wrapper to do part
  64. of the lifting in regards to merging keyrings. Fun for the whole family.
  65. */
  66. static bool iovprintf(std::ostream &out, const char *format,
  67. va_list &args, ssize_t &size) {
  68. char *S = (char*)malloc(size);
  69. ssize_t const n = vsnprintf(S, size, format, args);
  70. if (n > -1 && n < size) {
  71. out << S;
  72. free(S);
  73. return true;
  74. } else {
  75. if (n > -1)
  76. size = n + 1;
  77. else
  78. size *= 2;
  79. }
  80. free(S);
  81. return false;
  82. }
  83. static void APT_PRINTF(4) apt_error(std::ostream &outterm, int const statusfd, int fd[2], const char *format, ...)
  84. {
  85. std::ostringstream outstr;
  86. std::ostream &out = (statusfd == -1) ? outterm : outstr;
  87. va_list args;
  88. ssize_t size = 400;
  89. while (true) {
  90. bool ret;
  91. va_start(args,format);
  92. ret = iovprintf(out, format, args, size);
  93. va_end(args);
  94. if (ret == true)
  95. break;
  96. }
  97. if (statusfd != -1)
  98. {
  99. auto const errtag = "[APTKEY:] ERROR ";
  100. outstr << '\n';
  101. auto const errtext = outstr.str();
  102. if (FileFd::Write(fd[1], errtag, strlen(errtag)) == false ||
  103. FileFd::Write(fd[1], errtext.data(), errtext.size()) == false)
  104. outterm << errtext << std::flush;
  105. }
  106. }
  107. void ExecGPGV(std::string const &File, std::string const &FileGPG,
  108. int const &statusfd, int fd[2], std::string const &key)
  109. {
  110. #define EINTERNAL 111
  111. std::string const aptkey = _config->Find("Dir::Bin::apt-key", CMAKE_INSTALL_FULL_BINDIR "/apt-key");
  112. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  113. struct exiter {
  114. std::vector<const char *> files;
  115. void operator ()(int code) APT_NORETURN {
  116. std::for_each(files.begin(), files.end(), unlink);
  117. exit(code);
  118. }
  119. } local_exit;
  120. std::vector<const char *> Args;
  121. Args.reserve(10);
  122. Args.push_back(aptkey.c_str());
  123. Args.push_back("--quiet");
  124. Args.push_back("--readonly");
  125. auto const keysFileFpr = VectorizeString(key, ',');
  126. for (auto const &k: keysFileFpr)
  127. {
  128. if (unlikely(k.empty()))
  129. continue;
  130. if (k[0] == '/')
  131. {
  132. Args.push_back("--keyring");
  133. Args.push_back(k.c_str());
  134. }
  135. else
  136. {
  137. Args.push_back("--keyid");
  138. Args.push_back(k.c_str());
  139. }
  140. }
  141. Args.push_back("verify");
  142. char statusfdstr[10];
  143. if (statusfd != -1)
  144. {
  145. Args.push_back("--status-fd");
  146. snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
  147. Args.push_back(statusfdstr);
  148. }
  149. Configuration::Item const *Opts;
  150. Opts = _config->Tree("Acquire::gpgv::Options");
  151. if (Opts != 0)
  152. {
  153. Opts = Opts->Child;
  154. for (; Opts != 0; Opts = Opts->Next)
  155. {
  156. if (Opts->Value.empty() == true)
  157. continue;
  158. Args.push_back(Opts->Value.c_str());
  159. }
  160. }
  161. enum { DETACHED, CLEARSIGNED } releaseSignature = (FileGPG != File) ? DETACHED : CLEARSIGNED;
  162. char * sig = NULL;
  163. char * data = NULL;
  164. char * conf = nullptr;
  165. // Dump the configuration so apt-key picks up the correct Dir values
  166. {
  167. conf = GenerateTemporaryFileTemplate("apt.conf");
  168. if (conf == nullptr) {
  169. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for passing config to apt-key");
  170. local_exit(EINTERNAL);
  171. }
  172. int confFd = mkstemp(conf);
  173. if (confFd == -1) {
  174. apt_error(std::cerr, statusfd, fd, "Couldn't create temporary file %s for passing config to apt-key", conf);
  175. local_exit(EINTERNAL);
  176. }
  177. local_exit.files.push_back(conf);
  178. std::ofstream confStream(conf);
  179. close(confFd);
  180. _config->Dump(confStream);
  181. confStream.close();
  182. setenv("APT_CONFIG", conf, 1);
  183. }
  184. if (releaseSignature == DETACHED)
  185. {
  186. std::unique_ptr<FILE, decltype(&fclose)> detached{fopen(FileGPG.c_str(), "r"), &fclose};
  187. if (detached.get() == nullptr)
  188. {
  189. apt_error(std::cerr, statusfd, fd, "Detached signature file '%s' could not be opened", FileGPG.c_str());
  190. local_exit(EINTERNAL);
  191. }
  192. std::unique_ptr<char, decltype(&free)> buf{nullptr, &free};
  193. size_t buf_size = 0;
  194. bool open_signature = false;
  195. bool found_badcontent = false;
  196. size_t found_signatures = 0;
  197. while (GetLineErrno(buf, &buf_size, detached.get(), FileGPG, true))
  198. {
  199. if (open_signature && strcmp(buf.get(), "-----END PGP SIGNATURE-----") == 0)
  200. open_signature = false;
  201. else if (open_signature == false && strcmp(buf.get(), "-----BEGIN PGP SIGNATURE-----") == 0)
  202. {
  203. open_signature = true;
  204. ++found_signatures;
  205. }
  206. else if (open_signature == false)
  207. found_badcontent = true;
  208. }
  209. if (found_signatures == 0 && statusfd != -1)
  210. {
  211. // This is not an attack attempt but a file even gpgv would complain about
  212. // likely the result of a paywall which is covered by the gpgv method
  213. auto const errtag = "[GNUPG:] NODATA\n";
  214. FileFd::Write(fd[1], errtag, strlen(errtag));
  215. local_exit(113);
  216. }
  217. else if (found_badcontent)
  218. {
  219. apt_error(std::cerr, statusfd, fd, "Detached signature file '%s' contains lines not belonging to a signature", FileGPG.c_str());
  220. local_exit(112);
  221. }
  222. if (open_signature == true)
  223. {
  224. apt_error(std::cerr, statusfd, fd, "Detached signature file '%s' contains unclosed signatures", FileGPG.c_str());
  225. local_exit(112);
  226. }
  227. Args.push_back(FileGPG.c_str());
  228. Args.push_back(File.c_str());
  229. }
  230. else // clear-signed file
  231. {
  232. sig = GenerateTemporaryFileTemplate("apt.sig");
  233. data = GenerateTemporaryFileTemplate("apt.data");
  234. if (sig == NULL || data == NULL)
  235. {
  236. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for splitting up %s", File.c_str());
  237. local_exit(EINTERNAL);
  238. }
  239. int const sigFd = mkstemp(sig);
  240. int const dataFd = mkstemp(data);
  241. if (dataFd != -1)
  242. local_exit.files.push_back(data);
  243. if (sigFd != -1)
  244. local_exit.files.push_back(sig);
  245. if (sigFd == -1 || dataFd == -1)
  246. {
  247. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfiles for splitting up %s", File.c_str());
  248. local_exit(EINTERNAL);
  249. }
  250. FileFd signature;
  251. signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
  252. FileFd message;
  253. message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
  254. if (signature.Failed() == true || message.Failed() == true ||
  255. SplitClearSignedFile(File, &message, nullptr, &signature) == false)
  256. {
  257. apt_error(std::cerr, statusfd, fd, "Splitting up %s into data and signature failed", File.c_str());
  258. local_exit(112);
  259. }
  260. Args.push_back(sig);
  261. Args.push_back(data);
  262. }
  263. Args.push_back(NULL);
  264. if (Debug == true)
  265. {
  266. std::clog << "Preparing to exec: ";
  267. for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
  268. std::clog << " " << *a;
  269. std::clog << std::endl;
  270. }
  271. if (statusfd != -1)
  272. {
  273. int const nullfd = open("/dev/null", O_WRONLY);
  274. close(fd[0]);
  275. // Redirect output to /dev/null; we read from the status fd
  276. if (statusfd != STDOUT_FILENO)
  277. dup2(nullfd, STDOUT_FILENO);
  278. if (statusfd != STDERR_FILENO)
  279. dup2(nullfd, STDERR_FILENO);
  280. // Redirect the pipe to the status fd (3)
  281. dup2(fd[1], statusfd);
  282. putenv((char *)"LANG=");
  283. putenv((char *)"LC_ALL=");
  284. putenv((char *)"LC_MESSAGES=");
  285. }
  286. // We have created tempfiles we have to clean up
  287. // and we do an additional check, so fork yet another time …
  288. pid_t pid = ExecFork();
  289. if(pid < 0) {
  290. apt_error(std::cerr, statusfd, fd, "Fork failed for %s to check %s", Args[0], File.c_str());
  291. local_exit(EINTERNAL);
  292. }
  293. if(pid == 0)
  294. {
  295. if (statusfd != -1)
  296. dup2(fd[1], statusfd);
  297. execvp(Args[0], (char **) &Args[0]);
  298. apt_error(std::cerr, statusfd, fd, "Couldn't execute %s to check %s", Args[0], File.c_str());
  299. local_exit(EINTERNAL);
  300. }
  301. // Wait and collect the error code - taken from WaitPid as we need the exact Status
  302. int Status;
  303. while (waitpid(pid,&Status,0) != pid)
  304. {
  305. if (errno == EINTR)
  306. continue;
  307. apt_error(std::cerr, statusfd, fd, _("Waited for %s but it wasn't there"), "apt-key");
  308. local_exit(EINTERNAL);
  309. }
  310. // check if it exit'ed normally …
  311. if (WIFEXITED(Status) == false)
  312. {
  313. apt_error(std::cerr, statusfd, fd, _("Sub-process %s exited unexpectedly"), "apt-key");
  314. local_exit(EINTERNAL);
  315. }
  316. // … and with a good exit code
  317. if (WEXITSTATUS(Status) != 0)
  318. {
  319. // we forward the statuscode, so don't generate a message on the fd in this case
  320. apt_error(std::cerr, -1, fd, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
  321. local_exit(WEXITSTATUS(Status));
  322. }
  323. // everything fine
  324. local_exit(0);
  325. }
  326. /*}}}*/
  327. // SplitClearSignedFile - split message into data/signature /*{{{*/
  328. bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
  329. std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
  330. {
  331. std::unique_ptr<FILE, decltype(&fclose)> in{fopen(InFile.c_str(), "r"), &fclose};
  332. if (in.get() == nullptr)
  333. return _error->Errno("fopen", "can not open %s", InFile.c_str());
  334. struct ScopedErrors
  335. {
  336. ScopedErrors() { _error->PushToStack(); }
  337. ~ScopedErrors() { _error->MergeWithStack(); }
  338. } scoped;
  339. std::unique_ptr<char, decltype(&free)> buf{nullptr, &free};
  340. size_t buf_size = 0;
  341. // start of the message
  342. if (GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  343. return false; // empty or read error
  344. if (strcmp(buf.get(), "-----BEGIN PGP SIGNED MESSAGE-----") != 0)
  345. {
  346. // this might be an unsigned file we don't want to report errors for,
  347. // but still finish unsuccessful none the less.
  348. while (GetLineErrno(buf, &buf_size, in.get(), InFile, true))
  349. if (strcmp(buf.get(), "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
  350. return _error->Error("Clearsigned file '%s' does not start with a signed message block.", InFile.c_str());
  351. return false;
  352. }
  353. // save "Hash" Armor Headers
  354. while (true)
  355. {
  356. if (GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  357. return false;
  358. if (*buf == '\0')
  359. break; // empty line ends the Armor Headers
  360. if (ContentHeader != NULL && strncmp(buf.get(), "Hash: ", strlen("Hash: ")) == 0)
  361. ContentHeader->push_back(buf.get());
  362. }
  363. // the message itself
  364. bool first_line = true;
  365. bool good_write = true;
  366. while (true)
  367. {
  368. if (good_write == false || GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  369. return false;
  370. if (strcmp(buf.get(), "-----BEGIN PGP SIGNATURE-----") == 0)
  371. {
  372. if (SignatureFile != nullptr)
  373. {
  374. good_write &= SignatureFile->Write(buf.get(), strlen(buf.get()));
  375. good_write &= SignatureFile->Write("\n", 1);
  376. }
  377. break;
  378. }
  379. // we don't have any fields which need dash-escaped,
  380. // but implementations are free to encode all lines …
  381. char const *dashfree = buf.get();
  382. if (strncmp(dashfree, "- ", 2) == 0)
  383. dashfree += 2;
  384. if (first_line == true) // first line does not need a newline
  385. first_line = false;
  386. else if (ContentFile != nullptr)
  387. good_write &= ContentFile->Write("\n", 1);
  388. if (ContentFile != nullptr)
  389. good_write &= ContentFile->Write(dashfree, strlen(dashfree));
  390. }
  391. // collect all signatures
  392. bool open_signature = true;
  393. while (true)
  394. {
  395. if (good_write == false)
  396. return false;
  397. if (GetLineErrno(buf, &buf_size, in.get(), InFile, true) == false)
  398. break;
  399. if (open_signature && strcmp(buf.get(), "-----END PGP SIGNATURE-----") == 0)
  400. open_signature = false;
  401. else if (open_signature == false && strcmp(buf.get(), "-----BEGIN PGP SIGNATURE-----") == 0)
  402. open_signature = true;
  403. else if (open_signature == false)
  404. return _error->Error("Clearsigned file '%s' contains unsigned lines.", InFile.c_str());
  405. if (SignatureFile != nullptr)
  406. {
  407. good_write &= SignatureFile->Write(buf.get(), strlen(buf.get()));
  408. good_write &= SignatureFile->Write("\n", 1);
  409. }
  410. }
  411. if (open_signature == true)
  412. return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
  413. // Flush the files
  414. if (SignatureFile != nullptr)
  415. SignatureFile->Flush();
  416. if (ContentFile != nullptr)
  417. ContentFile->Flush();
  418. // Catch-all for "unhandled" read/sync errors
  419. if (_error->PendingError())
  420. return false;
  421. return true;
  422. }
  423. /*}}}*/
  424. bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
  425. {
  426. char * const message = GenerateTemporaryFileTemplate("fileutl.message");
  427. int const messageFd = mkstemp(message);
  428. if (messageFd == -1)
  429. {
  430. free(message);
  431. return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
  432. }
  433. // we have the fd, that's enough for us
  434. unlink(message);
  435. free(message);
  436. MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
  437. if (MessageFile.Failed() == true)
  438. return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
  439. _error->PushToStack();
  440. bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
  441. bool const errorDone = _error->PendingError();
  442. _error->MergeWithStack();
  443. if (splitDone == false)
  444. {
  445. MessageFile.Close();
  446. if (errorDone == true)
  447. return false;
  448. // we deal with an unsigned file
  449. MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
  450. }
  451. else // clear-signed
  452. {
  453. if (MessageFile.Seek(0) == false)
  454. return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
  455. }
  456. return MessageFile.Failed() == false;
  457. }
  458. /*}}}*/