summaryrefslogtreecommitdiffstats
path: root/java/com/google/gerrit/sshd/SshKeyCacheImpl.java
blob: 58e331bb657b16770df91c487ed0405a2d15d221 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.sshd;

import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME;

import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.exceptions.InvalidSshKeyException;
import com.google.gerrit.server.account.AccountSshKey;
import com.google.gerrit.server.account.VersionedAuthorizedKeys;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gerrit.server.account.externalids.ExternalIdKeyFactory;
import com.google.gerrit.server.account.externalids.ExternalIds;
import com.google.gerrit.server.cache.CacheModule;
import com.google.gerrit.server.logging.Metadata;
import com.google.gerrit.server.logging.TraceContext;
import com.google.gerrit.server.logging.TraceContext.TraceTimer;
import com.google.gerrit.server.ssh.SshKeyCache;
import com.google.gerrit.server.ssh.SshKeyCreator;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.eclipse.jgit.errors.ConfigInvalidException;

/** Provides the {@link SshKeyCacheEntry}. */
@Singleton
public class SshKeyCacheImpl implements SshKeyCache {
  private static final FluentLogger logger = FluentLogger.forEnclosingClass();

  private static final String CACHE_NAME = "sshkeys";

  static final Iterable<SshKeyCacheEntry> NO_SUCH_USER = none();
  static final Iterable<SshKeyCacheEntry> NO_KEYS = none();

  public static Module module() {
    return new CacheModule() {
      @Override
      protected void configure() {
        cache(CACHE_NAME, String.class, new TypeLiteral<Iterable<SshKeyCacheEntry>>() {})
            .loader(Loader.class);
        bind(SshKeyCacheImpl.class);
        bind(SshKeyCache.class).to(SshKeyCacheImpl.class);
        bind(SshKeyCreator.class).to(SshKeyCreatorImpl.class);
      }
    };
  }

  private static Iterable<SshKeyCacheEntry> none() {
    return Collections.unmodifiableCollection(Arrays.asList(new SshKeyCacheEntry[0]));
  }

  private final LoadingCache<String, Iterable<SshKeyCacheEntry>> cache;

  @Inject
  SshKeyCacheImpl(@Named(CACHE_NAME) LoadingCache<String, Iterable<SshKeyCacheEntry>> cache) {
    this.cache = cache;
  }

  Iterable<SshKeyCacheEntry> get(String username) {
    try {
      return cache.get(username);
    } catch (ExecutionException e) {
      logger.atWarning().withCause(e).log("Cannot load SSH keys for %s", username);
      return Collections.emptyList();
    }
  }

  @Override
  public void evict(String username) {
    if (username != null) {
      logger.atFine().log("Evict SSH key for username %s", username);
      cache.invalidate(username);
    }
  }

  static class Loader extends CacheLoader<String, Iterable<SshKeyCacheEntry>> {
    private final ExternalIds externalIds;
    private final VersionedAuthorizedKeys.Accessor authorizedKeys;
    private final ExternalIdKeyFactory externalIdKeyFactory;

    @Inject
    Loader(
        ExternalIds externalIds,
        VersionedAuthorizedKeys.Accessor authorizedKeys,
        ExternalIdKeyFactory externalIdKeyFactory) {
      this.externalIds = externalIds;
      this.authorizedKeys = authorizedKeys;
      this.externalIdKeyFactory = externalIdKeyFactory;
    }

    @Override
    public Iterable<SshKeyCacheEntry> load(String username) throws Exception {
      try (TraceTimer timer =
          TraceContext.newTimer(
              "Loading SSH keys for account with username",
              Metadata.builder().username(username).build())) {
        Optional<ExternalId> user =
            externalIds.get(externalIdKeyFactory.create(SCHEME_USERNAME, username));
        if (!user.isPresent()) {
          return NO_SUCH_USER;
        }

        List<SshKeyCacheEntry> kl = new ArrayList<>(4);
        for (AccountSshKey k : authorizedKeys.getKeys(user.get().accountId())) {
          if (k.valid()) {
            add(kl, k);
          }
        }

        if (kl.isEmpty()) {
          return NO_KEYS;
        }
        return Collections.unmodifiableList(kl);
      }
    }

    private void add(List<SshKeyCacheEntry> kl, AccountSshKey k) {
      try {
        kl.add(new SshKeyCacheEntry(k.accountId(), SshUtil.parse(k)));
      } catch (OutOfMemoryError e) {
        // This is the only case where we assume the problem has nothing
        // to do with the key object, and instead we must abort this load.
        //
        throw e;
      } catch (InvalidKeyAlgorithmException e) {
        logger.atWarning().withCause(e).log(
            "SSH key %d of account %s has an invalid algorithm %s: fixing the algorithm to %s",
            k.seq(), k.accountId(), e.getInvalidKeyAlgo(), e.getExpectedKeyAlgo());
        if (fixKeyAlgorithm(k, e.getExpectedKeyAlgo())) {
          kl.add(new SshKeyCacheEntry(k.accountId(), e.getPublicKey()));
        } else {
          markInvalid(k);
        }
      } catch (Throwable e) {
        markInvalid(k);
      }
    }

    private void markInvalid(AccountSshKey k) {
      try {
        logger.atInfo().log("Flagging SSH key %d of account %s invalid", k.seq(), k.accountId());
        authorizedKeys.markKeyInvalid(k.accountId(), k.seq());
      } catch (IOException | ConfigInvalidException e) {
        logger.atSevere().withCause(e).log(
            "Failed to mark SSH key %d of account %s invalid", k.seq(), k.accountId());
      }
    }

    private boolean fixKeyAlgorithm(AccountSshKey k, String keyAlgo) {
      try {
        logger.atInfo().log(
            "Fixing SSH key %d of account %s algorithm to %s", k.seq(), k.accountId(), keyAlgo);
        authorizedKeys.deleteKey(k.accountId(), k.seq());
        String sshKey = k.sshPublicKey();
        authorizedKeys.addKey(k.accountId(), keyAlgo + sshKey.substring(sshKey.indexOf(' ')));
        return true;
      } catch (IOException | ConfigInvalidException | InvalidSshKeyException e) {
        logger.atSevere().withCause(e).log(
            "Failed to fix SSH key %d of account %s with algo %s", k.seq(), k.accountId(), keyAlgo);
        return false;
      }
    }
  }
}