feat: Allow import of trust-only certificates

- These certificates do not have keys, because they are solely for trusting them.
- Also more rigorously verify arguments passed to OpenSSL
This commit is contained in:
Magnus Leßmann (@MarkL4YG) 2024-11-24 11:38:35 +01:00
parent 286c9dcf28
commit a4f495ab91
8 changed files with 157 additions and 30 deletions

View file

@ -10,6 +10,8 @@ import java.nio.file.Path;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
@Service
@ -24,7 +26,10 @@ public class CertificateCreationService {
final Certificate certificate = createEntityFromRequest(certificateInfo);
try (OpenSSLCertificateResult certificateCreatorResult = openSSLService.createCertificate(certificateInfo);) {
certificate.setPrivateKey(Files.readAllBytes(certificateCreatorResult.certificateKeyPath()));
Path keyPath = certificateCreatorResult.certificateKeyPath();
if (keyPath != null) {
certificate.setPrivateKey(Files.readAllBytes(keyPath));
}
certificate.setCert(Files.readAllBytes(certificateCreatorResult.certificatePath()));
} catch (CommandLineOperationException | IOException e) {
throw new IllegalStateException("Failed to create certificate!", e);
@ -59,15 +64,22 @@ public class CertificateCreationService {
return certificate;
}
public Certificate importCertificate(Path certificate, Path keyFile, String passphrase) {
@NonNull
public Certificate importCertificate(
@NonNull Path certificate,
@Nullable Path keyFile,
@Nullable String keyPassphrase
) {
try {
String fingerprint = openSSLService.getCertificateFingerprint(certificate);
var generatedRequest = openSSLService.getCertificateInfo(certificate);
Certificate entity = createEntityFromRequest(generatedRequest);
entity.setCert(Files.readAllBytes(certificate));
entity.setPrivateKey(Files.readAllBytes(keyFile));
if (StringUtils.isNotBlank(passphrase)) {
passphraseService.storePassphrase("cert:" + fingerprint, passphrase);
if (keyFile != null) {
entity.setPrivateKey(Files.readAllBytes(keyFile));
}
if (StringUtils.isNotBlank(keyPassphrase)) {
passphraseService.storePassphrase("cert:" + fingerprint, keyPassphrase);
}
return certificateRepository.save(entity);
} catch (CommandLineOperationException | IOException e) {