summaryrefslogtreecommitdiff
path: root/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterKeyPasswordSafe.java
blob: de5d67b5e2d8df7683741165fe15f64b6603ccfd (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.ide.passwordSafe.impl.providers.masterKey;

import com.intellij.concurrency.AsyncFutureFactory;
import com.intellij.concurrency.AsyncFutureResult;
import com.intellij.ide.passwordSafe.MasterPasswordUnavailableException;
import com.intellij.ide.passwordSafe.PasswordSafeException;
import com.intellij.ide.passwordSafe.impl.PasswordSafeTimed;
import com.intellij.ide.passwordSafe.impl.providers.BasePasswordSafeProvider;
import com.intellij.ide.passwordSafe.impl.providers.ByteArrayWrapper;
import com.intellij.ide.passwordSafe.impl.providers.EncryptionUtil;
import com.intellij.ide.passwordSafe.impl.providers.masterKey.windows.WindowsCryptUtils;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * The password safe that stores information in configuration file encrypted by master password
 */
public class MasterKeyPasswordSafe extends BasePasswordSafeProvider {
  private static final String TEST_PASSWORD_KEY = "TEST_PASSWORD:";
  private static final String TEST_PASSWORD_VALUE = "test password";

  private final PasswordDatabase myDatabase;
  private transient final PasswordSafeTimed<Ref<Object>> myKey = new PasswordSafeTimed<Ref<Object>>() {
    protected Ref<Object> compute() {
      return Ref.create();
    }

    @Override
    protected int getMinutesToLive() {
      return Registry.intValue("passwordSafe.masterPassword.ttl");
    }
  };

  public MasterKeyPasswordSafe(PasswordDatabase database) {
    this.myDatabase = database;
  }

  /**
   * Reset password for the password safe (clears password database). The method is used from plugin's UI.
   *
   * @param password the password to set
   * @param encrypt  if the password should be encrypted an stored is master database
   */
  void resetMasterPassword(String password, boolean encrypt) {
    myKey.get().set(EncryptionUtil.genPasswordKey(password));
    myDatabase.clear();
    try {
      storePassword(null, MasterKeyPasswordSafe.class, testKey(password), TEST_PASSWORD_VALUE);
      if (encrypt) {
        myDatabase.setPasswordInfo(encryptPassword(password));
      }
      else {
        myDatabase.setPasswordInfo(ArrayUtil.EMPTY_BYTE_ARRAY);
      }
    }
    catch (PasswordSafeException e) {
      throw new IllegalStateException("There should be no problem with password at this point", e);
    }
  }

  /**
   * Set password to use (used from plugin's UI)
   *
   * @param password the password
   * @return true, if password is a correct one
   */
  boolean setMasterPassword(String password) {
    Object savedKey = myKey.get().get();
    myKey.get().set(EncryptionUtil.genPasswordKey(password));
    String rc;
    try {
      rc = getPassword(null, MasterKeyPasswordSafe.class, testKey(password));
    }
    catch (PasswordSafeException e) {
      throw new IllegalStateException("There should be no problem with password at this point", e);
    }
    if (!TEST_PASSWORD_VALUE.equals(rc)) {
      myKey.get().set(savedKey);
      return false;
    }
    else {
      return true;
    }
  }

  /**
   * Encrypt database with new password
   *
   * @param oldPassword the old password
   * @param newPassword the new password
   * @param encrypt
   * @return re-encrypted database
   */
  boolean changeMasterPassword(String oldPassword, String newPassword, boolean encrypt) {
    if (!setMasterPassword(oldPassword)) {
      return false;
    }
    byte[] oldKey = (byte[])myKey.get().get(); // set right in the previous call
    byte[] newKey = EncryptionUtil.genPasswordKey(newPassword);
    ByteArrayWrapper testKey = new ByteArrayWrapper(EncryptionUtil.dbKey(oldKey, MasterKeyPasswordSafe.class, testKey(oldPassword)));
    HashMap<ByteArrayWrapper, byte[]> oldDb = new HashMap<ByteArrayWrapper, byte[]>();
    myDatabase.copyTo(oldDb);
    HashMap<ByteArrayWrapper, byte[]> newDb = new HashMap<ByteArrayWrapper, byte[]>();
    for (Map.Entry<ByteArrayWrapper, byte[]> e : oldDb.entrySet()) {
      if (testKey.equals(e.getKey())) {
        continue;
      }
      byte[] decryptedKey = EncryptionUtil.decryptKey(oldKey, e.getKey().unwrap());
      String decryptedText = EncryptionUtil.decryptText(oldKey, e.getValue());
      newDb.put(new ByteArrayWrapper(EncryptionUtil.encryptKey(newKey, decryptedKey)), EncryptionUtil.encryptText(newKey, decryptedText));
    }
    synchronized (myDatabase.getDbLock()) {
      resetMasterPassword(newPassword, encrypt);
      myDatabase.putAll(newDb);
    }
    return true;
  }


  private static String testKey(String password) {
    return TEST_PASSWORD_KEY + password;
  }

  @NotNull
  @Override
  protected byte[] key(@Nullable final Project project, @NotNull final Class requestor) throws PasswordSafeException {
    Object key = myKey.get().get();
    if (key instanceof byte[]) return (byte[])key;
    if (key instanceof PasswordSafeException && ((PasswordSafeException)key).justHappened()) throw (PasswordSafeException)key;

    if (isPasswordEncrypted()) {
      try {
        setMasterPassword(decryptPassword(myDatabase.getPasswordInfo()));
        key = myKey.get().get();
        if (key instanceof byte[]) return (byte[])key;
      }
      catch (PasswordSafeException e) {
        // ignore exception and ask password
      }
    }

    if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
      throw new MasterPasswordUnavailableException("The provider is not available in headless environment");
    }

    key = invokeAndWait(new ThrowableComputable<Object, PasswordSafeException>() {
      @Override
      public Object compute() throws PasswordSafeException {
        Object key = myKey.get().get();
        if (key instanceof byte[] || key instanceof PasswordSafeException && ((PasswordSafeException)key).justHappened()) {
          return key;
        }
        try {
          if (myDatabase.isEmpty()) {
            if (!MasterPasswordDialog.resetMasterPasswordDialog(project, MasterKeyPasswordSafe.this, requestor).showAndGet()) {
              throw new MasterPasswordUnavailableException("Master password is required to store passwords in the database.");
            }
          }
          else {
            MasterPasswordDialog.askPassword(project, MasterKeyPasswordSafe.this, requestor);
          }
        }
        catch (PasswordSafeException e) {
          myKey.get().set(e);
          throw e;
        }
        return myKey.get().get();
      }
    }, project == null ? Condition.FALSE : project.getDisposed());
    if (key instanceof byte[]) return (byte[])key;
    if (key instanceof PasswordSafeException) throw (PasswordSafeException)key;

    throw new AssertionError();
  }

  private static final Object ourEDTLock = new Object();
  public <T, E extends Throwable> T invokeAndWait(@NotNull final ThrowableComputable<T, E> computable, @NotNull final Condition<?> expired) throws E {
    if (ApplicationManager.getApplication().isDispatchThread()) {
      return computable.compute();
    }

    final AsyncFutureResult<Object> future = AsyncFutureFactory.getInstance().createAsyncFutureResult();
    synchronized (ourEDTLock) {
      IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new ExpirableRunnable() {
        @Override
        public boolean isExpired() {
          boolean b = expired.value(null);
          if (b) future.setException(new ProcessCanceledException());
          return b;
        }

        @Override
        public void run() {
          try {
            future.set(computable.compute());
          }
          catch (Throwable e) {
            future.setException(e);
          }
        }
      });
    }
    try {
      return (T)future.get();
    }
    catch (InterruptedException e) {
      throw new ProcessCanceledException(e);
    }
    catch (ExecutionException e) {
      throw (E) e.getCause();
    }
  }

  @Override
  public String getPassword(@Nullable Project project, @NotNull Class requestor, String key) throws PasswordSafeException {
    if (myDatabase.isEmpty()) {
      return null;
    }
    return super.getPassword(project, requestor, key);
  }

  @Override
  public void removePassword(@Nullable Project project, @NotNull Class requester, String key) throws PasswordSafeException {
    if (myDatabase.isEmpty()) {
      return;
    }
    super.removePassword(project, requester, key);
  }

  @Override
  protected byte[] getEncryptedPassword(byte[] key) {
    return myDatabase.get(key);
  }

  @Override
  protected void removeEncryptedPassword(byte[] key) {
    myDatabase.remove(key);
  }

  @Override
  protected void storeEncryptedPassword(byte[] key, byte[] encryptedPassword) {
    myDatabase.put(key, encryptedPassword);
  }

  @Override
  public boolean isSupported() {
    return !ApplicationManager.getApplication().isHeadlessEnvironment();
  }

  @Override
  public String getDescription() {
    return "This provider stores passwords in IDEA config and uses master password to encrypt other passwords. " +
           "The passwords for the same resources are shared between different projects.";
  }

  @Override
  public String getName() {
    return "Master Key PasswordSafe";
  }


  public boolean isMasterPasswordEnabled() {
    return setMasterPassword("");
  }

  @SuppressWarnings({"MethodMayBeStatic"})
  public boolean isOsProtectedPasswordSupported() {
    // TODO extension point needed?
    return SystemInfo.isWindows;
  }


  /**
   * Encrypt master password
   *
   * @param pw the password to encrypt
   * @return the encrypted password
   * @throws MasterPasswordUnavailableException
   *          if encryption fails
   */
  private static byte[] encryptPassword(String pw) throws MasterPasswordUnavailableException {
    assert SystemInfo.isWindows;
    return WindowsCryptUtils.protect(EncryptionUtil.getUTF8Bytes(pw));
  }

  /**
   * Decrypt master password
   *
   * @param pw the password to decrypt
   * @return the decrypted password
   * @throws MasterPasswordUnavailableException
   *          if decryption fails
   */
  private static String decryptPassword(byte[] pw) throws MasterPasswordUnavailableException {
    if (!SystemInfo.isWindows) throw new AssertionError("Windows OS expected");

    try {
      return new String(WindowsCryptUtils.unprotect(pw), "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
      throw new IllegalStateException("UTF-8 not available", e);
    }
  }

  public boolean isPasswordEncrypted() {
    if (!isOsProtectedPasswordSupported()) return false;

    byte[] info = myDatabase.getPasswordInfo();
    return info != null && info.length > 0;
  }

  public boolean isEmpty() {
    return myDatabase.isEmpty();
  }
}