Skip to content
Merged
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
86 changes: 38 additions & 48 deletions src/main/java/org/pqca/scanning/go/GoScannerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.pqca.errors.ClientDisconnected;
import org.pqca.indexing.ProjectModule;
import org.pqca.progress.IProgressDispatcher;
Expand All @@ -46,36 +46,13 @@

public final class GoScannerService extends ScannerService {

private final GoConverter goConverter;

public GoScannerService(@Nonnull File projectDirectory) {
this(null, projectDirectory);
}

public GoScannerService(
@Nullable IProgressDispatcher progressDispatcher, @Nonnull File projectDirectory) {
super(progressDispatcher, projectDirectory);

try {
DefaultTempFolder tempFolder = new DefaultTempFolder(createDirectory());
goConverter = new GoConverter(tempFolder.newDir());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}

@Nonnull
private File createDirectory() throws IOException {
// create directory
final String folderId = UUID.randomUUID().toString().replace("-", "");
final File tempDir = new File(this.projectDirectory + File.separator + folderId);
if (tempDir.exists()) {
throw new IOException("Temp dir already exists " + tempDir.getPath());
}
if (!tempDir.mkdirs()) {
throw new IOException("Could not create temp dir" + tempDir.getPath());
}
return tempDir;
}

@Override
Expand All @@ -88,31 +65,45 @@ private File createDirectory() throws IOException {
int numberOfScannedLines = 0;
int numberOfScannedFiles = 0;

GoCheck visitor = new GoDetectionCollectionRule(this);
GoChecks checks = new GoRuleChecks(visitor);
final SensorContextTester sensorContext = SensorContextTester.create(projectDirectory);
// Go scanner (CryptoGoSensor) reads files from context
index.forEach(project -> project.inputFileList().forEach(sensorContext.fileSystem()::add));

for (ProjectModule project : index) {
numberOfScannedFiles += project.inputFileList().size();
numberOfScannedLines +=
project.inputFileList().stream().mapToInt(InputFile::lines).sum();

final String projectStr =
project.identifier() + " (" + counter + "/" + index.size() + ")";
if (this.progressDispatcher != null) {
this.progressDispatcher.send(
new ProgressMessage(
ProgressMessageType.LABEL, "Scanning go project " + projectStr));
}
LOGGER.info("Scanning go project {}", projectStr);

CryptoGoSensor.execute((SensorContext) sensorContext, goConverter, checks);
File goTempFolder = new DefaultTempFolder(this.projectDirectory).newDir();

counter += 1;
try {
GoConverter goConverter = new GoConverter(goTempFolder);
GoCheck visitor = new GoDetectionCollectionRule(this);
GoChecks checks = new GoRuleChecks(visitor);
final SensorContextTester sensorContext = SensorContextTester.create(projectDirectory);

// Go scanner (CryptoGoSensor) reads files from context
index.forEach(
project -> project.inputFileList().forEach(sensorContext.fileSystem()::add));

for (ProjectModule project : index) {
numberOfScannedFiles += project.inputFileList().size();
numberOfScannedLines +=
project.inputFileList().stream().mapToInt(InputFile::lines).sum();

final String projectStr =
project.identifier() + " (" + counter + "/" + index.size() + ")";
if (this.progressDispatcher != null) {
this.progressDispatcher.send(
new ProgressMessage(
ProgressMessageType.LABEL,
"Scanning go project " + projectStr));
}
LOGGER.info("Scanning go project {}", projectStr);

CryptoGoSensor.execute((SensorContext) sensorContext, goConverter, checks);

counter += 1;
}
LOGGER.info("Scanned {} go projects", index.size());
} finally {
try {
FileUtils.deleteDirectory(goTempFolder);
} catch (IOException e) {
LOGGER.error("Failed to delete temp dir {}", goTempFolder);
}
}
LOGGER.info("Scanned {} go projects", index.size());

return new ScanResultDTO(
scanTimeStart,
Expand All @@ -134,7 +125,6 @@ public List<GoCheck> all() {
return this.checks;
}

@SuppressWarnings("null")
public RuleKey ruleKey(GoCheck check) {
return RuleKey.of("sonar-cryptography", "go-rule");
}
Expand Down
18 changes: 14 additions & 4 deletions src/test/java/org/pqca/indexing/GoIndexServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,21 @@ class GoIndexServiceTest {
@Test
void testDefaultExclusion() throws ClientDisconnected {
final GoIndexService goIndexService =
new GoIndexService(new File("src/test/testdata/go/simple"));
new GoIndexService(new File("src/test/testdata/go/gocrypto"));
final List<ProjectModule> projectModules = goIndexService.index(null);
assertThat(projectModules).hasSize(1);
assertThat(projectModules.getFirst().inputFileList())
.extracting(Object::toString)
.containsExactlyInAnyOrder("go.mod", "module1/file.go");
assertThat(projectModules.getFirst().identifier()).isEqualTo("");
assertThat(projectModules.getFirst().inputFileList()).hasSize(36);
}

@Test
void testCustomExclusion() throws ClientDisconnected {
final GoIndexService goIndexService =
new GoIndexService(new File("src/test/testdata/go/gocrypto"));
goIndexService.setExcludePatterns(List.of("RSA"));
final List<ProjectModule> projectModules = goIndexService.index(null);
assertThat(projectModules).hasSize(1);
assertThat(projectModules.getFirst().identifier()).isEqualTo("");
assertThat(projectModules.getFirst().inputFileList()).hasSize(31);
}
}
88 changes: 88 additions & 0 deletions src/test/java/org/pqca/scanning/GoScannerServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* CBOMkit-lib
* Copyright (C) 2025 PQCA
*
* 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
*
* https://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.pqca.scanning;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.pqca.errors.ClientDisconnected;
import org.pqca.indexing.ProjectModule;
import org.pqca.indexing.go.GoIndexService;
import org.pqca.scanning.go.GoScannerService;
import org.pqca.utils.AssertableCBOM;

class GoScannerServiceTest {

@Test
void test() throws ClientDisconnected {
// indexing
final File projectDirectory = new File("src/test/testdata/go/gocrypto");
final GoIndexService goIndexService = new GoIndexService(projectDirectory);
final List<ProjectModule> goModules = goIndexService.index(null);
assertThat(goModules).hasSize(1);
final ProjectModule projectModule = goModules.getFirst();
assertThat(projectModule.inputFileList()).isNotEmpty();
// scanning
final GoScannerService goScannerService = new GoScannerService(projectDirectory);
ScanResultDTO scanResult = goScannerService.scan(goModules);

// check - verify cryptographic assets are detected
AssertableCBOM assertableCBOM = new AssertableCBOM(scanResult.cbom());
assertThat(scanResult.cbom().cycloneDXbom().getComponents()).hasSize(27);
assertableCBOM.hasNumberOfDetections(69);

assertThat(
assertableCBOM.hasDetectionWithNameAt(
"SHA256",
"src/test/testdata/go/gocrypto/GoCryptoSHA256TestFile.go",
10))
.isTrue();

assertThat(
assertableCBOM.hasDetectionWithNameAt(
"AES-GCM",
"src/test/testdata/go/gocrypto/GoCryptoAESTestFile.go",
18))
.isTrue();

assertThat(
assertableCBOM.hasDetectionWithNameAt(
"RSA-2048",
"src/test/testdata/go/gocrypto/GoCryptoRSATestFile.go",
10))
.isTrue();

assertThat(
assertableCBOM.hasDetectionWithNameAt(
"HMAC-SHA256",
"src/test/testdata/go/gocrypto/GoCryptoHMACTestFile.go",
11))
.isTrue();

assertThat(
assertableCBOM.hasDetectionWithNameAt(
"PBKDF2",
"src/test/testdata/go/gocrypto/GoCryptoPBKDF2TestFile.go",
15))
.isTrue();
}
}
37 changes: 37 additions & 0 deletions src/test/testdata/go/gocrypto/GoCryptoAESGCMEncryptTestFile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"crypto/aes"
"crypto/cipher"
crand "crypto/rand"
"encoding/base64"
"io"
)

// Encrypt encrypts "data" with the specified "key" (must be valid 32 char AES key).
//
// This method uses AES-256-GCM block cypher mode.
func Encrypt(data []byte, key string) (string, error) {
block, err := aes.NewCipher([]byte(key)) // Noncompliant {{(AuthenticatedEncryption) AES-GCM}}
if err != nil {
return "", err
}

gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}

nonce := make([]byte, gcm.NonceSize())

// populates the nonce with a cryptographically secure random sequence
if _, err := io.ReadFull(crand.Reader, nonce); err != nil {
return "", err
}

cipherByte := gcm.Seal(nonce, nonce, data, nil)

result := base64.StdEncoding.EncodeToString(cipherByte)

return result, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"crypto/aes"
"crypto/cipher"
)

// AES-GCM Decryption with custom nonce size
func AesGcmDecrypt(cipherText, cek, nonce, authTag, aad []byte) ([]byte, error) {
cipherTextWithAuthTag := append(cipherText, authTag...)

block, err := aes.NewCipher(cek) // Noncompliant {{(AuthenticatedEncryption) AES-GCM}}
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCMWithNonceSize(block, len(nonce))
if err != nil {
return nil, err
}
plainText, err := aesgcm.Open(nil, nonce, cipherTextWithAuthTag, aad)
if err != nil {
return nil, err
}
return plainText, nil
}

// AES-GCM Encryption with custom nonce size
func AesGcmEncrypt(plainText, cek, nonce, aad []byte) ([]byte, []byte, error) {
_len := len(plainText)
block, err := aes.NewCipher(cek) // Noncompliant {{(AuthenticatedEncryption) AES-GCM}}
if err != nil {
return nil, nil, err
}

aesGcm, err := cipher.NewGCMWithNonceSize(block, len(nonce))
if err != nil {
return nil, nil, err
}

cipherText := aesGcm.Seal(nil, nonce, plainText, aad)
return cipherText[:_len], cipherText[_len:], nil
}
41 changes: 41 additions & 0 deletions src/test/testdata/go/gocrypto/GoCryptoAESTestFile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)

func main() {
// Generate a random 32-byte key (AES-256)
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err)
}

// Create a new AES cipher block - this should be detected
block, err := aes.NewCipher(key) // Noncompliant {{(AuthenticatedEncryption) AES256-GCM}}
if err != nil {
panic(err)
}

// Create a GCM mode cipher
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err)
}

// Example plaintext
plaintext := []byte("Hello, World!")

// Generate a random nonce
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err)
}

// Encrypt
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
_ = ciphertext
}
14 changes: 14 additions & 0 deletions src/test/testdata/go/gocrypto/GoCryptoDESTestFile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

import (
"crypto/des"
)

func main() {
key := make([]byte, 8)
block, err := des.NewCipher(key) // Noncompliant {{(BlockCipher) DES64}}
if err != nil {
panic(err)
}
_ = block
}
Loading