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
|
/*
* 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.tomcat.buildutil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Ant task that submits a file to the Symantec code-signing service.
*/
public class SignCode extends Task {
private static final URL SIGNING_SERVICE_URL;
private static final String NS = "cod";
private static final MessageFactory SOAP_MSG_FACTORY;
static {
try {
SIGNING_SERVICE_URL = new URL("https://api.ws.symantec.com/webtrust/SigningService");
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
try {
SOAP_MSG_FACTORY = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
} catch (SOAPException e) {
throw new IllegalArgumentException(e);
}
}
private final List<FileSet> filesets = new ArrayList<>();
private String userName;
private String password;
private String partnerCode;
private String applicationName;
private String applicationVersion;
private String signingService;
public void addFileset(FileSet fileset) {
filesets.add(fileset);
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setPartnerCode(String partnerCode) {
this.partnerCode = partnerCode;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
public void setSigningService(String signingService) {
this.signingService = signingService;
}
@Override
public void execute() throws BuildException {
List<File> filesToSign = new ArrayList<>();
// Process the filesets and populate the list of files that need to be
// signed.
for (FileSet fileset : filesets) {
DirectoryScanner ds = fileset.getDirectoryScanner(getProject());
File basedir = ds.getBasedir();
String[] files = ds.getIncludedFiles();
if (files.length > 0) {
for (int i = 0; i < files.length; i++) {
File file = new File(basedir, files[i]);
filesToSign.add(file);
}
}
}
try {
String signingSetID = makeSigningRequest(filesToSign);
downloadSignedFiles(filesToSign, signingSetID);
} catch (SOAPException | IOException e) {
throw new BuildException(e);
}
}
private String makeSigningRequest(List<File> filesToSign) throws SOAPException, IOException {
log("Constructing the code signing request");
SOAPMessage message = SOAP_MSG_FACTORY.createMessage();
SOAPBody body = populateEnvelope(message, NS);
SOAPElement requestSigning = body.addChildElement("requestSigning", NS);
SOAPElement requestSigningRequest =
requestSigning.addChildElement("requestSigningRequest", NS);
addCredentials(requestSigningRequest, this.userName, this.password, this.partnerCode);
SOAPElement applicationName =
requestSigningRequest.addChildElement("applicationName", NS);
applicationName.addTextNode(this.applicationName);
SOAPElement applicationVersion =
requestSigningRequest.addChildElement("applicationVersion", NS);
applicationVersion.addTextNode(this.applicationVersion);
SOAPElement signingServiceName =
requestSigningRequest.addChildElement("signingServiceName", NS);
signingServiceName.addTextNode(this.signingService);
List<String> fileNames = getFileNames(filesToSign);
SOAPElement commaDelimitedFileNames =
requestSigningRequest.addChildElement("commaDelimitedFileNames", NS);
commaDelimitedFileNames.addTextNode(listToString(fileNames));
SOAPElement application =
requestSigningRequest.addChildElement("application", NS);
application.addTextNode(getApplicationString(fileNames, filesToSign));
// Send the message
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
log("Sending siging request to server and waiting for response");
SOAPMessage response = connection.call(message, SIGNING_SERVICE_URL);
log("Processing response");
SOAPElement responseBody = response.getSOAPBody();
// Should come back signed
NodeList bodyNodes = responseBody.getChildNodes();
NodeList requestSigningResponseNodes = bodyNodes.item(0).getChildNodes();
NodeList returnNodes = requestSigningResponseNodes.item(0).getChildNodes();
String signingSetID = null;
String signingSetStatus = null;
for (int i = 0; i < returnNodes.getLength(); i++) {
Node returnNode = returnNodes.item(i);
if (returnNode.getLocalName().equals("signingSetID")) {
signingSetID = returnNode.getTextContent();
} else if (returnNode.getLocalName().equals("signingSetStatus")) {
signingSetStatus = returnNode.getTextContent();
}
}
if (!"SIGNED".equals(signingSetStatus)) {
throw new BuildException("Signing failed. Status was: " + signingSetStatus);
}
return signingSetID;
}
private String listToString(List<String> list) {
StringBuilder sb = new StringBuilder(list.size() * 6);
boolean doneFirst = false;
for (String s : list) {
if (doneFirst) {
sb.append(',');
} else {
doneFirst = true;
}
sb.append(s);
}
return sb.toString();
}
private void downloadSignedFiles(List<File> filesToSign, String id)
throws SOAPException, IOException {
log("Downloading signed files. The signing set ID is: " + id);
SOAPMessage message = SOAP_MSG_FACTORY.createMessage();
SOAPBody body = populateEnvelope(message, NS);
SOAPElement getSigningSetDetails = body.addChildElement("getSigningSetDetails", NS);
SOAPElement getSigningSetDetailsRequest =
getSigningSetDetails.addChildElement("getSigningSetDetailsRequest", NS);
addCredentials(getSigningSetDetailsRequest, this.userName, this.password, this.partnerCode);
SOAPElement signingSetID =
getSigningSetDetailsRequest.addChildElement("signingSetID", NS);
signingSetID.addTextNode(id);
SOAPElement returnApplication =
getSigningSetDetailsRequest.addChildElement("returnApplication", NS);
returnApplication.addTextNode("true");
// Send the message
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
log("Requesting signed files from server and waiting for response");
SOAPMessage response = connection.call(message, SIGNING_SERVICE_URL);
log("Processing response");
SOAPElement responseBody = response.getSOAPBody();
// Check for success
// Extract the signed file(s) from the ZIP
NodeList bodyNodes = responseBody.getChildNodes();
NodeList getSigningSetDetailsResponseNodes = bodyNodes.item(0).getChildNodes();
NodeList returnNodes = getSigningSetDetailsResponseNodes.item(0).getChildNodes();
String result = null;
String data = null;
for (int i = 0; i < returnNodes.getLength(); i++) {
Node returnNode = returnNodes.item(i);
if (returnNode.getLocalName().equals("result")) {
result = returnNode.getChildNodes().item(0).getTextContent();
} else if (returnNode.getLocalName().equals("signingSet")) {
data = returnNode.getChildNodes().item(1).getTextContent();
}
}
if (!"0".equals(result)) {
throw new BuildException("Download failed. Result code was: " + result);
}
extractFilesFromApplicationString(data, filesToSign);
}
private static SOAPBody populateEnvelope(SOAPMessage message, String namespace)
throws SOAPException {
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(
"soapenv","http://schemas.xmlsoap.org/soap/envelope/");
envelope.addNamespaceDeclaration(
namespace,"http://api.ws.symantec.com/webtrust/codesigningservice");
return envelope.getBody();
}
private static void addCredentials(SOAPElement requestSigningRequest,
String user, String pwd, String code) throws SOAPException {
SOAPElement authToken = requestSigningRequest.addChildElement("authToken", NS);
SOAPElement userName = authToken.addChildElement("userName", NS);
userName.addTextNode(user);
SOAPElement password = authToken.addChildElement("password", NS);
password.addTextNode(pwd);
SOAPElement partnerCode = authToken.addChildElement("partnerCode", NS);
partnerCode.addTextNode(code);
}
/**
* Signing service requires unique files names. Since files will be returned
* in order, use dummy names that we know are unique but retain the file
* extension since the signing service appears to use it to figure out what
* to sign and how to sign it.
*/
private static List<String> getFileNames(List<File> filesToSign) {
List<String> result = new ArrayList<>(filesToSign.size());
for (int i = 0; i < filesToSign.size(); i++) {
File f = filesToSign.get(i);
String fileName = f.getName();
int extIndex = fileName.lastIndexOf('.');
String newName;
if (extIndex < 0) {
newName = Integer.toString(i);
} else {
newName = Integer.toString(i) + fileName.substring(extIndex);
}
result.add(newName);
}
return result;
}
/**
* Zips the files, base 64 encodes the resulting zip and then returns the
* string. It would be far more efficient to stream this directly to the
* signing server but the files that need to be signed are relatively small
* and this simpler to write.
*
* @param fileNames Modified names of files
* @param files Files to be signed
*/
private static String getApplicationString(List<String> fileNames, List<File> files)
throws IOException {
// 16 MB should be more than enough for Tomcat
ByteArrayOutputStream baos = new ByteArrayOutputStream(16 * 1024 * 1024);
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
byte[] buf = new byte[32 * 1024];
for (int i = 0; i < files.size(); i++) {
try (FileInputStream fis = new FileInputStream(files.get(i))) {
ZipEntry zipEntry = new ZipEntry(fileNames.get(i));
zos.putNextEntry(zipEntry);
int numRead;
while ( (numRead = fis.read(buf)) >= 0) {
zos.write(buf, 0, numRead);
}
}
}
}
return Base64.encodeBase64String(baos.toByteArray());
}
/**
* Removes base64 encoding, unzips the files and writes the new files over
* the top of the old ones.
*/
private static void extractFilesFromApplicationString(String data, List<File> files)
throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(data));
try (ZipInputStream zis = new ZipInputStream(bais)) {
byte[] buf = new byte[32 * 1024];
for (int i = 0; i < files.size(); i ++) {
try (FileOutputStream fos = new FileOutputStream(files.get(i))) {
zis.getNextEntry();
int numRead;
while ( (numRead = zis.read(buf)) >= 0) {
fos.write(buf, 0 , numRead);
}
}
}
}
}
}
|