QtPass Developer documentation
QtPass test coverage
Current view: top level - src/gpgkeystate.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 100.0 % 154 154
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 17 17
Branches: 89.3 % 149 133

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements the colon-listing parser: record classification, one
       6                 :             :  * handler per record type, and primary-fingerprint lookup.
       7                 :             :  */
       8                 :             : #include "gpgkeystate.h"
       9                 :             : #include "gpgkeystate_p.h"
      10                 :             : 
      11                 :             : #include "util.h"
      12                 :             : 
      13                 :             : #include <QDateTime>
      14                 :             : #include <QRegularExpression>
      15                 :             : 
      16                 :             : #include <cctype>
      17                 :             : 
      18                 :             : /** @brief Fewest fields a record must have to be read at all. */
      19                 :             : constexpr int GPG_MIN_FIELDS = 10;
      20                 :             : /** @brief Field index of the validity letter (`u`, `f`, `r`, ...). */
      21                 :             : constexpr int GPG_FIELD_VALIDITY = 1;
      22                 :             : /** @brief Field index of the key ID. */
      23                 :             : constexpr int GPG_FIELD_KEY_ID = 4;
      24                 :             : /** @brief Field index of the creation time, in seconds since the epoch. */
      25                 :             : constexpr int GPG_FIELD_CREATED = 5;
      26                 :             : /** @brief Field index of the expiry time; empty for a key without one. */
      27                 :             : constexpr int GPG_FIELD_EXPIRY = 6;
      28                 :             : /** @brief Field index of the user ID. */
      29                 :             : constexpr int GPG_FIELD_USERID = 9;
      30                 :             : /**
      31                 :             :  * @brief Field 9 of an `fpr` record: the fingerprint, in the slot the user
      32                 :             :  * ID occupies in a `uid` record.
      33                 :             :  */
      34                 :             : constexpr int GPG_FIELD_FINGERPRINT = 9;
      35                 :             : 
      36                 :        1023 : auto classifyRecord(const QString &record_type) -> GpgRecordType {
      37         [ +  + ]:        1023 :   if (record_type == "pub") {
      38                 :             :     return GpgRecordType::Pub;
      39                 :             :   }
      40         [ +  + ]:         752 :   if (record_type == "sec") {
      41                 :             :     return GpgRecordType::Sec;
      42                 :             :   }
      43         [ +  + ]:         716 :   if (record_type == "uid") {
      44                 :             :     return GpgRecordType::Uid;
      45                 :             :   }
      46         [ +  + ]:         406 :   if (record_type == "fpr") {
      47                 :             :     return GpgRecordType::Fpr;
      48                 :             :   }
      49         [ +  + ]:          75 :   if (record_type == "sub") {
      50                 :             :     return GpgRecordType::Sub;
      51                 :             :   }
      52         [ +  + ]:          28 :   if (record_type == "ssb") {
      53                 :             :     return GpgRecordType::Ssb;
      54                 :             :   }
      55         [ +  + ]:          19 :   if (record_type == "grp") {
      56                 :          12 :     return GpgRecordType::Grp;
      57                 :             :   }
      58                 :             :   return GpgRecordType::Unknown;
      59                 :             : }
      60                 :             : 
      61                 :         265 : void handlePubSecRecord(const QStringList &props, bool secret,
      62                 :             :                         UserInfo &current_user) {
      63         [ +  + ]:         265 :   if (props.size() < GPG_MIN_FIELDS) {
      64                 :           2 :     return;
      65                 :             :   }
      66                 :         263 :   current_user.key_id = props[GPG_FIELD_KEY_ID];
      67                 :         263 :   current_user.name = props[GPG_FIELD_USERID];
      68         [ +  + ]:         263 :   if (!props[GPG_FIELD_VALIDITY].isEmpty()) {
      69                 :         262 :     current_user.validity = props[GPG_FIELD_VALIDITY][0].toLatin1();
      70                 :             :   }
      71                 :             : 
      72                 :             :   // An empty field (GnuPG's "no expiry") leaves the QDateTime null, so
      73                 :             :   // callers distinguish "unset" from "set" with isValid() alone.
      74                 :         263 :   bool okCreated = false;
      75                 :             :   const qint64 createdSecs = props[GPG_FIELD_CREATED].toLongLong(&okCreated);
      76         [ +  + ]:         263 :   if (okCreated) {
      77                 :         262 :     current_user.created = QDateTime::fromSecsSinceEpoch(createdSecs);
      78                 :             :   }
      79                 :             : 
      80                 :         263 :   bool okExpiry = false;
      81                 :             :   const qint64 expirySecs = props[GPG_FIELD_EXPIRY].toLongLong(&okExpiry);
      82         [ +  + ]:         263 :   if (okExpiry) {
      83                 :           9 :     current_user.expiry = QDateTime::fromSecsSinceEpoch(expirySecs);
      84                 :             :   }
      85                 :             : 
      86                 :         263 :   current_user.have_secret = secret;
      87                 :             : }
      88                 :             : 
      89                 :             : /**
      90                 :             :  * @brief How far a uid record's own validity vouches for its name.
      91                 :             :  *
      92                 :             :  * The key's validity on the pub record is that of its best uid, so the
      93                 :             :  * name shown beside it has to be one that earned it: a certified key whose
      94                 :             :  * owner adds an uncertified uid and makes it primary must not show that
      95                 :             :  * name as valid.
      96                 :             :  * @param validity The record's validity field.
      97                 :             :  * @return 3 for ultimate or full, 2 for marginal, 1 for unknown or
      98                 :             :  *         undefined, 0 for anything else (invalid, revoked, expired, never).
      99                 :             :  */
     100                 :         273 : auto uidNameRank(const QString &validity) -> int {
     101   [ -  +  +  +  :         546 :   switch (validity.isEmpty() ? '\0' : validity.at(0).toLatin1()) {
                   +  + ]
     102                 :             :   case 'u':
     103                 :             :   case 'f':
     104                 :             :     return 3;
     105                 :           5 :   case 'm':
     106                 :           5 :     return 2;
     107                 :           6 :   case '-':
     108                 :             :   case 'q':
     109                 :           6 :     return 1;
     110                 :             :   default:
     111                 :             :     return 0;
     112                 :             :   }
     113                 :             : }
     114                 :             : 
     115                 :             : /**
     116                 :             :  * @brief Decode a field of GPG colon output: gpg writes a colon, a backslash
     117                 :             :  *        and control characters in a user ID as `\xHH`.
     118                 :             :  * @param field The field as gpg listed it
     119                 :             :  * @return The field with each `\xHH` replaced by its byte, read as UTF-8
     120                 :             :  */
     121                 :         273 : auto decodeColonField(const QString &field) -> QString {
     122         [ +  + ]:         273 :   if (!field.contains(QLatin1String("\\x"))) {
     123                 :             :     return field;
     124                 :             :   }
     125                 :             :   const QByteArray in = field.toUtf8();
     126                 :             :   const auto isHex = [](char c) {
     127                 :           4 :     return std::isxdigit(static_cast<unsigned char>(c)) != 0;
     128                 :             :   };
     129                 :           1 :   QByteArray out;
     130                 :           1 :   out.reserve(in.size());
     131         [ +  + ]:          34 :   for (int i = 0; i < in.size(); ++i) {
     132   [ +  -  +  -  :           2 :     if (in.at(i) == '\\' && i + 3 < in.size() && in.at(i + 1) == 'x' &&
                   +  - ]
     133   [ +  +  +  -  :          35 :         isHex(in.at(i + 2)) && isHex(in.at(i + 3))) {
                   +  - ]
     134                 :           4 :       out.append(static_cast<char>(in.mid(i + 2, 2).toInt(nullptr, 16)));
     135                 :             :       i += 3;
     136                 :             :     } else {
     137                 :          31 :       out.append(in.at(i));
     138                 :             :     }
     139                 :             :   }
     140                 :             :   return QString::fromUtf8(out);
     141                 :             : }
     142                 :             : 
     143                 :             : /**
     144                 :             :  * @brief Handle a uid record in GPG colon output: its name is the key's
     145                 :             :  *        name unless an earlier uid vouches at least as well for its own.
     146                 :             :  * @param props The colon-split fields of the record
     147                 :             :  * @param current_user UserInfo to populate with user name
     148                 :             :  * @param nameRank uidNameRank() of the name taken so far; updated
     149                 :             :  */
     150                 :         273 : void handleUidRecord(const QStringList &props, UserInfo &current_user,
     151                 :             :                      int &nameRank) {
     152                 :         546 :   current_user.uids.append(decodeColonField(props[GPG_FIELD_USERID]));
     153                 :         273 :   const int rank = uidNameRank(props[GPG_FIELD_VALIDITY]);
     154   [ +  +  +  + ]:         273 :   if (current_user.name.isEmpty() || rank > nameRank) {
     155                 :         262 :     current_user.name = props[GPG_FIELD_USERID];
     156                 :         262 :     nameRank = rank;
     157                 :             :   }
     158                 :         273 : }
     159                 :             : 
     160                 :         256 : void handleFprRecord(const QStringList &props, UserInfo &current_user) {
     161         [ +  - ]:         256 :   if (props.size() < GPG_MIN_FIELDS) {
     162                 :             :     return;
     163                 :             :   }
     164                 :             :   // GnuPG reports the v4 key ID from the fingerprint's tail, and the v5/v6
     165                 :             :   // key ID from its head. Promote only an exact 16-hex key ID with the
     166                 :             :   // version-specific fingerprint shape and location; malformed or mismatched
     167                 :             :   // input stays a key ID rather than becoming a false full identity.
     168                 :             :   static const QRegularExpression keyIdShape(
     169   [ +  +  +  -  :         274 :       QStringLiteral("^[0-9A-Fa-f]{16}$"));
                      + ]
     170                 :             :   static const QRegularExpression v4FingerprintShape(
     171   [ +  +  +  -  :         268 :       QStringLiteral("^[0-9A-Fa-f]{40}$"));
                      + ]
     172                 :             :   static const QRegularExpression v5v6FingerprintShape(
     173   [ +  +  +  -  :         268 :       QStringLiteral("^[0-9A-Fa-f]{64}$"));
                      + ]
     174                 :         256 :   const QString &keyId = current_user.key_id;
     175      [ +  +  + ]:         256 :   if (!keyIdShape.match(keyId).hasMatch()) {
     176                 :             :     return;
     177                 :             :   }
     178                 :             : 
     179                 :             :   const QString &fingerprint = props[GPG_FIELD_FINGERPRINT];
     180   [ +  +  +  +  :         498 :   const bool isV4 = v4FingerprintShape.match(fingerprint).hasMatch() &&
                      + ]
     181                 :         228 :                     fingerprint.endsWith(keyId, Qt::CaseInsensitive);
     182   [ +  +  +  +  :         492 :   const bool isV5V6 = v5v6FingerprintShape.match(fingerprint).hasMatch() &&
                      + ]
     183                 :          16 :                       fingerprint.startsWith(keyId, Qt::CaseInsensitive);
     184         [ +  + ]:         245 :   if (isV4 || isV5V6) {
     185                 :         234 :     current_user.key_id = fingerprint;
     186                 :             :   }
     187                 :             : }
     188                 :             : 
     189                 :             : namespace {
     190                 :             : 
     191                 :             : /**
     192                 :             :  * @brief The keys read so far from a GPG colon listing, and the key whose
     193                 :             :  *        records are being read.
     194                 :             :  */
     195                 :         744 : struct ColonListing {
     196                 :             :   QList<UserInfo> users; ///< The keys that are complete.
     197                 :             :   UserInfo current;      ///< The key being read.
     198                 :             :   /// The next fpr record is the key's own. Short records, uids and subkey
     199                 :             :   /// records end the primary key's head. A designated revoker's rvk record
     200                 :             :   /// sits between pub and its fpr; a keygrip's grp record follows the fpr.
     201                 :             :   bool expectPrimaryFingerprint{};
     202                 :             :   /// A subkey's fpr record follows its sub or ssb record.
     203                 :             :   bool expectSubkeyFingerprint{};
     204                 :             :   /// uidNameRank() of current.name; a name GnuPG 1 put on the pub record
     205                 :             :   /// itself counts as unknown.
     206                 :             :   int nameRank = 0;
     207                 :             : 
     208                 :             :   /**
     209                 :             :    * @brief Keep the key being read, when there is one.
     210                 :             :    */
     211                 :         510 :   void keepCurrent() {
     212         [ +  + ]:         510 :     if (!current.key_id.isEmpty()) {
     213                 :         262 :       users.append(current);
     214                 :             :     }
     215                 :         510 :   }
     216                 :             : 
     217                 :             :   /**
     218                 :             :    * @brief A record too short to read: it ends what was expected next.
     219                 :             :    */
     220                 :             :   void takeShort() {
     221                 :           5 :     expectPrimaryFingerprint = false;
     222                 :           5 :     expectSubkeyFingerprint = false;
     223                 :             :   }
     224                 :             : 
     225                 :             :   /**
     226                 :             :    * @brief A pub or sec record: the key before it is complete, a new one
     227                 :             :    *        starts.
     228                 :             :    * @param props The colon-split fields of the record.
     229                 :             :    * @param secret Whether the record lists a secret key that is here.
     230                 :             :    */
     231                 :         262 :   void startKey(const QStringList &props, bool secret) {
     232                 :         262 :     keepCurrent();
     233                 :         262 :     current = UserInfo();
     234                 :         262 :     handlePubSecRecord(props, secret, current);
     235         [ +  + ]:         262 :     nameRank = current.name.isEmpty() ? 0 : 1;
     236                 :         262 :     expectPrimaryFingerprint = true;
     237                 :         262 :     expectSubkeyFingerprint = false;
     238                 :         262 :   }
     239                 :             : 
     240                 :             :   /**
     241                 :             :    * @brief A uid record. It ends the primary key's head.
     242                 :             :    * @param props The colon-split fields of the record.
     243                 :             :    */
     244                 :             :   void takeUid(const QStringList &props) {
     245                 :         273 :     expectPrimaryFingerprint = false;
     246                 :         273 :     handleUidRecord(props, current, nameRank);
     247                 :         273 :     expectSubkeyFingerprint = false;
     248                 :         273 :   }
     249                 :             : 
     250                 :             :   /**
     251                 :             :    * @brief A sub or ssb record. It ends the primary key's head.
     252                 :             :    * @param props The colon-split fields of the record.
     253                 :             :    */
     254                 :          29 :   void takeSubkey(const QStringList &props) {
     255                 :          29 :     expectPrimaryFingerprint = false;
     256         [ +  - ]:          29 :     if (!props[GPG_FIELD_KEY_ID].isEmpty()) {
     257                 :          29 :       current.subkeys.append(props[GPG_FIELD_KEY_ID]);
     258                 :             :     }
     259                 :          29 :     expectSubkeyFingerprint = true;
     260                 :          29 :   }
     261                 :             : 
     262                 :             :   /**
     263                 :             :    * @brief An fpr record: the primary key's, a subkey's, or neither.
     264                 :             :    * @param props The colon-split fields of the record.
     265                 :             :    */
     266                 :         265 :   void takeFingerprint(const QStringList &props) {
     267         [ +  + ]:         265 :     if (expectPrimaryFingerprint) {
     268                 :         243 :       handleFprRecord(props, current);
     269                 :         243 :       expectPrimaryFingerprint = false;
     270   [ +  -  +  - ]:          22 :     } else if (expectSubkeyFingerprint &&
     271                 :             :                !props[GPG_FIELD_FINGERPRINT].isEmpty()) {
     272                 :          22 :       current.subkeys.append(props[GPG_FIELD_FINGERPRINT]);
     273                 :             :     }
     274                 :         265 :     expectSubkeyFingerprint = false;
     275                 :         265 :   }
     276                 :             : };
     277                 :             : 
     278                 :             : } // namespace
     279                 :             : 
     280                 :         248 : auto parseGpgColonOutput(const QString &output, bool secret)
     281                 :             :     -> QList<UserInfo> {
     282                 :             :   const QStringList lines =
     283                 :         248 :       output.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
     284                 :             : 
     285                 :             :   ColonListing listing;
     286         [ +  + ]:        1094 :   for (const QString &key : lines) {
     287                 :         846 :     QStringList props = key.split(':');
     288         [ +  + ]:         846 :     if (props.size() < GPG_MIN_FIELDS) {
     289                 :             :       listing.takeShort();
     290                 :             :       continue;
     291                 :             :     }
     292                 :             : 
     293                 :             :     const QString &record_type = props[0];
     294                 :         841 :     const GpgRecordType type = classifyRecord(record_type);
     295   [ +  +  +  +  :         841 :     switch (type) {
                      + ]
     296                 :         262 :     case GpgRecordType::Pub:
     297                 :             :     case GpgRecordType::Sec:
     298                 :         262 :       listing.startKey(props, secret && (type == GpgRecordType::Sec));
     299                 :             :       break;
     300                 :             :     case GpgRecordType::Uid:
     301                 :             :       listing.takeUid(props);
     302                 :             :       break;
     303                 :          29 :     case GpgRecordType::Sub:
     304                 :             :     case GpgRecordType::Ssb:
     305                 :          29 :       listing.takeSubkey(props);
     306                 :             :       break;
     307                 :         265 :     case GpgRecordType::Fpr:
     308                 :         265 :       listing.takeFingerprint(props);
     309                 :             :       break;
     310                 :             :     default:
     311                 :             :       break;
     312                 :             :     }
     313                 :             :   }
     314                 :             : 
     315                 :         248 :   listing.keepCurrent();
     316                 :         248 :   return listing.users;
     317                 :             : }
     318                 :             : 
     319                 :          22 : auto primaryFingerprintOf(const QString &output, const QString &key)
     320                 :             :     -> QString {
     321                 :          22 :   const QStringList holders = blocksHolding(output, key);
     322         [ +  + ]:          22 :   return holders.size() == 1 ? holders.first() : QString();
     323                 :             : }
     324                 :             : 
     325                 :             : namespace {
     326                 :             : /**
     327                 :             :  * @brief A key as gpg is given it, reduced to the ID or fingerprint its
     328                 :             :  *        colon listing shows: upper case, without a `0x` or a trailing `!`.
     329                 :             :  * @param key The key as configured or typed.
     330                 :             :  * @return The bare ID or fingerprint; empty for none.
     331                 :             :  */
     332                 :          26 : auto bareKey(const QString &key) -> QString {
     333                 :          26 :   QString wanted = key.trimmed().toUpper();
     334      [ +  +  + ]:          26 :   if (wanted.endsWith(QLatin1Char('!'))) {
     335                 :           1 :     wanted.chop(1);
     336                 :             :   }
     337      [ +  +  + ]:          26 :   if (wanted.startsWith(QLatin1String("0X"))) {
     338                 :           2 :     wanted.remove(0, 2);
     339                 :             :   }
     340                 :          26 :   return wanted;
     341                 :             : }
     342                 :             : 
     343                 :             : /**
     344                 :             :  * @brief Add the block's primary fingerprint to @p holders when the block
     345                 :             :  *        holds the key, once.
     346                 :             :  * @param holders The primaries found so far.
     347                 :             :  * @param primary The block's primary fingerprint; empty when none was read.
     348                 :             :  * @param holds Whether the block holds the key.
     349                 :             :  */
     350                 :          66 : void addHolder(QStringList &holders, const QString &primary, bool holds) {
     351   [ +  +  +  -  :          92 :   if (holds && !primary.isEmpty() && !holders.contains(primary)) {
                   +  - ]
     352                 :             :     holders << primary;
     353                 :             :   }
     354                 :          66 : }
     355                 :             : } // namespace
     356                 :             : 
     357                 :          26 : auto blocksHolding(const QString &output, const QString &key) -> QStringList {
     358                 :          26 :   const QString wanted = bareKey(key);
     359         [ +  + ]:          26 :   if (wanted.isEmpty()) {
     360                 :           1 :     return {};
     361                 :             :   }
     362   [ +  +  +  + ]:          25 :   const bool isId = wanted.size() == 8 || wanted.size() == 16;
     363                 :          25 :   QStringList holders;
     364                 :          25 :   QString primary;
     365                 :             :   bool expectPrimary = false;
     366                 :          25 :   bool holds = false;
     367                 :             :   // A pub or sub record carries the key's own ID: the fingerprint's tail
     368                 :             :   // for v4 keys, its head for v5/v6. A short ID is the long one's tail.
     369                 :          59 :   const auto namesKeyId = [&](const QStringList &props) {
     370      [ +  +  + ]:          97 :     return isId && props[GPG_FIELD_KEY_ID].toUpper().endsWith(wanted);
     371                 :          25 :   };
     372                 :          66 :   const auto endBlock = [&] {
     373                 :          66 :     addHolder(holders, primary, holds);
     374                 :          66 :     primary.clear();
     375                 :          66 :     holds = false;
     376                 :          91 :   };
     377                 :             :   const QStringList lines =
     378                 :          25 :       output.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
     379         [ +  + ]:         197 :   for (const QString &line : lines) {
     380                 :         172 :     const QStringList props = line.split(QLatin1Char(':'));
     381         [ +  + ]:         172 :     if (props.size() < GPG_MIN_FIELDS) {
     382                 :             :       continue;
     383                 :             :     }
     384   [ +  +  +  +  :         163 :     switch (classifyRecord(props[0])) {
                      + ]
     385                 :          41 :     case GpgRecordType::Pub:
     386                 :          41 :       endBlock();
     387                 :             :       expectPrimary = true;
     388   [ +  -  +  +  :          41 :       holds = holds || namesKeyId(props);
                      + ]
     389                 :          41 :       break;
     390                 :          23 :     case GpgRecordType::Sub:
     391                 :             :       expectPrimary = false;
     392   [ +  +  +  +  :          23 :       holds = holds || namesKeyId(props);
                      + ]
     393                 :          23 :       break;
     394                 :          64 :     case GpgRecordType::Fpr:
     395         [ +  + ]:          64 :       if (expectPrimary) {
     396                 :          41 :         primary = props[GPG_FIELD_FINGERPRINT].toUpper();
     397                 :             :         expectPrimary = false;
     398                 :             :       }
     399   [ +  +  +  + ]:         109 :       if (!isId && props[GPG_FIELD_FINGERPRINT].toUpper() == wanted) {
     400                 :          17 :         holds = true;
     401                 :             :       }
     402                 :             :       break;
     403                 :             :     default:
     404                 :             :       break;
     405                 :             :     }
     406                 :             :   }
     407                 :          25 :   endBlock();
     408                 :             :   return holders;
     409                 :             : }
        

Generated by: LCOV version 2.0-1