aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/AbstractJarSignerTask.java
blob: bc8c03195495d30e323ec3d3142080b6fad767a8 (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
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
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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 org.apache.tools.ant.taskdefs;

import java.io.File;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.filters.LineContainsRegExp;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.RedirectorElement;
import org.apache.tools.ant.types.RegularExpression;
import org.apache.tools.ant.util.JavaEnvUtils;

/**
 * This is factored out from {@link SignJar}; a base class that can be used
 * for both signing and verifying JAR files using jarsigner
 */

public abstract class AbstractJarSignerTask extends Task {
    // CheckStyle:VisibilityModifier OFF - bc
    /**
     * The name of the jar file.
     */
    protected File jar;
    /**
     * The alias of signer.
     */
    protected String alias;
    /**
     * The url or path of keystore file.
     */
    protected String keystore;
    /**
     * password for the store
     */
    protected String storepass;
    /**
     * type of store,-storetype param
     */
    protected String storetype;
    /**
     * password for the key in the store
     */
    protected String keypass;
    /**
     * verbose output
     */
    protected boolean verbose;
    /**
     * strict checking
     * @since Ant 1.9.1
     */
    protected boolean strict = false;
    /**
     * The maximum amount of memory to use for Jar signer
     */
    protected String maxMemory;
    /**
     * the filesets of the jars to sign
     */
    protected Vector<FileSet> filesets = new Vector<FileSet>();
    /**
     * name of JDK program we are looking for
     */
    protected static final String JARSIGNER_COMMAND = "jarsigner";

    // CheckStyle:VisibilityModifier ON

    /**
     * redirector used to talk to the jarsigner program
     */
    private RedirectorElement redirector;

    /**
     * Java declarations -J-Dname=value
     */
    private Environment sysProperties = new Environment();

    /**
     * error string for unit test verification: {@value}
     */
    public static final String ERROR_NO_SOURCE = "jar must be set through jar attribute "
            + "or nested filesets";

    /**
     * Path holding all non-filesets of filesystem resources we want to sign.
     *
     * @since Ant 1.7
     */
    private Path path = null;

    /**
     * The executable to use instead of jarsigner.
     *
     * @since Ant 1.8.0
     */
    private String executable;

    /**
     * Set the maximum memory to be used by the jarsigner process
     *
     * @param max a string indicating the maximum memory according to the JVM
     *            conventions (e.g. 128m is 128 Megabytes)
     */
    public void setMaxmemory(String max) {
        maxMemory = max;
    }

    /**
     * the jar file to sign; required
     *
     * @param jar the jar file to sign
     */
    public void setJar(final File jar) {
        this.jar = jar;
    }

    /**
     * the alias to sign under; required
     *
     * @param alias the alias to sign under
     */
    public void setAlias(final String alias) {
        this.alias = alias;
    }

    /**
     * keystore location; required
     *
     * @param keystore the keystore location
     */
    public void setKeystore(final String keystore) {
        this.keystore = keystore;
    }

    /**
     * password for keystore integrity; required
     *
     * @param storepass the password for the keystore
     */
    public void setStorepass(final String storepass) {
        this.storepass = storepass;
    }

    /**
     * keystore type; optional
     *
     * @param storetype the keystore type
     */
    public void setStoretype(final String storetype) {
        this.storetype = storetype;
    }

    /**
     * password for private key (if different); optional
     *
     * @param keypass the password for the key (if different)
     */
    public void setKeypass(final String keypass) {
        this.keypass = keypass;
    }

    /**
     * Enable verbose output when signing ; optional: default false
     *
     * @param verbose if true enable verbose output
     */
    public void setVerbose(final boolean verbose) {
        this.verbose = verbose;
    }

    /**
     * do strict checking
     * @since Ant 1.9.1
     * @param strict
     */
    public void setStrict(boolean strict) {
        this.strict = strict;
    }

    /**
     * Adds a set of files to sign
     *
     * @param set a set of files to sign
     * @since Ant 1.4
     */
    public void addFileset(final FileSet set) {
        filesets.addElement(set);
    }

    /**
     * Add a system property.
     *
     * @param sysp system property.
     */
    public void addSysproperty(Environment.Variable sysp) {
        sysProperties.addVariable(sysp);
    }

    /**
     * Adds a path of files to sign.
     *
     * @return a path of files to sign.
     * @since Ant 1.7
     */
    public Path createPath() {
        if (path == null) {
            path = new Path(getProject());
        }
        return path.createPath();
    }

    /**
     * init processing logic; this is retained through our execution(s)
     */
    protected void beginExecution() {

        redirector = createRedirector();
    }

    /**
     * any cleanup logic
     */
    protected void endExecution() {
        redirector = null;
    }

    /**
     * Create the redirector to use, if any.
     *
     * @return a configured RedirectorElement.
     */
    private RedirectorElement createRedirector() {
        RedirectorElement result = new RedirectorElement();
        if (storepass != null) {
            StringBuffer input = new StringBuffer(storepass).append('\n');
            if (keypass != null) {
                input.append(keypass).append('\n');
            }
            result.setInputString(input.toString());
            result.setLogInputString(false);
            // Try to avoid showing password prompts on log output, as they would be confusing.
            LineContainsRegExp filter = new LineContainsRegExp();
            RegularExpression rx = new RegularExpression();
            // TODO only handles English locale, not ja or zh_CN
            rx.setPattern("^(Enter Passphrase for keystore: |Enter key password for .+: )$");
            filter.addConfiguredRegexp(rx);
            filter.setNegate(true);
            result.createErrorFilterChain().addLineContainsRegExp(filter);
        }
        return result;
    }

    /**
     * get the redirector. Non-null between invocations of
     * {@link #beginExecution()} and {@link #endExecution()}
     * @return a redirector or null
     */
    public RedirectorElement getRedirector() {
        return redirector;
    }

    /**
     * Sets the actual executable command to invoke, instead of the binary
     * <code>jarsigner</code> found in Ant's JDK.
     * @param executable the command to invoke.
     * @since Ant 1.8.0
     */
    public void setExecutable(String executable) {
        this.executable = executable;
    }

    /**
     * these are options common to signing and verifying
     * @param cmd  command to configure
     */
    protected void setCommonOptions(final ExecTask cmd) {
        if (maxMemory != null) {
            addValue(cmd, "-J-Xmx" + maxMemory);
        }

        if (verbose) {
            addValue(cmd, "-verbose");
        }

        if (strict) {
            addValue(cmd, "-strict");
        }

        //now patch in all system properties
        for (Environment.Variable variable : sysProperties.getVariablesVector()) {
            declareSysProperty(cmd, variable);
        }
    }

    /**
     *
     * @param cmd command to configure
     * @param property property to set
     * @throws BuildException if the property is not correctly defined.
     */
    protected void declareSysProperty(
        ExecTask cmd, Environment.Variable property) throws BuildException {
        addValue(cmd, "-J-D" + property.getContent());
    }


    /**
     * bind to a keystore if the attributes are there
     * @param cmd command to configure
     */
    protected void bindToKeystore(final ExecTask cmd) {
        if (null != keystore) {
            // is the keystore a file
            addValue(cmd, "-keystore");
            String loc;
            File keystoreFile = getProject().resolveFile(keystore);
            if (keystoreFile.exists()) {
                loc = keystoreFile.getPath();
            } else {
                // must be a URL - just pass as is
                loc = keystore;
            }
            addValue(cmd, loc);
        }
        if (null != storetype) {
            addValue(cmd, "-storetype");
            addValue(cmd, storetype);
        }
    }

    /**
     * create the jarsigner executable task
     * @return a task set up with the executable of jarsigner, failonerror=true
     * and bound to our redirector
     */
    protected ExecTask createJarSigner() {
        final ExecTask cmd = new ExecTask(this);
        if (executable == null) {
            cmd.setExecutable(JavaEnvUtils.getJdkExecutable(JARSIGNER_COMMAND));
        } else {
            cmd.setExecutable(executable);
        }
        cmd.setTaskType(JARSIGNER_COMMAND);
        cmd.setFailonerror(true);
        cmd.addConfiguredRedirector(redirector);
        return cmd;
    }

    /**
     * clone our filesets vector, and patch in the jar attribute as a new
     * fileset, if is defined
     * @return a vector of FileSet instances
     */
    protected Vector<FileSet> createUnifiedSources() {
        @SuppressWarnings("unchecked")
        Vector<FileSet> sources = (Vector<FileSet>) filesets.clone();
        if (jar != null) {
            //we create a fileset with the source file.
            //this lets us combine our logic for handling output directories,
            //mapping etc.
            FileSet sourceJar = new FileSet();
            sourceJar.setProject(getProject());
            sourceJar.setFile(jar);
            sourceJar.setDir(jar.getParentFile());
            sources.add(sourceJar);
        }
        return sources;
    }

    /**
     * clone our path and add all explicitly specified FileSets as
     * well, patch in the jar attribute as a new fileset if it is
     * defined.
     * @return a path that contains all files to sign
     * @since Ant 1.7
     */
    protected Path createUnifiedSourcePath() {
        Path p = path == null ? new Path(getProject()) : (Path) path.clone();
        for (FileSet fileSet : createUnifiedSources()) {
            p.add(fileSet);
        }
        return p;
    }

    /**
     * Has either a path or a fileset been specified?
     * @return true if a path or fileset has been specified.
     * @since Ant 1.7
     */
    protected boolean hasResources() {
        return path != null || filesets.size() > 0;
    }

    /**
     * add a value argument to a command
     * @param cmd command to manipulate
     * @param value value to add
     */
    protected void addValue(final ExecTask cmd, String value) {
        cmd.createArg().setValue(value);
    }
}