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

IJHack / QtPass / 24080834108

07 Apr 2026 12:16PM UTC coverage: 20.046%. First build
24080834108

Pull #895

github

web-flow
Merge df35d01db into e7f408717
Pull Request #895: fix: kill stale GPG agents before key generation

17 of 38 new or added lines in 3 files covered. (44.74%)

1047 of 5223 relevant lines covered (20.05%)

7.76 hits per line

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

38.35
/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 <QFileInfo>
9
#include <QProcess>
10
#include <QRandomGenerator>
11
#include <QRegularExpression>
12
#include <utility>
13

14
#ifdef QT_DEBUG
15
#include "debughelper.h"
16
#endif
17

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

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

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

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

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

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

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

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

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

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

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

204
ResolvedGpgconfCommand Pass::resolveGpgconfCommand(const QString &gpgPath) {
7✔
205
  if (gpgPath.trimmed().isEmpty()) {
7✔
206
    return {"gpgconf", {}};
207
  }
208

209
  QStringList parts = QProcess::splitCommand(gpgPath);
6✔
210
  if (!parts.isEmpty()) {
6✔
211
    QString first = parts.first();
212
    if (first == "wsl" || first == "wsl.exe") {
8✔
213
      if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
7✔
214
        return {"gpgconf", {}};
215
      }
216
      if (parts.last().startsWith("gpg")) {
6✔
217
        parts.removeLast();
2✔
218
        parts.append("gpgconf");
4✔
219
        return {parts.first(), parts.mid(1)};
2✔
220
      }
221
      return {"gpgconf", {}};
222
    }
223
  }
224

225
  if (!gpgPath.contains('/') && !gpgPath.contains('\\')) {
2✔
226
    return {"gpgconf", {}};
227
  }
228

229
  QFileInfo gpgInfo(gpgPath);
1✔
230
  if (!gpgInfo.isAbsolute()) {
1✔
231
    return {"gpgconf", {}};
232
  }
233

234
  QDir dir(gpgInfo.absolutePath());
1✔
235

236
#ifdef Q_OS_WIN
237
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
238
  if (candidateExe.isExecutable()) {
239
    return {candidateExe.filePath(), {}};
240
  }
241
#endif
242

243
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
244
  if (candidate.isExecutable()) {
1✔
245
    return {candidate.filePath(), {}};
246
  }
247

248
  return {"gpgconf", {}};
249
}
7✔
250

251
/**
252
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
253
 * @param batch GnuPG style configuration string
254
 */
255
void Pass::GenerateGPGKeys(QString batch) {
×
256
  // Kill any stale GPG agents that might be holding locks on the key database
257
  // This helps avoid "database locked" timeouts during key generation
258
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
259
  if (!gpgPath.isEmpty()) {
×
NEW
260
    ResolvedGpgconfCommand gpgconf = resolveGpgconfCommand(gpgPath);
×
261
    QStringList killArgs = gpgconf.arguments;
NEW
262
    killArgs << "--kill";
×
NEW
263
    killArgs << "gpg-agent";
×
264
    // Use same environment as key generation to target correct gpg-agent
NEW
265
    Executor::executeBlocking(env, gpgconf.program, killArgs);
×
266
  }
267

268
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
269
                 std::move(batch));
270
}
×
271

272
/**
273
 * @brief Pass::listKeys list users
274
 * @param keystrings
275
 * @param secret list private keys
276
 * @return QList<UserInfo> users
277
 */
278
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
279
  QList<UserInfo> users;
×
280
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
281
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
282

283
  for (const QString &keystring : AS_CONST(keystrings)) {
×
284
    if (!keystring.isEmpty()) {
×
285
      args.append(keystring);
286
    }
287
  }
288
  QString p_out;
×
289
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
290
                                &p_out) != 0) {
291
    return users;
292
  }
293
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
294
  const QStringList keys =
295
      p_out.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
×
296
#else
297
  const QStringList keys =
298
      p_out.split(Util::newLinesRegex(), QString::SkipEmptyParts);
299
#endif
300
  UserInfo current_user;
×
301
  for (const QString &key : keys) {
×
302
    QStringList props = key.split(':');
×
303
    if (props.size() < 10) {
×
304
      continue;
305
    }
306
    if (props[0] == (secret ? "sec" : "pub")) {
×
307
      if (!current_user.key_id.isEmpty()) {
×
308
        users.append(current_user);
309
      }
310
      current_user = UserInfo();
×
311
      current_user.key_id = props[4];
×
312
      current_user.name = props[9].toUtf8();
×
313
      current_user.validity = props[1][0].toLatin1();
×
314
      current_user.created.setSecsSinceEpoch(props[5].toUInt());
×
315
      current_user.expiry.setSecsSinceEpoch(props[6].toUInt());
×
316
    } else if (current_user.name.isEmpty() && props[0] == "uid") {
×
317
      current_user.name = props[9];
×
318
    } else if ((props[0] == "fpr") && props[9].endsWith(current_user.key_id)) {
×
319
      current_user.key_id = props[9];
×
320
    }
321
  }
322
  if (!current_user.key_id.isEmpty()) {
×
323
    users.append(current_user);
324
  }
325
  return users;
326
}
×
327

328
/**
329
 * @brief Pass::listKeys list users
330
 * @param keystring
331
 * @param secret list private keys
332
 * @return QList<UserInfo> users
333
 */
334
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
335
  return listKeys(QStringList(keystring), secret);
×
336
}
337

338
/**
339
 * @brief Pass::processFinished reemits specific signal based on what process
340
 * has finished
341
 * @param id    id of Pass process that was scheduled and finished
342
 * @param exitCode  return code of a process
343
 * @param out   output generated by process(if capturing was requested, empty
344
 *              otherwise)
345
 * @param err   error output generated by process(if capturing was requested,
346
 *              or error occurred)
347
 */
348
void Pass::finished(int id, int exitCode, const QString &out,
×
349
                    const QString &err) {
350
  auto pid = static_cast<PROCESS>(id);
351
  if (exitCode != 0) {
×
352
    emit processErrorExit(exitCode, err);
×
353
    return;
×
354
  }
355
  switch (pid) {
×
356
  case GIT_INIT:
×
357
    emit finishedGitInit(out, err);
×
358
    break;
×
359
  case GIT_PULL:
×
360
    emit finishedGitPull(out, err);
×
361
    break;
×
362
  case GIT_PUSH:
×
363
    emit finishedGitPush(out, err);
×
364
    break;
×
365
  case PASS_SHOW:
×
366
    emit finishedShow(out);
×
367
    break;
×
368
  case PASS_OTP_GENERATE:
×
369
    emit finishedOtpGenerate(out);
×
370
    break;
×
371
  case PASS_INSERT:
×
372
    emit finishedInsert(out, err);
×
373
    break;
×
374
  case PASS_REMOVE:
×
375
    emit finishedRemove(out, err);
×
376
    break;
×
377
  case PASS_INIT:
×
378
    emit finishedInit(out, err);
×
379
    break;
×
380
  case PASS_MOVE:
×
381
    emit finishedMove(out, err);
×
382
    break;
×
383
  case PASS_COPY:
×
384
    emit finishedCopy(out, err);
×
385
    break;
×
386
  case GPG_GENKEYS:
×
387
    emit finishedGenerateGPGKeys(out, err);
×
388
    break;
×
389
  default:
390
#ifdef QT_DEBUG
391
    dbg() << "Unhandled process type" << pid;
392
#endif
393
    break;
394
  }
395
}
396

397
/**
398
 * @brief Pass::updateEnv update the execution environment (used when
399
 * switching profiles)
400
 */
401
void Pass::updateEnv() {
×
402
  // put PASSWORD_STORE_SIGNING_KEY in env
403
  QStringList envSigningKey = env.filter("PASSWORD_STORE_SIGNING_KEY=");
×
404
  QString currentSigningKey = QtPassSettings::getPassSigningKey();
×
405
  if (envSigningKey.isEmpty()) {
×
406
    if (!currentSigningKey.isEmpty()) {
×
407
      // dbg()<< "Added
408
      // PASSWORD_STORE_SIGNING_KEY with" + currentSigningKey;
409
      env.append("PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
410
    }
411
  } else {
412
    if (currentSigningKey.isEmpty()) {
×
413
      // dbg() << "Removed
414
      // PASSWORD_STORE_SIGNING_KEY";
415
      env.removeAll(envSigningKey.first());
416
    } else {
417
      // dbg()<< "Update
418
      // PASSWORD_STORE_SIGNING_KEY with " + currentSigningKey;
419
      env.replaceInStrings(envSigningKey.first(),
×
420
                           "PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
421
    }
422
  }
423
  // put PASSWORD_STORE_DIR in env
424
  QStringList store = env.filter("PASSWORD_STORE_DIR=");
×
425
  if (store.isEmpty()) {
×
426
    // dbg()<< "Added
427
    // PASSWORD_STORE_DIR";
428
    env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
×
429
  } else {
430
    // dbg()<< "Update
431
    // PASSWORD_STORE_DIR with " + passStore;
432
    env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
×
433
                                            QtPassSettings::getPassStore());
×
434
  }
435
  exec.setEnvironment(env);
×
436
}
×
437

438
/**
439
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
440
 * @param for_file which file (folder) would you like the gpgid file path for.
441
 * @return path to the gpgid file.
442
 */
443
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
8✔
444
  QString passStore =
445
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
16✔
446
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
8✔
447
  QString fullPath = normalizedFile.startsWith(passStore)
8✔
448
                         ? normalizedFile
8✔
449
                         : passStore + "/" + normalizedFile;
6✔
450
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
8✔
451
  bool found = false;
452
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
10✔
453
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
454
      found = true;
455
      break;
456
    }
457
    if (!gpgIdDir.cdUp()) {
×
458
      break;
459
    }
460
  }
461
  QString gpgIdPath(found ? gpgIdDir.absoluteFilePath(".gpg-id")
8✔
462
                          : QtPassSettings::getPassStore() + ".gpg-id");
22✔
463

464
  return gpgIdPath;
8✔
465
}
8✔
466

467
/**
468
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
469
 * @param for_file which file (folder) would you like recipients for
470
 * @return recipients gpg-id contents
471
 */
472
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
5✔
473
  QFile gpgId(getGpgIdPath(for_file));
5✔
474
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
5✔
475
    return {};
×
476
  }
477
  QStringList recipients;
5✔
478
  while (!gpgId.atEnd()) {
14✔
479
    QString recipient(gpgId.readLine());
18✔
480
    recipient = recipient.split("#")[0].trimmed();
18✔
481
    if (!recipient.isEmpty()) {
9✔
482
      recipients += recipient;
483
    }
484
  }
485
  return recipients;
486
}
5✔
487

488
/**
489
 * @brief Pass::getRecipientString formatted string for use with GPG
490
 * @param for_file which file (folder) would you like recipients for
491
 * @param separator formating separator eg: " -r "
492
 * @param count
493
 * @return recipient string
494
 */
495
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
496
                              int *count) -> QStringList {
497
  Q_UNUSED(separator)
498
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
499
  if (count) {
2✔
500
    *count = recipients.size();
1✔
501
  }
502
  return recipients;
2✔
503
}
504

505
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
506
 */
507

508
/**
509
 * @brief Generates a random number bounded by the given value.
510
 * @param bound Upper bound (exclusive)
511
 * @return Random number in range [0, bound)
512
 */
513
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,160✔
514
  if (bound < 2) {
1,160✔
515
    return 0;
516
  }
517

518
  quint32 randval;
519
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,160✔
520

521
  do {
522
    randval = QRandomGenerator::system()->generate();
523
  } while (randval < max_mod_bound);
1,160✔
524

525
  return randval % bound;
1,160✔
526
}
527

528
/**
529
 * @brief Generates a random password from the given charset.
530
 * @param charset Characters to use in the password
531
 * @param length Desired password length
532
 * @return Generated password string
533
 */
534
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,004✔
535
    -> QString {
536
  QString out;
1,004✔
537
  for (unsigned int i = 0; i < length; ++i) {
2,164✔
538
    out.append(charset.at(static_cast<int>(
1,160✔
539
        boundedRandom(static_cast<quint32>(charset.length())))));
1,160✔
540
  }
541
  return out;
1,004✔
542
}
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