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 "debughelper.h"
3 #include "qtpasssettings.h"
4 #include "util.h"
5 
6 using namespace std;
7 using namespace Enums;
8 
12 Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
13  connect(&exec,
14  static_cast<void (Executor::*)(int, int, const QString &,
15  const QString &)>(&Executor::finished),
16  this, &Pass::finished);
17 
18  // TODO(bezet): stop using process
19  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
20  // SIGNAL(error(QProcess::ProcessError)));
21 
23 }
24 
25 void Pass::executeWrapper(PROCESS id, const QString &app,
26  const QStringList &args, bool readStdout,
27  bool readStderr) {
28  executeWrapper(id, app, args, QString(), readStdout, readStderr);
29 }
30 
31 void Pass::executeWrapper(PROCESS id, const QString &app,
32  const QStringList &args, QString input,
33  bool readStdout, bool readStderr) {
34  dbg() << app << args;
35  exec.execute(id, QtPassSettings::getPassStore(), app, args, input, readStdout,
36  readStderr);
37 }
38 
39 void Pass::init() {
40 #ifdef __APPLE__
41  // If it exists, add the gpgtools to PATH
42  if (QFile("/usr/local/MacGPG2/bin").exists())
43  env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
44  // Add missing /usr/local/bin
45  if (env.filter("/usr/local/bin").isEmpty())
46  env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
47 #endif
48 
49  if (!QtPassSettings::getGpgHome().isEmpty()) {
50  QDir absHome(QtPassSettings::getGpgHome());
51  absHome.makeAbsolute();
52  env << "GNUPGHOME=" + absHome.path();
53  }
54 }
55 
63 QString Pass::Generate_b(unsigned int length, const QString &charset) {
64  QString passwd;
66  // --secure goes first as it overrides --no-* otherwise
67  QStringList args;
68  args.append("-1");
70  args.append("--secure");
71  args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
72  : "--capitalize");
73  args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
74  : "--numerals");
76  args.append("--symbols");
77  args.append(QString::number(length));
78  QString p_out;
79  // TODO(bezet): try-catch here(2 statuses to merge o_O)
81  &passwd) == 0)
82  passwd.remove(QRegExp("[\\n\\r]"));
83  else {
84  passwd.clear();
85  qDebug() << __FILE__ << ":" << __LINE__ << "\t"
86  << "pwgen fail";
87  // TODO(bezet): emit critical ?
88  }
89  } else {
90  if (charset.length() > 0) {
91  passwd = generateRandomPassword(charset, length);
92  } else {
93  emit critical(
94  tr("No characters chosen"),
95  tr("Can't generate password, there are no characters to choose from "
96  "set in the configuration!"));
97  }
98  }
99  return passwd;
100 }
101 
106 void Pass::GenerateGPGKeys(QString batch) {
108  {"--gen-key", "--no-tty", "--batch"}, batch);
109  // TODO check status / error messages - probably not here, it's just started
110  // here, see finished for details
111  // https://github.com/IJHack/QtPass/issues/202#issuecomment-251081688
112 }
113 
120 QList<UserInfo> Pass::listKeys(QStringList keystrings, bool secret) {
121  QList<UserInfo> users;
122  QStringList args = {"--no-tty", "--with-colons"};
123  args.append(secret ? "--list-secret-keys" : "--list-keys");
124 
125  foreach (QString keystring, keystrings) {
126  if (!keystring.isEmpty()) {
127  args.append(keystring);
128  }
129  }
130  QString p_out;
132  0)
133  return users;
134  QStringList keys = p_out.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
135  UserInfo current_user;
136  foreach (QString key, keys) {
137  QStringList props = key.split(':');
138  if (props.size() < 10)
139  continue;
140  if (props[0] == (secret ? "sec" : "pub")) {
141  if (!current_user.key_id.isEmpty())
142  users.append(current_user);
143  current_user = UserInfo();
144  current_user.key_id = props[4];
145  current_user.name = props[9].toUtf8();
146  current_user.validity = props[1][0].toLatin1();
147  current_user.created.setTime_t(props[5].toUInt());
148  current_user.expiry.setTime_t(props[6].toUInt());
149  } else if (current_user.name.isEmpty() && props[0] == "uid") {
150  current_user.name = props[9];
151  }
152  }
153  if (!current_user.key_id.isEmpty())
154  users.append(current_user);
155  return users;
156 }
157 
164 QList<UserInfo> Pass::listKeys(QString keystring, bool secret) {
165  return listKeys(QStringList(keystring), secret);
166 }
167 
178 void Pass::finished(int id, int exitCode, const QString &out,
179  const QString &err) {
180  PROCESS pid = static_cast<PROCESS>(id);
181  if (exitCode != 0) {
182  emit processErrorExit(exitCode, err);
183  return;
184  }
185  switch (pid) {
186  case GIT_INIT:
187  emit finishedGitInit(out, err);
188  break;
189  case GIT_PULL:
190  emit finishedGitPull(out, err);
191  break;
192  case GIT_PUSH:
193  emit finishedGitPush(out, err);
194  break;
195  case PASS_SHOW:
196  emit finishedShow(out);
197  break;
198  case PASS_OTP_GENERATE:
199  emit finishedOtpGenerate(out);
200  break;
201  case PASS_INSERT:
202  emit finishedInsert(out, err);
203  break;
204  case PASS_REMOVE:
205  emit finishedRemove(out, err);
206  break;
207  case PASS_INIT:
208  emit finishedInit(out, err);
209  break;
210  case PASS_MOVE:
211  emit finishedMove(out, err);
212  break;
213  case PASS_COPY:
214  emit finishedCopy(out, err);
215  break;
216  default:
217  dbg() << "Unhandled process type" << pid;
218  break;
219  }
220 }
221 
227  QStringList store = env.filter("PASSWORD_STORE_DIR");
228  // put PASSWORD_STORE_DIR in env
229  if (store.isEmpty()) {
230  // dbg()<< "Added
231  // PASSWORD_STORE_DIR";
232  env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
233  } else {
234  // dbg()<< "Update
235  // PASSWORD_STORE_DIR with " + passStore;
236  env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
238  }
239  exec.setEnvironment(env);
240 }
241 
247 QStringList Pass::getRecipientList(QString for_file) {
248  QDir gpgIdPath(QFileInfo(for_file.startsWith(QtPassSettings::getPassStore())
249  ? for_file
250  : QtPassSettings::getPassStore() + for_file)
251  .absoluteDir());
252  bool found = false;
253  while (gpgIdPath.exists() &&
254  gpgIdPath.absolutePath().startsWith(QtPassSettings::getPassStore())) {
255  if (QFile(gpgIdPath.absoluteFilePath(".gpg-id")).exists()) {
256  found = true;
257  break;
258  }
259  if (!gpgIdPath.cdUp())
260  break;
261  }
262  QFile gpgId(found ? gpgIdPath.absoluteFilePath(".gpg-id")
263  : QtPassSettings::getPassStore() + ".gpg-id");
264  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text))
265  return QStringList();
266  QStringList recipients;
267  while (!gpgId.atEnd()) {
268  QString recipient(gpgId.readLine());
269  recipient = recipient.trimmed();
270  if (!recipient.isEmpty())
271  recipients += recipient;
272  }
273  return recipients;
274 }
275 
283 QStringList Pass::getRecipientString(QString for_file, QString separator,
284  int *count) {
285  return Pass::getRecipientList(for_file);
286 }
287 
288 /* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
289  */
290 
291 quint32 Pass::boundedRandom(quint32 bound) {
292  if (bound < 2) {
293  return 0;
294  }
295 
296  quint32 randval;
297  const quint32 max_mod_bound = (1 + ~bound) % bound;
298 
299 #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
300  static int fd = -1;
301  if (fd == -1) {
302  assert((fd = open("/dev/urandom", O_RDONLY)) >= 0);
303  }
304 #endif
305 
306  do {
307 #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
308  assert(read(fd, &randval, sizeof(randval)) == sizeof(randval));
309 #else
310  randval = QRandomGenerator::system()->generate();
311 #endif
312  } while (randval < max_mod_bound);
313 
314  return randval % bound;
315 }
316 
317 QString Pass::generateRandomPassword(const QString &charset,
318  unsigned int length) {
319  QString out;
320  for (unsigned int i = 0; i < length; ++i) {
321  out.append(charset.at(static_cast<int>(
322  boundedRandom(static_cast<quint32>(charset.length())))));
323  }
324  return out;
325 }
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:106
PROCESS
Definition: enums.h:16
QList< UserInfo > listKeys(QStringList keystring, bool secret=false)
Pass::listKeys list users.
Definition: pass.cpp:120
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:172
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:317
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:12
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:51
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:283
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:178
void init()
Definition: pass.cpp:39
static QStringList getRecipientList(QString for_file)
Pass::getRecipientList return list of gpg-id&#39;s to encrypt for.
Definition: pass.cpp:247
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:63
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:25
quint32 boundedRandom(quint32 bound)
Definition: pass.cpp:291
void updateEnv()
Pass::updateEnv update the execution environment (used when switching profiles)
Definition: pass.cpp:226
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 &)
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:125