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
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,6 @@
import com.ibm.engine.rule.DetectionRule;
import com.ibm.engine.rule.MethodDetectionRule;
import com.ibm.engine.rule.Parameter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.go.symbols.Symbol;
import org.sonar.go.symbols.Usage;
import org.sonar.go.symbols.Usage.UsageType;
Expand All @@ -58,6 +52,13 @@
import org.sonar.plugins.go.api.VariableDeclarationTree;
import org.sonar.plugins.go.api.checks.GoCheck;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
* Detection engine implementation for Go. Handles detection of cryptographic patterns in Go AST.
*/
Expand Down Expand Up @@ -310,33 +311,14 @@ private <O> List<ResolvedValue<O, Tree>> resolveValues(
resolveValues(clazz, valueTree, valueFactory, selections));
}
}
// PARAMETER and REFERENCE types are handled by outer scope resolution
// REFERENCE and PARAMETER are resolved outside
}

if (!result.isEmpty()) {
return result;
}
}
}

// Fallback: try to resolve the identifier name as a constant, but only if the
// identifier is not a function parameter (parameters don't have resolvable values
// without a concrete call site).
boolean isParameter =
symbol != null
&& symbol.getUsages() != null
&& symbol.getUsages().stream()
.anyMatch(u -> u.type() == UsageType.PARAMETER);
if (!isParameter) {
String name = identifierTree.name();
if (name != null && !name.isEmpty()) {
Optional<O> value = resolveConstant(clazz, name);
if (value.isPresent()) {
return List.of(new ResolvedValue<>(value.get(), tree));
}
}
}
return Collections.emptyList();
}

// Handle MemberSelectTree - pkg.member or receiver.method patterns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,47 @@ private GoCryptoCipherModes() {
.inBundle(() -> "GoCrypto")
.withoutDependingDetectionRules();

// cipher.NewGCMWithNonceSize(cipher cipher.Block, size int) (cipher.AEAD, error)
// Returns a new GCM mode wrapper with a custom nonce size
public static final IDetectionRule<Tree> NEW_GCM_WITH_NONCE_SIZE =
new DetectionRuleBuilder<Tree>()
.createDetectionRule()
.forObjectTypes("crypto/cipher")
.forMethods("NewGCMWithNonceSize")
.shouldBeDetectedAs(new ValueActionFactory<>("GCM"))
.withMethodParameter("cipher.Block")
.withMethodParameter("int")
.buildForContext(new CipherContext())
.inBundle(() -> "GoCrypto")
.withoutDependingDetectionRules();

// cipher.NewGCMWithRandomNonce(cipher cipher.Block) (cipher.AEAD, error)
// Returns a new GCM mode wrapper that generates random nonces (Go 1.25+)
public static final IDetectionRule<Tree> NEW_GCM_WITH_RANDOM_NONCE =
new DetectionRuleBuilder<Tree>()
.createDetectionRule()
.forObjectTypes("crypto/cipher")
.forMethods("NewGCMWithRandomNonce")
.shouldBeDetectedAs(new ValueActionFactory<>("GCM"))
.withMethodParameter("cipher.Block")
.buildForContext(new CipherContext())
.inBundle(() -> "GoCrypto")
.withoutDependingDetectionRules();

// cipher.NewGCMWithTagSize(cipher cipher.Block, tagSize int) (cipher.AEAD, error)
// Returns a new GCM mode wrapper with a custom tag size
public static final IDetectionRule<Tree> NEW_GCM_WITH_TAG_SIZE =
new DetectionRuleBuilder<Tree>()
.createDetectionRule()
.forObjectTypes("crypto/cipher")
.forMethods("NewGCMWithTagSize")
.shouldBeDetectedAs(new ValueActionFactory<>("GCM"))
.withMethodParameter("cipher.Block")
.withMethodParameter("int")
.buildForContext(new CipherContext())
.inBundle(() -> "GoCrypto")
.withoutDependingDetectionRules();

// cipher.NewCBCEncrypter(block cipher.Block, iv []byte) cipher.BlockMode
// Returns a BlockMode which encrypts in cipher block chaining mode
public static final IDetectionRule<Tree> NEW_CBC_ENCRYPTER =
Expand Down Expand Up @@ -134,6 +175,9 @@ private GoCryptoCipherModes() {
public static List<IDetectionRule<Tree>> rules() {
return List.of(
NEW_GCM,
NEW_GCM_WITH_NONCE_SIZE,
NEW_GCM_WITH_RANDOM_NONCE,
NEW_GCM_WITH_TAG_SIZE,
NEW_CBC_ENCRYPTER,
NEW_CBC_DECRYPTER,
NEW_CFB_ENCRYPTER,
Expand Down
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
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Sonar Cryptography Plugin
* Copyright (C) 2024 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
*
* 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 com.ibm.plugin.rules.detection.gocrypto;

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

import com.ibm.engine.detection.DetectionStore;
import com.ibm.engine.language.go.GoScanContext;
import com.ibm.engine.model.IValue;
import com.ibm.engine.model.KeySize;
import com.ibm.engine.model.ValueAction;
import com.ibm.engine.model.context.CipherContext;
import com.ibm.mapper.model.AuthenticatedEncryption;
import com.ibm.mapper.model.BlockSize;
import com.ibm.mapper.model.INode;
import com.ibm.mapper.model.Mode;
import com.ibm.mapper.model.Oid;
import com.ibm.plugin.TestBase;
import java.util.List;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.Test;
import org.sonar.go.symbols.Symbol;
import org.sonar.go.testing.GoVerifier;
import org.sonar.plugins.go.api.Tree;
import org.sonar.plugins.go.api.checks.GoCheck;

class GoCryptoAESGCMWithNonceSizeTest extends TestBase {

public GoCryptoAESGCMWithNonceSizeTest() {
super(GoCryptoAES.rules());
}

@Test
void test() {
GoVerifier.verify("rules/detection/gocrypto/GoCryptoAESGCMWithNonceSizeTestFile.go", this);
}

@Override
public void asserts(
int findingId,
@Nonnull DetectionStore<GoCheck, Tree, Symbol, GoScanContext> detectionStore,
@Nonnull List<INode> nodes) {

/*
* Detection Store
*/
assertThat(detectionStore).isNotNull();
assertThat(detectionStore.getDetectionValues()).hasSize(1);
assertThat(detectionStore.getDetectionValueContext()).isInstanceOf(CipherContext.class);
IValue<Tree> value0 = detectionStore.getDetectionValues().get(0);
assertThat(value0).isInstanceOf(ValueAction.class);
assertThat(value0.asString()).isEqualTo("AES");

DetectionStore<GoCheck, Tree, Symbol, GoScanContext> store1 =
getStoreOfValueType(ValueAction.class, detectionStore.getChildren());
assertThat(store1).isNotNull();
assertThat(store1.getDetectionValues()).hasSize(1);
assertThat(store1.getDetectionValueContext()).isInstanceOf(CipherContext.class);
IValue<Tree> value01 = store1.getDetectionValues().get(0);
assertThat(value01).isInstanceOf(ValueAction.class);
assertThat(value01.asString()).isEqualTo("GCM");

// Key size should not be resolved since 'cek' is a function parameter
DetectionStore<GoCheck, Tree, Symbol, GoScanContext> store2 =
getStoreOfValueType(KeySize.class, detectionStore.getChildren());
assertThat(store2).isNull();

/*
* Translation
*/
assertThat(nodes).hasSize(1);

// AuthenticatedEncryption
INode authenticatedEncryptionNode = nodes.get(0);
assertThat(authenticatedEncryptionNode.getKind()).isEqualTo(AuthenticatedEncryption.class);
assertThat(authenticatedEncryptionNode.getChildren()).hasSize(3);
assertThat(authenticatedEncryptionNode.asString()).isEqualTo("AES-GCM");

// BlockSize under AuthenticatedEncryption
INode blockSizeNode = authenticatedEncryptionNode.getChildren().get(BlockSize.class);
assertThat(blockSizeNode).isNotNull();
assertThat(blockSizeNode.asString()).isEqualTo("128");

// Oid under AuthenticatedEncryption
INode oidNode = authenticatedEncryptionNode.getChildren().get(Oid.class);
assertThat(oidNode).isNotNull();
assertThat(oidNode.asString()).isEqualTo("2.16.840.1.101.3.4.1");

// Mode under AuthenticatedEncryption
INode modeNode = authenticatedEncryptionNode.getChildren().get(Mode.class);
assertThat(modeNode).isNotNull();
assertThat(modeNode.asString()).isEqualTo("GCM");
}
}