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

IJHack / QtPass / 23657125318

27 Mar 2026 04:40PM UTC coverage: 18.29% (-0.09%) from 18.381%
23657125318

push

github

web-flow
Merge pull request #781 from IJHack/fix/780-validate-custom-charset

Fix weak passwords from test settings persisting (#780)

6 of 7 new or added lines in 2 files covered. (85.71%)

8 existing lines in 3 files now uncovered.

911 of 4981 relevant lines covered (18.29%)

7.53 hits per line

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

32.74
/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()) {
10✔
32
  connect(&exec,
10✔
33
          static_cast<void (Executor::*)(int, int, const QString &,
34
                                         const QString &)>(&Executor::finished),
35
          this, &Pass::finished);
10✔
36

37
  // TODO(bezet): stop using process
38
  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
39
  //        SIGNAL(error(QProcess::ProcessError)));
40

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

45
void Pass::executeWrapper(PROCESS id, const QString &app,
×
46
                          const QStringList &args, bool readStdout,
47
                          bool readStderr) {
48
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
49
}
×
50

51
void Pass::executeWrapper(PROCESS id, const QString &app,
×
52
                          const QStringList &args, QString input,
53
                          bool readStdout, bool readStderr) {
54
#ifdef QT_DEBUG
55
  dbg() << app << args;
56
#endif
57
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
×
58
               readStdout, readStderr);
59
}
×
60

61
void Pass::init() {
1✔
62
#ifdef __APPLE__
63
  // If it exists, add the gpgtools to PATH
64
  if (QFile("/usr/local/MacGPG2/bin").exists())
65
    env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
66
  // Add missing /usr/local/bin
67
  if (env.filter("/usr/local/bin").isEmpty())
68
    env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
69
#endif
70

71
  if (!QtPassSettings::getGpgHome().isEmpty()) {
2✔
72
    QDir absHome(QtPassSettings::getGpgHome());
×
73
    absHome.makeAbsolute();
×
74
    env << "GNUPGHOME=" + absHome.path();
×
75
  }
×
76
}
1✔
77

78
/**
79
 * @brief Pass::Generate use either pwgen or internal password
80
 * generator
81
 * @param length of the desired password
82
 * @param charset to use for generation
83
 * @return the password
84
 */
85
auto Pass::Generate_b(unsigned int length, const QString &charset) -> QString {
1,004✔
86
  QString passwd;
1,004✔
87
  if (QtPassSettings::isUsePwgen()) {
1,004✔
88
    // --secure goes first as it overrides --no-* otherwise
89
    QStringList args;
×
90
    args.append("-1");
×
91
    if (!QtPassSettings::isLessRandom()) {
×
92
      args.append("--secure");
×
93
    }
94
    args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
×
95
                                                  : "--capitalize");
96
    args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
×
97
                                                 : "--numerals");
98
    if (QtPassSettings::isUseSymbols()) {
×
99
      args.append("--symbols");
×
100
    }
101
    args.append(QString::number(length));
×
102
    // TODO(bezet): try-catch here(2 statuses to merge o_O)
103
    if (Executor::executeBlocking(QtPassSettings::getPwgenExecutable(), args,
×
104
                                  &passwd) == 0) {
105
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
106
      passwd.remove(literalNewLines);
×
107
    } else {
108
      passwd.clear();
×
109
#ifdef QT_DEBUG
110
      qDebug() << __FILE__ << ":" << __LINE__ << "\t"
111
               << "pwgen fail";
112
#endif
113
      // TODO(bezet): emit critical ?
114
    }
115
  } else {
116
    // Validate charset - if CUSTOM is selected but chars are empty,
117
    // fall back to ALLCHARS to prevent weak passwords (issue #780)
118
    QString effectiveCharset = charset;
119
    if (effectiveCharset.isEmpty()) {
1,004✔
120
      effectiveCharset = QtPassSettings::getPasswordConfiguration()
2✔
121
                             .Characters[PasswordConfiguration::ALLCHARS];
122
    }
123
    if (effectiveCharset.length() > 0) {
1,004✔
124
      passwd = generateRandomPassword(effectiveCharset, length);
2,008✔
125
    } else {
UNCOV
126
      emit critical(
×
UNCOV
127
          tr("No characters chosen"),
×
UNCOV
128
          tr("Can't generate password, there are no characters to choose from "
×
129
             "set in the configuration!"));
130
    }
131
  }
132
  return passwd;
1,004✔
133
}
134

135
/**
136
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
137
 * @param batch GnuPG style configuration string
138
 */
139
void Pass::GenerateGPGKeys(QString batch) {
×
140
  executeWrapper(GPG_GENKEYS, QtPassSettings::getGpgExecutable(),
×
141
                 {"--gen-key", "--no-tty", "--batch"}, std::move(batch));
142
  // TODO(annejan): check status / error messages - probably not here, it's just
143
  // started
144
  // here, see finished for details
145
  // https://github.com/IJHack/QtPass/issues/202#issuecomment-251081688
146
}
×
147

148
/**
149
 * @brief Pass::listKeys list users
150
 * @param keystrings
151
 * @param secret list private keys
152
 * @return QList<UserInfo> users
153
 */
154
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
155
  QList<UserInfo> users;
×
156
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
157
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
158

159
  for (const QString &keystring : AS_CONST(keystrings)) {
×
160
    if (!keystring.isEmpty()) {
×
161
      args.append(keystring);
162
    }
163
  }
164
  QString p_out;
×
165
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
166
                                &p_out) != 0) {
167
    return users;
168
  }
169
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
170
  const QStringList keys =
171
      p_out.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
×
172
#else
173
  const QStringList keys =
174
      p_out.split(Util::newLinesRegex(), QString::SkipEmptyParts);
175
#endif
176
  UserInfo current_user;
×
177
  for (const QString &key : keys) {
×
178
    QStringList props = key.split(':');
×
179
    if (props.size() < 10) {
×
180
      continue;
181
    }
182
    if (props[0] == (secret ? "sec" : "pub")) {
×
183
      if (!current_user.key_id.isEmpty()) {
×
184
        users.append(current_user);
185
      }
186
      current_user = UserInfo();
×
187
      current_user.key_id = props[4];
×
188
      current_user.name = props[9].toUtf8();
×
189
      current_user.validity = props[1][0].toLatin1();
×
190
      current_user.created.setSecsSinceEpoch(props[5].toUInt());
×
191
      current_user.expiry.setSecsSinceEpoch(props[6].toUInt());
×
192
    } else if (current_user.name.isEmpty() && props[0] == "uid") {
×
193
      current_user.name = props[9];
×
194
    } else if ((props[0] == "fpr") && props[9].endsWith(current_user.key_id)) {
×
195
      current_user.key_id = props[9];
×
196
    }
197
  }
198
  if (!current_user.key_id.isEmpty()) {
199
    users.append(current_user);
200
  }
201
  return users;
202
}
×
203

204
/**
205
 * @brief Pass::listKeys list users
206
 * @param keystring
207
 * @param secret list private keys
208
 * @return QList<UserInfo> users
209
 */
210
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
211
  return listKeys(QStringList(keystring), secret);
×
212
}
213

214
/**
215
 * @brief Pass::processFinished reemits specific signal based on what process
216
 * has finished
217
 * @param id    id of Pass process that was scheduled and finished
218
 * @param exitCode  return code of a process
219
 * @param out   output generated by process(if capturing was requested, empty
220
 *              otherwise)
221
 * @param err   error output generated by process(if capturing was requested,
222
 *              or error occurred)
223
 */
224
void Pass::finished(int id, int exitCode, const QString &out,
×
225
                    const QString &err) {
226
  auto pid = static_cast<PROCESS>(id);
227
  if (exitCode != 0) {
×
228
    emit processErrorExit(exitCode, err);
×
229
    return;
×
230
  }
231
  switch (pid) {
×
232
  case GIT_INIT:
×
233
    emit finishedGitInit(out, err);
×
234
    break;
×
235
  case GIT_PULL:
×
236
    emit finishedGitPull(out, err);
×
237
    break;
×
238
  case GIT_PUSH:
×
239
    emit finishedGitPush(out, err);
×
240
    break;
×
241
  case PASS_SHOW:
×
242
    emit finishedShow(out);
×
243
    break;
×
244
  case PASS_OTP_GENERATE:
×
245
    emit finishedOtpGenerate(out);
×
246
    break;
×
247
  case PASS_INSERT:
×
248
    emit finishedInsert(out, err);
×
249
    break;
×
250
  case PASS_REMOVE:
×
251
    emit finishedRemove(out, err);
×
252
    break;
×
253
  case PASS_INIT:
×
254
    emit finishedInit(out, err);
×
255
    break;
×
256
  case PASS_MOVE:
×
257
    emit finishedMove(out, err);
×
258
    break;
×
259
  case PASS_COPY:
×
260
    emit finishedCopy(out, err);
×
261
    break;
×
262
  case GPG_GENKEYS:
×
263
    emit finishedGenerateGPGKeys(out, err);
×
264
    break;
×
265
  default:
266
#ifdef QT_DEBUG
267
    dbg() << "Unhandled process type" << pid;
268
#endif
269
    break;
270
  }
271
}
272

273
/**
274
 * @brief Pass::updateEnv update the execution environment (used when
275
 * switching profiles)
276
 */
277
void Pass::updateEnv() {
×
278
  // put PASSWORD_STORE_SIGNING_KEY in env
279
  QStringList envSigningKey = env.filter("PASSWORD_STORE_SIGNING_KEY=");
×
280
  QString currentSigningKey = QtPassSettings::getPassSigningKey();
×
281
  if (envSigningKey.isEmpty()) {
×
282
    if (!currentSigningKey.isEmpty()) {
×
283
      // dbg()<< "Added
284
      // PASSWORD_STORE_SIGNING_KEY with" + currentSigningKey;
285
      env.append("PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
286
    }
287
  } else {
288
    if (currentSigningKey.isEmpty()) {
×
289
      // dbg() << "Removed
290
      // PASSWORD_STORE_SIGNING_KEY";
291
      env.removeAll(envSigningKey.first());
292
    } else {
293
      // dbg()<< "Update
294
      // PASSWORD_STORE_SIGNING_KEY with " + currentSigningKey;
295
      env.replaceInStrings(envSigningKey.first(),
×
296
                           "PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
297
    }
298
  }
299
  // put PASSWORD_STORE_DIR in env
300
  QStringList store = env.filter("PASSWORD_STORE_DIR=");
×
301
  if (store.isEmpty()) {
×
302
    // dbg()<< "Added
303
    // PASSWORD_STORE_DIR";
304
    env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
×
305
  } else {
306
    // dbg()<< "Update
307
    // PASSWORD_STORE_DIR with " + passStore;
308
    env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
×
309
                                            QtPassSettings::getPassStore());
×
310
  }
311
  exec.setEnvironment(env);
×
312
}
×
313

314
/**
315
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
316
 * @param for_file which file (folder) would you like the gpgid file path for.
317
 * @return path to the gpgid file.
318
 */
319
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
8✔
320
  QString passStore =
321
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
16✔
322
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
8✔
323
  QString fullPath = normalizedFile.startsWith(passStore)
8✔
324
                         ? normalizedFile
8✔
325
                         : passStore + "/" + normalizedFile;
6✔
326
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
8✔
327
  bool found = false;
328
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
10✔
329
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
330
      found = true;
331
      break;
332
    }
333
    if (!gpgIdDir.cdUp()) {
×
334
      break;
335
    }
336
  }
337
  QString gpgIdPath(found ? gpgIdDir.absoluteFilePath(".gpg-id")
8✔
338
                          : QtPassSettings::getPassStore() + ".gpg-id");
22✔
339

340
  return gpgIdPath;
8✔
341
}
8✔
342

343
/**
344
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
345
 * @param for_file which file (folder) would you like recepients for
346
 * @return recepients gpg-id contents
347
 */
348
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
5✔
349
  QFile gpgId(getGpgIdPath(for_file));
5✔
350
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
5✔
351
    return {};
×
352
  }
353
  QStringList recipients;
5✔
354
  while (!gpgId.atEnd()) {
14✔
355
    QString recipient(gpgId.readLine());
18✔
356
    recipient = recipient.split("#")[0].trimmed();
18✔
357
    if (!recipient.isEmpty()) {
9✔
358
      recipients += recipient;
359
    }
360
  }
361
  return recipients;
362
}
5✔
363

364
/**
365
 * @brief Pass::getRecipientString formated string for use with GPG
366
 * @param for_file which file (folder) would you like recepients for
367
 * @param separator formating separator eg: " -r "
368
 * @param count
369
 * @return recepient string
370
 */
371
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
372
                              int *count) -> QStringList {
373
  Q_UNUSED(separator)
374
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
375
  if (count) {
2✔
376
    *count = recipients.size();
1✔
377
  }
378
  return recipients;
2✔
379
}
380

381
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
382
 */
383

384
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,160✔
385
  if (bound < 2) {
1,160✔
386
    return 0;
387
  }
388

389
  quint32 randval;
390
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,160✔
391

392
  do {
393
    randval = QRandomGenerator::system()->generate();
394
  } while (randval < max_mod_bound);
1,160✔
395

396
  return randval % bound;
1,160✔
397
}
398

399
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,004✔
400
    -> QString {
401
  QString out;
1,004✔
402
  for (unsigned int i = 0; i < length; ++i) {
2,164✔
403
    out.append(charset.at(static_cast<int>(
1,160✔
404
        boundedRandom(static_cast<quint32>(charset.length())))));
1,160✔
405
  }
406
  return out;
1,004✔
407
}
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