CleanerError and warning output (#194)

Co-authored-by: Chris Rizzitello <crizzitello@ics.com>
main
crizzitello 2022-07-14 15:39:31 -04:00 committed by GitHub
parent 2fb6c7d43f
commit c85f4ca237
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 40 additions and 40 deletions

View File

@ -24,9 +24,8 @@ void DatabaseConnection::withConnection(const QString& dbPath, const QString &db
conn.connect(); conn.connect();
try { try {
actions(conn); actions(conn);
} } catch(const std::runtime_error& e) {
catch(const std::runtime_error& e) { qWarning() << "Error running action: " << e.what();
QTextStream(stderr) << "Ran into an error dealing with database actions: " << e.what() << Qt::endl;
} }
conn.close(); conn.close();
@ -117,7 +116,7 @@ model::Evidence DatabaseConnection::getEvidenceDetails(qint64 evidenceID) {
rtn.tags = getTagsForEvidenceID(evidenceID); rtn.tags = getTagsForEvidenceID(evidenceID);
} }
else { else {
QTextStream(stderr) << "Could not find evidence with id: " << evidenceID << Qt::endl; qWarning() << "Could not find evidence with id: " << evidenceID;
} }
return rtn; return rtn;
} }
@ -132,7 +131,7 @@ bool DatabaseConnection::deleteEvidence(qint64 evidenceID)
auto q = executeQuery(getDB(), "DELETE FROM evidence WHERE id=?", {evidenceID}); auto q = executeQuery(getDB(), "DELETE FROM evidence WHERE id=?", {evidenceID});
if (q.lastError().type() == QSqlError::NoError) if (q.lastError().type() == QSqlError::NoError)
return true; return true;
QTextStream(stderr) << "Unable to Delete " << evidenceID << " " << q.lastError().text(); qWarning() << "Unable to Delete " << evidenceID << " " << q.lastError().text();
return false; return false;
} }
@ -336,7 +335,7 @@ QList<model::Evidence> DatabaseConnection::createEvidenceExportView(
// Throws exceptions/FileError if a migration file cannot be found. // Throws exceptions/FileError if a migration file cannot be found.
bool DatabaseConnection::migrateDB() { bool DatabaseConnection::migrateDB() {
auto db = getDB(); auto db = getDB();
QTextStream(stdout) << "Checking database state" << Qt::endl; qInfo() << "Checking database state";
auto migrationsToApply = DatabaseConnection::getUnappliedMigrations(db); auto migrationsToApply = DatabaseConnection::getUnappliedMigrations(db);
for (const QString &newMigration : migrationsToApply) { for (const QString &newMigration : migrationsToApply) {
@ -347,14 +346,14 @@ bool DatabaseConnection::migrateDB() {
auto content = QString(migrationFile.readAll()); auto content = QString(migrationFile.readAll());
migrationFile.close(); migrationFile.close();
QTextStream(stdout) << "Applying Migration: " << newMigration << Qt::endl; qInfo() << "Applying Migration: " << newMigration;
auto upScript = extractMigrateUpContent(content); auto upScript = extractMigrateUpContent(content);
executeQuery(db, upScript); executeQuery(db, upScript);
executeQuery(db, executeQuery(db,
"INSERT INTO migrations (migration_name, applied_at) VALUES (?, datetime('now'))", "INSERT INTO migrations (migration_name, applied_at) VALUES (?, datetime('now'))",
{newMigration}); {newMigration});
} }
QTextStream(stdout) << "All migrations applied" << Qt::endl; qInfo() << "All migrations applied";
return true; return true;
} }
@ -390,7 +389,7 @@ QStringList DatabaseConnection::getUnappliedMigrations(const QSqlDatabase &db)
appliedMigrations.removeAt(foundIndex); appliedMigrations.removeAt(foundIndex);
} }
if (!appliedMigrations.empty()) { if (!appliedMigrations.empty()) {
QTextStream(stderr) << "Database is in an inconsistent state"; qWarning() << "Database is in an inconsistent state";
} }
return migrationsToApply; return migrationsToApply;
} }

View File

@ -132,7 +132,7 @@ class ReleaseDigest {
static ReleaseDigest fromReleases(QString curVersion, const QList<GithubRelease> &borrowedReleases) { static ReleaseDigest fromReleases(QString curVersion, const QList<GithubRelease> &borrowedReleases) {
if (curVersion.contains(QStringLiteral("v0.0.0"))) { if (curVersion.contains(QStringLiteral("v0.0.0"))) {
QTextStream(stdout) << "skipping unversioned/development release check" << Qt::endl; qInfo() << "skipping unversioned/development release check";
return ReleaseDigest(); return ReleaseDigest();
} }

View File

@ -264,10 +264,10 @@ void EvidenceManager::deleteSet(QList<qint64> ids) {
} }
if (!removedAllDbRecords) { if (!removedAllDbRecords) {
QTextStream(stderr) << "Could not delete evidence from internal database. Errors: " << Qt::endl; qWarning() << "Could not delete evidence from internal database. Errors: ";
for (const auto& resp : responses) { for (const auto& resp : responses) {
if (!resp.dbDeleteSuccess) { if (!resp.dbDeleteSuccess) {
QTextStream(stderr) << " id: " << resp.model.id << " ;; Error: "<< resp.errorText << Qt::endl; qWarning() << " id: " << resp.model.id << " ;; Error: "<< resp.errorText;
} }
} }
} }
@ -380,8 +380,7 @@ void EvidenceManager::loadEvidence() {
} }
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Could not retrieve evidence for operation. Error: " << e.text() qWarning() << "Could not retrieve evidence for operation. Error: " << e.text();
<< Qt::endl;
} }
} }
@ -439,7 +438,7 @@ void EvidenceManager::refreshRow(int row) {
setRowText(row, updatedData); setRowText(row, updatedData);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Could not refresh table row: " << e.text() << Qt::endl; qWarning() << "Could not refresh table row: " << e.text();
} }
} }
@ -506,8 +505,7 @@ void EvidenceManager::onUploadComplete() {
db->updateEvidenceError(errMessage, evidenceIDForRequest); db->updateEvidenceError(errMessage, evidenceIDForRequest);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Upload failed. Could not update internal database. Error: " qWarning() << "Upload failed. Could not update internal database. Error: " << e.text();
<< e.text() << Qt::endl;
} }
QMessageBox::warning(this, tr("Cannot Submit Evidence"), QMessageBox::warning(this, tr("Cannot Submit Evidence"),
tr("Upload failed: Network error. Check your connection and try again.\n" tr("Upload failed: Network error. Check your connection and try again.\n"
@ -518,8 +516,7 @@ void EvidenceManager::onUploadComplete() {
db->updateEvidenceSubmitted(evidenceIDForRequest); db->updateEvidenceSubmitted(evidenceIDForRequest);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Upload successful. Could not update internal database. Error: " qWarning() << "Upload successful. Could not update internal database. Error: " << e.text();
<< e.text() << Qt::endl;
} }
Q_EMIT evidenceChanged(evidenceIDForRequest, true); // lock the editing form Q_EMIT evidenceChanged(evidenceIDForRequest, true); // lock the editing form
} }

View File

@ -136,8 +136,7 @@ void GetInfo::onUploadComplete() {
db->updateEvidenceError(errMessage, evidenceID); db->updateEvidenceError(errMessage, evidenceID);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Upload failed. Could not update internal database. Error: " qWarning() << "Upload failed. Could not update internal database. Error: " << e.text();
<< e.text() << Qt::endl;
} }
QMessageBox::warning(this, tr("Cannot submit evidence"), QMessageBox::warning(this, tr("Cannot submit evidence"),
tr("Upload failed: Network error. Check your connection and try again.\n" tr("Upload failed: Network error. Check your connection and try again.\n"
@ -152,8 +151,7 @@ void GetInfo::onUploadComplete() {
close(); close();
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "Upload successful. Could not update internal database. Error: " qWarning() << "Upload successful. Could not update internal database. Error: " << e.text();
<< e.text() << Qt::endl;
} }
} }
// we don't actually need anything from the uploadAssets reply, so just clean it up. // we don't actually need anything from the uploadAssets reply, so just clean it up.

View File

@ -30,7 +30,7 @@ class FileHelpers {
if (file.open(QIODevice::ReadOnly)) if (file.open(QIODevice::ReadOnly))
data = file.readAll(); data = file.readAll();
if (file.error() != QFile::NoError) if (file.error() != QFile::NoError)
QTextStream(stderr) << "Unable to read from file: " << path << '\n' << file.error(); qWarning() << "Unable to read from file: " << path << '\n' << file.error();
return data; return data;
} }

View File

@ -123,7 +123,7 @@ public:
/// Callers should retrieve the result by listening for the releasesChecked signal /// Callers should retrieve the result by listening for the releasesChecked signal
static void checkForNewRelease(QString owner, QString repo) { static void checkForNewRelease(QString owner, QString repo) {
if (owner.isEmpty() || repo.isEmpty()) { if (owner.isEmpty() || repo.isEmpty()) {
QTextStream(stderr) << "Skipping release check: no owner or repo set." << Qt::endl; qWarning() << "Skipping release check: no owner or repo set.";
return; return;
} }
get()->githubReleaseReply = get()->getGithubReleases(owner, repo); get()->githubReleaseReply = get()->getGithubReleases(owner, repo);

View File

@ -181,7 +181,7 @@ class RequestBuilder {
reply = nam->post(req, body); reply = nam->post(req, body);
break; break;
default: default:
QTextStream(stderr) << "Requestbuilder contains an unsupported request method" << Qt::endl; qWarning() << "Requestbuilder contains an unsupported request method";
} }
if (autodelete) { if (autodelete) {
delete this; delete this;

View File

@ -31,16 +31,15 @@ int main(int argc, char* argv[]) {
QCoreApplication::setOrganizationName("ashirt"); QCoreApplication::setOrganizationName("ashirt");
#endif #endif
DatabaseConnection* conn = new DatabaseConnection(Constants::dbLocation, Constants::defaultDbName); DatabaseConnection* conn = new DatabaseConnection(Constants::dbLocation, Constants::defaultDbName);
if (!conn->connect()) { if (!conn->connect()) {
QTextStream(stderr) << "Unable to connect to Database" << Qt::endl; QMessageBox::critical(nullptr, QStringLiteral("ASHIRT Error"), QStringLiteral("Unable to connect to database"));
return -1; return -1;
} }
auto configError = AppConfig::getInstance().errorText; auto configError = AppConfig::getInstance().errorText;
if (!configError.isEmpty()) { // quick check & preload config data if (!configError.isEmpty()) { // quick check & preload config data
QTextStream(stderr) << "Unable to load config file: " << configError << Qt::endl; QMessageBox::critical(nullptr, QStringLiteral("ASHIRT Error"), QStringLiteral("Unable to connect to load settings"));
return -1; return -1;
} }
@ -67,10 +66,10 @@ int main(int argc, char* argv[]) {
window->deleteLater(); window->deleteLater();
} }
catch (std::exception const& ex) { catch (std::exception const& ex) {
QTextStream(stderr) << "Exception while running: " << ex.what() << Qt::endl; qWarning() << "Exception while running: " << ex.what();
} }
catch (...) { catch (...) {
QTextStream(stderr) << "Unhandled exception while running" << Qt::endl; qWarning() << "Unhandled exception while running";
} }
return rtn; return rtn;
} }
@ -90,14 +89,14 @@ int main(int argc, char *argv[]) { handleCLI(std::vector<string>(argv, argv + ar
void handleCLI(std::vector<std::string> args) { void handleCLI(std::vector<std::string> args) {
size_t trueCount = args.size() - 1; size_t trueCount = args.size() - 1;
QTextStream(stdout) << "You provided " << trueCount << " arguments.\n"; qInfo() << "You provided " << trueCount << " arguments";
if (trueCount == 0) { if (trueCount == 0) {
QTextStream(stdout) << "Next time try suppling some arguments." << Qt::endl; qInfo() << "Next time try suppling some arguments.";
return; return;
} }
QTextStream(stdout) << "All arguments:" << Qt::endl; qInfo() << "All arguments:";
for (size_t i = 1; i < args.size(); i++) { for (size_t i = 1; i < args.size(); i++) {
QTextStream(stdout) << "\t" << QString::fromStdString(args.at(i)) << Qt::endl; qInfo() << "\t" << QString::fromStdString(args.at(i));
} }
} }

View File

@ -216,7 +216,7 @@ void TrayManager::onClipboardCapture()
return; return;
Codeblock evidence(clipboardContent); Codeblock evidence(clipboardContent);
if(!Codeblock::saveCodeblock(evidence)) { if(!Codeblock::saveCodeblock(evidence)) {
QTextStream(stderr) << "Error Gathering Evidence from clipboard" << Qt::endl; setTrayMessage(NO_ACTION, _recordErrorTitle, tr("Error Gathering Evidence from clipboard"), QSystemTrayIcon::Information);
return; return;
} }
path = evidence.filePath(); path = evidence.filePath();
@ -235,7 +235,7 @@ void TrayManager::onClipboardCapture()
evidenceID = createNewEvidence(path, type); evidenceID = createNewEvidence(path, type);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "could not write to the database: " << e.text() << Qt::endl; showDBWriteErrorTrayMessage(e.text());
return; return;
} }
spawnGetInfoWindow(evidenceID); spawnGetInfoWindow(evidenceID);
@ -247,12 +247,17 @@ void TrayManager::onScreenshotCaptured(const QString& path) {
spawnGetInfoWindow(evidenceID); spawnGetInfoWindow(evidenceID);
} }
catch (QSqlError& e) { catch (QSqlError& e) {
QTextStream(stderr) << "could not write to the database: " << e.text() << Qt::endl; showDBWriteErrorTrayMessage(e.text());
} }
} }
void TrayManager::showDBWriteErrorTrayMessage(const QString &errorMessage)
{
setTrayMessage(NO_ACTION, _recordErrorTitle, tr("Could not write to database: %1").arg(errorMessage), QSystemTrayIcon::Warning);
}
void TrayManager::showNoOperationSetTrayMessage() { void TrayManager::showNoOperationSetTrayMessage() {
setTrayMessage(NO_ACTION, tr("Unable to Record Evidence"), setTrayMessage(NO_ACTION, _recordErrorTitle,
tr("No Operation has been selected. Please select an operation first."), tr("No Operation has been selected. Please select an operation first."),
QSystemTrayIcon::Warning); QSystemTrayIcon::Warning);
} }

View File

@ -61,6 +61,7 @@ class TrayManager : public QDialog {
qint64 createNewEvidence(const QString& filepath, const QString& evidenceType); qint64 createNewEvidence(const QString& filepath, const QString& evidenceType);
void spawnGetInfoWindow(qint64 evidenceID); void spawnGetInfoWindow(qint64 evidenceID);
void showNoOperationSetTrayMessage(); void showNoOperationSetTrayMessage();
void showDBWriteErrorTrayMessage(const QString &errorMessage = QString());
void checkForUpdate(); void checkForUpdate();
void cleanChooseOpSubmenu(); void cleanChooseOpSubmenu();
/// setTrayMessage mostly mirrors QSystemTrayIcon::showMessage, but adds the ability to set a message type, /// setTrayMessage mostly mirrors QSystemTrayIcon::showMessage, but adds the ability to set a message type,
@ -88,6 +89,7 @@ class TrayManager : public QDialog {
private: private:
inline static const int MS_IN_DAY = 86400000; inline static const int MS_IN_DAY = 86400000;
QString _recordErrorTitle = tr("Unable to Record Evidence");
DatabaseConnection *db = nullptr; DatabaseConnection *db = nullptr;
HotkeyManager *hotkeyManager = nullptr; HotkeyManager *hotkeyManager = nullptr;
Screenshot *screenshotTool = nullptr; Screenshot *screenshotTool = nullptr;