libzypp 17.25.7
KeyManager.cc
Go to the documentation of this file.
1/*---------------------------------------------------------------------\
2| ____ _ __ __ ___ |
3| |__ / \ / / . \ . \ |
4| / / \ V /| _/ _/ |
5| / /__ | | | | | | |
6| /_____||_| |_| |_| |
7| |
8\---------------------------------------------------------------------*/
9#include <zypp/KeyManager.h>
10#include <zypp/KeyRing.h>
11#include <zypp/PathInfo.h>
12#include <zypp/base/Logger.h>
13#include <zypp/TmpPath.h>
14#include <zypp/base/String.h>
15#include <zypp/AutoDispose.h>
16
17#include <boost/thread/once.hpp>
18#include <boost/interprocess/smart_ptr/scoped_ptr.hpp>
19#include <gpgme.h>
20
21#include <stdio.h>
22using std::endl;
23
24#undef ZYPP_BASE_LOGGER_LOGGROUP
25#define ZYPP_BASE_LOGGER_LOGGROUP "zypp::gpg"
26
28namespace zypp
29{
31 namespace
32 {
33 // @TODO [threading]
34 // make sure to call the init code of gpgme only once
35 // this might need to be moved to a different location when
36 // threads are introduced into libzypp
37 boost::once_flag gpgme_init_once = BOOST_ONCE_INIT;
38
39 void initGpgme ()
40 {
41 const char *version = gpgme_check_version(NULL);
42 if ( version )
43 {
44 MIL << "Initialized libgpgme version: " << version << endl;
45 }
46 else
47 {
48 MIL << "Initialized libgpgme with unknown version" << endl;
49 }
50 }
51
52 //using boost::interprocess pointer because it allows a custom deleter
53 typedef boost::interprocess::scoped_ptr<gpgme_data, boost::function<void (gpgme_data_t)>> GpgmeDataPtr;
54 typedef boost::interprocess::scoped_ptr<_gpgme_key, boost::function<void (gpgme_key_t)>> GpgmeKeyPtr;
55 typedef boost::interprocess::scoped_ptr<FILE, boost::function<int (FILE *)>> FILEPtr;
56
57 struct GpgmeErr
58 {
59 GpgmeErr( gpgme_error_t err_r = GPG_ERR_NO_ERROR )
60 : _err( err_r )
61 {}
62 operator gpgme_error_t() const { return _err; }
63 private:
64 gpgme_error_t _err;
65 };
66
67 std::ostream & operator<<( std::ostream & str, const GpgmeErr & obj )
68 { return str << "<" << gpgme_strsource(obj) << "> " << gpgme_strerror(obj); }
69
71 std::ostream & operator<<( std::ostream & str, const _gpgme_op_import_result & obj )
72 {
73 str << "gpgme_op_import_result {" << endl;
74 str << " " << obj.considered << " The total number of considered keys." << endl;
75 str << " " << obj.no_user_id << " The number of keys without user ID." << endl;
76 str << " " << obj.imported << " The total number of imported keys." << endl;
77 str << " " << obj.imported_rsa << " imported RSA keys." << endl;
78 str << " " << obj.unchanged << " unchanged keys." << endl;
79 str << " " << obj.new_user_ids << " new user IDs." << endl;
80 str << " " << obj.new_sub_keys << " new sub keys." << endl;
81 str << " " << obj.new_signatures << " new signatures." << endl;
82 str << " " << obj.new_revocations << " new revocations." << endl;
83 str << " " << obj.secret_read << " secret keys read." << endl;
84 str << " " << obj.secret_imported << " imported secret keys." << endl;
85 str << " " << obj.secret_unchanged << " unchanged secret keys." << endl;
86 str << " " << obj.not_imported << " keys not imported." << endl;
87 for ( gpgme_import_status_t p = obj.imports; p; p = p->next )
88 {
89 str << " - " << p->fpr << ": " << p->result << endl;
90 }
91 // In V.1.11: str << " " << obj.skipped_v3_keys << " skipped v3 keys." << endl;
92 return str << "}";
93 }
94 } // namespace
96
98 {
99 GpgmeException( const std::string & in_r, const GpgmeErr & err_r )
100 : KeyRingException( str::Format( "libgpgme error in '%1%': %2%" ) % in_r % err_r )
101 {}
102 };
103
105 {
106 public:
108 { boost::call_once( gpgme_init_once, initGpgme ); }
109
111 { if ( _ctx ) gpgme_release( _ctx ); }
112
113
115 std::list<std::string> readSignaturesFprs( const Pathname & signature_r )
116 { return readSignaturesFprsOptVerify( signature_r ); }
117
119 bool verifySignaturesFprs( const Pathname & file_r, const Pathname & signature_r )
120 {
121 bool verify = false;
122 readSignaturesFprsOptVerify( signature_r, file_r, &verify );
123 return verify;
124 }
125
126 gpgme_ctx_t _ctx { nullptr };
127 bool _volatile { false };
128
129 private:
135 std::list<std::string> readSignaturesFprsOptVerify( const Pathname & signature_r, const Pathname & file_r = "/dev/null", bool * verify_r = nullptr );
136 };
137
138std::list<std::string> KeyManagerCtx::Impl::readSignaturesFprsOptVerify( const Pathname & signature_r, const Pathname & file_r, bool * verify_r )
139{
140 //lets be pessimistic
141 if ( verify_r )
142 *verify_r = false;
143
144
145 if (!PathInfo( signature_r ).isExist())
146 return std::list<std::string>();
147
148 FILEPtr dataFile(fopen(file_r.c_str(), "rb"), fclose);
149 if (!dataFile)
150 return std::list<std::string>();
151
152 GpgmeDataPtr fileData(nullptr, gpgme_data_release);
153 GpgmeErr err = gpgme_data_new_from_stream (&fileData.get(), dataFile.get());
154 if (err) {
155 ERR << err << endl;
156 return std::list<std::string>();
157 }
158
159 FILEPtr sigFile(fopen(signature_r.c_str(), "rb"), fclose);
160 if (!sigFile) {
161 ERR << "Unable to open signature file '" << signature_r << "'" <<endl;
162 return std::list<std::string>();
163 }
164
165 GpgmeDataPtr sigData(nullptr, gpgme_data_release);
166 err = gpgme_data_new_from_stream (&sigData.get(), sigFile.get());
167 if (err) {
168 ERR << err << endl;
169 return std::list<std::string>();
170 }
171
172 err = gpgme_op_verify(_ctx, sigData.get(), fileData.get(), NULL);
173 if (err != GPG_ERR_NO_ERROR) {
174 ERR << err << endl;
175 return std::list<std::string>();
176 }
177
178 gpgme_verify_result_t res = gpgme_op_verify_result(_ctx);
179 if (!res || !res->signatures) {
180 ERR << "Unable to read signature fingerprints" <<endl;
181 return std::list<std::string>();
182 }
183
184 bool foundBadSignature = false;
185 bool foundGoodSignature = false;
186 std::list<std::string> signatures;
187 for ( gpgme_signature_t sig = res->signatures; sig; sig = sig->next ) {
188
189 if ( sig->fpr )
190 {
191 // bsc#1100427: With libgpgme11-1.11.0 and if a recent gpg version was used
192 // to create the signature, the field may contain the full fingerprint, but
193 // we're expected to return the ID.
194 // [https://github.com/gpg/gpgme/commit/478d1650bbef84958ccce439fac982ef57b16cd0]
195 std::string id( sig->fpr );
196 if ( id.size() > 16 )
197 id = id.substr( id.size()-16 );
198
199 DBG << "Found signature with ID: " << id << " in " << file_r << std::endl;
200 signatures.push_back( std::move(id) );
201 }
202
203 if ( verify_r && sig->status != GPG_ERR_NO_ERROR ) {
204 const auto status = gpgme_err_code(sig->status);
205
206 // bsc#1180721: libgpgme started to return signatures of unknown keys, which breaks
207 // our workflow when verifying files that have multiple signatures, including some that are
208 // not in the trusted keyring. We should not fail if we have unknown or expired keys and at least a good one.
209 // We will however keep the behaviour of failing if we find a bad signatures even if others are good.
210 if ( status != GPG_ERR_KEY_EXPIRED && status != GPG_ERR_NO_PUBKEY )
211 {
212 WAR << "Failed signature check: " << file_r << " " << GpgmeErr(sig->status) << endl;
213 if ( !foundBadSignature )
214 foundBadSignature = true;
215 }
216 else
217 {
218 WAR << "Legacy: Ignore expired or unknown key: " << file_r << " " << GpgmeErr(sig->status) << endl;
219 // for now treat expired keys as good signature
220 if ( status == GPG_ERR_KEY_EXPIRED )
221 foundGoodSignature = true;
222 }
223 } else {
224 foundGoodSignature = true;
225 }
226 }
227
228 if ( verify_r )
229 *verify_r = (!foundBadSignature) && foundGoodSignature;
230 return signatures;
231}
232
233
235: _pimpl( new Impl )
236{}
237
239{
240 static Pathname tmppath( zypp::myTmpDir() / "PublicKey" );
241 filesystem::assert_dir( tmppath );
242
243 KeyManagerCtx ret { createForOpenPGP( tmppath ) };
244 ret._pimpl->_volatile = true; // readKeyFromFile workaround bsc#1140670
245 return ret;
246}
247
249{
250 DBG << "createForOpenPGP(" << keyring_r << ")" << endl;
251
252 KeyManagerCtx ret;
253 gpgme_ctx_t & ctx { ret._pimpl->_ctx };
254
255 // create the context
256 GpgmeErr err = gpgme_new( &ctx );
257 if ( err != GPG_ERR_NO_ERROR )
258 ZYPP_THROW( GpgmeException( "gpgme_new", err ) );
259
260 // use OpenPGP
261 err = gpgme_set_protocol( ctx, GPGME_PROTOCOL_OpenPGP );
262 if ( err != GPG_ERR_NO_ERROR )
263 ZYPP_THROW( GpgmeException( "gpgme_set_protocol", err ) );
264
265 if ( !keyring_r.empty() ) {
266 // get engine information to read current state
267 gpgme_engine_info_t enginfo = gpgme_ctx_get_engine_info( ctx );
268 if ( !enginfo )
269 ZYPP_THROW( GpgmeException( "gpgme_ctx_get_engine_info", err ) );
270
271 err = gpgme_ctx_set_engine_info( ctx, GPGME_PROTOCOL_OpenPGP, enginfo->file_name, keyring_r.c_str() );
272 if ( err != GPG_ERR_NO_ERROR )
273 ZYPP_THROW( GpgmeException( "gpgme_ctx_set_engine_info", err ) );
274 }
275
276 return ret;
277}
278
280{
281 Pathname ret;
282 if ( gpgme_engine_info_t enginfo = gpgme_ctx_get_engine_info( _pimpl->_ctx ) )
283 ret = enginfo->home_dir;
284 return ret;
285}
286
287std::list<PublicKeyData> KeyManagerCtx::listKeys()
288{
289 std::list<PublicKeyData> ret;
290 GpgmeErr err = GPG_ERR_NO_ERROR;
291
292 // Reset gpgme_keylist_mode on return!
293 AutoDispose<gpgme_keylist_mode_t> guard { gpgme_get_keylist_mode( _pimpl->_ctx ), bind( &gpgme_set_keylist_mode, _pimpl->_ctx, _1 ) };
294 // Let listed keys include signatures (required if PublicKeyData are created from the key)
295 if ( (err = gpgme_set_keylist_mode( _pimpl->_ctx, GPGME_KEYLIST_MODE_LOCAL | GPGME_KEYLIST_MODE_SIGS )) != GPG_ERR_NO_ERROR ) {
296 ERR << "gpgme_set_keylist_mode: " << err << endl;
297 return ret;
298 }
299
300 if ( (err = gpgme_op_keylist_start( _pimpl->_ctx, NULL, 0 )) != GPG_ERR_NO_ERROR ) {
301 ERR << "gpgme_op_keylist_start: " << err << endl;
302 return ret;
303 }
304 // Close list operation on return!
305 AutoDispose<gpgme_ctx_t> guard2 { _pimpl->_ctx, &gpgme_op_keylist_end };
306
307 AutoDispose<gpgme_key_t> key { nullptr, &gpgme_key_release };
308 for ( ; gpgme_op_keylist_next( _pimpl->_ctx, &(*key) ) == GPG_ERR_NO_ERROR; key.getDispose()( key ) ) {
310 if ( data )
311 ret.push_back( data );
312 }
313
314 return ret;
315}
316
317#if 1
318std::list<PublicKeyData> KeyManagerCtx::readKeyFromFile( const Pathname & keyfile_r )
319{
320 // bsc#1140670: GPGME does not support reading keys from a keyfile using
321 // gpgme_data_t and gpgme_op_keylist_from_data_start. Despite GPGME_KEYLIST_MODE_SIGS
322 // the signatures are missing, but we need them to create proper PublicKeyData objects.
323 // While this is not resolved, we read into a temp. keyring. Impl::_volatile helps
324 // to detect whether we can clear and import into the current context or need to
325 // create a temp. one.
326 std::list<PublicKeyData> ret;
327
328 if ( _pimpl->_volatile ) {
329 // in a volatile context we can simple clear the keyring...
331 if ( importKey( keyfile_r ) )
332 ret = listKeys();
333 } else {
334 // read in a volatile context
335 ret = createForOpenPGP().readKeyFromFile( keyfile_r );
336 }
337
338 return ret;
339}
340#else
341std::list<PublicKeyData> KeyManagerCtx::readKeyFromFile( const Pathname & file_r )
342{
343 std::list<PublicKeyData> ret;
344 GpgmeErr err = GPG_ERR_NO_ERROR;
345
346 AutoDispose<gpgme_data_t> data { nullptr, &gpgme_data_release };
347 if ( (err = gpgme_data_new_from_file( &(*data), file_r.c_str(), 1 )) != GPG_ERR_NO_ERROR ) {
348 ERR << "gpgme_data_new_from_file " << file_r << ": " << err << endl;
349 return ret;
350 }
351
352 // Reset gpgme_keylist_mode on return!
353 AutoDispose<gpgme_keylist_mode_t> guard { gpgme_get_keylist_mode( _pimpl->_ctx ), bind( &gpgme_set_keylist_mode, _pimpl->_ctx, _1 ) };
354 // Let listed keys include signatures (required if PublicKeyData are created from the key)
355 if ( (err = gpgme_set_keylist_mode( _pimpl->_ctx, GPGME_KEYLIST_MODE_LOCAL | GPGME_KEYLIST_MODE_SIGS )) != GPG_ERR_NO_ERROR ) {
356 ERR << "gpgme_set_keylist_mode: " << err << endl;
357 return ret;
358 }
359
360 if ( (err = gpgme_op_keylist_from_data_start( _pimpl->_ctx, data, 0 )) != GPG_ERR_NO_ERROR ) {
361 ERR << "gpgme_op_keylist_from_data_start " << file_r << ": " << err << endl;
362 return ret;
363 }
364 // Close list operation on return!
365 AutoDispose<gpgme_ctx_t> guard2 { _pimpl->_ctx, &gpgme_op_keylist_end };
366
367 AutoDispose<gpgme_key_t> key { nullptr, &gpgme_key_release };
368 for ( ; gpgme_op_keylist_next( _pimpl->_ctx, &(*key) ) == GPG_ERR_NO_ERROR; key.getDispose()( key ) ) {
369 PublicKeyData data { PublicKeyData::fromGpgmeKey( key ) };
370 if ( data )
371 ret.push_back( data );
372 }
373
374 return ret;
375}
376#endif
377
378bool KeyManagerCtx::verify(const Pathname &file, const Pathname &signature)
379{
380 return _pimpl->verifySignaturesFprs(file, signature);
381}
382
383bool KeyManagerCtx::exportKey(const std::string &id, std::ostream &stream)
384{
385 GpgmeErr err = GPG_ERR_NO_ERROR;
386
387 GpgmeKeyPtr foundKey;
388
389 //search for requested key id
390 gpgme_key_t key;
391 gpgme_op_keylist_start(_pimpl->_ctx, NULL, 0);
392 while (!(err = gpgme_op_keylist_next(_pimpl->_ctx, &key))) {
393 if (key->subkeys && id == str::asString(key->subkeys->keyid)) {
394 GpgmeKeyPtr(key, gpgme_key_release).swap(foundKey);
395 break;
396 }
397 gpgme_key_release(key);
398 }
399 gpgme_op_keylist_end(_pimpl->_ctx);
400
401 if (!foundKey) {
402 WAR << "Key " << id << "not found" << endl;
403 return false;
404 }
405
406 //function needs a array of keys to export
407 gpgme_key_t keyarray[2];
408 keyarray[0] = foundKey.get();
409 keyarray[1] = NULL;
410
411 GpgmeDataPtr out(nullptr, gpgme_data_release);
412 err = gpgme_data_new (&out.get());
413 if (err) {
414 ERR << err << endl;
415 return false;
416 }
417
418 //format as ascii armored
419 gpgme_set_armor (_pimpl->_ctx, 1);
420 // bsc#1179222: Remove outdated self signatures when exporting the key.
421 // The keyring does not order the signatures when multiple versions of the
422 // same key are imported. Rpm however uses the 1st to compute the -release
423 // of the gpg-pubkey. So we export only the latest to get a proper-release.
424 err = gpgme_op_export_keys (_pimpl->_ctx, keyarray, GPGME_EXPORT_MODE_MINIMAL, out.get());
425 if (!err) {
426 int ret = gpgme_data_seek (out.get(), 0, SEEK_SET);
427 if (ret) {
428 ERR << "Unable to seek in exported key data" << endl;
429 return false;
430 }
431
432 const int bufsize = 512;
433 char buf[bufsize + 1];
434 while ((ret = gpgme_data_read(out.get(), buf, bufsize)) > 0) {
435 stream.write(buf, ret);
436 }
437
438 //failed to read from buffer
439 if (ret < 0) {
440 ERR << "Unable to read exported key data" << endl;
441 return false;
442 }
443 } else {
444 ERR << "Error exporting key: "<< err << endl;
445 return false;
446 }
447
448 //if we reach this point export was successful
449 return true;
450}
451
453{
454 if ( !PathInfo( keyfile ).isExist() ) {
455 ERR << "Keyfile '" << keyfile << "' does not exist.";
456 return false;
457 }
458
459 GpgmeDataPtr data(nullptr, gpgme_data_release);
460 GpgmeErr err;
461
462 err = gpgme_data_new_from_file(&data.get(), keyfile.c_str(), 1);
463 if (err) {
464 ERR << "Error importing key: "<< err << endl;
465 return false;
466 }
467
468 err = gpgme_op_import(_pimpl->_ctx, data.get());
469 if (err) {
470 ERR << "Error importing key: "<< err << endl;
471 return false;
472 }
473
474 // Work around bsc#1127220 [libgpgme] no error upon incomplete import due to signal received.
475 // We need this error, otherwise RpmDb will report the missing keys as 'probably v3'.
476 if ( gpgme_import_result_t res = gpgme_op_import_result(_pimpl->_ctx) )
477 {
478 if ( ! res->considered && PathInfo(keyfile).size() )
479 {
480 DBG << *res << endl;
481 ERR << "Error importing key: No keys considered (bsc#1127220, [libgpgme] signal received?)" << endl;
482 return false;
483 }
484 }
485
486 return (err == GPG_ERR_NO_ERROR);
487}
488
489bool KeyManagerCtx::deleteKey(const std::string &id)
490{
491 gpgme_key_t key;
492 GpgmeErr err = GPG_ERR_NO_ERROR;
493
494 gpgme_op_keylist_start(_pimpl->_ctx, NULL, 0);
495
496 while (!(err = gpgme_op_keylist_next(_pimpl->_ctx, &key))) {
497 if (key->subkeys && id == str::asString(key->subkeys->keyid)) {
498 err = gpgme_op_delete(_pimpl->_ctx, key, 0);
499
500 gpgme_key_release(key);
501 gpgme_op_keylist_end(_pimpl->_ctx);
502
503 if (err) {
504 ERR << "Error deleting key: "<< err << endl;
505 return false;
506 }
507 return true;
508 }
509 gpgme_key_release(key);
510 }
511
512 gpgme_op_keylist_end(_pimpl->_ctx);
513 WAR << "Key: '"<< id << "' not found." << endl;
514 return false;
515}
516
517std::list<std::string> KeyManagerCtx::readSignatureFingerprints(const Pathname &signature)
518{ return _pimpl->readSignaturesFprs(signature); }
519
520} // namespace zypp
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
gpgme_error_t _err
Definition: KeyManager.cc:64
#define DBG
Definition: Logger.h:78
#define MIL
Definition: Logger.h:79
#define ERR
Definition: Logger.h:81
#define WAR
Definition: Logger.h:80
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:93
std::list< std::string > readSignaturesFprs(const Pathname &signature_r)
Return all fingerprints found in signature_r.
Definition: KeyManager.cc:115
bool _volatile
readKeyFromFile workaround bsc#1140670
Definition: KeyManager.cc:127
std::list< std::string > readSignaturesFprsOptVerify(const Pathname &signature_r, const Pathname &file_r="/dev/null", bool *verify_r=nullptr)
Return all fingerprints found in signature_r and optionally verify the file_r on the fly.
Definition: KeyManager.cc:138
bool verifySignaturesFprs(const Pathname &file_r, const Pathname &signature_r)
Tries to verify the file_r using signature_r.
Definition: KeyManager.cc:119
bool exportKey(const std::string &id, std::ostream &stream)
Exports the key with id into the given stream, returns true on success.
Definition: KeyManager.cc:383
std::list< PublicKeyData > listKeys()
Returns a list of all public keys found in the current keyring.
Definition: KeyManager.cc:287
bool verify(const Pathname &file, const Pathname &signature)
Tries to verify file using signature, returns true on success.
Definition: KeyManager.cc:378
static KeyManagerCtx createForOpenPGP()
Creates a new KeyManagerCtx for PGP using a volatile temp.
Definition: KeyManager.cc:238
std::list< std::string > readSignatureFingerprints(const Pathname &signature)
Reads all fingerprints from the signature file , returns a list of all found fingerprints.
Definition: KeyManager.cc:517
std::list< PublicKeyData > readKeyFromFile(const Pathname &file)
Returns a list of all PublicKeyData found in file.
Definition: KeyManager.cc:318
RW_pointer< Impl > _pimpl
Pointer to implementation.
Definition: KeyManager.h:83
bool deleteKey(const std::string &id)
Tries to delete a key specified by id, returns true on success.
Definition: KeyManager.cc:489
Pathname homedir() const
Return the homedir/keyring.
Definition: KeyManager.cc:279
bool importKey(const Pathname &keyfile)
Tries to import a key from keyfile, returns true on success.
Definition: KeyManager.cc:452
Class representing one GPG Public Keys data.
Definition: PublicKey.h:140
static PublicKeyData fromGpgmeKey(_gpgme_key *data)
Definition: PublicKey.cc:305
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:221
const char * c_str() const
String representation.
Definition: Pathname.h:110
bool empty() const
Test for an empty path.
Definition: Pathname.h:114
String related utilities and Regular expression matching.
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
Definition: PathInfo.cc:320
int clean_dir(const Pathname &path)
Like 'rm -r DIR/ *'.
Definition: PathInfo.cc:443
const std::string & asString(const std::string &t)
Global asString() that works with std::string too.
Definition: String.h:136
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:2
std::ostream & operator<<(std::ostream &str, const Exception &obj)
Definition: Exception.cc:147
Pathname myTmpDir()
Global access to the zypp.TMPDIR (created on demand, deleted when libzypp is unloaded)
Definition: ZYppImpl.cc:228
GpgmeException(const std::string &in_r, const GpgmeErr &err_r)
Definition: KeyManager.cc:99