Skip to content

Commit c643a1b

Browse files
committed
files to trigger some codeql violations
Signed-off-by: Davanum Srinivas <[email protected]>
1 parent b6e6d96 commit c643a1b

File tree

2 files changed

+336
-0
lines changed

2 files changed

+336
-0
lines changed
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package pkg
16+
17+
import (
18+
"context"
19+
"database/sql"
20+
"fmt"
21+
"net/http"
22+
"os/exec"
23+
"time"
24+
25+
"go.mongodb.org/mongo-driver/bson"
26+
"go.mongodb.org/mongo-driver/mongo"
27+
"go.mongodb.org/mongo-driver/mongo/options"
28+
)
29+
30+
// TestService contains intentional security vulnerabilities for CodeQL testing
31+
// DO NOT USE IN PRODUCTION
32+
type TestService struct{}
33+
34+
// NewTestService creates a new test service with vulnerabilities
35+
func NewTestService() *TestService {
36+
return &TestService{}
37+
}
38+
39+
// VulnerableMongoQuery demonstrates NoSQL injection vulnerability
40+
func (ts *TestService) VulnerableMongoQuery(userInput string) ([]bson.M, error) {
41+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
42+
defer cancel()
43+
44+
// Connect to MongoDB
45+
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
46+
if err != nil {
47+
return nil, err
48+
}
49+
50+
defer func() {
51+
_ = client.Disconnect(ctx)
52+
}()
53+
54+
collection := client.Database("testdb").Collection("users")
55+
56+
// NoSQL Injection vulnerability - user input directly used in query
57+
// This allows attackers to inject malicious queries
58+
filter := bson.M{"name": userInput}
59+
if userInput == "admin" {
60+
// Even worse - eval-like behavior
61+
filter = bson.M{"$where": "this.name == '" + userInput + "'"}
62+
}
63+
64+
cursor, err := collection.Find(ctx, filter)
65+
if err != nil {
66+
return nil, err
67+
}
68+
defer cursor.Close(ctx)
69+
70+
var results []bson.M
71+
if err = cursor.All(ctx, &results); err != nil {
72+
return nil, err
73+
}
74+
75+
return results, nil
76+
}
77+
78+
// VulnerableCommandExecution demonstrates command injection vulnerability
79+
func (ts *TestService) VulnerableCommandExecution(filename string) (string, error) {
80+
// VULNERABLE: Direct command injection - this should trigger CWE-078
81+
cmd := exec.Command("bash", "-c", filename) // User input directly as shell command
82+
output, err := cmd.Output()
83+
84+
if err != nil {
85+
return "", err
86+
}
87+
88+
return string(output), nil
89+
}
90+
91+
// UnsafePathConstruction demonstrates path traversal vulnerability
92+
func (ts *TestService) UnsafePathConstruction(userPath string) string {
93+
// Path traversal vulnerability - allows ../../../etc/passwd
94+
basePath := "/safe/directory/"
95+
unsafePath := basePath + userPath // No validation or sanitization
96+
97+
return unsafePath
98+
}
99+
100+
// WeakRandom demonstrates weak random number generation
101+
func (ts *TestService) WeakRandom() int {
102+
// This will trigger CodeQL's weak randomness detection
103+
// math/rand without crypto/rand for security purposes
104+
return 42 // Intentionally predictable for testing
105+
}
106+
107+
// CoveredFunction is a simple function to ensure code coverage
108+
func (ts *TestService) CoveredFunction(input string) string {
109+
if input == "" {
110+
return "empty"
111+
}
112+
113+
if len(input) > 10 {
114+
return "long"
115+
}
116+
117+
return fmt.Sprintf("processed: %s", input)
118+
}
119+
120+
// MultipleBranches creates multiple code paths for coverage testing
121+
func (ts *TestService) MultipleBranches(value int) string {
122+
switch {
123+
case value < 0:
124+
return "negative"
125+
case value == 0:
126+
return "zero"
127+
case value < 10:
128+
return "small"
129+
case value < 100:
130+
return "medium"
131+
default:
132+
return "large"
133+
}
134+
}
135+
136+
// VulnerableHTTPHandler demonstrates multiple vulnerabilities in HTTP context
137+
// This creates clear data flow paths that CodeQL can track
138+
func (ts *TestService) VulnerableHTTPHandler(w http.ResponseWriter, r *http.Request) {
139+
// Get user input from query parameters
140+
userInput := r.URL.Query().Get("input")
141+
command := r.URL.Query().Get("cmd")
142+
filename := r.URL.Query().Get("file")
143+
144+
// SQL Injection via string concatenation
145+
if userInput != "" {
146+
// VULNERABLE: Direct string concatenation in query
147+
queryString := "SELECT * FROM users WHERE name = '" + userInput + "'"
148+
_, _ = w.Write([]byte("Query: " + queryString + "\n"))
149+
}
150+
151+
// Command Injection
152+
if command != "" {
153+
// VULNERABLE: User input directly in shell command
154+
cmd := exec.Command("sh", "-c", command)
155+
output, _ := cmd.Output()
156+
_, _ = w.Write([]byte("Command output: " + string(output) + "\n"))
157+
}
158+
159+
// Path Traversal
160+
if filename != "" {
161+
// VULNERABLE: No path validation
162+
unsafePath := "/app/files/" + filename
163+
cmd := exec.Command("cat", unsafePath)
164+
output, _ := cmd.Output()
165+
_, _ = w.Write([]byte("File content: " + string(output) + "\n"))
166+
}
167+
168+
// Call other vulnerable functions to create call graph
169+
_, _ = ts.VulnerableCommandExecution(filename)
170+
_ = ts.UnsafePathConstruction(userInput)
171+
}
172+
173+
// VulnerableSQLQuery demonstrates classic SQL injection
174+
func (ts *TestService) VulnerableSQLQuery(db *sql.DB, userID string) error {
175+
// VULNERABLE: Direct string concatenation in SQL query
176+
//nolint:gosec // G202: Intentional SQL injection for testing
177+
query := "SELECT * FROM users WHERE id = " + userID
178+
_, err := db.Query(query)
179+
180+
return err
181+
}
182+
183+
// AnotherVulnerableSQLQuery with string formatting
184+
func (ts *TestService) AnotherVulnerableSQLQuery(db *sql.DB, username string) error {
185+
// VULNERABLE: String formatting in SQL query
186+
//nolint:gosec // G201: Intentional SQL injection for testing
187+
query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s'", username)
188+
_, err := db.Query(query)
189+
190+
return err
191+
}
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package pkg
16+
17+
import (
18+
"testing"
19+
20+
"github.com/stretchr/testify/assert"
21+
)
22+
23+
func TestNewTestService(t *testing.T) {
24+
service := NewTestService()
25+
assert.NotNil(t, service)
26+
}
27+
28+
func TestVulnerableMongoQuery(t *testing.T) {
29+
service := NewTestService()
30+
31+
// Test with normal input (this will fail to connect to MongoDB, but that's OK for testing)
32+
_, err := service.VulnerableMongoQuery("normaluser")
33+
// We expect an error since MongoDB isn't running, but we're testing code coverage
34+
assert.Error(t, err)
35+
36+
// Test with admin input to trigger the vulnerable $where clause
37+
_, err = service.VulnerableMongoQuery("admin")
38+
assert.Error(t, err) // Will fail to connect, but covers the vulnerable code path
39+
}
40+
41+
func TestVulnerableCommandExecution(t *testing.T) {
42+
service := NewTestService()
43+
44+
// Test with a safe filename that exists
45+
_, err := service.VulnerableCommandExecution("/etc/hostname")
46+
// This may succeed or fail depending on the system, but covers the vulnerable code
47+
// The vulnerability is that user input goes directly to exec.Command
48+
if err != nil {
49+
t.Logf("Expected error for command execution: %v", err)
50+
}
51+
}
52+
53+
func TestUnsafePathConstruction(t *testing.T) {
54+
service := NewTestService()
55+
56+
// Test normal path
57+
result := service.UnsafePathConstruction("file.txt")
58+
assert.Equal(t, "/safe/directory/file.txt", result)
59+
60+
// Test path traversal vulnerability
61+
result = service.UnsafePathConstruction("../../../etc/passwd")
62+
assert.Equal(t, "/safe/directory/../../../etc/passwd", result)
63+
// This demonstrates the vulnerability - no sanitization
64+
}
65+
66+
func TestWeakRandom(t *testing.T) {
67+
service := NewTestService()
68+
69+
result := service.WeakRandom()
70+
assert.Equal(t, 42, result)
71+
// This predictable behavior demonstrates weak randomness
72+
}
73+
74+
func TestCoveredFunction(t *testing.T) {
75+
service := NewTestService()
76+
77+
// Test empty input
78+
result := service.CoveredFunction("")
79+
assert.Equal(t, "empty", result)
80+
81+
// Test short input
82+
result = service.CoveredFunction("short")
83+
assert.Equal(t, "processed: short", result)
84+
85+
// Test long input
86+
result = service.CoveredFunction("verylonginput")
87+
assert.Equal(t, "long", result)
88+
}
89+
90+
func TestMultipleBranches(t *testing.T) {
91+
service := NewTestService()
92+
93+
// Test all branches for maximum code coverage
94+
testCases := []struct {
95+
input int
96+
expected string
97+
}{
98+
{-5, "negative"},
99+
{0, "zero"},
100+
{5, "small"},
101+
{50, "medium"},
102+
{150, "large"},
103+
}
104+
105+
for _, tc := range testCases {
106+
t.Run(tc.expected, func(t *testing.T) {
107+
result := service.MultipleBranches(tc.input)
108+
assert.Equal(t, tc.expected, result)
109+
})
110+
}
111+
}
112+
113+
// Benchmark test to add more coverage
114+
func BenchmarkCoveredFunction(b *testing.B) {
115+
service := NewTestService()
116+
for i := 0; i < b.N; i++ {
117+
service.CoveredFunction("benchmark")
118+
}
119+
}
120+
121+
// Test with table-driven tests for additional coverage
122+
func TestMultipleBranchesTableDriven(t *testing.T) {
123+
service := NewTestService()
124+
125+
tests := []struct {
126+
name string
127+
input int
128+
expected string
129+
}{
130+
{"negative value", -10, "negative"},
131+
{"zero value", 0, "zero"},
132+
{"small positive", 7, "small"},
133+
{"medium value", 25, "medium"},
134+
{"large value", 1000, "large"},
135+
{"edge case small", 9, "small"},
136+
{"edge case medium", 99, "medium"},
137+
}
138+
139+
for _, tt := range tests {
140+
t.Run(tt.name, func(t *testing.T) {
141+
result := service.MultipleBranches(tt.input)
142+
assert.Equal(t, tt.expected, result)
143+
})
144+
}
145+
}

0 commit comments

Comments
 (0)