Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sct parsing and cleanup tests #7

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ byte[] signed = signature.sign();
CertificateRequest cReq = new CertificateRequest(keys.getPublic(), signed);

// ask fulcio for a signing cert chain for our public key
CertificateResponse cResp = fulcioClient.SigningCert(cReq, token);
SigningCertificate signingCert = fulcioClient.SigningCert(cReq, token);

// sign something with our private key, throw it away and save the cert with the artifact
```
Expand Down
3 changes: 3 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ dependencies {
implementation("com.google.api-client:google-api-client-gson:1.31.5")

implementation("com.google.code.gson:gson:2.8.9")
implementation("org.conscrypt:conscrypt-openjdk-uber:2.5.2") {
because("contains library code for all platforms")
}

testImplementation("junit:junit:4.12")
testImplementation("com.nimbusds:oauth2-oidc-sdk:6.21.2")
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/dev/sigstore/fulcio/client/CertificateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
*/
package dev.sigstore.fulcio.client;

import dev.sigstore.json.GsonSupplier;
import java.security.PublicKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class CertificateRequest {
Expand Down Expand Up @@ -49,4 +51,16 @@ public PublicKey getPublicKey() {
public byte[] getSignedEmailAddress() {
return signedEmailAddress;
}

public String toJsonPayload() {
HashMap<String, Object> key = new HashMap<>();
key.put("content", getPublicKey().getEncoded());
key.put("algorithm", getPublicKey().getAlgorithm());

HashMap<String, Object> data = new HashMap<>();
data.put("publicKey", key);
data.put("signedEmailAddress", getSignedEmailAddress());

return new GsonSupplier().get().toJson(data);
}
}
33 changes: 0 additions & 33 deletions src/main/java/dev/sigstore/fulcio/client/CertificateRequests.java

This file was deleted.

39 changes: 0 additions & 39 deletions src/main/java/dev/sigstore/fulcio/client/CertificateResponse.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,18 @@

import com.google.api.client.http.*;
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
import com.google.api.client.util.PemReader;
import java.io.ByteArrayInputStream;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.HttpClientBuilder;
import org.conscrypt.ct.SerializationException;

public class Client {
public class FulcioClient {
public static final String PUBLIC_FULCIO_SERVER = "https://fulcio.sigstore.dev";
public static final String SIGNING_CERT_PATH = "/api/v1/signingCert";
public static final String DEFAULT_USER_AGENT = "fulcioJavaClient/0.0.1";
Expand All @@ -40,22 +37,26 @@ public class Client {
private final HttpTransport httpTransport;
private final URI serverUrl;
private final String userAgent;
private final boolean requireSct;

public static Builder Builder() {
public static Builder builder() {
return new Builder();
}

private Client(HttpTransport httpTransport, URI serverUrl, String userAgent) {
private FulcioClient(
HttpTransport httpTransport, URI serverUrl, String userAgent, boolean requireSct) {
this.httpTransport = httpTransport;
this.serverUrl = serverUrl;
this.userAgent = userAgent;
this.requireSct = requireSct;
}

public static class Builder {
private long timeout = DEFAULT_TIMEOUT;
private URI serverUrl = URI.create(PUBLIC_FULCIO_SERVER);
private String userAgent = DEFAULT_USER_AGENT;
private boolean useSSLVerification = true;
private boolean requireSct = true;

private Builder() {}

Expand Down Expand Up @@ -85,28 +86,32 @@ public Builder setUseSSLVerification(boolean enable) {
return this;
}

public Client build() {
public Builder requireSct(boolean requireSct) {
this.requireSct = requireSct;
return this;
}

public FulcioClient build() {
HttpClientBuilder hcb = ApacheHttpTransport.newDefaultHttpClientBuilder();
hcb.setConnectionTimeToLive(timeout, TimeUnit.SECONDS);
if (!useSSLVerification) {
hcb = hcb.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
}
HttpTransport httpTransport = new ApacheHttpTransport(hcb.build());
return new Client(httpTransport, serverUrl, userAgent);
return new FulcioClient(httpTransport, serverUrl, userAgent, requireSct);
}
}

public CertificateResponse SigningCert(CertificateRequest cr, String bearerToken)
throws IOException, CertificateException {
public SigningCertificate SigningCert(CertificateRequest cr, String bearerToken)
throws IOException, CertificateException, SerializationException {
URI fulcioEndpoint = serverUrl.resolve(SIGNING_CERT_PATH);

HttpRequest req =
httpTransport
.createRequestFactory()
.buildPostRequest(
new GenericUrl(fulcioEndpoint),
ByteArrayContent.fromString(
"application/json", CertificateRequests.toJsonPayload(cr)));
ByteArrayContent.fromString("application/json", cr.toJsonPayload()));

req.getHeaders().setAccept("application/pem-certificate-chain");
req.getHeaders().setAuthorization("Bearer " + bearerToken);
Expand All @@ -119,29 +124,14 @@ public CertificateResponse SigningCert(CertificateRequest cr, String bearerToken
}

String sctHeader = resp.getHeaders().getFirstHeaderStringValue("SCT");
if (sctHeader == null) {
if (sctHeader == null && requireSct) {
throw new IOException("no signed certificate timestamps were found in response from Fulcio");
}
byte[] sct = Base64.getDecoder().decode(sctHeader);

System.out.println(new String(sct));

CertificateFactory cf = CertificateFactory.getInstance("X.509");
ArrayList<X509Certificate> certList = new ArrayList<>();
PemReader pemReader = new PemReader(new InputStreamReader(resp.getContent()));
while (true) {
PemReader.Section section = pemReader.readNextSection();
if (section == null) {
break;
}

byte[] certBytes = section.getBase64DecodedBytes();
certList.add((X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes)));
try (InputStream content = resp.getContent()) {
return SigningCertificate.newSigningCertificate(
CharStreams.toString(new InputStreamReader(content, resp.getContentCharset())),
sctHeader);
}
if (certList.isEmpty()) {
throw new IOException("no certificates were found in response from Fulcio");
}

return new CertificateResponse(cf.generateCertPath(certList), sct);
}
}
125 changes: 125 additions & 0 deletions src/main/java/dev/sigstore/fulcio/client/SigningCertificate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright 2022 The Sigstore Authors.
*
* Licensed 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 dev.sigstore.fulcio.client;

import com.google.api.client.util.PemReader;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import dev.sigstore.json.GsonSupplier;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.cert.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Optional;
import javax.annotation.Nullable;
import org.conscrypt.ct.DigitallySigned;
import org.conscrypt.ct.SerializationException;
import org.conscrypt.ct.SignedCertificateTimestamp;

/** Response from Fulcio that includes a certPath and an SCT */
public class SigningCertificate {

private final CertPath certPath;
@Nullable private final SignedCertificateTimestamp sct;

static SigningCertificate newSigningCertificate(String certs, @Nullable String sctHeader)
throws CertificateException, IOException, SerializationException {
CertPath certPath = decodeCerts(certs);
if (sctHeader != null) {
SignedCertificateTimestamp sct = decodeSCT(sctHeader);
return new SigningCertificate(certPath, sct);
}
return new SigningCertificate(certPath, null);
}

@VisibleForTesting
static CertPath decodeCerts(String content) throws CertificateException, IOException {
PemReader pemReader = new PemReader(new StringReader(content));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ArrayList<X509Certificate> certList = new ArrayList<>();
while (true) {
PemReader.Section section = pemReader.readNextSection();
if (section == null) {
break;
}

byte[] certBytes = section.getBase64DecodedBytes();
certList.add((X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes)));
}
if (certList.isEmpty()) {
throw new IOException("no valid PEM certificates were found in response from Fulcio");
}

return cf.generateCertPath(certList);
}

@VisibleForTesting
static SignedCertificateTimestamp decodeSCT(String sctHeader) throws SerializationException {
byte[] sct = Base64.getDecoder().decode(sctHeader);
Gson gson = new GsonSupplier().get();
return gson.fromJson(
new InputStreamReader(new ByteArrayInputStream(sct), StandardCharsets.UTF_8),
SctJson.class)
.toSct();
}

private static class SctJson {
private int sct_version;
private byte[] id;
private long timestamp;
private byte[] extensions;
private byte[] signature;

public SignedCertificateTimestamp toSct() throws JsonParseException, SerializationException {
if (sct_version != 0) {
throw new JsonParseException(
"Invalid SCT version:" + sct_version + ", only 0 (V1) is allowed");
}
if (extensions.length != 0) {
throw new JsonParseException(
"SCT has extensions that cannot be handled by client:" + new String(extensions));
}

DigitallySigned digiSig = DigitallySigned.decode(signature);
return new SignedCertificateTimestamp(
SignedCertificateTimestamp.Version.V1,
id,
timestamp,
extensions,
digiSig,
SignedCertificateTimestamp.Origin.OCSP_RESPONSE);
}
}

private SigningCertificate(CertPath certPath, @Nullable SignedCertificateTimestamp sct) {
this.certPath = certPath;
this.sct = sct;
}

public CertPath getCertPath() {
return certPath;
}

public Certificate getLeafCertificate() {
return certPath.getCertificates().get(0);
}

Optional<SignedCertificateTimestamp> getSct() {
return Optional.ofNullable(sct);
}
}
Loading