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 rule based DL cases for typescript. #98

Closed
wants to merge 2 commits 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-code-injection@v1.0 defects=0}
import express, { Request, Response } from 'express';
import axios from 'axios';

const app = express();

function compliant(): void {
app.get("/add", function (req: Request, res: Response): void {
// Compliant: Trusted user input is being passed into dynamically executable code.
let calculated: number = eval("2 + 3");
Comment on lines +12 to +13
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the example doesn't apply to the user input.

res.send("Addition has been calculated");
});
}

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-code-injection@v1.0 defects=1}
import express, { Request, Response } from 'express';
const app = express();

function nonCompliant(): void {
app.get("/add/:num1/:num2", function (req: Request, res: Response): void {
// Noncompliant: Untrusted user input is being passed into dynamically executable code.
eval(req.params.num1 + "+" + req.params.num2);
res.send("Evaluated the result");
});
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-crypto-compliant-cipher@v1.0 defects=0}
import * as crypto from 'crypto';

function compliant(): void {
const key: Buffer = crypto.randomBytes(24);
const iv: Buffer = crypto.randomBytes(12);

// Compliant: Usage of `aes` with `gcm`, which is a secure cipher algorithm.
const cipher: crypto.CipherGCM = crypto.createCipheriv('aes-192-gcm', key, iv);

const plaintext: string = "Hello world";

const aad: Buffer = Buffer.from("additional authenticated data", "utf8");

cipher.setAAD(aad, {
plaintextLength: Buffer.byteLength(plaintext)
});

let ciphertext: string = cipher.update(plaintext, "utf8", "hex");
ciphertext += cipher.final("hex");

const tag: Buffer = cipher.getAuthTag();

console.log("Ciphertext:", ciphertext);
console.log("Auth Tag:", tag.toString("hex"));
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-crypto-compliant-cipher@v1.0 defects=1}
import * as crypto from 'crypto';

function nonCompliant(): void {
const key: Buffer = crypto.randomBytes(24);
const iv: Buffer = crypto.randomBytes(24);

// Noncompliant: Usage of `des`, which is not a secure cipher algorithm.
const cipher: crypto.Cipher = crypto.createCipheriv("DES", key, iv);

const plaintext: string = "Hello world";

const aad: Buffer = Buffer.from("00112233445566778899aabbccddeeff", "hex");

cipher.setAAD(aad, {
plaintextLength: Buffer.byteLength(plaintext)
});

let ciphertext: string = cipher.update(plaintext, "utf8", "hex");
ciphertext += cipher.final("hex");

const tag: Buffer = cipher.getAuthTag();

console.log("Ciphertext:", ciphertext);
console.log("Auth Tag:", tag.toString("hex"));
}

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-avoid-escaping-for-untrusted-user-input@v1.0 defects=0}
import csrf from 'csurf';
import cookieParser from 'cookie-parser';
import Handlebars from 'handlebars';
import express, { Request, Response } from 'express';
import fetch from 'node-fetch';

const app = express();

app.use(cookieParser());

const csrfProtection = csrf();
app.use(csrfProtection);

async function compliant(): Promise<string> {
try {
const response = await fetch("link");
const data = await response.json();
// Compliant: Escape the data for security.
return Handlebars.escapeExpression(data);
} catch (error) {
console.error("Error in compliant function:", error);
throw error;
}
}

app.get('/secure', async (req: Request, res: Response) => {
try {
const sanitizedData = await compliant();
res.json({ data: sanitizedData });
} catch (error) {
res.status(500).send("An error occurred while processing your request.");
}
});

const PORT: number = process.env.PORT ? parseInt(process.env.PORT) : 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-avoid-escaping-for-untrusted-user-input@v1.0 defects=1}
import csrf from 'csurf';
import cookieParser from 'cookie-parser';
import Handlebars from 'handlebars';
import express, { Request, Response } from 'express';
import fetch from 'node-fetch';

const app = express();

app.use(cookieParser());

const csrfProtection = csrf();
app.use(csrfProtection);

async function compliant(): Promise<Handlebars.SafeString> {
try {
const response = await fetch("link");
const data = await response.json();
// Noncompliant: Using `Handlebars.SafeString()` with untrusted user input without escaping can lead to XSS vulnerabilities.
return new Handlebars.SafeString(data);
} catch (error) {
console.error("Error in compliant function:", error);
throw error;
}
}

app.get('/secure', async (req: Request, res: Response) => {
try {
const data = await compliant();
res.json({ data });
} catch (error) {
res.status(500).send("An error occurred while processing your request.");
}
});

const PORT: number = process.env.PORT ? parseInt(process.env.PORT) : 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-construct-regular-expression-from-user-input@v1.0 defects=0}
import escapeStringRegexp from 'escape-string-regexp';
import fetch from 'node-fetch';

function complaint()
{
fetch("some link")
// Compliant: Creating RegExp from validated user input.
.then(res => res.json())
.then((data:string) => RegExp(escapeStringRegexp(data)))
.catch((error) => {
console.error("Error in function:", error);
});
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-construct-regular-expression-from-user-input@v1.0 defects=1}
import fetch from 'node-fetch';

async function nonCompliant(): Promise<void> {
try {
const response = await fetch("some link");
const data = await response.text();
// Noncompliant: Creating RegExp from unvalidated user input is unsafe.
const regex = RegExp(data);
} catch (error) {
console.error("Error:", error);
throw error;
}
}

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-forward-user-ip-address-using-http-proxy@v1.0 defects=0}
import { createProxyMiddleware } from 'http-proxy-middleware';
import express from 'express';

const app = express();

app.use(
createProxyMiddleware("/api", {
// Compliant: xfwd's defaults value is false.
target: 'http://localhost:8081/',
changeOrigin: true,
})
);
app.listen(3000);

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-do-not-forward-user-ip-address-using-http-proxy@v1.0 defects=1}
import express from 'express';
import { createProxyMiddleware, RequestHandler } from 'http-proxy-middleware';
import { Request, Response } from 'express';

const app = express();

const nonCompliant = (): void => {
const app = express();

const onProxyReq = (proxyRes: Request): void => {
console.log('req');
};

const onProxyRes = (proxyRes: Response): void => {
console.log('res');
};

const getProxy = (): RequestHandler => {
return createProxyMiddleware({
target: "API_SERVICE_URL",
changeOrigin: true,
onProxyReq,
onProxyRes,
// Noncompliant: Setting true for xfwd is insecure.
xfwd: true
});
};

const PORT: number = 5000;
const HOST: string = "http://127.0.0.1";

app.listen(PORT, () => {
console.log(`Starting Proxy at ${HOST}:${PORT}`);
});
};

// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-dynamo-db-batch-keys@v1.0 defects=0}
import * as AWS from 'aws-sdk';

const dynamodb = new AWS.DynamoDB();

function compliant(): void {
const params: AWS.DynamoDB.BatchGetItemInput = {
RequestItems: {
MyTable: {
Keys: [
{ id: { S: "123" } },
],
ProjectionExpression: "id, attributeName",
},
},
};

dynamodb.batchGetItem(params, (err: AWS.AWSError, data: AWS.DynamoDB.BatchGetItemOutput) => {
if (err) {
console.error("Error occurred:", err);
return;
}

// Compliant: Checks for `Unprocessed` keys.
if (data.UnprocessedKeys && Object.keys(data.UnprocessedKeys).length > 0) {
console.log("Do something, we still have unprocessed data:", data.UnprocessedKeys);
} else {
console.log("We are all done:", data.Responses);
}
});
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-dynamo-db-batch-keys@v1.0 defects=1}
import * as AWS from 'aws-sdk';

const dynamodb = new AWS.DynamoDB();

function compliant(): void {
const params: AWS.DynamoDB.BatchGetItemInput = {
RequestItems: {
MyTable: {
Keys: [
{ id: { S: "123" } },
],
ProjectionExpression: "id, attributeName",
},
},
};

dynamodb.batchGetItem(params, (err: AWS.AWSError, data: AWS.DynamoDB.BatchGetItemOutput) => {
if (err) {
console.error("Error occurred:", err);
return;
}

// Noncompliant: Missing check for unprocessed keys
console.log("Processed query:");
if (data.Responses) {
Object.entries(data.Responses).forEach(([tableName, items]) => {
console.log(`Table: ${tableName}`);
console.log("Items:", items);
});
} else {
console.log("No data found in the response.");
}
});
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-2.0

// {fact rule=typescript-express-bodyparser@v1.0 defects=0}
import express, { Application } from 'express';

const app: Application = express();

const configureApp = (): void => {
app.set("port", process.env.PORT || 3000);
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
// Compliant: BodyParser has not been used.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
};

configureApp();
// {/fact}
Loading