Exemplo n.º 1
0
StringX PWSAuxParse::GetAutoTypeString(const CItemData &ci,
                                       const PWScore &core,
                                       std::vector<size_t> &vactionverboffsets)
{
  // Set up all the data (a shortcut entry will change all of them!)
  StringX sxgroup = ci.GetGroup();
  StringX sxtitle = ci.GetTitle();
  StringX sxuser = ci.GetUser();
  StringX sxpwd = ci.GetPassword();
  StringX sxnotes = ci.GetNotes();
  StringX sxurl = ci.GetURL();
  StringX sxemail = ci.GetEmail();
  StringX sxautotype = ci.GetAutoType();

  if (ci.IsAlias()) {
    const CItemData *pbci = core.GetBaseEntry(&ci);
    if (pbci != NULL) {
      sxpwd = pbci->GetPassword();
    } else { // Problem - alias entry without a base!
      ASSERT(0);
    }
  } else if (ci.IsShortcut()) {
    const CItemData *pbci = core.GetBaseEntry(&ci);
    if (pbci != NULL) {
      sxgroup = pbci->GetGroup();
      sxtitle = pbci->GetTitle();
      sxuser = pbci->GetUser();
      sxpwd = pbci->GetPassword();
      sxnotes = pbci->GetNotes();
      sxurl = pbci->GetURL();
      sxemail = pbci->GetEmail();
      sxautotype = pbci->GetAutoType();
    } else { // Problem - shortcut entry without a base!
      ASSERT(0);
    }
  } // ci.IsShortcut()

  // If empty, try the database default
  if (sxautotype.empty()) {
    sxautotype = PWSprefs::GetInstance()->
              GetPref(PWSprefs::DefaultAutotypeString);

    // If still empty, take this default
    if (sxautotype.empty()) {
      // checking for user and password for default settings
      if (!sxpwd.empty()){
        if (!sxuser.empty())
          sxautotype = DEFAULT_AUTOTYPE;
        else
          sxautotype = _T("\\p\\n");
      }
    }
  }
  return PWSAuxParse::GetAutoTypeString(sxautotype, sxgroup,
                                        sxtitle, sxuser, sxpwd,
                                        sxnotes, sxurl, sxemail,
                                        vactionverboffsets);
}
Exemplo n.º 2
0
void print_conflicts(const CompareData &conflicts, const PWScore &core,
                            const PWScore &otherCore, conflict_hdr_func_t hdr_fn,
                            item_diff_func_t diff_fn)
{
  for( const auto &cd: conflicts ) {
    const CItemData &item = core.Find(cd.uuid0)->second;
    const CItemData &otherItem = otherCore.Find(cd.uuid1)->second;
    if (cd.bsDiffs.count() == 1 && cd.bsDiffs.test(CItemData::POLICY) && have_empty_policies(item, otherItem))
        continue;
    hdr_fn(cd, item, otherItem);
    print_conflicting_item(item, otherItem, cd.bsDiffs, diff_fn);
  }
}
Exemplo n.º 3
0
int ReadCore(PWScore& othercore, const wxString& file, const StringX& combination, 
                bool showMsgbox /*= true*/, wxWindow* msgboxParent /*= NULL*/)
{
  othercore.ClearData();

  // Reading a new file changes the preferences!
  const StringX sxSavePrefString(PWSprefs::GetInstance()->Store());
  const bool bDBPrefsChanged = PWSprefs::GetInstance()->IsDBprefsChanged();

  StringX dbpath(tostringx(file));
  int rc = othercore.ReadFile(dbpath, combination);

  // Reset database preferences - first to defaults then add saved changes!
  PWSprefs::GetInstance()->Load(sxSavePrefString);
  PWSprefs::GetInstance()->SetDBprefsChanged(bDBPrefsChanged);

  switch (rc) {
    case PWScore::SUCCESS:
      othercore.SetCurFile(tostringx(file));
      break;

    case PWScore::CANT_OPEN_FILE:
      if (showMsgbox)
        wxMessageBox(wxString(file) << _("\n\nCould not open file for reading!"),
                    _("File Read Error"), wxOK | wxICON_ERROR, msgboxParent );
      break;

    case PWScore::BAD_DIGEST:
      if (showMsgbox && wxMessageBox(wxString(file) << _("\n\nFile corrupt or truncated!\nData may have been lost or modified.\nContinue anyway?"), 
            _("File Read Error"), wxYES_NO | wxICON_QUESTION, msgboxParent) == wxYES) {
        rc = PWScore::SUCCESS;
      }
      break;

#ifdef DEMO
    case PWScore::LIMIT_REACHED:
      if( showMsgbox)
        wxMessageBox(wxString::Format(_("This version of PasswordSafe does not support more than %d entries in a database.\nTo get an unlimited version for the U3 platform, please visit http://software.u3.com\nNote: Saving this database will result in the removal of unread entries!"), MAXDEMO),
                        _("Trial Version Limitation"), wxOK | wxICON_WARNING, msgboxParent);
      break;
#endif

    default:
      if (showMsgbox)
        wxMessageBox( wxString(file) << _("\n\nUnknown error"), _("File Read Error"), wxOK | wxICON_ERROR, msgboxParent);
      break;
  }
  
  return rc;
}
Exemplo n.º 4
0
///////////////////////////////////
// dispatcher. Called from main()
/////////
int Diff(PWScore &core, const UserArgs &ua)
{
  CompareData current, comparison, conflicts, identical;
  PWScore otherCore;
  const StringX otherSafe{std2stringx(ua.opArg)};

  CItemData::FieldBits safeFields{ua.fields};
  for( auto ft: diff_fields ) {
    if (ua.fields.test(ft) && CItemData::IsTextField(ft)) {
      safeFields.set(ft);
    }
  }
  safeFields.reset(CItem::RMTIME);

  int status = OpenCore(otherCore, otherSafe);
  if ( status == PWScore::SUCCESS ) {
    constexpr bool treatWhitespacesAsEmpty = false;
    core.Compare( &otherCore,
                  safeFields,
                         ua.subset.valid(),
                         treatWhitespacesAsEmpty,
                         ua.subset.value,
                         ua.subset.field,
                         ua.subset.rule,
                         current,
                         comparison,
                         conflicts,
                         identical);

    switch (ua.dfmt) {
      case UserArgs::DiffFmt::Unified:
        unified_diff(core, otherCore, current, comparison, conflicts, identical);
        break;
      case UserArgs::DiffFmt::Context:
        context_diff(core, otherCore, current, comparison, conflicts, identical);
        break;
      case UserArgs::DiffFmt::SideBySide:
        sidebyside_diff(core, otherCore, current, comparison, conflicts, identical, safeFields, ua.colwidth);
        break;
      default:
        assert(false);
        break;
    }
    otherCore.UnlockFile(otherSafe.c_str());
  }
  return status;
}
Exemplo n.º 5
0
void CManagePSWDPols::OnPolicyRightClick(NMHDR * /*pNotifyStruct*/, LRESULT *pLResult)
{
  *pLResult = 0; // Perform default processing on return
  POSITION pos = m_PolicyNames.GetFirstSelectedItemPosition();

  if (pos == NULL)
    return;

  int nItem = m_PolicyNames.GetNextSelectedItem(pos);

  // Ignore is default policy (first entry)
  if (nItem == 0)
    return;

  const StringX sxPolicyName = m_PolicyNames.GetItemText(nItem, 0);

  // Ignore if no entries using this policy
  if (m_MapPSWDPLC[sxPolicyName].usecount == 0)
    return;

  PWScore *pcore = (PWScore *)GetMainDlg()->GetCore();
  m_ventries.clear();
  // Ignore if can't find any even if there should be!
  if (!pcore->GetEntriesUsingNamedPasswordPolicy(sxPolicyName, m_ventries))
    return;

  CPoint msg_pt = ::GetMessagePos();
  CMenu menu;
  int ipopup = IDR_POPLISTENTRIES;

  if (menu.LoadMenu(ipopup)) {
    MENUINFO minfo = { 0 };
    minfo.cbSize = sizeof(MENUINFO);
    minfo.fMask = MIM_MENUDATA;
    minfo.dwMenuData = ipopup;
    BOOL brc = menu.SetMenuInfo(&minfo);
    ASSERT(brc != 0);

    CMenu *pPopup = menu.GetSubMenu(0);
    ASSERT(pPopup != NULL);

    pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, msg_pt.x, msg_pt.y, this);
  }
}
Exemplo n.º 6
0
int ReadCore(PWScore& othercore, const wxString& file, const StringX& combination,
             bool showMsgbox /*= true*/, wxWindow* msgboxParent /*= NULL*/,
        bool setupCopy /*= false*/)
{
  othercore.ClearData();

  StringX dbpath(tostringx(file));
  int rc = othercore.ReadFile(dbpath, combination);

  if (setupCopy)
    PWSprefs::GetInstance()->SetupCopyPrefs();

  switch (rc) {
    case PWScore::SUCCESS:
      othercore.SetCurFile(tostringx(file));
      break;

    case PWScore::CANT_OPEN_FILE:
      if (showMsgbox)
        wxMessageBox(wxString(file) << wxT("\n\n") << _("Could not open file for reading!"),
                    _("File Read Error"), wxOK | wxICON_ERROR, msgboxParent );
      break;

    case PWScore::BAD_DIGEST:
      if (showMsgbox && wxMessageBox(wxString(file) << wxT("\n\n") << _("File corrupt or truncated!\nData may have been lost or modified.\nContinue anyway?"),
            _("File Read Error"), wxYES_NO | wxICON_QUESTION, msgboxParent) == wxYES) {
        rc = PWScore::SUCCESS;
      }
      break;

    default:
      if (showMsgbox)
        wxMessageBox( wxString(file) << wxT("\n\n") << _("Unknown error"), _("File Read Error"), wxOK | wxICON_ERROR, msgboxParent);
      break;
  }

  return rc;
}
Exemplo n.º 7
0
void sbs_print(const PWScore &core,
               const PWScore &otherCore,
               const CompareData &matches,
               const CItemData::FieldBits &comparedFields,
               unsigned int cols, bool print_fields)
{
  for( const auto &cd: matches ) {
    const CItemData &item = core.Find(cd.uuid0)->second;
    const CItemData &otherItem = otherCore.Find(cd.uuid1)->second;
    if (cd.bsDiffs.count() == 1 && cd.bsDiffs.test(CItemData::POLICY) && have_empty_policies(item, otherItem))
        continue;
    const CItemData::FieldBits &df = cd.bsDiffs.any()? cd.bsDiffs: comparedFields;
    left_line_t left_line{core, cd.uuid0, cols};
    right_line_t right_line{otherCore, cd.uuid1, cols};
    wcout << left_line() << L'|' << right_line() << endl;
    if ( print_fields ) {
      for( auto ft: diff_fields ) {
        // print the fields if they were actually found to be different
        if (df.test(ft) && !have_empty_policies(item, otherItem)) {
          StringXStream wssl, wssr;
          wssl << left_line(ft) << flush;
          wssr << right_line(ft) << flush;
          lines_vec left_lines{resize_lines(stream2vec(wssl), cols)},
                  right_lines{resize_lines(stream2vec(wssr), cols)};
          const int ndiff = left_lines.size() - right_lines.size();
          if (ndiff < 0)
              left_lines.insert(left_lines.end(), -ndiff, StringX(cols, L' '));
          else if (ndiff > 0)
              right_lines.insert(right_lines.end(), ndiff, StringX(cols, L' '));
          for (lines_vec::size_type idx = 0; idx < left_lines.size(); ++idx)
              wcout << left_lines[idx] << L'|' << right_lines[idx] << endl;
        }
      }
    }
    wcout << resize(wstring(cols/5, left_line.sep_char), cols) << L'|'
          << resize(wstring(cols/5, right_line.sep_char), cols) << endl;
  }
};
Exemplo n.º 8
0
void print_unique_items(wchar_t tag, const CompareData &cd, const PWScore &core,
                            unique_hdr_func_t hdr_fn)
{
  for(const auto &d: cd) {
    hdr_fn(d, tag);
    const CItemData &item = core.Find(d.indatabase == CURRENT? d.uuid0: d.uuid1)->second;
    for( auto ft : diff_fields ) {
      switch(ft) {
        case CItem::GROUP:
        case CItem::TITLE:
        case CItem::USER:
          break;
        default:
          if ( d.bsDiffs.test(ft) && !item.GetFieldValue(ft).empty() ) {
            print_field_value(wcout, tag, item, ft);
          }
      }
    }
  }
}
Exemplo n.º 9
0
static int
ImportXML(PWScore &core, const StringX &fname)
{
  const std::wstring XSDfn(L"pwsafe.xsd");
  std::wstring XSDFilename = PWSdirs::GetXMLDir() + XSDfn;

#if USE_XML_LIBRARY == MSXML || USE_XML_LIBRARY == XERCES
  if (!pws_os::FileExists(XSDFilename)) {
    wcerr << L"Can't find XML Schema Definition file"
          << XSDFilename << endl
          << L"Can't import without it." << endl;
    return PWScore::XML_FAILED_IMPORT;
  }
#endif

  std::wstring ImportedPrefix;
  std::wstring dir;
  std::wstring strXMLErrors, strSkippedList, strPWHErrorList, strRenameList;
  int numValidated, numImported, numSkipped, numRenamed, numPWHErrors;
  bool bImportPSWDsOnly = false;

  
  // Create report as we go
  CReport rpt;
  std::wstring str_text;
  rpt.StartReport(L"Import_XML", core.GetCurFile().c_str());
  str_text = L"XML file being imported: ";
  str_text += fname.c_str();
  rpt.WriteLine(str_text);
  rpt.WriteLine();
  std::vector<StringX> vgroups;
  Command *pcmd = NULL;

  int rc = core.ImportXMLFile(ImportedPrefix.c_str(), fname.c_str(),
                              XSDFilename.c_str(), bImportPSWDsOnly,
                              strXMLErrors, strSkippedList, strPWHErrorList,
                              strRenameList, numValidated, numImported,
                              numSkipped, numPWHErrors, numRenamed,
                              rpt, pcmd);

  switch (rc) {
  case PWScore::XML_FAILED_VALIDATION:
    rpt.WriteLine(strXMLErrors.c_str());
    str_text = L"File ";
    str_text += fname.c_str();
    str_text += L" failed to validate.";
    delete pcmd;
    break;
  case PWScore::XML_FAILED_IMPORT:
    rpt.WriteLine(strXMLErrors.c_str());
    str_text = L"File ";
    str_text += fname.c_str();
    str_text += L" validated but hadd errors during import.";
    delete pcmd;
    break;
  case PWScore::SUCCESS:
  case PWScore::OK_WITH_ERRORS:
    if (pcmd != NULL)
      rc = core.Execute(pcmd);

    if (!strXMLErrors.empty() ||
        numRenamed > 0 || numPWHErrors > 0) {
      wstring csErrors;
      if (!strXMLErrors.empty())
        csErrors = strXMLErrors + L"\n";

      if (!csErrors.empty()) {
        rpt.WriteLine(csErrors.c_str());
      }

      wstring cs_renamed, cs_PWHErrors, cs_skipped;
      if (numSkipped > 0) {
        rpt.WriteLine(wstring(L"The following records were skipped:"));
        wostringstream oss;
        oss << L" / skipped " << numSkipped;
        cs_skipped = oss.str();
        rpt.WriteLine(strSkippedList.c_str());
        rpt.WriteLine();
      }
      if (numPWHErrors > 0) {
        rpt.WriteLine(wstring(L"The following records had errors in their Password History:"));
        wostringstream oss;
        oss << L" / with Password History errors " << numPWHErrors;
        cs_PWHErrors = oss.str();
        rpt.WriteLine(strPWHErrorList.c_str());
        rpt.WriteLine();
      }
      if (numRenamed > 0) {
        rpt.WriteLine(wstring(L"The following records were renamed as an entry already exists in your database or in the Import file:"));
        wostringstream oss;
        oss << L" / renamed " << numRenamed;
        cs_renamed = oss.str();
        rpt.WriteLine(strRenameList.c_str());
        rpt.WriteLine();
      }

      wostringstream os2;
      os2 << L"File " << fname << L" was imported (entries validated"
          << numValidated << L" / imported " << numImported
          << cs_skipped <<  cs_renamed << cs_PWHErrors;
      str_text = os2.str();
    } else {
      const wstring validate(numValidated == 1 ? L" entry" : L" entries");
      const wstring import(numImported == 1 ? L" entry" : L" entries");
      wostringstream oss;
      oss << L"Validated " << numValidated << validate << L'\t'
          << L"Imported " << numImported << import << endl;
      str_text = oss.str();
    }

    break;
  default:
    ASSERT(0);
  } // switch

    // Finish Report
  rpt.WriteLine(str_text);
  rpt.EndReport();
  return rc;
}
Exemplo n.º 10
0
inline StringX safe_file_hdr(const wchar_t *tag, const PWScore &core)
{
  StringXStream os;
  os << tag << L' ' << core.GetCurFile() << L" " << modtime(core.GetCurFile());
  return os.str();
}
Exemplo n.º 11
0
bool PWSFilterManager::PassesAttFiltering(const CItemData *pci, const PWScore &core) const
{
  bool thistest_rc;
  const bool bPresent = pci->HasAttRef();
  bool bValue(false);

  
  for (auto group_iter = m_vAflgroups.begin();
       group_iter != m_vAflgroups.end(); group_iter++) {
    const vfiltergroup &group = *group_iter;

    int tests(0);
    bool thisgroup_rc = false;
    for (auto num_iter = group.begin();
      num_iter != group.end(); num_iter++) {
      const int &num = *num_iter;
      if (num == -1) // Padding for FT_PWHIST & FT_POLICY - shouldn't happen here
        continue;

      const st_FilterRow &st_fldata = m_currentfilter.vAfldata.at(num);
      thistest_rc = false;

      PWSMatch::MatchType mt(PWSMatch::MT_INVALID);
      const FieldType ft = st_fldata.ftype;

      switch (ft) {
        case AT_PRESENT:
          bValue = bPresent;
          mt = PWSMatch::MT_BOOL;
          break;
        case AT_TITLE:
        case AT_FILENAME:
        case AT_FILEPATH:
        case AT_MEDIATYPE:
          mt = PWSMatch::MT_STRING;
          break;
        case AT_CTIME:
        case AT_FILECTIME:
        case AT_FILEMTIME:
        case AT_FILEATIME:
          mt = PWSMatch::MT_DATE;
          break;
        default:
          ASSERT(0);
      }

      const int ifunction = (int)st_fldata.rule;
      switch (mt) {
        case PWSMatch::MT_BOOL:
          thistest_rc = PWSMatch::Match(bValue, ifunction);
          tests++;
          break;
        case PWSMatch::MT_STRING:
          if (bPresent) {
            const CItemAtt &att = core.GetAtt(pci->GetAttUUID());

            thistest_rc = att.Matches(st_fldata.fstring.c_str(), (int)ft,
              st_fldata.fcase ? -ifunction : ifunction);
          } else {
            thistest_rc = false;
          }
          tests++;
          break;
        case PWSMatch::MT_DATE:
          if (bPresent) {
            const CItemAtt &att = core.GetAtt(pci->GetAttUUID());

            time_t t1(st_fldata.fdate1), t2(st_fldata.fdate2);
            if (st_fldata.fdatetype == 1 /* Relative */) {
              time_t now;
              time(&now);
              t1 = now + (st_fldata.fnum1 * 86400);
              if (ifunction == PWSMatch::MR_BETWEEN)
                t2 = now + (st_fldata.fnum2 * 86400);
            }
            thistest_rc = att.Matches(t1, t2, (int)ft, ifunction);
          } else {
            thistest_rc = false;
          }
          tests++;
          break;
        default:
          ASSERT(0);
      }

      if (tests <= 1)
        thisgroup_rc = thistest_rc;
      else {
        //Within groups, tests are always "AND" connected
        thisgroup_rc = thistest_rc && thisgroup_rc;
      }
    }
    // This group of tests completed -
    //   if 'thisgroup_rc == true', leave now; else go on to next group
    if (thisgroup_rc)
      return true;
  }

  // We finished all the groups and haven't found one that is true - exclude entry.
  return false;
}
Exemplo n.º 12
0
 field_to_line(const PWScore &core, const pws_os::CUUID& uuid, unsigned int cols)
 : item{core.Find(uuid)->second}, columns{cols}
 {}
Exemplo n.º 13
0
TEST_F(FileV4Test, CoreRWTest)
{
  PWScore core;
  const StringX passkey(L"3rdMambo");

  fullItem.SetAttUUID(attItem.GetUUID());
  EXPECT_EQ(0U, attItem.GetRefcount());

  core.SetPassKey(passkey);
  core.Execute(AddEntryCommand::Create(&core, fullItem, pws_os::CUUID::NullUUID(), &attItem));
  EXPECT_TRUE(core.HasAtt(attItem.GetUUID()));
  EXPECT_EQ(1U, core.GetAtt(attItem.GetUUID()).GetRefcount());
  EXPECT_EQ(PWSfile::SUCCESS, core.WriteFile(fname.c_str(), PWSfile::V40));

  core.ClearDBData();
  EXPECT_EQ(PWSfile::FAILURE, core.ReadFile(fname.c_str(), L"WrongPassword", true));
  EXPECT_EQ(PWSfile::SUCCESS, core.ReadFile(fname.c_str(), passkey, true));
  ASSERT_EQ(1, core.GetNumEntries());
  ASSERT_EQ(1, core.GetNumAtts());
  ASSERT_TRUE(core.Find(fullItem.GetUUID()) != core.GetEntryEndIter());

  const CItemData readFullItem = core.GetEntry(core.Find(fullItem.GetUUID()));
  EXPECT_TRUE(readFullItem.HasAttRef());
  EXPECT_EQ(attItem.GetUUID(), readFullItem.GetAttUUID());
  EXPECT_EQ(fullItem, readFullItem);
  ASSERT_TRUE(core.HasAtt(attItem.GetUUID()));
  EXPECT_EQ(1U, core.GetAtt(attItem.GetUUID()).GetRefcount());

  core.Execute(DeleteEntryCommand::Create(&core, readFullItem));
  ASSERT_EQ(0, core.GetNumEntries());
  ASSERT_EQ(0, core.GetNumAtts());

  // Get core to delete any existing commands
  core.ClearCommands();
}
Exemplo n.º 14
0
void AliasShortcutTest::TearDown()
{
  // Get core to delete any existing commands
  core.ClearCommands();
}
Exemplo n.º 15
0
bool PWSFilterManager::PassesFiltering(const CItemData &ci, const PWScore &core)
{
  bool thistest_rc;
  bool bValue(false);
  bool bFilterForStatus(false), bFilterForType(false);
  const CItemData *pci;

  if (!m_currentfilter.IsActive())
    return true;

  const CItemData::EntryType entrytype = ci.GetEntryType();

  for (auto groups_iter = m_vMflgroups.begin();
       groups_iter != m_vMflgroups.end(); groups_iter++) {
    const vfiltergroup &group = *groups_iter;

    int tests(0);
    bool thisgroup_rc = false;
    for (auto iter = group.begin();
         iter != group.end(); iter++) {
      const int &num = *iter;
      if (num == -1) // Padding to ensure group size is correct for FT_PWHIST & FT_POLICY
        continue;

      const st_FilterRow &st_fldata = m_currentfilter.vMfldata.at(num);
      thistest_rc = false;

      PWSMatch::MatchType mt(PWSMatch::MT_INVALID);
      const FieldType ft = m_currentfilter.vMfldata[num].ftype;
      const int ifunction = (int)st_fldata.rule;

      switch (ft) {
        case FT_GROUPTITLE:
        case FT_GROUP:
        case FT_TITLE:
        case FT_USER:
        case FT_NOTES:
        case FT_URL:
        case FT_AUTOTYPE:
        case FT_RUNCMD:
        case FT_EMAIL:
        case FT_SYMBOLS:
        case FT_POLICYNAME:
          mt = PWSMatch::MT_STRING;
          break;
        case FT_PASSWORD:
          mt = PWSMatch::MT_PASSWORD;
          break;
        case FT_DCA:
          mt = PWSMatch::MT_DCA;
          break;
        case FT_SHIFTDCA:
          mt = PWSMatch::MT_SHIFTDCA;
          break;
        case FT_CTIME:
        case FT_PMTIME:
        case FT_ATIME:
        case FT_XTIME:
        case FT_RMTIME:
          mt = PWSMatch::MT_DATE;
          break;
        case FT_PWHIST:
          mt = PWSMatch::MT_PWHIST;
          break;
        case FT_POLICY:
          mt = PWSMatch::MT_POLICY;
          break;
        case FT_XTIME_INT:
          mt = PWSMatch::MT_INTEGER;
          break;
        case FT_KBSHORTCUT:
          bValue = !ci.GetKBShortcut().empty();
          mt = PWSMatch::MT_BOOL;
          break;
        case FT_UNKNOWNFIELDS:
          bValue = ci.NumberUnknownFields() > 0;
          mt = PWSMatch::MT_BOOL;
          break;
        case FT_PROTECTED:
          bValue = ci.IsProtected();
          mt = PWSMatch::MT_BOOL;
          break;
        case FT_PASSWORDLEN:
          mt = PWSMatch::MT_INTEGER;
          break;
        case FT_ENTRYTYPE:
          mt = PWSMatch::MT_ENTRYTYPE;
          break;
        case FT_ENTRYSTATUS:
          mt = PWSMatch::MT_ENTRYSTATUS;
          break;
        case FT_ENTRYSIZE:
          mt = PWSMatch::MT_ENTRYSIZE;
          break;
        case FT_ATTACHMENT:
          mt = PWSMatch::MT_ATTACHMENT;
          break;
        default:
          ASSERT(0);
      }

      if (ft == FT_ENTRYSTATUS) {
        bFilterForStatus = true;
      }

      if (ft == FT_ENTRYTYPE) {
        bFilterForType = true;
      }

      pci = &ci;

      if (ft == FT_PASSWORD && entrytype == CItemData::ET_ALIAS) {
        pci = core.GetBaseEntry(pci); // This is an alias
      }

      if (entrytype == CItemData::ET_SHORTCUT && !bFilterForStatus && !bFilterForType) {
        // Only include shortcuts if the filter is on the group, title or user fields
        // Note: "GROUPTITLE = 0x00", "GROUP = 0x02", "TITLE = 0x03", "USER = 0x04"
        //   "UUID = 0x01" but no filter is implemented against this field
        // The following is a simple single test rather than testing against every value
        if (ft > FT_USER) {
          pci = core.GetBaseEntry(pci); // This is an shortcut
        }
      }

      switch (mt) {
        case PWSMatch::MT_PASSWORD:
          if (ifunction == PWSMatch::MR_EXPIRED) {
            // Special Password "string" case
            thistest_rc = pci->IsExpired();
            tests++;
            break;
          } else if (ifunction == PWSMatch::MR_WILLEXPIRE) {
            // Special Password "string" case
            thistest_rc = pci->WillExpire(st_fldata.fnum1);
            tests++;
            break;
          }
          // Note: purpose drop through to standard 'string' processing
        case PWSMatch::MT_STRING:
          thistest_rc = pci->Matches(st_fldata.fstring.c_str(), (int)ft,
                                 st_fldata.fcase ? -ifunction : ifunction);
          tests++;
          break;
        case PWSMatch::MT_INTEGER:
          thistest_rc = pci->Matches(st_fldata.fnum1, st_fldata.fnum2,
                                     (int)ft, ifunction);
          tests++;
          break;
        case PWSMatch::MT_DATE:
        {
          time_t t1(st_fldata.fdate1), t2(st_fldata.fdate2);
          if (st_fldata.fdatetype == 1 /* Relative */) {
            time_t now;
            time(&now);
            t1 = now + (st_fldata.fnum1 * 86400);
            if (ifunction == PWSMatch::MR_BETWEEN)
              t2 = now + (st_fldata.fnum2 * 86400);
          }
          thistest_rc = pci->MatchesTime(t1, t2,
                                     (int)ft, ifunction);
          tests++;
          break;
        }
        case PWSMatch::MT_PWHIST:
          if (m_currentfilter.num_Hactive != 0) {
            thistest_rc = PassesPWHFiltering(pci);
            tests++;
          }
          break;
        case PWSMatch::MT_POLICY:
          if (m_currentfilter.num_Pactive != 0) {
            thistest_rc = PassesPWPFiltering(pci);
            tests++;
          }
          break;
        case PWSMatch::MT_BOOL:
          thistest_rc = PWSMatch::Match(bValue, ifunction);
          tests++;
          break;
        case PWSMatch::MT_ENTRYTYPE:
          thistest_rc = pci->Matches(st_fldata.etype, ifunction);
          tests++;
          break;
        case PWSMatch::MT_DCA:
        case PWSMatch::MT_SHIFTDCA:
          thistest_rc = pci->Matches(st_fldata.fdca, ifunction, mt == PWSMatch::MT_SHIFTDCA);
          tests++;
          break;
        case PWSMatch::MT_ENTRYSTATUS:
          thistest_rc = pci->Matches(st_fldata.estatus, ifunction);
          tests++;
          break;
        case PWSMatch::MT_ENTRYSIZE:
          thistest_rc = pci->Matches(st_fldata.fnum1, st_fldata.fnum2,
                                     (int)ft, ifunction);
          tests++;
          break;
        case PWSMatch::MT_ATTACHMENT:
          if (m_currentfilter.num_Aactive != 0) {
            thistest_rc = PassesAttFiltering(pci, core);
            tests++;
          }
          break;
        default:
          ASSERT(0);
      }

      if (tests <= 1)
        thisgroup_rc = thistest_rc;
      else {
        //Within groups, tests are always "AND" connected
        thisgroup_rc = thistest_rc && thisgroup_rc;
      }
    }
    // This group of tests completed -
    //   if 'thisgroup_rc == true', leave now; else go on to next group
    if (thisgroup_rc)
      return true;
  }

  // We finished all the groups and haven't found one that is true - exclude entry.
  return false;
}
Exemplo n.º 16
0
static int
ImportText(PWScore &core, const StringX &fname)
{
  int numImported(0), numSkipped(0), numPWHErrors(0), numRenamed(0);
  std::wstring strError;
  wchar_t delimiter = L' ';
  wchar_t fieldSeparator = L'\t';
  StringX ImportedPrefix;
  bool bImportPSWDsOnly = false;

  // Create report as we go
  CReport rpt;
  rpt.StartReport(L"Import_Text", core.GetCurFile().c_str());
  wstring str(L"Text file being imported: ");
  str += core.GetCurFile().c_str();
  rpt.WriteLine(str.c_str());
  rpt.WriteLine();

  Command *pcmd = NULL;
  int rc = core.ImportPlaintextFile(ImportedPrefix, fname, fieldSeparator,
                                    delimiter, bImportPSWDsOnly,
                                    strError,
                                    numImported, numSkipped,
                                    numPWHErrors, numRenamed,
                                    rpt, pcmd);
  switch (rc) {
  case PWScore::CANT_OPEN_FILE:
  case PWScore::INVALID_FORMAT:
  case PWScore::FAILURE:
    delete pcmd;
    break;
  case PWScore::SUCCESS:
  case PWScore::OK_WITH_ERRORS:
    // deliberate fallthru
  default:
    {
      rc = core.Execute(pcmd);

      rpt.WriteLine();
      wstring op(bImportPSWDsOnly ? L"Updated " : L"Imported ");
      wstring entries(numImported == 1 ? L" entry" : L" entries");
      wostringstream os;
      os << op << numImported << entries;
      rpt.WriteLine(os.str().c_str());

      if (numSkipped != 0) {
        wostringstream oss;
        entries = (numSkipped == 1 ?  L" entry" : L" entries");
        oss << L"\nSkipped " << numSkipped << entries;
        rpt.WriteLine(oss.str().c_str());
      }

      if (numPWHErrors != 0) {
        wostringstream oss;
        entries = (numPWHErrors == 1 ?  L" entry" : L" entries");
        oss << L"\nwith Password History errors" << numPWHErrors << entries;
        rpt.WriteLine(oss.str().c_str());
      }

      if (numRenamed != 0) {
        wostringstream oss;
        entries = (numRenamed == 1 ?  L" entry" : L" entries");
        oss << L"\nRenamed " << numRenamed << entries;
        rpt.WriteLine(oss.str().c_str());
      }
      break;
    }
  } // switch
  rpt.EndReport();
  return rc;
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
  UserArgs ua;
  if (!parseArgs(argc, argv, ua)) {
    usage(argv[0]);
    return 1;
  }

  PWScore core;
  if (!pws_os::FileExists(ua.safe.c_str())) {
    cerr << argv[1] << " - file not found" << endl;
    return 2;
  }
  wstring wpk;
  cout << "Enter Password: "******"CheckPasskey returned: " << status_text(status) << endl;
    goto done;
  }
  {
    CUTF8Conv conv;
    const char *user = getlogin() != NULL ? getlogin() : "unknown";
    StringX locker;
    if (!conv.FromUTF8((const unsigned char *)user, strlen(user), locker)) {
      cerr << "Could not convert user " << user << " to StringX" << endl;
      return 2;
    }
    stringT lk(locker.c_str());
    if (!core.LockFile(ua.safe.c_str(), lk)) {
      wcout << L"Couldn't lock file " << ua.safe
            << L": locked by " << locker << endl;
      status = -1;
      goto done;
    }
  }
  // Since we may be writing the same file we're reading,
  // it behooves us to set the Current File and use its' related
  // functions
  core.SetCurFile(ua.safe);
  status = core.ReadCurFile(pk);
  if (status != PWScore::SUCCESS) {
    cout << "ReadFile returned: " << status_text(status) << endl;
    goto done;
  }

  if (ua.ImpExp == UserArgs::Export) {
    CItemData::FieldBits all(~0L);
    int N;
    if (ua.Format == UserArgs::XML) {
      status = core.WriteXMLFile(ua.fname, all, L"", 0, 0, L' ', N);
    } else { // export text
      status = core.WritePlaintextFile(ua.fname, all, L"", 0, 0, L' ', N);
    }
  } else { // Import
    if (ua.Format == UserArgs::XML) {
      status = ImportXML(core, ua.fname);
    } else { // import text
      status = ImportText(core, ua.fname);
    }
    if (status == PWScore::SUCCESS)
      status = core.WriteCurFile();
  }
  if (status != PWScore::SUCCESS) {
    cout << "Operation returned status: " << status_text(status) << endl;
    goto done;
  }
 done:
  core.UnlockFile(ua.safe.c_str());
  return status;
}