File: UpdateCertificates.java

package info (click to toggle)
ca-certificates-java 20121112%2Bnmu2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 84 kB
  • sloc: java: 298; sh: 189; makefile: 71
file content (223 lines) | stat: -rw-r--r-- 7,574 bytes parent folder | download
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
/*
 * Copyright (C) 2011 Torsten Werner <twerner@debian.org>
 * Copyright (C) 2012 Damien Raude-Morvan <drazzib@debian.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

/**
 * This code is a re-implementation of the idea from Ludwig Nussel found in
 * http://gitorious.org/opensuse/ca-certificates/blobs/master/keystore.java
 * for the Debian operating system. It updates the global JVM keystore.
 * 
 * @author Torsten Werner
 * @author Damien Raude-Morvan
 */
public class UpdateCertificates {
	
    private char[] password = null;
    
    private String ksFilename = null;
    
    private KeyStore ks = null;
    
    private CertificateFactory certFactory = null;
    
    public static void main(String[] args) throws IOException, GeneralSecurityException {
        String passwordString = "changeit";
        if (args.length == 2 && args[0].equals("-storepass")) {
            passwordString = args[1];
        }
        else if (args.length > 0) {
            System.err.println("Usage: java UpdateCertificates [-storepass <password>]");
            System.exit(1);
        }

		try {
			UpdateCertificates uc = new UpdateCertificates(passwordString, "/etc/ssl/certs/java/cacerts");
	        // Force reading of inputstream in UTF-8
	        uc.processChanges(new InputStreamReader(System.in, "UTF8"));
	        uc.writeKeyStore();
		} catch (Exceptions.InvalidKeystorePassword e) {
			e.printStackTrace(System.err);
			System.exit(1);
		} catch (Exceptions.UnableToSaveKeystore e) {
			e.printStackTrace(System.err);
			System.exit(1);
		}
    }
    
    public UpdateCertificates(final String passwordString, final String keystoreFile) throws IOException, GeneralSecurityException, Exceptions.InvalidKeystorePassword {
        this.password = passwordString.toCharArray();
        this.ksFilename = keystoreFile;
        this.ks = openKeyStore();
        this.certFactory = CertificateFactory.getInstance("X.509");
	}

    /**
     * Try to open a existing keystore or create an new one.
     */
    private KeyStore openKeyStore() throws GeneralSecurityException, IOException, Exceptions.InvalidKeystorePassword {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        File certInputFile = new File(this.ksFilename);
        FileInputStream certInputStream = null;
        if (certInputFile.canRead()) {
            certInputStream = new FileInputStream(certInputFile);
        }
        try {
            ks.load(certInputStream, this.password);
        }
        catch (IOException e) {
            throw new Exceptions.InvalidKeystorePassword("Cannot open Java keystore. Is the password correct?", e);
        }
        if (certInputStream != null) {
            certInputStream.close();
        }
        return ks;
    }
    
    /**
     * Until reader EOF, try to read changes and send each to {@link #parseLine(String)}.
     */
    protected void processChanges(final Reader reader)
            throws IOException, GeneralSecurityException {
        String line;
        BufferedReader bufferedStdinReader = new BufferedReader(reader);
        while((line = bufferedStdinReader.readLine()) != null) {
        	try {
        		parseLine(line);
        	} catch (Exceptions.UnknownInput e) {
        		System.err.println("Unknown input: " + line);
        		// Keep processing for others lines
        	}
        }
    }
    
    /**
     * Parse given line to choose between {@link #addAlias(String, Certificate)}
     * or {@link #deleteAlias(String)}.
     */
    protected void parseLine(final String line)
            throws GeneralSecurityException, IOException, Exceptions.UnknownInput {
    	assert this.ks != null;
    	
        String path = line.substring(1);
        String filename = path.substring(path.lastIndexOf("/") + 1);
        String alias = "debian:" + filename;
        if(line.startsWith("+")) {
            Certificate cert = loadCertificate(path);
            if (cert == null) {
                return;
            }
            addAlias(alias, cert);
        }
        else if (line.startsWith("-")) {
            deleteAlias(alias);
            // Remove old non-prefixed aliases, too. This code should be
            // removed after the release of Wheezy.
            deleteAlias(filename);
        }
        else {
        	throw new Exceptions.UnknownInput(line);
        }        
    }
    
    /**
     * Delete cert in keystore at given alias.
     */
    private void deleteAlias(final String alias) throws GeneralSecurityException {
    	assert this.ks != null;
    	
        if (contains(alias)) {
            System.out.println("Removing " + alias);
            this.ks.deleteEntry(alias);
        }
    }

    /**
     * Add or replace existing cert in keystore with given alias.
     */
	private void addAlias(final String alias, final Certificate cert)
			throws KeyStoreException {
		assert this.ks != null;
		
		if(contains(alias)) {
		    System.out.println("Replacing " + alias);
		    this.ks.deleteEntry(alias);
		}
		else {
		    System.out.println("Adding " + alias);
		}
		this.ks.setCertificateEntry(alias, cert);
	}

	/**
	 * Returns true when alias exist in keystore.
	 */
	protected boolean contains(String alias) throws KeyStoreException {
		assert this.ks != null;
		
		return this.ks.containsAlias(alias);
	}

	/**
	 * Try to load a certificate instance from given path.
	 */
    private Certificate loadCertificate(final String path) {
    	assert this.certFactory != null;
    	
        Certificate cert = null;
        try {
            FileInputStream certFile = new FileInputStream(path);
            cert = this.certFactory.generateCertificate(certFile);
            certFile.close();
        }
        catch (Exception e) {
            System.err.println("Warning: there was a problem reading the certificate file " +
                path + ". Message:\n  " + e.getMessage());
        }
        return cert;
    }
    
    /**
     * Write actual keystore content to disk.
     */
    protected void writeKeyStore() throws GeneralSecurityException, Exceptions.UnableToSaveKeystore {
    	assert this.ks != null;
    	
        try {
            FileOutputStream certOutputFile = new FileOutputStream(this.ksFilename);
            this.ks.store(certOutputFile, this.password);
            certOutputFile.close();
        }
        catch (IOException e) {
        	throw new Exceptions.UnableToSaveKeystore("There was a problem saving the new Java keystore.", e);
        }
    }
}