Search in sources :

Example 16 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class AccountIT method reAddExistingGpgKey.

@Test
public void reAddExistingGpgKey() throws Exception {
    addExternalIdEmail(admin, "test5@example.com");
    TestKey key = validKeyWithSecondUserId();
    String id = key.getKeyIdString();
    PGPPublicKey pk = key.getPublicKey();
    GpgKeyInfo info = addGpgKey(armor(pk)).get(id);
    assertThat(info.userIds).hasSize(2);
    assertIteratorSize(2, getOnlyKeyFromStore(key).getUserIDs());
    pk = PGPPublicKey.removeCertification(pk, "foo:myId");
    info = addGpgKey(armor(pk)).get(id);
    assertThat(info.userIds).hasSize(1);
    assertIteratorSize(1, getOnlyKeyFromStore(key).getUserIDs());
}
Also used : TestKey(com.google.gerrit.gpg.testutil.TestKey) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) GpgKeyInfo(com.google.gerrit.extensions.common.GpgKeyInfo) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 17 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class PostGpgKeys method apply.

@Override
public Map<String, GpgKeyInfo> apply(AccountResource rsrc, Input input) throws ResourceNotFoundException, BadRequestException, ResourceConflictException, PGPException, OrmException, IOException, ConfigInvalidException {
    GpgKeys.checkVisible(self, rsrc);
    Collection<ExternalId> existingExtIds = externalIds.byAccount(rsrc.getUser().getAccountId(), SCHEME_GPGKEY);
    try (PublicKeyStore store = storeProvider.get()) {
        Set<Fingerprint> toRemove = readKeysToRemove(input, existingExtIds);
        List<PGPPublicKeyRing> newKeys = readKeysToAdd(input, toRemove);
        List<ExternalId> newExtIds = new ArrayList<>(existingExtIds.size());
        for (PGPPublicKeyRing keyRing : newKeys) {
            PGPPublicKey key = keyRing.getPublicKey();
            ExternalId.Key extIdKey = toExtIdKey(key.getFingerprint());
            Account account = getAccountByExternalId(extIdKey);
            if (account != null) {
                if (!account.getId().equals(rsrc.getUser().getAccountId())) {
                    throw new ResourceConflictException("GPG key already associated with another account");
                }
            } else {
                newExtIds.add(ExternalId.create(extIdKey, rsrc.getUser().getAccountId()));
            }
        }
        storeKeys(rsrc, newKeys, toRemove);
        List<ExternalId.Key> extIdKeysToRemove = toRemove.stream().map(fp -> toExtIdKey(fp.get())).collect(toList());
        externalIdsUpdateFactory.create().replace(rsrc.getUser().getAccountId(), extIdKeysToRemove, newExtIds);
        accountCache.evict(rsrc.getUser().getAccountId());
        return toJson(newKeys, toRemove, store, rsrc.getUser());
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) OrmException(com.google.gwtorm.server.OrmException) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) ByteArrayInputStream(java.io.ByteArrayInputStream) GpgKeyInfo(com.google.gerrit.extensions.common.GpgKeyInfo) Map(java.util.Map) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PGPException(org.bouncycastle.openpgp.PGPException) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) SCHEME_GPGKEY(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_GPGKEY) Sets(com.google.common.collect.Sets) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) InternalAccountQuery(com.google.gerrit.server.query.account.InternalAccountQuery) GerritPublicKeyChecker(com.google.gerrit.gpg.GerritPublicKeyChecker) Fingerprint(com.google.gerrit.gpg.Fingerprint) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Account(com.google.gerrit.reviewdb.client.Account) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ArmoredInputStream(org.bouncycastle.bcpg.ArmoredInputStream) CheckResult(com.google.gerrit.gpg.CheckResult) Input(com.google.gerrit.gpg.server.PostGpgKeys.Input) CurrentUser(com.google.gerrit.server.CurrentUser) Logger(org.slf4j.Logger) BaseEncoding(com.google.common.io.BaseEncoding) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AccountResource(com.google.gerrit.server.account.AccountResource) EmailException(com.google.gerrit.common.errors.EmailException) PublicKeyChecker(com.google.gerrit.gpg.PublicKeyChecker) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AddKeySender(com.google.gerrit.server.mail.send.AddKeySender) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountState(com.google.gerrit.server.account.AccountState) BcPGPObjectFactory(org.bouncycastle.openpgp.bc.BcPGPObjectFactory) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) InputStream(java.io.InputStream) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Account(com.google.gerrit.reviewdb.client.Account) Fingerprint(com.google.gerrit.gpg.Fingerprint) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey)

Example 18 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class PostGpgKeys method storeKeys.

private void storeKeys(AccountResource rsrc, List<PGPPublicKeyRing> keyRings, Set<Fingerprint> toRemove) throws BadRequestException, ResourceConflictException, PGPException, IOException {
    try (PublicKeyStore store = storeProvider.get()) {
        List<String> addedKeys = new ArrayList<>();
        for (PGPPublicKeyRing keyRing : keyRings) {
            PGPPublicKey key = keyRing.getPublicKey();
            // Don't check web of trust; admins can fill in certifications later.
            CheckResult result = checkerFactory.create(rsrc.getUser(), store).disableTrust().check(key);
            if (!result.isOk()) {
                throw new BadRequestException(String.format("Problems with public key %s:\n%s", keyToString(key), Joiner.on('\n').join(result.getProblems())));
            }
            addedKeys.add(PublicKeyStore.keyToString(key));
            store.add(keyRing);
        }
        for (Fingerprint fp : toRemove) {
            store.remove(fp.get());
        }
        CommitBuilder cb = new CommitBuilder();
        PersonIdent committer = serverIdent.get();
        cb.setAuthor(rsrc.getUser().newCommitterIdent(committer.getWhen(), committer.getTimeZone()));
        cb.setCommitter(committer);
        RefUpdate.Result saveResult = store.save(cb);
        switch(saveResult) {
            case NEW:
            case FAST_FORWARD:
            case FORCED:
                try {
                    addKeyFactory.create(rsrc.getUser(), addedKeys).send();
                } catch (EmailException e) {
                    log.error("Cannot send GPG key added message to " + rsrc.getUser().getAccount().getPreferredEmail(), e);
                }
                break;
            case NO_CHANGE:
                break;
            case IO_FAILURE:
            case LOCK_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            default:
                // TODO(dborowitz): Backoff and retry on LOCK_FAILURE.
                throw new ResourceConflictException("Failed to save public keys: " + saveResult);
        }
    }
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Fingerprint(com.google.gerrit.gpg.Fingerprint) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) CheckResult(com.google.gerrit.gpg.CheckResult) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) EmailException(com.google.gerrit.common.errors.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 19 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class PublicKeyStore method getSigner.

/**
   * Choose the public key that produced a signature.
   *
   * <p>
   *
   * @param keyRings candidate keys.
   * @param sig signature object.
   * @param data signed payload.
   * @return the key chosen from {@code keyRings} that was able to verify the signature, or {@code
   *     null} if none was found.
   * @throws PGPException if an error occurred verifying the signature.
   */
public static PGPPublicKey getSigner(Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data) throws PGPException {
    for (PGPPublicKeyRing kr : keyRings) {
        PGPPublicKey k = kr.getPublicKey();
        sig.init(new BcPGPContentVerifierBuilderProvider(), k);
        sig.update(data);
        if (sig.verify()) {
            return k;
        }
    }
    return null;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) BcPGPContentVerifierBuilderProvider(org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider)

Example 20 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class PushCertificateChecker method checkSignature.

private Result checkSignature(PGPSignature sig, PushCertificate cert, PublicKeyStore store) throws PGPException, IOException {
    PGPPublicKeyRingCollection keys = store.get(sig.getKeyID());
    if (!keys.getKeyRings().hasNext()) {
        return new Result(null, CheckResult.bad("No public keys found for key ID " + keyIdToString(sig.getKeyID())));
    }
    PGPPublicKey signer = PublicKeyStore.getSigner(keys, sig, Constants.encode(cert.toText()));
    if (signer == null) {
        return new Result(null, CheckResult.bad("Signature by " + keyIdToString(sig.getKeyID()) + " is not valid"));
    }
    CheckResult result = publicKeyChecker.setStore(store).setEffectiveTime(sig.getCreationTime()).check(signer);
    if (!result.getProblems().isEmpty()) {
        StringBuilder err = new StringBuilder("Invalid public key ").append(keyToString(signer)).append(":\n  ").append(Joiner.on("\n  ").join(result.getProblems()));
        return new Result(signer, CheckResult.create(result.getStatus(), err.toString()));
    }
    return new Result(signer, result);
}
Also used : PGPPublicKeyRingCollection(org.bouncycastle.openpgp.PGPPublicKeyRingCollection) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey)

Aggregations

PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)26 PGPPublicKeyRing (org.bouncycastle.openpgp.PGPPublicKeyRing)12 PublicKeyStore.keyToString (com.google.gerrit.gpg.PublicKeyStore.keyToString)8 PublicKeyStore.keyIdToString (com.google.gerrit.gpg.PublicKeyStore.keyIdToString)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 PublicKeyStore (com.google.gerrit.gpg.PublicKeyStore)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 PGPException (org.bouncycastle.openpgp.PGPException)4 GpgKeyInfo (com.google.gerrit.extensions.common.GpgKeyInfo)3 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 CheckResult (com.google.gerrit.gpg.CheckResult)3 Fingerprint (com.google.gerrit.gpg.Fingerprint)3 TestKey (com.google.gerrit.gpg.testutil.TestKey)3 GerritPersonIdent (com.google.gerrit.server.GerritPersonIdent)3 IOException (java.io.IOException)3 PGPPublicKeyRingCollection (org.bouncycastle.openpgp.PGPPublicKeyRingCollection)3 BcPGPContentVerifierBuilderProvider (org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider)3 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)3