• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ebourg / jsign / #400

06 Jul 2026 05:44PM UTC coverage: 80.842% (-0.03%) from 80.872%
#400

push

ebourg
Fixed opensc-pkcs11.so lookup on LD_LIBRARY_PATH

0 of 1 new or added line in 1 file covered. (0.0%)

50 existing lines in 4 files now uncovered.

5068 of 6269 relevant lines covered (80.84%)

0.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.11
/jsign-core/src/main/java/net/jsign/msi/MSIFile.java
1
/*
2
 * Copyright 2019 Emmanuel Bourg
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package net.jsign.msi;
18

19
import java.io.ByteArrayInputStream;
20
import java.io.DataInputStream;
21
import java.io.File;
22
import java.io.FileInputStream;
23
import java.io.FileNotFoundException;
24
import java.io.FilterInputStream;
25
import java.io.IOException;
26
import java.io.InputStream;
27
import java.io.RandomAccessFile;
28
import java.nio.ByteBuffer;
29
import java.nio.ByteOrder;
30
import java.nio.channels.Channels;
31
import java.nio.channels.SeekableByteChannel;
32
import java.security.MessageDigest;
33
import java.util.ArrayList;
34
import java.util.List;
35
import java.util.Map;
36
import java.util.NoSuchElementException;
37
import java.util.TreeMap;
38

39
import org.apache.poi.poifs.filesystem.DocumentEntry;
40
import org.apache.poi.poifs.filesystem.DocumentInputStream;
41
import org.apache.poi.poifs.filesystem.DocumentNode;
42
import org.apache.poi.poifs.filesystem.Entry;
43
import org.apache.poi.poifs.filesystem.POIFSDocument;
44
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
45
import org.apache.poi.poifs.property.DirectoryProperty;
46
import org.apache.poi.poifs.property.DocumentProperty;
47
import org.apache.poi.poifs.property.Property;
48
import org.apache.poi.util.IOUtils;
49
import org.bouncycastle.asn1.ASN1Object;
50
import org.bouncycastle.asn1.DERNull;
51
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
52
import org.bouncycastle.asn1.x509.DigestInfo;
53
import org.bouncycastle.cms.CMSSignedData;
54

55
import net.jsign.DigestAlgorithm;
56
import net.jsign.Signable;
57
import net.jsign.SignatureUtils;
58
import net.jsign.asn1.authenticode.AuthenticodeObjectIdentifiers;
59
import net.jsign.asn1.authenticode.SpcAttributeTypeAndOptionalValue;
60
import net.jsign.asn1.authenticode.SpcIndirectDataContent;
61
import net.jsign.asn1.authenticode.SpcSipInfo;
62
import net.jsign.asn1.authenticode.SpcUuid;
63

64
import static org.apache.poi.poifs.common.POIFSConstants.*;
65

66
/**
67
 * A Microsoft Installer package.
68
 * 
69
 * @author Emmanuel Bourg
70
 * @since 3.0
71
 */
72
public class MSIFile implements Signable {
73

74
    private static final long MSI_HEADER = 0xD0CF11E0A1B11AE1L;
75

76
    private static final String DIGITAL_SIGNATURE_ENTRY_NAME = "\u0005DigitalSignature";
77
    private static final String MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME = "\u0005MsiDigitalSignatureEx";
78

79
    /**
80
     * The POI filesystem used for reading the file. A separate filesystem has
81
     * to be used because POI maps the file in memory in read/write mode and
82
     * this leads to OOM errors when the file is parsed.
83
     * See https://github.com/ebourg/jsign/issues/82 for more info.
84
     */
85
    private POIFSFileSystem fsRead;
86

87
    /** The POI filesystem used for writing to the file */
88
    private POIFSFileSystem fsWrite;
89

90
    /** The channel used for in-memory signing */
91
    private SeekableByteChannel channel;
92

93
    /** The underlying file */
94
    private File file;
95

96
    /**
97
     * Tells if the specified file is a MSI file.
98
     * 
99
     * @param file the file to check
100
     * @return <code>true</code> if the file is a Microsoft installer, <code>false</code> otherwise
101
     * @throws IOException if an I/O error occurs
102
     */
103
    public static boolean isMSIFile(File file) throws IOException {
104
        if (file.length() < 8) {
1✔
105
            return false;
1✔
106
        }
107
        try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
1✔
108
            return in.readLong() == MSI_HEADER;
1✔
109
        }
110
    }
111

112
    /**
113
     * Create a MSIFile from the specified file.
114
     * 
115
     * @param file the file to open
116
     * @throws IOException if an I/O error occurs
117
     */
118
    public MSIFile(File file) throws IOException {
1✔
119
        this.file = file;
1✔
120
        try {
121
            this.fsRead = new POIFSFileSystem(file, true);
1✔
122
            this.fsWrite = new POIFSFileSystem(file, false);
1✔
123
        } catch (NegativeArraySizeException | IndexOutOfBoundsException | IllegalStateException | ClassCastException e) {
1✔
124
            throw new IOException("MSI file format error", e);
1✔
125
        }
1✔
126
    }
1✔
127

128
    /**
129
     * Create a MSIFile from the specified channel.
130
     * 
131
     * @param channel the channel to read the file from
132
     * @throws IOException if an I/O error occurs
133
     */
134
    public MSIFile(final SeekableByteChannel channel) throws IOException {
1✔
135
        this.channel = channel;
1✔
136
        InputStream in = new FilterInputStream(Channels.newInputStream(channel)) {
1✔
137
            public void close() { }
1✔
138
        };
139
        try {
140
            this.fsRead = new POIFSFileSystem(in);
1✔
141
            this.fsWrite = fsRead;
1✔
UNCOV
142
        } catch (NegativeArraySizeException | IndexOutOfBoundsException | IllegalStateException | ClassCastException e) {
×
UNCOV
143
            throw new IOException("MSI file format error", e);
×
144
        }
1✔
145
    }
1✔
146

147
    /**
148
     * Closes the file
149
     *
150
     * @throws IOException if an I/O error occurs
151
     */
152
    public void close() throws IOException {
153
        try (POIFSFileSystem fsRead = this.fsRead; POIFSFileSystem fsWrite = this.fsWrite; SeekableByteChannel channel = this.channel) {
1✔
154
            // do nothing
155
        }
1✔
156
    }
1✔
157

158
    /**
159
     * Tells if the MSI file has an extended signature (MsiDigitalSignatureEx)
160
     * containing a hash of the streams metadata (name, size, date).
161
     * 
162
     * @return <code>true</code> if the file has a MsiDigitalSignatureEx stream, <code>false</code> otherwise
163
     */
164
    public boolean hasExtendedSignature() {
165
        try {
UNCOV
166
            fsRead.getRoot().getEntry(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME);
×
UNCOV
167
            return true;
×
UNCOV
168
        } catch (FileNotFoundException e) {
×
UNCOV
169
            return false;
×
170
        }
171
    }
172

173
    @Override
174
    public byte[] computeDigest(DigestAlgorithm digestAlgorithm) throws IOException {
175
        MessageDigest digest = digestAlgorithm.getMessageDigest();
1✔
176

177
        try {
178
            // hash the MsiDigitalSignatureEx entry if there is one
179
            if (fsRead.getRoot().hasEntry(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME)) {
1✔
180
                Entry msiDigitalSignatureExEntry = fsRead.getRoot().getEntry(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME);
1✔
181
                POIFSDocument msiDigitalSignatureExDocument = new POIFSDocument((DocumentNode) msiDigitalSignatureExEntry);
1✔
182
                updateDigest(digest, msiDigitalSignatureExDocument);
1✔
183
            }
184

185
            updateDigest(digest, fsRead.getPropertyTable().getRoot());
1✔
186

187
            return digest.digest();
1✔
188
        } catch (IndexOutOfBoundsException | IllegalArgumentException | IllegalStateException | NoSuchElementException | ClassCastException e) {
1✔
189
            throw new IOException("MSI file format error", e);
1✔
190
        }
191
    }
192

193
    private void updateDigest(MessageDigest digest, DirectoryProperty node) {
194
        Map<MSIStreamName, Property> sortedEntries = new TreeMap<>();
1✔
195
        for (Property child : node) {
1✔
196
            sortedEntries.put(new MSIStreamName(child.getName()), child);
1✔
197
        }
1✔
198

199
        for (Property property : sortedEntries.values()) {
1✔
200
            if (!property.isDirectory()) {
1✔
201
                String name = new MSIStreamName(property.getName()).decode();
1✔
202
                if (name.equals(DIGITAL_SIGNATURE_ENTRY_NAME) || name.equals(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME)) {
1✔
203
                    continue;
1✔
204
                }
205

206
                POIFSDocument document = new POIFSDocument((DocumentProperty) property, fsRead);
1✔
207
                updateDigest(digest, document);
1✔
208
            } else {
1✔
209
                updateDigest(digest, (DirectoryProperty) property);
1✔
210
            }
211
        }
1✔
212

213
        // hash the package ClassID, in serialized form
214
        byte[] classId = new byte[16];
1✔
215
        node.getStorageClsid().write(classId, 0);
1✔
216
        digest.update(classId);
1✔
217
    }
1✔
218

219
    private void updateDigest(MessageDigest digest, POIFSDocument document) {
220
        long remaining = document.getSize();
1✔
221
        for (ByteBuffer buffer : document) {
1✔
222
            int size = buffer.remaining();
1✔
223
            buffer.limit(buffer.position() + (int) Math.min(remaining, size));
1✔
224
            digest.update(buffer);
1✔
225
            remaining -= size;
1✔
226
        }
1✔
227
    }
1✔
228

229
    @Override
230
    public ASN1Object createIndirectData(DigestAlgorithm digestAlgorithm) throws IOException {
231
        AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(digestAlgorithm.oid, DERNull.INSTANCE);
1✔
232
        DigestInfo digestInfo = new DigestInfo(algorithmIdentifier, computeDigest(digestAlgorithm));
1✔
233

234
        SpcUuid uuid = new SpcUuid("F1100C00-0000-0000-C000-000000000046");
1✔
235
        SpcAttributeTypeAndOptionalValue data = new SpcAttributeTypeAndOptionalValue(AuthenticodeObjectIdentifiers.SPC_SIPINFO_OBJID, new SpcSipInfo(1, uuid));
1✔
236

237
        return new SpcIndirectDataContent(data, digestInfo);
1✔
238
    }
239

240
    @Override
241
    public List<CMSSignedData> getSignatures() throws IOException {
242
        try {
243
            DocumentEntry digitalSignature = (DocumentEntry) fsRead.getRoot().getEntry(DIGITAL_SIGNATURE_ENTRY_NAME);
1✔
244
            if (digitalSignature != null) {
1✔
245
                byte[] signatureBytes = IOUtils.toByteArray(new DocumentInputStream(digitalSignature));
1✔
246

247
                return SignatureUtils.getSignatures(signatureBytes);
1✔
248
            }
249
        } catch (FileNotFoundException e) {
1✔
UNCOV
250
        }
×
251
        
252
        return new ArrayList<>();
1✔
253
    }
254

255
    @Override
256
    public void setSignature(CMSSignedData signature) throws IOException {
257
        if (signature != null) {
1✔
258
            byte[] signatureBytes = signature.toASN1Structure().getEncoded("DER");
1✔
259
            try {
260
                fsWrite.getRoot().createOrUpdateDocument(DIGITAL_SIGNATURE_ENTRY_NAME, new ByteArrayInputStream(signatureBytes));
1✔
261
            } catch (IndexOutOfBoundsException e) {
1✔
262
                throw new IOException("MSI file format error", e);
1✔
263
            }
1✔
264
        } else {
1✔
265
            // remove the signature
266
            if (fsWrite.getRoot().hasEntry(DIGITAL_SIGNATURE_ENTRY_NAME)) {
1✔
267
                fsWrite.getRoot().getEntry(DIGITAL_SIGNATURE_ENTRY_NAME).delete();
1✔
268
            }
269
            if (fsWrite.getRoot().hasEntry(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME)) {
1✔
270
                fsWrite.getRoot().getEntry(MSI_DIGITAL_SIGNATURE_EX_ENTRY_NAME).delete();
1✔
271
            }
272
        }
273
    }
1✔
274

275
    @Override
276
    public void save() throws IOException {
277
        // get the number of directory sectors to be written in the header to work around https://bz.apache.org/bugzilla/show_bug.cgi?id=66590
278
        ByteBuffer directorySectorsCount = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
1✔
279
        directorySectorsCount.putInt(fsWrite.getPropertyTable().countBlocks()).flip();
1✔
280
        int version = fsWrite.getBigBlockSize() == SMALLER_BIG_BLOCK_SIZE ? 3 : 4;
1✔
281

282
        if (channel == null) {
1✔
283
            fsWrite.writeFilesystem();
1✔
284

285
            // update the number of directory sectors in the header
286
            if (version == 4) {
1✔
287
                fsWrite.close();
1✔
288
                try (RandomAccessFile in = new RandomAccessFile(file, "rw")) {
1✔
289
                    in.seek(0x28);
1✔
290
                    in.write(directorySectorsCount.array());
1✔
291
                }
292
                try {
293
                    fsWrite = new POIFSFileSystem(file, false);
1✔
UNCOV
294
                } catch (IndexOutOfBoundsException e) {
×
UNCOV
295
                    throw new IOException("MSI file format error", e);
×
296
                }
1✔
297
            }
298

299
            fsRead.close();
1✔
300
            try {
301
                fsRead = new POIFSFileSystem(file, true);
1✔
302
            } catch (IndexOutOfBoundsException e) {
1✔
303
                throw new IOException("MSI file format error", e);
1✔
304
            }
1✔
305
        } else {
306
            channel.position(0);
1✔
307
            fsWrite.writeFilesystem(Channels.newOutputStream(channel));
1✔
308
            channel.truncate(channel.position());
1✔
309

310
            // update the number of directory sectors in the header
311
            if (version == 4) {
1✔
312
                channel.position(0x28);
1✔
313
                channel.write(directorySectorsCount);
1✔
314
            }
315
        }
316
    }
1✔
317
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc