QtPass  1.2.3
Multi-platform GUI for pass, the standard unix password manager.
pass.cpp
Go to the documentation of this file.
1 #include "pass.h"
2 #include "qtpasssettings.h"
3 #include "util.h"
4 
5 #ifdef QT_DEBUG
6 #include "debughelper.h"
7 #endif
8 
9 using namespace std;
10 using namespace Enums;
11 
15 Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
16  connect(&exec,
17  static_cast<void (Executor::*)(int, int, const QString &,
18  const QString &)>(&Executor::finished),
19  this, &Pass::finished);
20 
21  // TODO(bezet): stop using process
22  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
23  // SIGNAL(error(QProcess::ProcessError)));
24 
26  env.append("WSLENV=PASSWORD_STORE_DIR/p");
27 }
28 
29 void Pass::executeWrapper(PROCESS id, const QString &app,
30  const QStringList &args, bool readStdout,
31  bool readStderr) {
32  executeWrapper(id, app, args, QString(), readStdout, readStderr);
33 }
34 
35 void Pass::executeWrapper(PROCESS id, const QString &app,
36  const QStringList &args, QString input,
37  bool readStdout, bool readStderr) {
38 #ifdef QT_DEBUG
39  dbg() << app << args;
40 #endif
41  exec.execute(id, QtPassSettings::getPassStore(), app, args, input, readStdout,
42  readStderr);
43 }
44 
45 void Pass::init() {
46 #ifdef __APPLE__
47  // If it exists, add the gpgtools to PATH
48  if (QFile("/usr/local/MacGPG2/bin").exists())
49  env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
50  // Add missing /usr/local/bin
51  if (env.filter("/usr/local/bin").isEmpty())
52  env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
53 #endif
54 
55  if (!QtPassSettings::getGpgHome().isEmpty()) {
56  QDir absHome(QtPassSettings::getGpgHome());
57  absHome.makeAbsolute();
58  env << "GNUPGHOME=" + absHome.path();
59  }
60 }
61 
69 QString Pass::Generate_b(unsigned int length, const QString &charset) {
70  QString passwd;
72  // --secure goes first as it overrides --no-* otherwise
73  QStringList args;
74  args.append("-1");
76  args.append("--secure");
77  args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
78  : "--capitalize");
79  args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
80  : "--numerals");
82  args.append("--symbols");
83  args.append(QString::number(length));
84  QString p_out;
85  // TODO(bezet): try-catch here(2 statuses to merge o_O)
87  &passwd) == 0)
88  passwd.remove(QRegExp("[\\n\\r]"));
89  else {
90  passwd.clear();
91 #ifdef QT_DEBUG
92  qDebug() << __FILE__ << ":" << __LINE__ << "\t"
93  << "pwgen fail";
94 #endif
95  // TODO(bezet): emit critical ?
96  }
97  } else {
98  if (charset.length() > 0) {
99  passwd = generateRandomPassword(charset, length);
100  } else {
101  emit critical(
102  tr("No characters chosen"),
103  tr("Can't generate password, there are no characters to choose from "
104  "set in the configuration!"));
105  }
106  }
107  return passwd;
108 }
109 
114 void Pass::GenerateGPGKeys(QString batch) {
116  {"--gen-key", "--no-tty", "--batch"}, batch);
117  // TODO check status / error messages - probably not here, it's just started
118  // here, see finished for details
119  // https://github.com/IJHack/QtPass/issues/202#issuecomment-251081688
120 }
121 
128 QList<UserInfo> Pass::listKeys(QStringList keystrings, bool secret) {
129  QList<UserInfo> users;
130  QStringList args = {"--no-tty", "--with-colons"};
131  args.append(secret ? "--list-secret-keys" : "--list-keys");
132 
133  foreach (QString keystring, keystrings) {
134  if (!keystring.isEmpty()) {
135  args.append(keystring);
136  }
137  }
138  QString p_out;
140  0)
141  return users;
142  QStringList keys = p_out.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
143  UserInfo current_user;
144  foreach (QString key, keys) {
145  QStringList props = key.split(':');
146  if (props.size() < 10)
147  continue;
148  if (props[0] == (secret ? "sec" : "pub")) {
149  if (!current_user.key_id.isEmpty())
150  users.append(current_user);
151  current_user = UserInfo();
152  current_user.key_id = props[4];
153  current_user.name = props[9].toUtf8();
154  current_user.validity = props[1][0].toLatin1();
155  current_user.created.setTime_t(props[5].toUInt());
156  current_user.expiry.setTime_t(props[6].toUInt());
157  } else if (current_user.name.isEmpty() && props[0] == "uid") {
158  current_user.name = props[9];
159  }
160  }
161  if (!current_user.key_id.isEmpty())
162  users.append(current_user);
163  return users;
164 }
165 
172 QList<UserInfo> Pass::listKeys(QString keystring, bool secret) {
173  return listKeys(QStringList(keystring), secret);
174 }
175 
186 void Pass::finished(int id, int exitCode, const QString &out,
187  const QString &err) {
188  PROCESS pid = static_cast<PROCESS>(id);
189  if (exitCode != 0) {
190  emit processErrorExit(exitCode, err);
191  return;
192  }
193  switch (pid) {
194  case GIT_INIT:
195  emit finishedGitInit(out, err);
196  break;
197  case GIT_PULL:
198  emit finishedGitPull(out, err);
199  break;
200  case GIT_PUSH:
201  emit finishedGitPush(out, err);
202  break;
203  case PASS_SHOW:
204  emit finishedShow(out);
205  break;
206  case PASS_OTP_GENERATE:
207  emit finishedOtpGenerate(out);
208  break;
209  case PASS_INSERT:
210  emit finishedInsert(out, err);
211  break;
212  case PASS_REMOVE:
213  emit finishedRemove(out, err);
214  break;
215  case PASS_INIT:
216  emit finishedInit(out, err);
217  break;
218  case PASS_MOVE:
219  emit finishedMove(out, err);
220  break;
221  case PASS_COPY:
222  emit finishedCopy(out, err);
223  break;
224  default:
225 #ifdef QT_DEBUG
226  dbg() << "Unhandled process type" << pid;
227 #endif
228  break;
229  }
230 }
231 
237  QStringList store = env.filter("PASSWORD_STORE_DIR=");
238  // put PASSWORD_STORE_DIR in env
239  if (store.isEmpty()) {
240  // dbg()<< "Added
241  // PASSWORD_STORE_DIR";
242  env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
243  } else {
244  // dbg()<< "Update
245  // PASSWORD_STORE_DIR with " + passStore;
246  env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
248  }
249  exec.setEnvironment(env);
250 }
251 
257 QStringList Pass::getRecipientList(QString for_file) {
258  QDir gpgIdPath(QFileInfo(for_file.startsWith(QtPassSettings::getPassStore())
259  ? for_file
260  : QtPassSettings::getPassStore() + for_file)
261  .absoluteDir());
262  bool found = false;
263  while (gpgIdPath.exists() &&
264  gpgIdPath.absolutePath().startsWith(QtPassSettings::getPassStore())) {
265  if (QFile(gpgIdPath.absoluteFilePath(".gpg-id")).exists()) {
266  found = true;
267  break;
268  }
269  if (!gpgIdPath.cdUp())
270  break;
271  }
272  QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id")
273  : QtPassSettings::getPassStore() + ".gpg-id");
274  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text))
275  return QStringList();
276  QStringList recipients;
277  while (!gpgId.atEnd()) {
278  QString recipient(gpgId.readLine());
279  recipient = recipient.trimmed();
280  if (!recipient.isEmpty())
281  recipients += recipient;
282  }
283  return recipients;
284 }
285 
293 QStringList Pass::getRecipientString(QString for_file, QString separator,
294  int *count) {
295  Q_UNUSED(separator)
296  Q_UNUSED(count)
297  return Pass::getRecipientList(for_file);
298 }
299 
300 /* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
301  */
302 
303 quint32 Pass::boundedRandom(quint32 bound) {
304  if (bound < 2) {
305  return 0;
306  }
307 
308  quint32 randval;
309  const quint32 max_mod_bound = (1 + ~bound) % bound;
310 
311 #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
312  static int fd = -1;
313  if (fd == -1) {
314  assert((fd = open("/dev/urandom", O_RDONLY)) >= 0);
315  }
316 #endif
317 
318  do {
319 #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
320  assert(read(fd, &randval, sizeof(randval)) == sizeof(randval));
321 #else
322  randval = QRandomGenerator::system()->generate();
323 #endif
324  } while (randval < max_mod_bound);
325 
326  return randval % bound;
327 }
328 
329 QString Pass::generateRandomPassword(const QString &charset,
330  unsigned int length) {
331  QString out;
332  for (unsigned int i = 0; i < length; ++i) {
333  out.append(charset.at(static_cast<int>(
334  boundedRandom(static_cast<quint32>(charset.length())))));
335  }
336  return out;
337 }
void finishedMove(const QString &, const QString &)
void finishedCopy(const QString &, const QString &)
QDateTime expiry
UserInfo::expiry date/time key expires.
Definition: userinfo.h:54
static bool isLessRandom(const bool &defaultValue=QVariant().toBool())
QDateTime created
UserInfo::created date/time key was created.
Definition: userinfo.h:58
void GenerateGPGKeys(QString batch)
Pass::GenerateGPGKeys internal gpg keypair generator . .
Definition: pass.cpp:114
PROCESS
Definition: enums.h:16
QList< UserInfo > listKeys(QStringList keystring, bool secret=false)
Pass::listKeys list users.
Definition: pass.cpp:128
static QString getGpgHome(const QString &defaultValue=QVariant().toString())
void finishedGitPush(const QString &, const QString &)
#define dbg()
Definition: debughelper.h:7
void setEnvironment(const QStringList &env)
Executor::setEnvironment set environment variables for executor processes.
Definition: executor.cpp:213
QString key_id
UserInfo::key_id hexadecimal representation.
Definition: userinfo.h:36
void finishedInsert(const QString &, const QString &)
QString generateRandomPassword(const QString &charset, unsigned int length)
Definition: pass.cpp:329
Executes external commands for handleing password, git and other data.
Definition: executor.h:12
static bool isAvoidNumbers(const bool &defaultValue=QVariant().toBool())
char validity
UserInfo::validity GnuPG representation of validity http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob_plain;f=doc/DETAILS.
Definition: userinfo.h:41
Pass()
Pass::Pass wrapper for using either pass or the pass imitation.
Definition: pass.cpp:15
void finishedRemove(const QString &, const QString &)
Executor exec
Definition: pass.h:32
void execute(int id, const QString &app, const QStringList &args, bool readStdout, bool readStderr=true)
Executor::execute execute an app.
Definition: executor.cpp:63
static QString getPassStore(const QString &defaultValue=QVariant().toString())
Enumerators for configuration and runtime items.
void finishedGitPull(const QString &, const QString &)
static QStringList getRecipientString(QString for_file, QString separator=" ", int *count=NULL)
Pass::getRecipientString formated string for use with GPG.
Definition: pass.cpp:293
void critical(QString, QString)
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Pass::processFinished reemits specific signal based on what process has finished. ...
Definition: pass.cpp:186
void init()
Definition: pass.cpp:45
static QStringList getRecipientList(QString for_file)
Pass::getRecipientList return list of gpg-id&#39;s to encrypt for.
Definition: pass.cpp:257
static bool isAvoidCapitals(const bool &defaultValue=QVariant().toBool())
void starting()
starting signal that is emited when process starts
virtual QString Generate_b(unsigned int length, const QString &charset)
Pass::Generate use either pwgen or internal password generator.
Definition: pass.cpp:69
void finishedInit(const QString &, const QString &)
static bool isUsePwgen(const bool &defaultValue=QVariant().toBool())
static QString getPwgenExecutable(const QString &defaultValue=QVariant().toString())
static bool isUseSymbols(const bool &defaultValue=QVariant().toBool())
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Definition: pass.cpp:29
quint32 boundedRandom(quint32 bound)
Definition: pass.cpp:303
void updateEnv()
Pass::updateEnv update the execution environment (used when switching profiles)
Definition: pass.cpp:236
QString name
UserInfo::name full name.
Definition: userinfo.h:32
Stores key info lines including validity, creation date and more.
Definition: userinfo.h:11
static QString getGpgExecutable(const QString &defaultValue=QVariant().toString())
void finishedShow(const QString &)
void finishedGitInit(const QString &, const QString &)
void startingExecuteWrapper()
void processErrorExit(int exitCode, const QString &err)
void finishedOtpGenerate(const QString &)
static int executeBlocking(QString app, const QStringList &args, QString input=QString(), QString *process_out=Q_NULLPTR, QString *process_err=Q_NULLPTR)
Executor::executeBlocking blocking version of the executor, takes input and presents it as stdin...
Definition: executor.cpp:160