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

Report stack trace in iast #5055

Merged
merged 16 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from 13 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
5 changes: 4 additions & 1 deletion docs/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ tracer.init({
redactionEnabled: true,
redactionNamePattern: 'password',
redactionValuePattern: 'bearer',
telemetryVerbosity: 'OFF'
telemetryVerbosity: 'OFF',
stackTrace: {
enabled: true
}
}
});

Expand Down
12 changes: 11 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2233,7 +2233,17 @@ declare namespace tracer {
/**
* Specifies the verbosity of the sent telemetry. Default 'INFORMATION'
*/
telemetryVerbosity?: string
telemetryVerbosity?: string,

/**
* Configuration for stack trace reporting
*/
stackTrace?: {
/** Whether to enable stack trace reporting.
* @default true
*/
enabled?: boolean,
}
}

export namespace llmobs {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ class CookieAnalyzer extends Analyzer {
return super._checkOCE(context, value)
}

_getLocation (value) {
_getLocation (value, callSiteFrames) {
if (!value) {
return super._getLocation()
return super._getLocation(value, callSiteFrames)
}

if (value.location) {
return value.location
}
const location = super._getLocation(value)
const location = super._getLocation(value, callSiteFrames)
value.location = location
return location
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict'

const { storage } = require('../../../../../datadog-core')
const { getFirstNonDDPathAndLine } = require('../path-line')
const { addVulnerability } = require('../vulnerability-reporter')
const { getIastContext } = require('../iast-context')
const { getNonDDCallSiteFrames } = require('../path-line')
const { addVulnerability, canAddVulnerability, getVulnerabilityCallSiteFrames } = require('../vulnerability-reporter')
const { getIastContext, getIastStackTraceId } = require('../iast-context')
const overheadController = require('../overhead-controller')
const { SinkIastPlugin } = require('../iast-plugin')
const { getOriginalPathAndLineFromSourceMap } = require('../taint-tracking/rewriter')
Expand All @@ -28,12 +28,28 @@ class Analyzer extends SinkIastPlugin {
}

_reportEvidence (value, context, evidence) {
const location = this._getLocation(value)
const callSiteFrames = getVulnerabilityCallSiteFrames()
const nonDDCallSiteFrames = getNonDDCallSiteFrames(callSiteFrames, this._getExcludedPaths())

const location = this._getLocation(value, nonDDCallSiteFrames)

if (!this._isExcluded(location)) {
const locationSourceMap = this._replaceLocationFromSourceMap(location)
const originalLocation = this._getOriginalLocation(location)
const spanId = context && context.rootSpan && context.rootSpan.context().toSpanId()
const vulnerability = this._createVulnerability(this._type, evidence, spanId, locationSourceMap)
addVulnerability(context, vulnerability)
const stackId = getIastStackTraceId(context)
const vulnerability = this._createVulnerability(
this._type,
evidence,
spanId,
originalLocation,
stackId
)

if (canAddVulnerability(vulnerability)) {
const originalCallSiteList = nonDDCallSiteFrames.map(callsite => this._replaceCallsiteFromSourceMap(callsite))
iunanua marked this conversation as resolved.
Show resolved Hide resolved

addVulnerability(context, vulnerability, originalCallSiteList, stackId)
iunanua marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

Expand All @@ -49,24 +65,43 @@ class Analyzer extends SinkIastPlugin {
return { value }
}

_getLocation () {
return getFirstNonDDPathAndLine(this._getExcludedPaths())
_getLocation (value, callSiteFrames) {
return callSiteFrames[0]
}

_getOriginalLocation (location) {
const locationFromSourceMap = this._replaceCallsiteFromSourceMap(location)
iunanua marked this conversation as resolved.
Show resolved Hide resolved
const originalLocation = {}

if (locationFromSourceMap?.path) {
originalLocation.path = locationFromSourceMap.path
}
if (locationFromSourceMap?.line) {
originalLocation.line = locationFromSourceMap.line
}
if (locationFromSourceMap?.column) {
originalLocation.column = locationFromSourceMap.column
}

return originalLocation
}

_replaceLocationFromSourceMap (location) {
if (location) {
const { path, line, column } = getOriginalPathAndLineFromSourceMap(location)
_replaceCallsiteFromSourceMap (callsite) {
iunanua marked this conversation as resolved.
Show resolved Hide resolved
if (callsite) {
const { path, line, column } = getOriginalPathAndLineFromSourceMap(callsite)
if (path) {
location.path = path
callsite.file = path
callsite.path = path
}
if (line) {
location.line = line
callsite.line = line
}
if (column) {
location.column = column
callsite.column = column
}
}
return location

return callsite
}

_getExcludedPaths () {}
Expand Down Expand Up @@ -102,12 +137,13 @@ class Analyzer extends SinkIastPlugin {
return overheadController.hasQuota(overheadController.OPERATIONS.REPORT_VULNERABILITY, context)
}

_createVulnerability (type, evidence, spanId, location) {
_createVulnerability (type, evidence, spanId, location, stackId) {
if (type && evidence) {
const _spanId = spanId || 0
return {
type,
evidence,
stackId,
location: {
spanId: _spanId,
...location
Expand Down
12 changes: 12 additions & 0 deletions packages/dd-trace/src/appsec/iast/iast-context.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ function getIastContext (store, topContext) {
return iastContext
}

function getIastStackTraceId (iastContext) {
if (!iastContext) return 0

if (!iastContext.stackTraceId) {
iastContext.stackTraceId = 0
}

iastContext.stackTraceId += 1
iunanua marked this conversation as resolved.
Show resolved Hide resolved
return iastContext.stackTraceId
}

/* TODO Fix storage problem when the close event is called without
finish event to remove `topContext` references
We have to save the context in two places, because
Expand Down Expand Up @@ -51,6 +62,7 @@ module.exports = {
getIastContext,
saveIastContext,
cleanIastContext,
getIastStackTraceId,
IAST_CONTEXT_KEY,
IAST_TRANSACTION_ID
}
42 changes: 19 additions & 23 deletions packages/dd-trace/src/appsec/iast/path-line.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
const path = require('path')
const process = require('process')
const { calculateDDBasePath } = require('../../util')
const { getCallSiteList } = require('../stack_trace')
const pathLine = {
getFirstNonDDPathAndLine,
getNodeModulesPaths,
getRelativePath,
getFirstNonDDPathAndLineFromCallsites, // Exported only for test purposes
getNonDDCallSiteFrames,
calculateDDBasePath, // Exported only for test purposes
ddBasePath: calculateDDBasePath(__dirname) // Only for test purposes
}
Expand All @@ -25,31 +23,33 @@ const EXCLUDED_PATH_PREFIXES = [
'async_hooks'
]

function getFirstNonDDPathAndLineFromCallsites (callsites, externallyExcludedPaths) {
if (callsites) {
for (let i = 0; i < callsites.length; i++) {
const callsite = callsites[i]
const filepath = callsite.getFileName()
if (!isExcluded(callsite, externallyExcludedPaths) && filepath.indexOf(pathLine.ddBasePath) === -1) {
return {
path: getRelativePath(filepath),
line: callsite.getLineNumber(),
column: callsite.getColumnNumber(),
isInternal: !path.isAbsolute(filepath)
}
}
function getNonDDCallSiteFrames (callSiteFrames, externallyExcludedPaths) {
if (!callSiteFrames) {
return []
}

const result = []

for (const callsite of callSiteFrames) {
const filepath = callsite.file
if (!isExcluded(callsite, externallyExcludedPaths) && filepath.indexOf(pathLine.ddBasePath) === -1) {
callsite.path = getRelativePath(filepath)
callsite.isInternal = !path.isAbsolute(filepath)

result.push(callsite)
}
}
return null

return result
}

function getRelativePath (filepath) {
return path.relative(process.cwd(), filepath)
}

function isExcluded (callsite, externallyExcludedPaths) {
if (callsite.isNative()) return true
const filename = callsite.getFileName()
if (callsite.isNative) return true
const filename = callsite.file
if (!filename) {
return true
}
Expand All @@ -73,10 +73,6 @@ function isExcluded (callsite, externallyExcludedPaths) {
return false
}

function getFirstNonDDPathAndLine (externallyExcludedPaths) {
return getFirstNonDDPathAndLineFromCallsites(getCallSiteList(), externallyExcludedPaths)
}

function getNodeModulesPaths (...paths) {
const nodeModulesPaths = []

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ class VulnerabilityFormatter {
const formattedVulnerability = {
type: vulnerability.type,
hash: vulnerability.hash,
stackId: vulnerability.stackId,
evidence: this.formatEvidence(vulnerability.type, vulnerability.evidence, sourcesIndexes, sources),
location: {
spanId: vulnerability.location.spanId
Expand Down
79 changes: 55 additions & 24 deletions packages/dd-trace/src/appsec/iast/vulnerability-reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const { IAST_ENABLED_TAG_KEY, IAST_JSON_TAG_KEY } = require('./tags')
const standalone = require('../standalone')
const { SAMPLING_MECHANISM_APPSEC } = require('../../constants')
const { keepTrace } = require('../../priority_sampler')
const { reportStackTrace, getCallsiteFrames, STACK_TRACE_NAMESPACES } = require('../stack_trace')

const VULNERABILITIES_KEY = 'vulnerabilities'
const VULNERABILITY_HASHES_MAX_SIZE = 1000
Expand All @@ -15,39 +16,59 @@ const RESET_VULNERABILITY_CACHE_INTERVAL = 60 * 60 * 1000 // 1 hour
let tracer
let resetVulnerabilityCacheTimer
let deduplicationEnabled = true
let stackTraceEnabled = true
let stackTraceMaxDepth
let maxStackTraces

function addVulnerability (iastContext, vulnerability) {
if (vulnerability?.evidence && vulnerability?.type && vulnerability?.location) {
if (deduplicationEnabled && isDuplicatedVulnerability(vulnerability)) return
function canAddVulnerability (vulnerability) {
const hasRequiredFields = vulnerability?.evidence && vulnerability?.type && vulnerability?.location
if (!hasRequiredFields) return false

VULNERABILITY_HASHES.set(`${vulnerability.type}${vulnerability.hash}`, true)
const isDuplicated = deduplicationEnabled && isDuplicatedVulnerability(vulnerability)

let span = iastContext?.rootSpan
return !isDuplicated
}

if (!span && tracer) {
span = tracer.startSpan('vulnerability', {
type: 'vulnerability'
})
function addVulnerability (iastContext, vulnerability, callSiteFrames, stackId) {
if (!canAddVulnerability(vulnerability)) return

vulnerability.location.spanId = span.context().toSpanId()
VULNERABILITY_HASHES.set(`${vulnerability.type}${vulnerability.hash}`, true)

span.addTags({
[IAST_ENABLED_TAG_KEY]: 1
})
}
let span = iastContext?.rootSpan

if (!span) return
if (!span && tracer) {
span = tracer.startSpan('vulnerability', {
type: 'vulnerability'
})

keepTrace(span, SAMPLING_MECHANISM_APPSEC)
standalone.sample(span)
vulnerability.location.spanId = span.context().toSpanId()

if (iastContext?.rootSpan) {
iastContext[VULNERABILITIES_KEY] = iastContext[VULNERABILITIES_KEY] || []
iastContext[VULNERABILITIES_KEY].push(vulnerability)
} else {
sendVulnerabilities([vulnerability], span)
span.finish()
}
span.addTags({
[IAST_ENABLED_TAG_KEY]: 1
})
}

if (!span) return

keepTrace(span, SAMPLING_MECHANISM_APPSEC)
standalone.sample(span)

if (stackTraceEnabled) {
reportStackTrace(
iastContext?.rootSpan,
iunanua marked this conversation as resolved.
Show resolved Hide resolved
stackId,
maxStackTraces,
callSiteFrames,
STACK_TRACE_NAMESPACES.IAST
)
}

if (iastContext?.rootSpan) {
iastContext[VULNERABILITIES_KEY] = iastContext[VULNERABILITIES_KEY] || []
iastContext[VULNERABILITIES_KEY].push(vulnerability)
} else {
sendVulnerabilities([vulnerability], span)
span.finish()
}
}

Expand Down Expand Up @@ -94,8 +115,16 @@ function isDuplicatedVulnerability (vulnerability) {
return VULNERABILITY_HASHES.get(`${vulnerability.type}${vulnerability.hash}`)
}

function getVulnerabilityCallSiteFrames () {
return getCallsiteFrames(stackTraceMaxDepth)
}

function start (config, _tracer) {
deduplicationEnabled = config.iast.deduplicationEnabled
stackTraceEnabled = config.iast.stackTrace.enabled
stackTraceMaxDepth = config.appsec.stackTrace.maxDepth
maxStackTraces = config.appsec.stackTrace.maxStackTraces
IlyasShabi marked this conversation as resolved.
Show resolved Hide resolved

vulnerabilitiesFormatter.setRedactVulnerabilities(
config.iast.redactionEnabled,
config.iast.redactionNamePattern,
Expand All @@ -113,7 +142,9 @@ function stop () {

module.exports = {
addVulnerability,
canAddVulnerability,
sendVulnerabilities,
getVulnerabilityCallSiteFrames,
clearCache,
start,
stop
Expand Down
Loading
Loading