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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/*
 * @(#)DeploySigningCertStore.java  1.45 05/04/19 
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.deploy.security;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.AccessController;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;
import java.util.HashSet;
import com.sun.deploy.util.Trace;
import com.sun.deploy.config.Config;
import com.sun.deploy.resources.ResourceManager;
import com.sun.deploy.ui.UIFactory;
import java.net.PasswordAuthentication;


/**
 * DeploySigningCertStore is a class that represents the permanent certificate 
 * store which contains all the certificates that are recognized. It 
 * is used in the certification verification process when signed jar is 
 * encountered.
 */
public final class DeploySigningCertStore implements CertStore
{
    private static String _userFilename = null;
    private static String _systemFilename = null;

    private long _userLastModified = 0;
    private long _sysLastModified = 0;

    // Collection of deployment certificates
    private KeyStore _deploymentUserCerts = CertUtils.createEmptyKeyStore();
    private KeyStore _deploymentSystemCerts = CertUtils.createEmptyKeyStore();

    // Password for keystore
    private char[] keyPassphrase = new char[0];
    private boolean cancelFlag = false;
    private int certStoreType = 0;

    static
    {
    // Get deployment certificate filenames
    _userFilename = Config.getUserTrustedCertificateFile(); 
    _systemFilename = Config.getSystemTrustedCertificateFile();
    }

    private DeploySigningCertStore(int storeType) {
    certStoreType = storeType;
    }

    public static CertStore getCertStore() {
    return new ImmutableCertStore(new DeploySigningCertStore(CertStore.ALL));
    }

    public static CertStore getUserCertStore() {
    return new DeploySigningCertStore(CertStore.USER);
    }

    public static CertStore getSystemCertStore() {
    return new ImmutableCertStore(new DeploySigningCertStore(CertStore.SYSTEM));
    }

    /**
     * Load the certificate store into memory without integrity check.
     */
    public void load() throws IOException, CertificateException,
                  KeyStoreException, NoSuchAlgorithmException
    {
    load(false);
    }

    public void load(boolean integrityCheck) throws 
            IOException, CertificateException, 
            KeyStoreException, NoSuchAlgorithmException
    {
    long lastModified;

    if ((certStoreType & CertStore.USER) == CertStore.USER) {
       if (_userFilename != null) {
          // lastModified will return 0 if file not exist, so it
          // won't be loaded
          lastModified = CertUtils.getFileLastModified(_userFilename);
          if (lastModified != _userLastModified) {
         _deploymentUserCerts = loadCertStore(_userFilename, integrityCheck);
         _userLastModified = lastModified;
          } 
       }
    }   

    if ((certStoreType & CertStore.SYSTEM) == CertStore.SYSTEM) {
       if (_systemFilename != null) {
          lastModified = CertUtils.getFileLastModified(_systemFilename);
          if (lastModified != _sysLastModified) {   
         _deploymentSystemCerts = loadCertStore(_systemFilename, integrityCheck);
         _sysLastModified = lastModified;
          } 
       }
    }
    }

    private KeyStore loadCertStore(final String filename, final boolean integrityCheck) 
            throws IOException, CertificateException, 
            KeyStoreException, NoSuchAlgorithmException 
    {
    Trace.msgSecurityPrintln("deploycertstore.cert.loading", 
                  new Object[] {filename});

    final File file = new File(filename);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

    try
    { 
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            
        public Object run() throws IOException, CertificateException,
                   KeyStoreException, NoSuchAlgorithmException
        {
            // Only load the cert store if it exists
            if (file.exists())
            {
            FileInputStream fis = new FileInputStream(file);
                        BufferedInputStream bis = new BufferedInputStream(fis);

                        // Initialize the keystore with/without no password
            if (integrityCheck) {
               cancelFlag = false;
                           keyStore.load(bis, new char[0]);
            }
            else {
                           keyStore.load(bis, null);
            }

                        bis.close();
                        fis.close();
            }
            return null;
        }
       });
    }
    catch (PrivilegedActionException e)
    {
        Exception ex = e.getException();

        if (ex instanceof IOException) {
        if (integrityCheck) {
           FileInputStream fis = new FileInputStream(file);
                   BufferedInputStream bis = new BufferedInputStream(fis);
           
                   CredentialInfo passwordInfo = 
                           UIFactory.showPasswordDialog(null,
                           ResourceManager.getMessage("password.dialog.title"),
                           ResourceManager.getMessage(
                           "deploycertstore.password.dialog.text"), 
                           false, false, null, false);

           // User didn't hit cancel button
           if ( passwordInfo != null) {
               cancelFlag = false;
                       // Get modified password for trusted certificate store
                       keyPassphrase = passwordInfo.getPassword();
                       keyStore.load(bis, keyPassphrase);
           }
           else {
              cancelFlag = true;
           }

                   bis.close();
                   fis.close();
        }
        else {
          throw (IOException)ex;
        }
        }
        else if (ex instanceof CertificateException)
        throw (CertificateException)ex;
        else if (ex instanceof KeyStoreException)
        throw (KeyStoreException)ex;
        else if (ex instanceof NoSuchAlgorithmException)
        throw (NoSuchAlgorithmException)ex;
        else
        Trace.securityPrintException(e);
    }

    Trace.msgSecurityPrintln("deploycertstore.cert.loaded", 
                  new Object[]{filename});
    return keyStore;
    }

    /**
     * Persist the certificate store.
     */
    public void save() throws IOException, CertificateException,
                  KeyStoreException, NoSuchAlgorithmException
    {
    Trace.msgSecurityPrintln("deploycertstore.cert.saving", 
                  new Object[]{_userFilename});
    try
    { 
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            
        public Object run() throws IOException, CertificateException,
                   KeyStoreException, NoSuchAlgorithmException
        {
            File file = new File(_userFilename);
            file.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

                _deploymentUserCerts.store(bos, keyPassphrase);

            bos.close();
            fos.close();

            return null;
        }
             });
    }
    catch (PrivilegedActionException e)
    {
        Exception ex = e.getException();
        
        if (ex instanceof IOException)
        throw (IOException)ex;
        else if (ex instanceof CertificateException)
        throw (CertificateException)ex;
        else if (ex instanceof KeyStoreException)
        throw (KeyStoreException)ex;
        else if (ex instanceof NoSuchAlgorithmException)
        throw (NoSuchAlgorithmException)ex;
        else
        Trace.securityPrintException(e);
    }

    Trace.msgSecurityPrintln("deploycertstore.cert.saved", 
                  new Object[] {_userFilename});
    }


    /**
     * Add a certificate into the certificate store.
     *
     * @param cert Certificate object.
     */
    public boolean add(Certificate cert) throws KeyStoreException 
    {
    return add(cert, false);
    }

    /**
     * Add a certificate into the certificate store.
     *
     * @param cert Certificate object.
     * @param tsFlag true if certificate is valid.
     */
    public boolean add(Certificate cert, boolean tsFlag) throws KeyStoreException 
    {
    Trace.msgSecurityPrintln("deploycertstore.cert.adding");

    if (cancelFlag) {
       return false;
    }

    // Add one only if it doesn't exist in User keyStore
    // or it exist but has a Timestamping flag in alias
        String oldAlias = _deploymentUserCerts.getCertificateAlias(cert);
    boolean certNotExist = true;

    if (oldAlias != null) {
       try {
           // If we found a match in trusted cert store,
           // We probably don't need to add to cert store if
           // 1. We encounter a valid certificate. Or
           // 2. No TSFLAG in alias name for the matched cert
           if ( tsFlag || (oldAlias.indexOf(TSFLAG) == -1)) {
              certNotExist = false;
           }
           else {
          // If this is an expired certificate and 
              // we found a Timestamping flag in alias name,
              // we have to remove this certificate first
          remove(cert);
           }
       }
       catch (IOException ioe)
       { Trace.securityPrintException(ioe); }
    }

        if (certNotExist)
    {
            // Generate a unique alias for the certificate
        Random rand = new Random();
        String alias = null;

        // Generate a unique alias name which is not in the trusted store
        while (true) {
           if (tsFlag) {
          alias = "deploymentusercert" + TSFLAG + rand.nextLong();
           }
           else {
              alias = "deploymentusercert" + rand.nextLong();
           }
               if (_deploymentUserCerts.getCertificate(alias) == null)
          break;
        }

        _deploymentUserCerts.setCertificateEntry(alias, cert);
        Trace.msgSecurityPrintln("deploycertstore.cert.added", 
                      new Object[]{ alias});
    }

    return true;
    }

    /**
     * Remove a certificate from the certificate store.
     * 
     * @param cert Certificate object.
     */
    public boolean remove(Certificate cert) throws IOException,  KeyStoreException 
    {
    if (cancelFlag) {
       return false;
    }

    Trace.msgSecurityPrintln("deploycertstore.cert.removing");

    String alias = _deploymentUserCerts.getCertificateAlias(cert);

    if (alias != null)
        _deploymentUserCerts.deleteEntry(alias);

    Trace.msgSecurityPrintln("deploycertstore.cert.removed", new Object[] {alias});

    return true;
    }

    /**
     * Check if a certificate is stored within the certificate store.
     *
     * @param cert Certificate object.
     * @return true if certificate is in the store.
     */
    public boolean contains(Certificate cert) throws KeyStoreException
    {
    return contains(cert, false);
    }

    /**
     * Check if a certificate is stored within the certificate store.
     *
     * @param cert Certificate object.
     * @param tsFlag true if only valid certificate is checked.
     * @return true if certificate is in the store.
     */
    public boolean contains(Certificate cert, boolean tsFlag) throws KeyStoreException
    {
    Trace.msgSecurityPrintln("deploycertstore.cert.instore");

    // Certificate alias returned only if there is a match
    String alias = _deploymentUserCerts.getCertificateAlias(cert);

    if (alias != null && ( !tsFlag || alias.indexOf(TSFLAG) > -1)) {
       return true;
    }

    alias = _deploymentSystemCerts.getCertificateAlias(cert);
    return (alias != null && (!tsFlag || alias.indexOf(TSFLAG) > -1));
    }

    /**
     * Verify if a certificate is issued by one of the certificate
     * in the certificate store.
     *
     * @param cert Certificate object.
     * @return true if certificate is issued by one in the store.
     */
    public boolean verify(Certificate cert)
    {
        Trace.msgSecurityPrintln("deploycertstore.cert.canverify");

    // Deployn Cert store is not intended to be used for verification.

    return false;
    }

    /**
     * Obtain all the certificates that are stored in this 
     * certificate store.
     *
     * @return Collection for certificates
     */
    public Collection getCertificates() throws KeyStoreException
    {
        HashSet deploySigningCerts = new HashSet();

    if ((certStoreType & CertStore.USER)  == CertStore.USER) {
           deploySigningCerts.addAll(getCertificates(CertStore.USER));
        }

    if ((certStoreType & CertStore.SYSTEM) == CertStore.SYSTEM) {
           deploySigningCerts.addAll(getCertificates(CertStore.SYSTEM));
        }

        return deploySigningCerts;
    }

    private Collection getCertificates(int myCertStoreType) throws KeyStoreException
    {
    Trace.msgSecurityPrintln("deploycertstore.cert.getcertificates");

    Collection certCollection = new ArrayList();
    KeyStore ks = null;

        if (myCertStoreType == CertStore.USER) {
           ks = _deploymentUserCerts;
        }
        else {
           ks = _deploymentSystemCerts;
        }
    Enumeration keyAliases = ks.aliases();
    
    // Construct a TreeSet object to sort the certificate list
        TreeSet tsCerts = new TreeSet();

        while (keyAliases.hasMoreElements())
        {
            // Get certificate alias from iterator
            String alias = (String) keyAliases.nextElement();
            tsCerts.add(alias);
        }

        Iterator itrCerts = tsCerts.iterator();
    while (itrCerts.hasNext())
    {
        // Get certificate from store
        String sortAlias = (String) itrCerts.next();
            Certificate cert = ks.getCertificate(sortAlias);

        // Add certificate into collection
        certCollection.add(cert);
    }       

    return certCollection;
    }
}
			
			

Browsed Source: [clear]