• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 23906374481

02 Apr 2026 02:47PM UTC coverage: 19.861% (-0.01%) from 19.873%
23906374481

Pull #892

github

web-flow
Merge b9d8446fc into 7a9fe4c42
Pull Request #892: fix: kill stale GPG agents before key generation

0 of 4 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

1030 of 5186 relevant lines covered (19.86%)

7.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

33.33
/src/pass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "pass.h"
4
#include "helpers.h"
5
#include "qtpasssettings.h"
6
#include "util.h"
7
#include <QDir>
8
#include <QRandomGenerator>
9
#include <QRegularExpression>
10
#include <utility>
11

12
#ifdef QT_DEBUG
13
#include "debughelper.h"
14
#endif
15

16
using Enums::GIT_INIT;
17
using Enums::GIT_PULL;
18
using Enums::GIT_PUSH;
19
using Enums::GPG_GENKEYS;
20
using Enums::PASS_COPY;
21
using Enums::PASS_INIT;
22
using Enums::PASS_INSERT;
23
using Enums::PASS_MOVE;
24
using Enums::PASS_OTP_GENERATE;
25
using Enums::PASS_REMOVE;
26
using Enums::PASS_SHOW;
27

28
/**
29
 * @brief Pass::Pass wrapper for using either pass or the pass imitation
30
 */
31
Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
11✔
32
  connect(&exec,
11✔
33
          static_cast<void (Executor::*)(int, int, const QString &,
34
                                         const QString &)>(&Executor::finished),
35
          this, &Pass::finished);
11✔
36

37
  // This was previously using direct QProcess signals.
38
  // The code now uses Executor instead of raw QProcess for better control.
39
  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
40
  //        SIGNAL(error(QProcess::ProcessError)));
41

42
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
11✔
43
  env.append("WSLENV=PASSWORD_STORE_DIR/p");
11✔
44
}
11✔
45

46
/**
47
 * @brief Executes a wrapper command.
48
 * @param id Process ID
49
 * @param app Application to execute
50
 * @param args Arguments
51
 * @param readStdout Whether to read stdout
52
 * @param readStderr Whether to read stderr
53
 */
54
void Pass::executeWrapper(PROCESS id, const QString &app,
×
55
                          const QStringList &args, bool readStdout,
56
                          bool readStderr) {
57
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
58
}
×
59

60
void Pass::executeWrapper(PROCESS id, const QString &app,
×
61
                          const QStringList &args, QString input,
62
                          bool readStdout, bool readStderr) {
63
#ifdef QT_DEBUG
64
  dbg() << app << args;
65
#endif
66
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
×
67
               readStdout, readStderr);
68
}
×
69

70
/**
71
 * @brief Initializes the pass wrapper environment.
72
 */
73
void Pass::init() {
1✔
74
#ifdef __APPLE__
75
  // If it exists, add the gpgtools to PATH
76
  if (QFile("/usr/local/MacGPG2/bin").exists())
77
    env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
78
  // Add missing /usr/local/bin
79
  if (env.filter("/usr/local/bin").isEmpty())
80
    env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
81
#endif
82

83
  if (!QtPassSettings::getGpgHome().isEmpty()) {
2✔
84
    QDir absHome(QtPassSettings::getGpgHome());
×
85
    absHome.makeAbsolute();
×
86
    env << "GNUPGHOME=" + absHome.path();
×
87
  }
×
88
}
1✔
89

90
/**
91
 * @brief Pass::Generate use either pwgen or internal password
92
 * generator
93
 * @param length of the desired password
94
 * @param charset to use for generation
95
 * @return the password
96
 */
97
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,004✔
98
    -> QString {
99
  QString passwd;
1,004✔
100
  if (QtPassSettings::isUsePwgen()) {
1,004✔
101
    // --secure goes first as it overrides --no-* otherwise
102
    QStringList args;
×
103
    args.append("-1");
×
104
    if (!QtPassSettings::isLessRandom()) {
×
105
      args.append("--secure");
×
106
    }
107
    args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
×
108
                                                  : "--capitalize");
109
    args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
×
110
                                                 : "--numerals");
111
    if (QtPassSettings::isUseSymbols()) {
×
112
      args.append("--symbols");
×
113
    }
114
    args.append(QString::number(length));
×
115
    // executeBlocking returns 0 on success, non-zero on failure
116
    if (Executor::executeBlocking(QtPassSettings::getPwgenExecutable(), args,
×
117
                                  &passwd) == 0) {
118
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
119
      passwd.remove(literalNewLines);
×
120
    } else {
121
      passwd.clear();
×
122
#ifdef QT_DEBUG
123
      qDebug() << __FILE__ << ":" << __LINE__ << "\t"
124
               << "pwgen fail";
125
#endif
126
      // Error is already handled by clearing passwd; no need for critical
127
      // signal here
128
    }
129
  } else {
130
    // Validate charset - if CUSTOM is selected but chars are empty,
131
    // fall back to ALLCHARS to prevent weak passwords (issue #780)
132
    QString effectiveCharset = charset;
133
    if (effectiveCharset.isEmpty()) {
1,004✔
134
      effectiveCharset = QtPassSettings::getPasswordConfiguration()
2✔
135
                             .Characters[PasswordConfiguration::ALLCHARS];
136
    }
137
    if (effectiveCharset.length() > 0) {
1,004✔
138
      passwd = generateRandomPassword(effectiveCharset, length);
2,008✔
139
    } else {
140
      emit critical(
×
141
          tr("No characters chosen"),
×
142
          tr("Can't generate password, there are no characters to choose from "
×
143
             "set in the configuration!"));
144
    }
145
  }
146
  return passwd;
1,004✔
147
}
148

149
/**
150
 * @brief Pass::gpgSupportsEd25519 check if GPG supports ed25519 (ECC)
151
 * GPG 2.1+ supports ed25519 which is much faster for key generation
152
 * @return true if ed25519 is supported
153
 */
154
bool Pass::gpgSupportsEd25519() {
3✔
155
  QString out, err;
3✔
156
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(),
12✔
157
                                {"--version"}, &out, &err) != 0) {
158
    return false;
159
  }
160
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
×
161
  QRegularExpressionMatch match = versionRegex.match(out);
×
162
  if (!match.hasMatch()) {
×
163
    return false;
164
  }
165
  int major = match.captured(1).toInt();
×
166
  int minor = match.captured(2).toInt();
×
167
  return major > 2 || (major == 2 && minor >= 1);
×
168
}
3✔
169

170
/**
171
 * @brief Pass::getDefaultKeyTemplate return default key generation template
172
 * Uses ed25519 if supported, otherwise falls back to RSA
173
 * @return GPG batch template string
174
 */
175
QString Pass::getDefaultKeyTemplate() {
1✔
176
  if (gpgSupportsEd25519()) {
1✔
177
    return QStringLiteral("%echo Generating a default key\n"
×
178
                          "Key-Type: EdDSA\n"
179
                          "Key-Curve: Ed25519\n"
180
                          "Subkey-Type: ECDH\n"
181
                          "Subkey-Curve: Curve25519\n"
182
                          "Name-Real: \n"
183
                          "Name-Comment: QtPass\n"
184
                          "Name-Email: \n"
185
                          "Expire-Date: 0\n"
186
                          "%no-protection\n"
187
                          "%commit\n"
188
                          "%echo done");
189
  }
190
  return QStringLiteral("%echo Generating a default key\n"
1✔
191
                        "Key-Type: RSA\n"
192
                        "Subkey-Type: RSA\n"
193
                        "Name-Real: \n"
194
                        "Name-Comment: QtPass\n"
195
                        "Name-Email: \n"
196
                        "Expire-Date: 0\n"
197
                        "%no-protection\n"
198
                        "%commit\n"
199
                        "%echo done");
200
}
201

202
/**
203
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
204
 * @param batch GnuPG style configuration string
205
 */
206
void Pass::GenerateGPGKeys(QString batch) {
×
207
  // Kill any stale GPG agents that might be holding locks on the key database
208
  // This helps avoid "database locked" timeouts during key generation
NEW
209
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
NEW
210
  if (!gpgPath.isEmpty()) {
×
NEW
211
    Executor::executeBlocking(gpgPath, {"gpgconf", "--kill", "gpg-agent"});
×
212
  }
213

NEW
214
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
215
                 std::move(batch));
UNCOV
216
}
×
217

218
/**
219
 * @brief Pass::listKeys list users
220
 * @param keystrings
221
 * @param secret list private keys
222
 * @return QList<UserInfo> users
223
 */
224
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
225
  QList<UserInfo> users;
×
226
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
227
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
228

229
  for (const QString &keystring : AS_CONST(keystrings)) {
×
230
    if (!keystring.isEmpty()) {
×
231
      args.append(keystring);
232
    }
233
  }
234
  QString p_out;
×
235
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
236
                                &p_out) != 0) {
237
    return users;
238
  }
239
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
240
  const QStringList keys =
241
      p_out.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
×
242
#else
243
  const QStringList keys =
244
      p_out.split(Util::newLinesRegex(), QString::SkipEmptyParts);
245
#endif
246
  UserInfo current_user;
×
247
  for (const QString &key : keys) {
×
248
    QStringList props = key.split(':');
×
249
    if (props.size() < 10) {
×
250
      continue;
251
    }
252
    if (props[0] == (secret ? "sec" : "pub")) {
×
253
      if (!current_user.key_id.isEmpty()) {
×
254
        users.append(current_user);
255
      }
256
      current_user = UserInfo();
×
257
      current_user.key_id = props[4];
×
258
      current_user.name = props[9].toUtf8();
×
259
      current_user.validity = props[1][0].toLatin1();
×
260
      current_user.created.setSecsSinceEpoch(props[5].toUInt());
×
261
      current_user.expiry.setSecsSinceEpoch(props[6].toUInt());
×
262
    } else if (current_user.name.isEmpty() && props[0] == "uid") {
×
263
      current_user.name = props[9];
×
264
    } else if ((props[0] == "fpr") && props[9].endsWith(current_user.key_id)) {
×
265
      current_user.key_id = props[9];
×
266
    }
267
  }
268
  if (!current_user.key_id.isEmpty()) {
×
269
    users.append(current_user);
270
  }
271
  return users;
272
}
×
273

274
/**
275
 * @brief Pass::listKeys list users
276
 * @param keystring
277
 * @param secret list private keys
278
 * @return QList<UserInfo> users
279
 */
280
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
281
  return listKeys(QStringList(keystring), secret);
×
282
}
283

284
/**
285
 * @brief Pass::processFinished reemits specific signal based on what process
286
 * has finished
287
 * @param id    id of Pass process that was scheduled and finished
288
 * @param exitCode  return code of a process
289
 * @param out   output generated by process(if capturing was requested, empty
290
 *              otherwise)
291
 * @param err   error output generated by process(if capturing was requested,
292
 *              or error occurred)
293
 */
294
void Pass::finished(int id, int exitCode, const QString &out,
×
295
                    const QString &err) {
296
  auto pid = static_cast<PROCESS>(id);
297
  if (exitCode != 0) {
×
298
    emit processErrorExit(exitCode, err);
×
299
    return;
×
300
  }
301
  switch (pid) {
×
302
  case GIT_INIT:
×
303
    emit finishedGitInit(out, err);
×
304
    break;
×
305
  case GIT_PULL:
×
306
    emit finishedGitPull(out, err);
×
307
    break;
×
308
  case GIT_PUSH:
×
309
    emit finishedGitPush(out, err);
×
310
    break;
×
311
  case PASS_SHOW:
×
312
    emit finishedShow(out);
×
313
    break;
×
314
  case PASS_OTP_GENERATE:
×
315
    emit finishedOtpGenerate(out);
×
316
    break;
×
317
  case PASS_INSERT:
×
318
    emit finishedInsert(out, err);
×
319
    break;
×
320
  case PASS_REMOVE:
×
321
    emit finishedRemove(out, err);
×
322
    break;
×
323
  case PASS_INIT:
×
324
    emit finishedInit(out, err);
×
325
    break;
×
326
  case PASS_MOVE:
×
327
    emit finishedMove(out, err);
×
328
    break;
×
329
  case PASS_COPY:
×
330
    emit finishedCopy(out, err);
×
331
    break;
×
332
  case GPG_GENKEYS:
×
333
    emit finishedGenerateGPGKeys(out, err);
×
334
    break;
×
335
  default:
336
#ifdef QT_DEBUG
337
    dbg() << "Unhandled process type" << pid;
338
#endif
339
    break;
340
  }
341
}
342

343
/**
344
 * @brief Pass::updateEnv update the execution environment (used when
345
 * switching profiles)
346
 */
347
void Pass::updateEnv() {
×
348
  // put PASSWORD_STORE_SIGNING_KEY in env
349
  QStringList envSigningKey = env.filter("PASSWORD_STORE_SIGNING_KEY=");
×
350
  QString currentSigningKey = QtPassSettings::getPassSigningKey();
×
351
  if (envSigningKey.isEmpty()) {
×
352
    if (!currentSigningKey.isEmpty()) {
×
353
      // dbg()<< "Added
354
      // PASSWORD_STORE_SIGNING_KEY with" + currentSigningKey;
355
      env.append("PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
356
    }
357
  } else {
358
    if (currentSigningKey.isEmpty()) {
×
359
      // dbg() << "Removed
360
      // PASSWORD_STORE_SIGNING_KEY";
361
      env.removeAll(envSigningKey.first());
362
    } else {
363
      // dbg()<< "Update
364
      // PASSWORD_STORE_SIGNING_KEY with " + currentSigningKey;
365
      env.replaceInStrings(envSigningKey.first(),
×
366
                           "PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
367
    }
368
  }
369
  // put PASSWORD_STORE_DIR in env
370
  QStringList store = env.filter("PASSWORD_STORE_DIR=");
×
371
  if (store.isEmpty()) {
×
372
    // dbg()<< "Added
373
    // PASSWORD_STORE_DIR";
374
    env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
×
375
  } else {
376
    // dbg()<< "Update
377
    // PASSWORD_STORE_DIR with " + passStore;
378
    env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
×
379
                                            QtPassSettings::getPassStore());
×
380
  }
381
  exec.setEnvironment(env);
×
382
}
×
383

384
/**
385
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
386
 * @param for_file which file (folder) would you like the gpgid file path for.
387
 * @return path to the gpgid file.
388
 */
389
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
8✔
390
  QString passStore =
391
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
16✔
392
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
8✔
393
  QString fullPath = normalizedFile.startsWith(passStore)
8✔
394
                         ? normalizedFile
8✔
395
                         : passStore + "/" + normalizedFile;
6✔
396
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
8✔
397
  bool found = false;
398
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
10✔
399
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
400
      found = true;
401
      break;
402
    }
403
    if (!gpgIdDir.cdUp()) {
×
404
      break;
405
    }
406
  }
407
  QString gpgIdPath(found ? gpgIdDir.absoluteFilePath(".gpg-id")
8✔
408
                          : QtPassSettings::getPassStore() + ".gpg-id");
22✔
409

410
  return gpgIdPath;
8✔
411
}
8✔
412

413
/**
414
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
415
 * @param for_file which file (folder) would you like recipients for
416
 * @return recipients gpg-id contents
417
 */
418
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
5✔
419
  QFile gpgId(getGpgIdPath(for_file));
5✔
420
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
5✔
421
    return {};
×
422
  }
423
  QStringList recipients;
5✔
424
  while (!gpgId.atEnd()) {
14✔
425
    QString recipient(gpgId.readLine());
18✔
426
    recipient = recipient.split("#")[0].trimmed();
18✔
427
    if (!recipient.isEmpty()) {
9✔
428
      recipients += recipient;
429
    }
430
  }
431
  return recipients;
432
}
5✔
433

434
/**
435
 * @brief Pass::getRecipientString formatted string for use with GPG
436
 * @param for_file which file (folder) would you like recipients for
437
 * @param separator formating separator eg: " -r "
438
 * @param count
439
 * @return recipient string
440
 */
441
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
442
                              int *count) -> QStringList {
443
  Q_UNUSED(separator)
444
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
445
  if (count) {
2✔
446
    *count = recipients.size();
1✔
447
  }
448
  return recipients;
2✔
449
}
450

451
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
452
 */
453

454
/**
455
 * @brief Generates a random number bounded by the given value.
456
 * @param bound Upper bound (exclusive)
457
 * @return Random number in range [0, bound)
458
 */
459
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,160✔
460
  if (bound < 2) {
1,160✔
461
    return 0;
462
  }
463

464
  quint32 randval;
465
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,160✔
466

467
  do {
468
    randval = QRandomGenerator::system()->generate();
469
  } while (randval < max_mod_bound);
1,160✔
470

471
  return randval % bound;
1,160✔
472
}
473

474
/**
475
 * @brief Generates a random password from the given charset.
476
 * @param charset Characters to use in the password
477
 * @param length Desired password length
478
 * @return Generated password string
479
 */
480
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,004✔
481
    -> QString {
482
  QString out;
1,004✔
483
  for (unsigned int i = 0; i < length; ++i) {
2,164✔
484
    out.append(charset.at(static_cast<int>(
1,160✔
485
        boundedRandom(static_cast<quint32>(charset.length())))));
1,160✔
486
  }
487
  return out;
1,004✔
488
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc