repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_data_asset_rule.go
pkg/risks/builtin/unnecessary_data_asset_rule.go
package builtin import ( "sort" "github.com/threagile/threagile/pkg/types" ) type UnnecessaryDataAssetRule struct{} func NewUnnecessaryDataAssetRule() *UnnecessaryDataAssetRule { return &UnnecessaryDataAssetRule{} } func (*UnnecessaryDataAssetRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unnecessary-data-asset", Title: "Unnecessary Data Asset", Description: "When a data asset is not processed by any data assets and also not transferred by any " + "communication links, this is an indicator for an unnecessary data asset (or for an incomplete model).", Impact: "If this risk is unmitigated, attackers might be able to access unnecessary data assets using " + "other vulnerabilities.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Attack Surface Reduction", Mitigation: "Try to avoid having data assets that are not required/used.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "Modelled data assets not processed by any data assets and also not transferred by any " + "communication links.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*UnnecessaryDataAssetRule) SupportedTags() []string { return []string{} } func (r *UnnecessaryDataAssetRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) // first create them in memory - otherwise in Go ranging over map is random order // range over them in sorted (hence re-producible) way: unusedDataAssetIDs := make(map[string]bool) for k := range input.DataAssets { unusedDataAssetIDs[k] = true } for _, technicalAsset := range input.TechnicalAssets { for _, processedDataAssetID := range technicalAsset.DataAssetsProcessed { delete(unusedDataAssetIDs, processedDataAssetID) } for _, storedDataAssetID := range technicalAsset.DataAssetsStored { delete(unusedDataAssetIDs, storedDataAssetID) } for _, commLink := range technicalAsset.CommunicationLinks { for _, sentDataAssetID := range commLink.DataAssetsSent { delete(unusedDataAssetIDs, sentDataAssetID) } for _, receivedDataAssetID := range commLink.DataAssetsReceived { delete(unusedDataAssetIDs, receivedDataAssetID) } } } var keys []string for k := range unusedDataAssetIDs { keys = append(keys, k) } sort.Strings(keys) for _, unusedDataAssetID := range keys { risks = append(risks, r.createRisk(input, unusedDataAssetID)) } return risks, nil } func (r *UnnecessaryDataAssetRule) createRisk(input *types.Model, unusedDataAssetID string) *types.Risk { unusedDataAsset := input.DataAssets[unusedDataAssetID] title := "<b>Unnecessary Data Asset</b> named <b>" + unusedDataAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantDataAssetId: unusedDataAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + unusedDataAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_data_asset_rule_test.go
pkg/risks/builtin/unnecessary_data_asset_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnnecessaryDataAssetRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataAssetRuleGenerateRisksDataAssetRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unnecessary Data Asset</b> named <b>data</b>", risks[0].Title) } func TestUnnecessaryDataAssetRuleGenerateRisksDataAssetStoredNoRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", DataAssetsStored: []string{"data"}, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataAssetRuleGenerateRisksDataAssetProcessedNoRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", DataAssetsProcessed: []string{"data"}, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataAssetRuleGenerateRisksDataAssetSentNoRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", DataAssetsSent: []string{"data"}, DataAssetsReceived: []string{}, }, }, }, "ta2": { Id: "ta2", }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataAssetRuleGenerateRisksDataAssetReceivedNoRisksCreated(t *testing.T) { rule := NewUnnecessaryDataAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", DataAssetsSent: []string{}, DataAssetsReceived: []string{"data"}, }, }, }, "ta2": { Id: "ta2", }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_hardening_rule.go
pkg/risks/builtin/missing_hardening_rule.go
package builtin import ( "strconv" "github.com/threagile/threagile/pkg/types" ) type MissingHardeningRule struct { raaLimit int raaLimitReduced int } func NewMissingHardeningRule() *MissingHardeningRule { return &MissingHardeningRule{raaLimit: 55, raaLimitReduced: 40} } func (r *MissingHardeningRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-hardening", Title: "Missing Hardening", Description: "Technical assets with a Relative Attacker Attractiveness (RAA) value of " + strconv.Itoa(r.raaLimit) + " % or higher should be " + "explicitly hardened taking best practices and vendor hardening guides into account.", Impact: "If this risk remains unmitigated, attackers might be able to easier attack high-value targets.", ASVS: "V14 - Configuration Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "System Hardening", Mitigation: "Try to apply all hardening best practices (like CIS benchmarks, OWASP recommendations, vendor " + "recommendations, DevSec Hardening Framework, DBSAT for Oracle databases, and others).", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.Tampering, DetectionLogic: "In-scope technical assets with RAA values of " + strconv.Itoa(r.raaLimit) + " % or higher. " + "Generally for high-value targets like data stores, application servers, identity providers and ERP systems this limit is reduced to " + strconv.Itoa(r.raaLimitReduced) + " %", RiskAssessment: "The risk rating depends on the sensitivity of the data processed in the technical asset.", FalsePositives: "Usually no false positives.", ModelFailurePossibleReason: false, CWE: 16, } } func (*MissingHardeningRule) SupportedTags() []string { return []string{"tomcat"} } func (r *MissingHardeningRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } if technicalAsset.RAA >= float64(r.raaLimit) || (technicalAsset.RAA >= float64(r.raaLimitReduced) && (technicalAsset.Type == types.Datastore || technicalAsset.Technologies.GetAttribute(types.IsHighValueTarget))) { risks = append(risks, r.createRisk(input, technicalAsset)) } } return risks, nil } func (r *MissingHardeningRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return technicalAsset.OutOfScope } func (r *MissingHardeningRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Missing Hardening</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.LowImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Likely, impact), ExploitationLikelihood: types.Likely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_file_validation_rule.go
pkg/risks/builtin/missing_file_validation_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingFileValidationRule struct{} func NewMissingFileValidationRule() *MissingFileValidationRule { return &MissingFileValidationRule{} } func (*MissingFileValidationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-file-validation", Title: "Missing File Validation", Description: "When a technical asset accepts files, these input files should be strictly validated about filename and type.", Impact: "If this risk is unmitigated, attackers might be able to provide malicious files to the application.", ASVS: "V12 - File and Resources Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html", Action: "File Validation", Mitigation: "Filter by file extension and discard (if feasible) the name provided. Whitelist the accepted file types " + "and determine the mime-type on the server-side (for example via \"Apache Tika\" or similar checks). If the file is retrievable by " + "end users and/or backoffice employees, consider performing scans for popular malware (if the files can be retrieved much later than they " + "were uploaded, also apply a fresh malware scan during retrieval to scan with newer signatures of popular malware). Also enforce " + "limits on maximum file size to avoid denial-of-service like scenarios.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Spoofing, DetectionLogic: "In-scope technical assets with custom-developed code accepting file data formats.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Fully trusted (i.e. cryptographically signed or similar) files can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 434, } } func (*MissingFileValidationRule) SupportedTags() []string { return []string{} } func (r *MissingFileValidationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } for _, format := range technicalAsset.DataFormatsAccepted { if format == types.File { risks = append(risks, r.createRisk(input, technicalAsset)) } } } return risks, nil } func (r *MissingFileValidationRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return technicalAsset.OutOfScope || !technicalAsset.CustomDevelopedParts } func (r *MissingFileValidationRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Missing File Validation</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.LowImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || input.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.VeryLikely, impact), ExploitationLikelihood: types.VeryLikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/xml_external_entity_rule_test.go
pkg/risks/builtin/xml_external_entity_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestXmlExternalEntityRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewXmlExternalEntityRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type XmlExternalEntityRuleTest struct { outOfScope bool acceptedFormat types.DataFormat confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality riskCreated bool expImpact types.RiskExploitationImpact } func TestXmlExternalEntityRuleSendDataAssetRisksCreated(t *testing.T) { testCases := map[string]XmlExternalEntityRuleTest{ "out of scope": { outOfScope: true, riskCreated: false, }, "json": { acceptedFormat: types.JSON, riskCreated: false, }, "serialization": { acceptedFormat: types.Serialization, riskCreated: false, }, "file": { acceptedFormat: types.File, riskCreated: false, }, "csv": { acceptedFormat: types.CSV, riskCreated: false, }, "yaml": { acceptedFormat: types.YAML, riskCreated: false, }, "xml": { acceptedFormat: types.XML, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, riskCreated: true, expImpact: types.MediumImpact, }, "strictly confidential": { acceptedFormat: types.XML, confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, riskCreated: true, expImpact: types.HighImpact, }, "mission critical integrity": { acceptedFormat: types.XML, confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, riskCreated: true, expImpact: types.HighImpact, }, "mission critical availability": { acceptedFormat: types.XML, confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, riskCreated: true, expImpact: types.HighImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewXmlExternalEntityRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta": { Id: "ta", Title: "Test Technical Asset", OutOfScope: testCase.outOfScope, DataFormatsAccepted: []types.DataFormat{ testCase.acceptedFormat, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, }, }) assert.Nil(t, err) if testCase.riskCreated { assert.Len(t, risks, 1) assert.Equal(t, testCase.expImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>XML External Entity (XXE)</b> risk at <b>%s</b>", "Test Technical Asset") assert.Equal(t, expTitle, risks[0].Title) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unencrypted_asset_rule.go
pkg/risks/builtin/unencrypted_asset_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UnencryptedAssetRule struct{} func NewUnencryptedAssetRule() *UnencryptedAssetRule { return &UnencryptedAssetRule{} } func (*UnencryptedAssetRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unencrypted-asset", Title: "Unencrypted Technical Assets", Description: "Due to the confidentiality rating of the technical asset itself and/or the stored data assets " + "this technical asset must be encrypted. The risk rating depends on the sensitivity technical asset itself and of the data assets stored.", Impact: "If this risk is unmitigated, attackers might be able to access unencrypted data when successfully compromising sensitive components.", ASVS: "V6 - Stored Cryptography Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html", Action: "Encryption of Technical Asset", Mitigation: "Apply encryption to the technical asset.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.InformationDisclosure, DetectionLogic: "In-scope unencrypted technical assets (excluding " + types.ReverseProxy + ", " + types.LoadBalancer + ", " + types.WAF + ", " + types.IDS + ", " + types.IPS + " and embedded components like " + types.Library + ") " + "storing data assets rated at least as " + types.Confidential.String() + " or " + types.Critical.String() + ". " + "For technical assets storing data assets rated as " + types.StrictlyConfidential.String() + " or " + types.MissionCritical.String() + " the " + "encryption must be of type " + types.DataWithEndUserIndividualKey.String() + ".", // NOTE: the risk assessment does not only consider the CIs of the *stored* data-assets RiskAssessment: "Depending on the confidentiality rating of the stored data-assets either medium or high risk.", FalsePositives: "When all sensitive data stored within the asset is already fully encrypted on document or data level.", ModelFailurePossibleReason: false, CWE: 311, } } func (*UnencryptedAssetRule) SupportedTags() []string { return []string{} } // check for technical assets that should be encrypted due to their confidentiality func (r *UnencryptedAssetRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] highestStoredConfidentiality := input.HighestStoredConfidentiality(technicalAsset) highestStoredIntegrity := input.HighestStoredIntegrity(technicalAsset) if technicalAsset.OutOfScope || isEncryptionWaiver(technicalAsset) { continue } if len(technicalAsset.DataAssetsStored) == 0 { continue } if highestStoredConfidentiality < types.Confidential || highestStoredIntegrity < types.Critical { continue } verySensitive := highestStoredConfidentiality == types.StrictlyConfidential || highestStoredIntegrity == types.MissionCritical requiresEndUserKey := verySensitive && technicalAsset.Technologies.GetAttribute(types.IsUsuallyStoringEndUserData) if technicalAsset.Encryption == types.NoneEncryption { impact := types.MediumImpact if verySensitive { impact = types.HighImpact } risks = append(risks, r.createRisk(technicalAsset, impact, requiresEndUserKey)) continue } if requiresEndUserKey && technicalAsset.Encryption != types.DataWithEndUserIndividualKey { risks = append(risks, r.createRisk(technicalAsset, types.MediumImpact, requiresEndUserKey)) continue } } return risks, nil } // Simple routing assets like 'Reverse Proxy' or 'Load Balancer' usually don't have their own storage and thus have no // encryption requirement for the asset itself (though for the communication, but that's a different rule) func isEncryptionWaiver(asset *types.TechnicalAsset) bool { return asset.Technologies.GetAttribute(types.IsNoStorageAtRest) || asset.Technologies.GetAttribute(types.IsEmbeddedComponent) } func (r *UnencryptedAssetRule) createRisk(technicalAsset *types.TechnicalAsset, impact types.RiskExploitationImpact, requiresEndUserKey bool) *types.Risk { title := "<b>Unencrypted Technical Asset</b> named <b>" + technicalAsset.Title + "</b>" if requiresEndUserKey { title += " missing end user individual encryption with " + types.DataWithEndUserIndividualKey.String() } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_waf_rule.go
pkg/risks/builtin/missing_waf_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingWafRule struct{} func NewMissingWafRule() *MissingWafRule { return &MissingWafRule{} } func (*MissingWafRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-waf", Title: "Missing Web Application Firewall (WAF)", Description: "To have a first line of filtering defense, security architectures with web-services or web-applications should include a WAF in front of them. " + "Even though a WAF is not a replacement for security (all components must be secure even without a WAF) it adds another layer of defense to the overall " + "system by delaying some attacks and having easier attack alerting through it.", Impact: "If this risk is unmitigated, attackers might be able to apply standard attack pattern tests at great speed without any filtering.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Virtual_Patching_Cheat_Sheet.html", Action: "Web Application Firewall (WAF)", Mitigation: "Consider placing a Web Application Firewall (WAF) in front of the web-services and/or web-applications. For cloud environments many cloud providers offer " + "pre-configured WAFs. Even reverse proxies can be enhances by a WAF component via ModSecurity plugins.", Check: "GetAttribute a Web Application Firewall (WAF) in place?", Function: types.Operations, STRIDE: types.Tampering, DetectionLogic: "In-scope web-services and/or web-applications accessed across a network trust boundary not having a Web Application Firewall (WAF) in front of them.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Targets only accessible via WAFs or reverse proxies containing a WAF component (like ModSecurity) can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*MissingWafRule) SupportedTags() []string { return []string{} } func (r *MissingWafRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if technicalAsset.OutOfScope { continue } if !technicalAsset.Technologies.GetAttribute(types.WebApplication) && !technicalAsset.Technologies.GetAttribute(types.IsWebService) { continue } for _, incomingAccess := range input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] { if isAcrossTrustBoundaryNetworkOnly(input, incomingAccess) && incomingAccess.Protocol.IsPotentialWebAccessProtocol() && !input.TechnicalAssets[incomingAccess.SourceId].Technologies.GetAttribute(types.WAF) { risks = append(risks, r.createRisk(input, technicalAsset)) break } } } return risks, nil } func (r *MissingWafRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Missing Web Application Firewall (WAF)</b> risk at <b>" + technicalAsset.Title + "</b>" likelihood := types.Unlikely impact := types.LowImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || input.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/helpers_test.go
pkg/risks/builtin/helpers_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func Test_IsAcrossTrustBoundaryNetworkOnly_EmptyDataReturnFalse(t *testing.T) { cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{} result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.False(t, result) } func Test_IsAcrossTrustBoundaryNetworkOnly_NoSourceIdReturnFalse(t *testing.T) { cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{}, } result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.False(t, result) } func Test_IsAcrossTrustBoundaryNetworkOnly_SourceIdIsNotNetworkBoundaryReturnFalse(t *testing.T) { cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{ TrustBoundaries: map[string]*types.TrustBoundary{ "trust-boundary": { Id: "trust-boundary", TrustBoundariesNested: []string{"trust-boundary-2"}, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "source": { Id: "trust-boundary", Type: types.ExecutionEnvironment, }, "target": { Id: "trust-boundary-2", Type: types.ExecutionEnvironment, }, }, } result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.False(t, result) } func Test_IsAcrossTrustBoundaryNetworkOnly_NoTargetIdReturnFalse(t *testing.T) { cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "source": { Id: "trust-boundary", }, }, } result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.False(t, result) } func Test_IsAcrossTrustBoundaryNetworkOnly_TargetIdIsNotNetworkBoundaryReturnFalse(t *testing.T) { cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "source": { Id: "trust-boundary", }, "target": { Id: "trust-boundary", Type: types.ExecutionEnvironment, }, }, } result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.False(t, result) } func Test_IsAcrossTrustBoundaryNetworkOnly_Compare(t *testing.T) { trustBoundary := types.TrustBoundary{ Id: "trust-boundary", } anotherTrustBoundary := types.TrustBoundary{ Id: "another-trust-boundary", } cl := &types.CommunicationLink{ SourceId: "source", TargetId: "target", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "source": &trustBoundary, "target": &anotherTrustBoundary, }, } result := isAcrossTrustBoundaryNetworkOnly(parsedModel, cl) assert.True(t, result) } func Test_isSameExecutionEnvironment_EmptyDataReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{} parsedModel := &types.Model{} result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameExecutionEnvironemnt_NoTrustBoundaryOfMyAssetReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "other-asset": {}, }, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameExecutionEnvironment_NoTrustBoundaryOfOtherAssetReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": {}, }, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameExecutionEnvironemnt_NoTrustBoundaryOfEitherAssetReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{}, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameExecutionEnvironment_TrustBoundariesAreDifferentReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: types.ExecutionEnvironment, } otherTrustBoundary := types.TrustBoundary{ Id: "other-trust-boundary", Type: types.ExecutionEnvironment, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &otherTrustBoundary, }, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameExecutionEnvironment_TrustBoundariesAreSameReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: types.ExecutionEnvironment, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &trustBoundary, }, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameExecutionEnvironment_TrustBoundariesAreNotBothExecutionEnvironmentReturnFalse(t *testing.T) { tests := []struct { name string assetTrustBoundaryType types.TrustBoundaryType otherAssetTrustBoundaryType types.TrustBoundaryType }{ {"ExecutionEnvironment, NetworkCloudProvider", types.ExecutionEnvironment, types.NetworkCloudProvider}, {"NetworkCloudProvider, ExecutionEnvironment", types.NetworkCloudProvider, types.ExecutionEnvironment}, {"NetworkCloudProvider, NetworkCloudProvider", types.NetworkCloudProvider, types.NetworkCloudProvider}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: tt.assetTrustBoundaryType, } anotherTrustBoundary := types.TrustBoundary{ Id: "other-trust-boundary", Type: tt.otherAssetTrustBoundaryType, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &anotherTrustBoundary, }, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.False(t, result) }) } } func Test_isSameTrustBoundaryNetworkOnly_EmptyDataReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{} parsedModel := &types.Model{} result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameTrustBoundaryNetworkOnly_NoTrustBoundaryOfMyAssetReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "other-asset": {}, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameTrustBoundaryNetworkOnly_NoTrustBoundaryOfOtherAssetReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": {}, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameExecutionEnvironemntNetworkOnly_NoTrustBoundaryOfEitherAssetReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{}, } result := isSameExecutionEnvironment(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameTrustBoundaryNetworkOnly_TrustBoundariesAreDifferentReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", } otherTrustBoundary := types.TrustBoundary{ Id: "other-trust-boundary", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &otherTrustBoundary, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameTrustBoundaryNetworkOnly_TrustBoundariesAreSameReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &trustBoundary, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameTrustBoundaryNetworkOnly_IsNetworkBoundaryTrustBoundariesAreDifferentButParentIsSameReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parentTrustBoundary := types.TrustBoundary{ Id: "parent-trust-boundary", TrustBoundariesNested: []string{"trust-boundary", "other-trust-boundary"}, } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: types.NetworkCloudProvider, } otherTrustBoundary := types.TrustBoundary{ Id: "other-trust-boundary", Type: types.NetworkCloudProvider, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &otherTrustBoundary, }, TrustBoundaries: map[string]*types.TrustBoundary{ "trust-boundary": &trustBoundary, "other-trust-boundary": &otherTrustBoundary, "parent-trust-boundary": &parentTrustBoundary, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameTrustBoundaryNetworkOnly_TrustBoundariesAreDifferentButParentIsDifferentReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } parentTrustBoundary := types.TrustBoundary{ Id: "parent-trust-boundary", TrustBoundariesNested: []string{"trust-boundary"}, } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", } otherTrustBoundary := types.TrustBoundary{ Id: "other-trust-boundary", } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &otherTrustBoundary, }, TrustBoundaries: map[string]*types.TrustBoundary{ "trust-boundary": &trustBoundary, "other-trust-boundary": &otherTrustBoundary, "parent-trust-boundary": &parentTrustBoundary, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_isSameTrustBoundaryNetworkOnly_NotNetworkBoundaryReturnTrue(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: types.ExecutionEnvironment, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &trustBoundary, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.True(t, result) } func Test_isSameTrustBoundaryNetworkOnly_DifferentNotNetworkBoundaryReturnFalse(t *testing.T) { ta := &types.TechnicalAsset{ Id: "asset", } trustBoundary := types.TrustBoundary{ Id: "trust-boundary", Type: types.ExecutionEnvironment, TechnicalAssetsInside: []string{"asset"}, } trustBoundary2 := types.TrustBoundary{ Id: "trust-boundary-2", TechnicalAssetsInside: []string{"other-asset"}, } parsedModel := &types.Model{ DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "asset": &trustBoundary, "other-asset": &trustBoundary2, }, } result := isSameTrustBoundaryNetworkOnly(parsedModel, ta, "other-asset") assert.False(t, result) } func Test_contains(t *testing.T) { tests := []struct { name string as []string b string expected bool }{ {"as null", nil, "foo", false}, {"no match", []string{"foo", "bar"}, "bat", false}, {"match", []string{"foo", "bar"}, "foo", true}, {"no match different case", []string{"foo", "bar"}, "FOO", false}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { result := contains(test.as, test.b) assert.Equal(t, test.expected, result) }) } } func Test_containsCaseInsensitiveAny(t *testing.T) { tests := []struct { name string as []string bs []string expected bool }{ {"as null, bs null", nil, nil, false}, {"as null, bs not null", nil, []string{"foo", "bar"}, false}, {"as not null, bs null", []string{"foo", "bar"}, nil, false}, {"no match", []string{"foo", "bar"}, []string{"bat", "baz"}, false}, {"match same case", []string{"foo", "bar"}, []string{"bat", "foo"}, true}, {"match different case", []string{"FOO", "bar"}, []string{"bat", "foo"}, true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { result := containsCaseInsensitiveAny(test.as, test.bs...) assert.Equal(t, test.expected, result) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_vault_isolation_rule_test.go
pkg/risks/builtin/missing_vault_isolation_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingVaultIsolationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingVaultIsolationRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingVaultIsolationRuleGenerateRisksNoVaultNoRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "no-vault", Attributes: map[string]bool{ types.Vault: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingVaultIsolationRuleGenerateRisksTwoVaultsNoRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "First Vault", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, "ta2": { Title: "Second Vault", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingVaultIsolationRuleGenerateRisksVaultAndStorageNoRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Vault", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Vault Datastore", OutOfScope: false, Type: types.Datastore, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingVaultIsolationRuleGenerateRisksDifferentTrustBoundariesNoRisksCreated(t *testing.T) { rule := NewMissingVaultIsolationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "First Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Second Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Vault", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Vault Consumer", OutOfScope: false, Type: types.Process, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingVaultIsolationRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality tbType types.TrustBoundaryType expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood expectedMessage string } func TestMissingVaultIsolationRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]MissingVaultIsolationRuleTest{ "medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, tbType: types.NetworkCloudProvider, expectedImpact: types.MediumImpact, expectedLikelihood: types.Unlikely, expectedMessage: "network segment", }, "strictly confidential high impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, tbType: types.NetworkCloudProvider, expectedImpact: types.HighImpact, expectedLikelihood: types.Unlikely, expectedMessage: "network segment", }, "mission critical integrity high impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, tbType: types.NetworkCloudProvider, expectedImpact: types.HighImpact, expectedLikelihood: types.Unlikely, expectedMessage: "network segment", }, "mission critical availability high impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, tbType: types.NetworkCloudProvider, expectedImpact: types.HighImpact, expectedLikelihood: types.Unlikely, expectedMessage: "network segment", }, "same execution environment": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, tbType: types.ExecutionEnvironment, expectedImpact: types.MediumImpact, expectedLikelihood: types.Likely, expectedMessage: "execution environment", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingVaultIsolationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "First Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Type: testCase.tbType, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Vault", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.Vault: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, "ta2": { Id: "ta2", Title: "Vault Consumer", OutOfScope: false, Type: types.Process, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) expTitle := fmt.Sprintf("<b>Missing Vault Isolation</b> to further encapsulate and protect vault-related asset <b>Vault</b> against unrelated "+ "lower protected assets <b>in the same %s</b>, which might be easier to compromise by attackers", testCase.expectedMessage) assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unguarded_access_from_internet_rule_test.go
pkg/risks/builtin/unguarded_access_from_internet_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnguardedAccessFromInternetRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnguardedAccessFromInternetRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type UnguardedAccessFromInternetRuleTest struct { outOfScope bool protocol types.Protocol customDevelopedParts bool isVPN bool raa float64 isSourceMonitoring bool isSourceFromInternet bool isHttpInternetAccessOK bool isFTPInternetAccessOK bool isLoadBalancer bool confidentiality types.Confidentiality integrity types.Criticality riskCreated bool expectedImpact types.RiskExploitationImpact } func TestUnguardedAccessFromInternetRuleGenerateRisks(t *testing.T) { testCases := map[string]UnguardedAccessFromInternetRuleTest{ "out of scope": { outOfScope: true, isLoadBalancer: false, riskCreated: false, }, "no risk when access from load balancer": { outOfScope: false, isLoadBalancer: true, riskCreated: false, }, "no risk when access from monitoring": { outOfScope: false, isLoadBalancer: false, isSourceMonitoring: true, riskCreated: false, }, "no risk when access from vpn": { outOfScope: false, isLoadBalancer: false, isVPN: true, riskCreated: false, }, "https access from not custom developed parts": { outOfScope: false, isLoadBalancer: false, customDevelopedParts: false, isHttpInternetAccessOK: true, protocol: types.HTTPS, riskCreated: false, }, "http access from not custom developed parts": { outOfScope: false, isLoadBalancer: false, customDevelopedParts: false, isHttpInternetAccessOK: true, protocol: types.HTTP, riskCreated: false, }, "ftp access from not custom developed parts": { outOfScope: false, isLoadBalancer: false, customDevelopedParts: false, isFTPInternetAccessOK: true, protocol: types.FTP, riskCreated: false, }, "ftps access from not custom developed parts": { outOfScope: false, isLoadBalancer: false, customDevelopedParts: false, isFTPInternetAccessOK: true, protocol: types.FTPS, riskCreated: false, }, "sftp access from not custom developed parts": { outOfScope: false, isLoadBalancer: false, customDevelopedParts: false, isFTPInternetAccessOK: true, protocol: types.SFTP, riskCreated: false, }, "no risk for low confidentiality and integrity": { outOfScope: false, isLoadBalancer: false, isVPN: false, confidentiality: types.Restricted, integrity: types.Operational, riskCreated: false, }, "no access from internet": { outOfScope: false, isLoadBalancer: false, isVPN: false, isSourceFromInternet: false, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: false, }, "low impact risk created": { outOfScope: false, isLoadBalancer: false, isVPN: false, isSourceFromInternet: true, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.LowImpact, }, "raa high impact risk created": { outOfScope: false, isLoadBalancer: false, isVPN: false, isSourceFromInternet: true, raa: 50, confidentiality: types.Confidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.MediumImpact, }, "strictly confidential medium impact risk created": { outOfScope: false, isLoadBalancer: false, isVPN: false, isSourceFromInternet: true, confidentiality: types.StrictlyConfidential, integrity: types.Critical, riskCreated: true, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact risk created": { outOfScope: false, isLoadBalancer: false, isVPN: false, isSourceFromInternet: true, confidentiality: types.Confidential, integrity: types.MissionCritical, riskCreated: true, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnguardedAccessFromInternetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", Internet: testCase.isSourceFromInternet, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.Monitoring: testCase.isSourceMonitoring, }, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: testCase.outOfScope, RAA: testCase.raa, CustomDevelopedParts: testCase.customDevelopedParts, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, VPN: testCase.isVPN, }, }, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.LoadBalancer: testCase.isLoadBalancer, types.IsHTTPInternetAccessOK: testCase.isHttpInternetAccessOK, types.IsFTPInternetAccessOK: testCase.isFTPInternetAccessOK, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, VPN: testCase.isVPN, }, }, }, }) assert.Nil(t, err) if testCase.riskCreated { assert.NotEmpty(t, risks) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expectedMessage := "<b>Unguarded Access from Internet</b> of <b>Target Technical Asset</b> by <b>Source Technical Asset</b> via <b>Test Communication Link</b>" assert.Equal(t, risks[0].Title, expectedMessage) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_communication_link_rule_test.go
pkg/risks/builtin/unnecessary_communication_link_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnnecessaryCommunicationLinkRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnnecessaryCommunicationLinkRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryCommunicationLinkRuleSomeDataSendNotRisksCreated(t *testing.T) { rule := NewUnnecessaryCommunicationLinkRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { CommunicationLinks: []*types.CommunicationLink{ { Id: "ta1", DataAssetsSent: []string{"data"}, DataAssetsReceived: []string{}, }, }, }, "ta2": { Id: "ta2", }, }, DataAssets: map[string]*types.DataAsset{ "data": {}, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryCommunicationLinkRuleSomeDataReceivedNotRisksCreated(t *testing.T) { rule := NewUnnecessaryCommunicationLinkRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", DataAssetsSent: []string{}, DataAssetsReceived: []string{"data"}, }, }, }, "ta2": { Id: "ta2", }, }, DataAssets: map[string]*types.DataAsset{ "data": {}, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryCommunicationLinkRuleBothTechnicalAssetsOutOfScopeNotRisksCreated(t *testing.T) { rule := NewUnnecessaryCommunicationLinkRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", }, }, OutOfScope: true, }, "ta2": { Id: "ta2", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryCommnuicationLinkRuleRisksCreated(t *testing.T) { rule := NewUnnecessaryCommunicationLinkRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test technical asset", CommunicationLinks: []*types.CommunicationLink{{ Title: "Test communication link", TargetId: "ta2", }, }, }, "ta2": { Id: "ta2", Title: "Second test technical asset", }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Unnecessary Communication Link</b> titled <b>Test communication link</b> at technical asset <b>Test technical asset</b>", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/wrong_communication_link_content_rule_test.go
pkg/risks/builtin/wrong_communication_link_content_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestWrongCommunicationLinkContentRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewWrongCommunicationLinkContentRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type WrongCommunicationLinkContentRuleTest struct { receiveAnyData bool sendAnyData bool readonly bool protocol types.Protocol targetAssetType types.TechnicalAssetType isLibrary bool isLocalFileSystem bool machine types.TechnicalAssetMachine riskCreated bool expectedReason string } func TestWrongCommunicationLinkContentRuleSendDataAssetRisksCreated(t *testing.T) { testCases := map[string]WrongCommunicationLinkContentRuleTest{ "not readonly no data asset send no risk": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.UnknownProtocol, riskCreated: false, }, "not readonly data asset send no received no risk": { receiveAnyData: false, sendAnyData: true, readonly: false, protocol: types.UnknownProtocol, riskCreated: false, }, "not readonly data asset received no send risk": { receiveAnyData: true, sendAnyData: false, readonly: false, protocol: types.UnknownProtocol, riskCreated: true, expectedReason: "(data assets sent/received not matching the communication link's readonly flag)", }, "not readonly data asset received and send no risk": { receiveAnyData: true, sendAnyData: true, readonly: false, protocol: types.UnknownProtocol, riskCreated: false, }, "readonly no data asset send no risk": { receiveAnyData: false, sendAnyData: false, readonly: true, protocol: types.UnknownProtocol, riskCreated: false, }, "readonly data asset send no received no risk": { receiveAnyData: false, sendAnyData: true, readonly: true, protocol: types.UnknownProtocol, riskCreated: true, expectedReason: "(data assets sent/received not matching the communication link's readonly flag)", }, "readonly data asset received no send risk": { receiveAnyData: true, sendAnyData: false, readonly: true, protocol: types.UnknownProtocol, riskCreated: false, }, "readonly data asset received and send no risk": { receiveAnyData: true, sendAnyData: true, readonly: true, protocol: types.UnknownProtocol, riskCreated: false, }, "protocol type InProcessLibraryCall does not match target technology type Library": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.InProcessLibraryCall, isLibrary: false, riskCreated: true, expectedReason: "(protocol type \"in-process-library-call\" does not match target technology type \"\": expected \"library\")", }, "protocol type InProcessLibraryCall match target technology type Library": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.InProcessLibraryCall, isLibrary: true, riskCreated: false, }, "protocol type InterProcessCommunication does not match target technology type Process": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.InterProcessCommunication, isLibrary: false, riskCreated: true, expectedReason: "(protocol type \"inter-process-communication\" does not match target technology type \"\": expected \"process\")", }, "protocol type InterProcessCommunication match target technology type Process": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.InterProcessCommunication, targetAssetType: types.Process, isLibrary: true, riskCreated: false, }, "protocol type LocalFileAccess does not match target technology type LocalFileSystem": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.LocalFileAccess, isLocalFileSystem: false, riskCreated: true, expectedReason: "(protocol type \"local-file-access\" does not match target technology type \"\": expected \"local-file-system\")", }, "protocol type LocalFileAccess match target technology type LocalFileSystem": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.LocalFileAccess, isLocalFileSystem: true, riskCreated: false, }, "protocol type ContainerSpawning does not match target target machine type": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.ContainerSpawning, machine: types.Physical, riskCreated: true, expectedReason: "(protocol type \"container-spawning\" does not match target machine type \"physical\": expected \"container\")", }, "protocol type ContainerSpawning match target machine type Container": { receiveAnyData: false, sendAnyData: false, readonly: false, protocol: types.ContainerSpawning, machine: types.Container, riskCreated: false, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewWrongCommunicationLinkContentRule() dataAssetsSend := []string{} if testCase.sendAnyData { dataAssetsSend = append(dataAssetsSend, "da1") } dataAssetsReceived := []string{} if testCase.receiveAnyData { dataAssetsReceived = append(dataAssetsReceived, "da1") } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "source", TargetId: "target", DataAssetsSent: dataAssetsSend, DataAssetsReceived: dataAssetsReceived, Protocol: testCase.protocol, Readonly: testCase.readonly, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", Machine: testCase.machine, Type: testCase.targetAssetType, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.Library: testCase.isLibrary, types.LocalFileSystem: testCase.isLocalFileSystem, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { Title: "Data Transfer", SourceId: "source", TargetId: "target", Protocol: testCase.protocol, Readonly: testCase.readonly, DataAssetsSent: dataAssetsSend, DataAssetsReceived: dataAssetsReceived, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", }, }, }) assert.Nil(t, err) if testCase.riskCreated { assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Wrong Communication Link Content</b> %s at <b>Source Technical Asset</b> regarding communication link <b>Data Transfer</b>", testCase.expectedReason) assert.Equal(t, expTitle, risks[0].Title) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/xml_external_entity_rule.go
pkg/risks/builtin/xml_external_entity_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type XmlExternalEntityRule struct{} func NewXmlExternalEntityRule() *XmlExternalEntityRule { return &XmlExternalEntityRule{} } func (*XmlExternalEntityRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "xml-external-entity", Title: "XML External Entity (XXE)", Description: "When a technical asset accepts data in XML format, XML External Entity (XXE) risks might arise.", Impact: "If this risk is unmitigated, attackers might be able to read sensitive files (configuration data, key/credential files, deployment files, " + "business data files, etc.) form the filesystem of affected components and/or access sensitive services or files " + "of other components.", ASVS: "V14 - Configuration Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html", Action: "XML Parser Hardening", Mitigation: "Apply hardening of all XML parser instances in order to stay safe from XML External Entity (XXE) vulnerabilities. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.InformationDisclosure, DetectionLogic: "In-scope technical assets accepting XML data formats.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed. " + "Also for cloud-based environments the exploitation impact is at least medium, as cloud backend services can be attacked via SSRF (and XXE vulnerabilities are often also SSRF vulnerabilities).", FalsePositives: "Fully trusted (i.e. cryptographically signed or similar) XML data can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 611, } } func (*XmlExternalEntityRule) SupportedTags() []string { return []string{} } func (r *XmlExternalEntityRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope { continue } for _, format := range technicalAsset.DataFormatsAccepted { if format == types.XML { risks = append(risks, r.createRisk(input, technicalAsset)) } } } return risks, nil } func (r *XmlExternalEntityRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>XML External Entity (XXE)</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.MediumImpact if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.HighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.VeryLikely, impact), ExploitationLikelihood: types.VeryLikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, // TODO: use the same logic here as for SSRF rule, as XXE is also SSRF ;) } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/search_query_injection_rule.go
pkg/risks/builtin/search_query_injection_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type SearchQueryInjectionRule struct{} func NewSearchQueryInjectionRule() *SearchQueryInjectionRule { return &SearchQueryInjectionRule{} } func (*SearchQueryInjectionRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "search-query-injection", Title: "Search-Query Injection", Description: "When a search engine server is accessed Search-Query Injection risks might arise." + "<br><br>See for example <a href=\"https://github.com/veracode-research/solr-injection\">https://github.com/veracode-research/solr-injection</a> and " + "<a href=\"https://github.com/veracode-research/solr-injection/blob/master/slides/DEFCON-27-Michael-Stepankin-Apache-Solr-Injection.pdf\">https://github.com/veracode-research/solr-injection/blob/master/slides/DEFCON-27-Michael-Stepankin-Apache-Solr-Injection.pdf</a> " + "for more details (here related to Solr, but in general showcasing the topic of search query injections).", Impact: "If this risk remains unmitigated, attackers might be able to read more data from the search index and " + "eventually further escalate towards a deeper system penetration via code executions.", ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html", Action: "Search-Query Injection Prevention", Mitigation: "Try to use libraries that properly encode search query meta characters in searches and don't expose the " + "query unfiltered to the caller. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Tampering, DetectionLogic: "In-scope clients accessing search engine servers via typical search access protocols.", RiskAssessment: "The risk rating depends on the sensitivity of the search engine server itself and of the data assets processed.", FalsePositives: "Server engine queries by search values not consisting of parts controllable by the caller can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 74, } } func (*SearchQueryInjectionRule) SupportedTags() []string { return []string{} } func (r *SearchQueryInjectionRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if !technicalAsset.Technologies.GetAttribute(types.IsSearchRelated) { continue } incomingFlows := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, incomingFlow := range incomingFlows { if input.TechnicalAssets[incomingFlow.SourceId].OutOfScope { continue } if incomingFlow.Protocol != types.HTTP && incomingFlow.Protocol != types.HTTPS && incomingFlow.Protocol != types.BINARY && incomingFlow.Protocol != types.BinaryEncrypted { continue } likelihood := types.VeryLikely if incomingFlow.Usage == types.DevOps { likelihood = types.Likely } risks = append(risks, r.createRisk(input, technicalAsset, incomingFlow, likelihood)) } } return risks, nil } func (r *SearchQueryInjectionRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingFlow *types.CommunicationLink, likelihood types.RiskExploitationLikelihood) *types.Risk { caller := input.TechnicalAssets[incomingFlow.SourceId] title := "<b>Search Query Injection</b> risk at <b>" + caller.Title + "</b> against search engine server <b>" + technicalAsset.Title + "</b>" + " via <b>" + incomingFlow.Title + "</b>" impact := types.MediumImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.HighImpact } else if input.HighestProcessedConfidentiality(technicalAsset) <= types.Internal && input.HighestProcessedIntegrity(technicalAsset) == types.Operational { impact = types.LowImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: caller.Id, MostRelevantCommunicationLinkId: incomingFlow.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + caller.Id + "@" + technicalAsset.Id + "@" + incomingFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_cloud_hardening_rule_test.go
pkg/risks/builtin/missing_cloud_hardening_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingCloudHardeningRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingCloudHardeningRuleGenerateRisksTrustBoundaryNotWithinCloudNoRisksCreated(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Trust Boundary", Tags: []string{"unspecific-cloud"}, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Trust Boundary", Tags: []string{"unspecific-cloud"}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Trust Boundary", Tags: []string{"unspecific-cloud"}, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Tags: []string{"unspecific-cloud"}, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type CloudHardeningRuleTest struct { cloud string expectedTitleSuffix string expectedMessageSuffix string } func TestMissingCloudHardeningRuleGenerateRisksTrustBoundaryWithoutCloudHardeningRiskCreated(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Trust Boundary", Tags: []string{testCase.cloud}, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, Type: types.NetworkCloudProvider, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Trust Boundary</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTrustBoundaryWithoutCloudHardeningWithConfidentialTechnicalAssetRiskCreatedWithHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, Confidentiality: types.Confidential, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Trust Boundary", Tags: []string{testCase.cloud}, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, Type: types.NetworkCloudProvider, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Trust Boundary</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTrustBoundaryWithoutCloudHardeningWithStrictlyConfidentialTechnicalAssetRiskCreatedWithVeryHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, Confidentiality: types.StrictlyConfidential, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Trust Boundary", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Trust Boundary", Tags: []string{testCase.cloud}, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, Type: types.NetworkCloudProvider, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.VeryHighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Trust Boundary</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksSharedRuntimeWithoutCloudHardeningRiskCreated(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Shared Runtime", }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "tb1": { Id: "tb1", Title: "Test Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Shared Runtime</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksSharedRuntimeWithoutCloudHardeningWithCriticallyAvailableTechnicalAssetRiskCreatedWithHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, Availability: types.Critical, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Shared Runtime", }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "tb1": { Id: "tb1", Title: "Test Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Shared Runtime</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksSharedRuntimeWithoutCloudHardeningWithMissionCriticalAvailableTechnicalAssetRiskCreatedWithVeryHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, "unspecific-cloud": { cloud: "unspecific-cloud", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, Availability: types.MissionCritical, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Shared Runtime", Tags: []string{testCase.cloud}, }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Shared Runtime", }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "tb1": { Id: "tb1", Title: "Test Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, Tags: []string{testCase.cloud}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.VeryHighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Test Shared Runtime</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTechnicalAssetWithoutCloudHardeningRiskCreated(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Technical Asset Without Cloud Hardening", Tags: []string{testCase.cloud}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Technical Asset Without Cloud Hardening</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTechnicalAssetWithoutCloudHardeningProcessingCriticallyAvailableDataRiskCreatedWithHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Technical Asset Without Cloud Hardening", Tags: []string{testCase.cloud}, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Data Asset", Availability: types.Critical, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Technical Asset Without Cloud Hardening</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTechnicalAssetWithoutCloudHardeningProcessingMissionCriticallyAvailableDataRiskCreatedWithVeryHighImpact(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws": { cloud: "aws", expectedTitleSuffix: " (AWS)", expectedMessageSuffix: ": <u>CIS Benchmark for AWS</u>", }, "azure": { cloud: "azure", expectedTitleSuffix: " (Azure)", expectedMessageSuffix: ": <u>CIS Benchmark for Microsoft Azure</u>", }, "gcp": { cloud: "gcp", expectedTitleSuffix: " (GCP)", expectedMessageSuffix: ": <u>CIS Benchmark for Google Cloud Computing Platform</u>", }, "ocp": { cloud: "ocp", expectedTitleSuffix: " (OCP)", expectedMessageSuffix: ": <u>Vendor Best Practices for Oracle Cloud Platform</u>", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Technical Asset Without Cloud Hardening", Tags: []string{testCase.cloud}, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Data Asset", Availability: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.VeryHighImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Technical Asset Without Cloud Hardening</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksTechnicalAssetSpecificWithoutCloudHardeningRiskCreated(t *testing.T) { testCases := map[string]CloudHardeningRuleTest{ "aws:ec2": { cloud: "aws:ec2", expectedTitleSuffix: " (EC2)", expectedMessageSuffix: ": <u>CIS Benchmark for Amazon Linux</u>", }, "aws:s3": { cloud: "aws:s3", expectedTitleSuffix: " (S3)", expectedMessageSuffix: ": <u>Security Best Practices for AWS S3</u>", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Technical Asset Without Cloud Hardening", Tags: []string{testCase.cloud}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 2) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Cloud Hardening (AWS)</b> risk at <b>Technical Asset Without Cloud Hardening</b>: <u>CIS Benchmark for AWS</u>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[1].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Cloud Hardening%s</b> risk at <b>Technical Asset Without Cloud Hardening</b>%s", testCase.expectedTitleSuffix, testCase.expectedMessageSuffix) assert.Equal(t, expTitle, risks[1].Title) }) } } func TestMissingCloudHardeningRuleGenerateRisksSpecificTagsCloudHardeningRiskCreated(t *testing.T) { rule := NewMissingCloudHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset Inside Trust Boundary", Tags: []string{"aws:lambda"}, }, "ta2": { Id: "ta2", Title: "Second Technical Asset Inside Trust Boundary", }, "ta3": { Id: "ta3", Title: "Technical Asset Outside Trust Boundary", }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1", "ta2"}, Tags: []string{"aws:vpc"}, Type: types.NetworkCloudProvider, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Cloud Hardening (AWS)</b> risk at <b>Test Trust Boundary</b>: <u>CIS Benchmark for AWS</u>", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_propagation_rule_test.go
pkg/risks/builtin/missing_identity_propagation_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingIdentityPropagationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingIdentityPropagationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityPropagationRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingIdentityPropagationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, RAA: 100, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingIdentityPropagationRuleRisksCreatedTest struct { multitenant bool confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality technologyAttribute string callerType types.TechnicalAssetType callerTechnologyAttribute string communicationLinkAuthentication types.Authentication communicationLinkAuthorization types.Authorization communicationLinkUsage types.Usage expectedImpact types.RiskExploitationImpact } func TestMissingIdentityPropagationRuleRisksCreated(t *testing.T) { testCases := map[string]MissingIdentityPropagationRuleRisksCreatedTest{ "confidential tech asset called from not data store": { multitenant: false, confidentiality: types.Confidential, integrity: types.Important, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "strictly confidential tech asset called from not data store": { multitenant: false, confidentiality: types.StrictlyConfidential, integrity: types.Important, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.MediumImpact, }, "restricted multitenant tech asset called from not data store": { multitenant: true, confidentiality: types.Restricted, integrity: types.Operational, availability: types.Operational, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "critically integrity tech asset called from not data store": { multitenant: false, confidentiality: types.Restricted, integrity: types.Critical, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "mission critically integrity tech asset called from not data store": { multitenant: false, confidentiality: types.Restricted, integrity: types.MissionCritical, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.MediumImpact, }, "important integrity multitenant tech asset called from not data store": { multitenant: true, confidentiality: types.Internal, integrity: types.Important, availability: types.Operational, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "critically availability tech asset called from not data store": { multitenant: false, confidentiality: types.Restricted, integrity: types.Important, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "mission critically availability tech asset called from not data store": { multitenant: false, confidentiality: types.Restricted, integrity: types.Important, availability: types.MissionCritical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.MediumImpact, }, "business technical user called from data store": { multitenant: true, confidentiality: types.Internal, integrity: types.Operational, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.TechnicalUser, communicationLinkUsage: types.Business, expectedImpact: types.LowImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingIdentityPropagationRule() input := &types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: testCase.multitenant, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, }, "caller": { Id: "caller", Title: "Test Caller Technical Asset", MultiTenant: testCase.multitenant, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Type: testCase.callerType, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Test Communication Link", SourceId: "caller", TargetId: "ta1", Authentication: testCase.communicationLinkAuthentication, Authorization: testCase.communicationLinkAuthorization, Usage: testCase.communicationLinkUsage, }, }, }, } input.TechnicalAssets["ta1"].Technologies[0].Attributes[testCase.technologyAttribute] = true input.TechnicalAssets["caller"].Technologies[0].Attributes[testCase.callerTechnologyAttribute] = true risks, err := rule.GenerateRisks(input) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing End User Identity Propagation</b> over communication link <b>Test Communication Link</b> from <b>Test Caller Technical Asset</b> to <b>Test Technical Asset</b>", risks[0].Title) }) } } func TestMissingIdentityPropagationRuleRisksNotCreated(t *testing.T) { testCases := map[string]MissingIdentityPropagationRuleRisksCreatedTest{ "cia lower to not create risk": { multitenant: false, confidentiality: types.Restricted, integrity: types.Important, availability: types.Important, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "cia lower to not create risk for multitenant": { multitenant: true, confidentiality: types.Internal, integrity: types.Operational, availability: types.Operational, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "is not processing end request": { multitenant: false, confidentiality: types.Confidential, integrity: types.Important, availability: types.Important, technologyAttribute: types.UnknownTechnology, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "caller from data store": { multitenant: false, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.Datastore, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "caller not able to propagate identity to outgoing targets": { multitenant: false, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.UnknownTechnology, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "none authentication in communication link": { multitenant: false, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.NoneAuthentication, communicationLinkAuthorization: types.NoneAuthorization, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "not enduser identity propagation authorization": { multitenant: false, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.EndUserIdentityPropagation, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, "devops without none authorization": { multitenant: false, confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, technologyAttribute: types.IsUsuallyProcessingEndUserRequests, callerType: types.ExternalEntity, callerTechnologyAttribute: types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets, communicationLinkAuthentication: types.ClientCertificate, communicationLinkAuthorization: types.TechnicalUser, communicationLinkUsage: types.DevOps, expectedImpact: types.LowImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingIdentityPropagationRule() input := &types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: testCase.multitenant, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, }, "caller": { Id: "caller", Title: "Test Caller Technical Asset", MultiTenant: testCase.multitenant, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Type: testCase.callerType, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Test Communication Link", SourceId: "caller", TargetId: "ta1", Authentication: testCase.communicationLinkAuthentication, Authorization: testCase.communicationLinkAuthorization, Usage: testCase.communicationLinkUsage, }, }, }, } input.TechnicalAssets["ta1"].Technologies[0].Attributes[testCase.technologyAttribute] = true input.TechnicalAssets["caller"].Technologies[0].Attributes[testCase.callerTechnologyAttribute] = true risks, err := rule.GenerateRisks(input) assert.Nil(t, err) assert.Empty(t, risks, 1) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/container_platform_escape_rule_test.go
pkg/risks/builtin/container_platform_escape_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestContainerPlatformEscapeRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerPlatformEscapeRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerPlatformEscapeRuleRuleGenerateRisksTechAssetNotContainerPlatformNotRisksCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.ContainerPlatform: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerPlatformEscapeRuleGenerateRisksTechAssetContainerPlatformRisksCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Docker", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.ContainerPlatform: true, }, }, }, Machine: types.Container, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Container Platform Escape</b> risk at <b>Docker</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.NotEmpty(t, risks[0].DataBreachTechnicalAssetIDs) assert.Equal(t, "ta1", risks[0].DataBreachTechnicalAssetIDs[0]) } func TestContainerPlatformEscapeRuleGenerateRisksTechAssetProcessedConfidentialityStrictlyConfidentialDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Docker", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.ContainerPlatform: true, }, }, }, Machine: types.Container, DataAssetsProcessed: []string{"strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "strictly-confidential-data-asset": { Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Container Platform Escape</b> risk at <b>Docker</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) assert.NotEmpty(t, risks[0].DataBreachTechnicalAssetIDs) assert.Equal(t, "ta1", risks[0].DataBreachTechnicalAssetIDs[0]) } func TestContainerPlatformEscapeRuleGenerateRisksTechAssetProcessedIntegrityMissionCriticalDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Docker", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.ContainerPlatform: true, }, }, }, Machine: types.Container, DataAssetsProcessed: []string{"strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "strictly-confidential-data-asset": { Integrity: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Container Platform Escape</b> risk at <b>Docker</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) assert.NotEmpty(t, risks[0].DataBreachTechnicalAssetIDs) assert.Equal(t, "ta1", risks[0].DataBreachTechnicalAssetIDs[0]) } func TestContainerPlatformEscapeRuleGenerateRisksTechAssetProcessedAvailabilityMissionCriticalDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerPlatformEscapeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Docker", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.ContainerPlatform: true, }, }, }, Machine: types.Container, DataAssetsProcessed: []string{"strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "strictly-confidential-data-asset": { Availability: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Container Platform Escape</b> risk at <b>Docker</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) assert.NotEmpty(t, risks[0].DataBreachTechnicalAssetIDs) assert.Equal(t, "ta1", risks[0].DataBreachTechnicalAssetIDs[0]) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/service_registry_poisoning_rule_test.go
pkg/risks/builtin/service_registry_poisoning_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestServiceRegistryPoisoningRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewServiceRegistryPoisoningRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestServiceRegistryPoisoningRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewServiceRegistryPoisoningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.ServiceRegistry: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestServiceRegistryPoisoningRuleGenerateRisksNoServiceRegistryNoRisksCreated(t *testing.T) { rule := NewServiceRegistryPoisoningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.ServiceRegistry: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type ServiceRegistryPoisoningRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality callerConfidentiality types.Confidentiality callerIntegrity types.Criticality callerAvailability types.Criticality communicationLinkDataSentConfidentiality types.Confidentiality communicationLinkDataSentIntegrity types.Criticality communicationLinkDataSentAvailability types.Criticality communicationLinkDataReceivedConfidentiality types.Confidentiality communicationLinkDataReceivedIntegrity types.Criticality communicationLinkDataReceivedAvailability types.Criticality expectedImpact types.RiskExploitationImpact } func TestServiceRegistryPoisoningRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]ServiceRegistryPoisoningRuleTest{ "low impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "strictly confidential caller medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.StrictlyConfidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical caller integration medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.MissionCritical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical caller availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.MissionCritical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "strictly confidential communication link data sent medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.StrictlyConfidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical communication link data sent availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.MissionCritical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical communication link data sent integrity medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.MissionCritical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "strictly confidential communication link data received medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.StrictlyConfidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical communication link data received integrity medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.MissionCritical, communicationLinkDataReceivedAvailability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical communication link data received availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, callerConfidentiality: types.Confidential, callerIntegrity: types.Critical, callerAvailability: types.Critical, communicationLinkDataSentConfidentiality: types.Confidential, communicationLinkDataSentIntegrity: types.Critical, communicationLinkDataSentAvailability: types.Critical, communicationLinkDataReceivedConfidentiality: types.Confidential, communicationLinkDataReceivedIntegrity: types.Critical, communicationLinkDataReceivedAvailability: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewServiceRegistryPoisoningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.ServiceRegistry: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: false, Confidentiality: testCase.callerConfidentiality, Integrity: testCase.callerIntegrity, Availability: testCase.callerAvailability, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Incoming Flow", SourceId: "ta2", DataAssetsSent: []string{"sent-data"}, DataAssetsReceived: []string{"received-data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "sent-data": { Confidentiality: testCase.communicationLinkDataSentConfidentiality, Integrity: testCase.communicationLinkDataSentIntegrity, Availability: testCase.communicationLinkDataSentAvailability, }, "received-data": { Confidentiality: testCase.communicationLinkDataReceivedConfidentiality, Integrity: testCase.communicationLinkDataReceivedIntegrity, Availability: testCase.communicationLinkDataReceivedAvailability, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Service Registry Poisoning</b> risk at <b>Test Technical Asset</b>", risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/code_backdooring_rule_test.go
pkg/risks/builtin/code_backdooring_rule_test.go
package builtin import ( "sort" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestCodeBackdooringRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestCodeBackdooringRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCodeBackdooringRuleGenerateRisksTechAssetFromInternetRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Title: "GitLab CI/CD", Internet: true, Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestCodeBackdooringRuleGenerateRisksTechAssetProcessConfidentialityRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Title: "GitLab CI/CD", Internet: true, Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, DataAssetsProcessed: []string{"critical-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "critical-data-asset": { Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) } func TestCodeBackdoogingRuleGenerateRisksTechAssetNotInternetButNotComingThroughVPNInternetRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Internet: false, Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, }, "reverse-proxy": { Title: "Reverse Proxy", Internet: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "reverse-proxy", TargetId: "git-lab-ci-cd", VPN: false, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestCodeBackdooringRuleGenerateRisksTechAssetNotInternetButComingThroughVPNNoInternetRisksNotCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Internet: false, Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, }, "vpn": { Title: "VPN", Internet: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "vpn", TargetId: "git-lab-ci-cd", VPN: true, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCodeBackdooringRuleGenerateRisksTechAssetNotInternetButComingThroughVPNInternetButOutOfScopeRisksNotCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Internet: false, OutOfScope: true, Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, }, "vpn": { Title: "VPN", Internet: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "vpn", TargetId: "git-lab-ci-cd", VPN: true, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCodeBackdooringRuleGenerateRisksNotImportantDataAssetNoAddingTargetRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Usage: types.DevOps, DataAssetsSent: []string{"not-important-data-asset"}, TargetId: "deployment-target", }, }, }, "reverse-proxy": { Id: "reverse-proxy", Title: "Reverse Proxy", Internet: true, }, "deployment-target": { Id: "deployment-target", Title: "Deployment Target", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "reverse-proxy", TargetId: "git-lab-ci-cd", }, }, }, DataAssets: map[string]*types.DataAsset{ "not-important-data-asset": { Integrity: types.Operational, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, []string{"git-lab-ci-cd"}, risks[0].DataBreachTechnicalAssetIDs) } func TestCodeBackdooringRuleGenerateRisksNotDevOpsDataAssetNoAddingTargetRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Usage: types.Business, DataAssetsSent: []string{"important-data-asset"}, TargetId: "deployment-target", }, }, }, "reverse-proxy": { Id: "reverse-proxy", Title: "Reverse Proxy", Internet: true, }, "deployment-target": { Id: "deployment-target", Title: "Deployment Target", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "reverse-proxy", TargetId: "git-lab-ci-cd", VPN: false, }, }, }, DataAssets: map[string]*types.DataAsset{ "important-data-asset": { Integrity: types.Important, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, []string{"git-lab-ci-cd"}, risks[0].DataBreachTechnicalAssetIDs) } func TestCodeBackdoogingRuleGenerateRisksDevOpsImportantDataAssetNoAddingTargetRisksCreated(t *testing.T) { rule := NewCodeBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "git-lab-ci-cd": { Id: "git-lab-ci-cd", Title: "GitLab CI/CD", Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Usage: types.DevOps, DataAssetsSent: []string{"important-data-asset"}, TargetId: "deployment-target", }, }, }, "reverse-proxy": { Id: "reverse-proxy", Title: "Reverse Proxy", Internet: true, }, "deployment-target": { Id: "deployment-target", Title: "Deployment Target", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "git-lab-ci-cd": { { SourceId: "reverse-proxy", TargetId: "git-lab-ci-cd", VPN: false, }, }, }, DataAssets: map[string]*types.DataAsset{ "important-data-asset": { Integrity: types.Important, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Code Backdooring</b> risk at <b>GitLab CI/CD</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) orderedDataBreachTechnicalAssetIDs := risks[0].DataBreachTechnicalAssetIDs sort.Strings(orderedDataBreachTechnicalAssetIDs) assert.Equal(t, []string{"deployment-target", "git-lab-ci-cd"}, orderedDataBreachTechnicalAssetIDs) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/wrong_trust_boundary_content_rule.go
pkg/risks/builtin/wrong_trust_boundary_content_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type WrongTrustBoundaryContentRule struct{} func NewWrongTrustBoundaryContentRule() *WrongTrustBoundaryContentRule { return &WrongTrustBoundaryContentRule{} } func (*WrongTrustBoundaryContentRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "wrong-trust-boundary-content", Title: "Wrong Trust Boundary Content", Description: "When a trust boundary of type " + types.NetworkPolicyNamespaceIsolation.String() + " contains " + "non-container assets it is likely to be a model failure.", Impact: "If this potential model error is not fixed, some risks might not be visible.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html", Action: "Model Consistency", Mitigation: "Try to model the correct types of trust boundaries and data assets.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "Trust boundaries which should only contain containers, but have different assets inside.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*WrongTrustBoundaryContentRule) SupportedTags() []string { return []string{} } func (r *WrongTrustBoundaryContentRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, trustBoundary := range input.TrustBoundaries { if trustBoundary.Type == types.NetworkPolicyNamespaceIsolation { for _, techAssetID := range trustBoundary.TechnicalAssetsInside { techAsset := input.TechnicalAssets[techAssetID] if techAsset.Machine != types.Container && techAsset.Machine != types.Serverless { risks = append(risks, r.createRisk(techAsset)) } } } } return risks, nil } func (r *WrongTrustBoundaryContentRule) createRisk(technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Wrong Trust Boundary Content</b> (non-container asset inside container trust boundary) at <b>" + technicalAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_technical_asset_rule.go
pkg/risks/builtin/unnecessary_technical_asset_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UnnecessaryTechnicalAssetRule struct{} func NewUnnecessaryTechnicalAssetRule() *UnnecessaryTechnicalAssetRule { return &UnnecessaryTechnicalAssetRule{} } func (*UnnecessaryTechnicalAssetRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unnecessary-technical-asset", Title: "Unnecessary Technical Asset", Description: "When a technical asset does not process any data assets, this is " + "an indicator for an unnecessary technical asset (or for an incomplete model). " + "This is also the case if the asset has no communication links (either outgoing or incoming).", Impact: "If this risk is unmitigated, attackers might be able to target unnecessary technical assets.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Attack Surface Reduction", Mitigation: "Try to avoid using technical assets that do not process or store anything.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "Technical assets not processing or storing any data assets.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*UnnecessaryTechnicalAssetRule) SupportedTags() []string { return []string{} } func (r *UnnecessaryTechnicalAssetRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if len(technicalAsset.DataAssetsProcessed) == 0 && len(technicalAsset.DataAssetsStored) == 0 || (len(technicalAsset.CommunicationLinks) == 0 && len(input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id]) == 0) { risks = append(risks, r.createRisk(technicalAsset)) } } return risks, nil } func (r *UnnecessaryTechnicalAssetRule) createRisk(technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Unnecessary Technical Asset</b> named <b>" + technicalAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_propagation_rule.go
pkg/risks/builtin/missing_identity_propagation_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingIdentityPropagationRule struct{} func NewMissingIdentityPropagationRule() *MissingIdentityPropagationRule { return &MissingIdentityPropagationRule{} } func (*MissingIdentityPropagationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-identity-propagation", Title: "Missing Identity Propagation", Description: "Technical assets (especially multi-tenant systems), which usually process data for end users should " + "authorize every request based on the identity of the end user when the data flow is authenticated (i.e. non-public). " + "For DevOps usages at least a technical-user authorization is required.", Impact: "If this risk is unmitigated, attackers might be able to access or modify foreign data after a successful compromise of a component within " + "the system due to missing resource-based authorization checks.", ASVS: "V4 - Access Control Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Access_Control_Cheat_Sheet.html", Action: "Identity Propagation and Resource-based Authorization", Mitigation: "When processing requests for end users if possible authorize in the backend against the propagated " + "identity of the end user. This can be achieved in passing JWTs or similar tokens and checking them in the backend " + "services. For DevOps usages apply at least a technical-user authorization.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope service-like technical assets which usually process data based on end user requests, if authenticated " + "(i.e. non-public), should authorize incoming requests based on the propagated end user identity when their rating is sensitive. " + "This is especially the case for all multi-tenant assets (there even less-sensitive rated ones). " + "DevOps usages are exempted from this risk.", RiskAssessment: "The risk rating (medium or high) " + "depends on the confidentiality, integrity, and availability rating of the technical asset.", FalsePositives: "Technical assets which do not process requests regarding functionality or data linked to end-users (customers) " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 284, } } func (*MissingIdentityPropagationRule) SupportedTags() []string { return []string{} } func (r *MissingIdentityPropagationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } // check each incoming authenticated data flow commLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, commLink := range commLinks { caller := input.TechnicalAssets[commLink.SourceId] if r.skipCommunicationLinkAsset(caller, commLink) { continue } highRisk := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical || technicalAsset.Availability == types.MissionCritical risks = append(risks, r.createRisk(input, technicalAsset, commLink, highRisk)) } } return risks, nil } func (r *MissingIdentityPropagationRule) skipCommunicationLinkAsset(caller *types.TechnicalAsset, commLink *types.CommunicationLink) bool { if !caller.Technologies.GetAttribute(types.IsUsuallyAbleToPropagateIdentityToOutgoingTargets) || caller.Type == types.Datastore { return true } if commLink.Authentication == types.NoneAuthentication || commLink.Authorization == types.EndUserIdentityPropagation { return true } if commLink.Usage == types.DevOps && commLink.Authorization != types.NoneAuthorization { return true } return false } func (r *MissingIdentityPropagationRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { if technicalAsset.OutOfScope { return true } if !technicalAsset.Technologies.GetAttribute(types.IsUsuallyProcessingEndUserRequests) { return true } if technicalAsset.MultiTenant && technicalAsset.Confidentiality < types.Restricted && technicalAsset.Integrity < types.Important && technicalAsset.Availability < types.Important { return true } if !technicalAsset.MultiTenant && technicalAsset.Confidentiality < types.Confidential && technicalAsset.Integrity < types.Critical && technicalAsset.Availability < types.Critical { return true } return false } func (r *MissingIdentityPropagationRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingAccess *types.CommunicationLink, moreRisky bool) *types.Risk { impact := types.LowImpact if moreRisky { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: "<b>Missing End User Identity Propagation</b> over communication link <b>" + incomingAccess.Title + "</b> " + "from <b>" + input.TechnicalAssets[incomingAccess.SourceId].Title + "</b> " + "to <b>" + technicalAsset.Title + "</b>", MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: incomingAccess.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + incomingAccess.Id + "@" + input.TechnicalAssets[incomingAccess.SourceId].Id + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/path_traversal_rule.go
pkg/risks/builtin/path_traversal_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type PathTraversalRule struct{} func NewPathTraversalRule() *PathTraversalRule { return &PathTraversalRule{} } func (*PathTraversalRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "path-traversal", Title: "Path-Traversal", Description: "When a filesystem is accessed Path-Traversal or Local-File-Inclusion (LFI) risks might arise. " + "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", Impact: "If this risk is unmitigated, attackers might be able to read sensitive files (configuration data, key/credential files, deployment files, " + "business data files, etc.) from the filesystem of affected components.", ASVS: "V12 - File and Resources Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html", Action: "Path-Traversal Prevention", Mitigation: "Before accessing the file cross-check that it resides in the expected folder and is of the expected " + "type and filename/suffix. Try to use a mapping if possible instead of directly accessing by a filename which is " + "(partly or fully) provided by the caller. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.InformationDisclosure, DetectionLogic: "Filesystems accessed by in-scope callers.", RiskAssessment: "The risk rating depends on the sensitivity of the data stored inside the technical asset.", FalsePositives: "File accesses by filenames not consisting of parts controllable by the caller can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 22, } } func (*PathTraversalRule) SupportedTags() []string { return []string{} } func (r *PathTraversalRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if !technicalAsset.Technologies.GetAttribute(types.IsFileStorage) { continue } incomingFlows := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, incomingFlow := range incomingFlows { if input.TechnicalAssets[incomingFlow.SourceId].OutOfScope { continue } likelihood := types.VeryLikely if incomingFlow.Usage == types.DevOps { likelihood = types.Likely } risks = append(risks, r.createRisk(input, technicalAsset, incomingFlow, likelihood)) } } return risks, nil } func (r *PathTraversalRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingFlow *types.CommunicationLink, likelihood types.RiskExploitationLikelihood) *types.Risk { caller := input.TechnicalAssets[incomingFlow.SourceId] title := "<b>Path-Traversal</b> risk at <b>" + caller.Title + "</b> against filesystem <b>" + technicalAsset.Title + "</b>" + " via <b>" + incomingFlow.Title + "</b>" impact := types.MediumImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.HighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: caller.Id, MostRelevantCommunicationLinkId: incomingFlow.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + caller.Id + "@" + technicalAsset.Id + "@" + incomingFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_vault_isolation_rule.go
pkg/risks/builtin/missing_vault_isolation_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingVaultIsolationRule struct{} func NewMissingVaultIsolationRule() *MissingVaultIsolationRule { return &MissingVaultIsolationRule{} } func (*MissingVaultIsolationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-vault-isolation", Title: "Missing Vault Isolation", Description: "Highly sensitive vault assets and their data stores should be isolated from other assets " + "by their own network segmentation trust-boundary (" + types.ExecutionEnvironment.String() + " boundaries do not count as network isolation).", Impact: "If this risk is unmitigated, attackers successfully attacking other components of the system might have an easy path towards " + "highly sensitive vault assets and their data stores, as they are not separated by network segmentation.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Network Segmentation", Mitigation: "Apply a network segmentation trust-boundary around the highly sensitive vault assets and their data stores.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope vault assets " + "when surrounded by other (not vault-related) assets (without a network trust-boundary in-between). " + "This risk is especially prevalent when other non-vault related assets are within the same execution environment (i.e. same database or same application server).", RiskAssessment: "Default is " + types.MediumImpact.String() + " impact. The impact is increased to " + types.HighImpact.String() + " when the asset missing the " + "trust-boundary protection is rated as " + types.StrictlyConfidential.String() + " or " + types.MissionCritical.String() + ".", FalsePositives: "When all assets within the network segmentation trust-boundary are hardened and protected to the same extend as if all were " + "vaults with data of highest sensitivity.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*MissingVaultIsolationRule) SupportedTags() []string { return []string{} } func (r *MissingVaultIsolationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if technicalAsset.OutOfScope || !technicalAsset.Technologies.GetAttribute(types.Vault) { continue } moreImpact := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical || technicalAsset.Availability == types.MissionCritical sameExecutionEnv := false createRiskEntry := false // now check for any other same-network assets of non-vault-related types for sparringAssetCandidateId := range input.TechnicalAssets { // so inner loop again over all assets if technicalAsset.Id == sparringAssetCandidateId { continue } sparringAssetCandidate := input.TechnicalAssets[sparringAssetCandidateId] if sparringAssetCandidate.Technologies.GetAttribute(types.Vault) || isVaultStorage(input, technicalAsset, sparringAssetCandidate) { continue } if isSameExecutionEnvironment(input, technicalAsset, sparringAssetCandidateId) { createRiskEntry = true sameExecutionEnv = true } else if isSameTrustBoundaryNetworkOnly(input, technicalAsset, sparringAssetCandidateId) { createRiskEntry = true } } if createRiskEntry { risks = append(risks, r.createRisk(technicalAsset, moreImpact, sameExecutionEnv)) } } return risks, nil } func isVaultStorage(parsedModel *types.Model, vault *types.TechnicalAsset, storage *types.TechnicalAsset) bool { return storage.Type == types.Datastore && parsedModel.HasDirectConnection(vault, storage.Id) } func (r *MissingVaultIsolationRule) createRisk(techAsset *types.TechnicalAsset, moreImpact bool, sameExecutionEnv bool) *types.Risk { impact := types.MediumImpact likelihood := types.Unlikely others := "<b>in the same network segment</b>" if moreImpact { impact = types.HighImpact } if sameExecutionEnv { likelihood = types.Likely others = "<b>in the same execution environment</b>" } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: "<b>Missing Vault Isolation</b> to further encapsulate and protect vault-related asset <b>" + techAsset.Title + "</b> against unrelated " + "lower protected assets " + others + ", which might be easier to compromise by attackers", MostRelevantTechnicalAssetId: techAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{techAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + techAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_build_infrastructure_rule.go
pkg/risks/builtin/missing_build_infrastructure_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingBuildInfrastructureRule struct{} func NewMissingBuildInfrastructureRule() *MissingBuildInfrastructureRule { return &MissingBuildInfrastructureRule{} } func (*MissingBuildInfrastructureRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-build-infrastructure", Title: "Missing Build Infrastructure", Description: "The modeled architecture does not contain a build infrastructure (devops-client, sourcecode-repo, build-pipeline, etc.), " + "which might be the risk of a model missing critical assets (and thus not seeing their risks). " + "If the architecture contains custom-developed parts, the pipeline where code gets developed " + "and built needs to be part of the model.", Impact: "If this risk is unmitigated, attackers might be able to exploit risks unseen in this threat model due to " + "critical build infrastructure components missing in the model.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Build Pipeline Hardening", Mitigation: "Include the build infrastructure in the model.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Tampering, DetectionLogic: "Models with in-scope custom-developed parts missing in-scope development (code creation) and build infrastructure " + "components (devops-client, sourcecode-repo, build-pipeline, etc.).", RiskAssessment: "The risk rating depends on the highest sensitivity of the in-scope assets running custom-developed parts.", FalsePositives: "Models not having any custom-developed parts " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: true, CWE: 1127, } } func (*MissingBuildInfrastructureRule) SupportedTags() []string { return []string{} } func (r *MissingBuildInfrastructureRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) hasCustomDevelopedParts, hasBuildPipeline, hasSourcecodeRepo, hasDevOpsClient := false, false, false, false impact := types.LowImpact var mostRelevantAsset *types.TechnicalAsset for _, id := range input.SortedTechnicalAssetIDs() { // use the sorted one to always get the same tech asset with the highest sensitivity as example asset technicalAsset := input.TechnicalAssets[id] getTechFlags(technicalAsset, &hasBuildPipeline, &hasSourcecodeRepo, &hasDevOpsClient) if r.skipAsset(technicalAsset) { continue } hasCustomDevelopedParts = true if impact == types.LowImpact { mostRelevantAsset = technicalAsset evaluateImpactFromHighestCIAValues(input, technicalAsset, &impact) } evaluateImpactFromTechnicalAssetCIAValues(technicalAsset, &impact) // just for referencing the most interesting asset if technicalAsset.HighestSensitivityScore() > mostRelevantAsset.HighestSensitivityScore() { mostRelevantAsset = technicalAsset } } hasBuildInfrastructure := hasBuildPipeline && hasSourcecodeRepo && hasDevOpsClient if hasCustomDevelopedParts && !hasBuildInfrastructure { risks = append(risks, r.createRisk(mostRelevantAsset, impact)) } return risks, nil } func (r *MissingBuildInfrastructureRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { if !technicalAsset.CustomDevelopedParts || technicalAsset.OutOfScope { return true } return false } func evaluateImpactFromHighestCIAValues(input *types.Model, technicalAsset *types.TechnicalAsset, impact *types.RiskExploitationImpact) { if input.HighestProcessedConfidentiality(technicalAsset) >= types.Confidential || input.HighestProcessedIntegrity(technicalAsset) >= types.Critical || input.HighestProcessedAvailability(technicalAsset) >= types.Critical { *impact = types.MediumImpact } } func evaluateImpactFromTechnicalAssetCIAValues(technicalAsset *types.TechnicalAsset, impact *types.RiskExploitationImpact) { if technicalAsset.Confidentiality >= types.Confidential || technicalAsset.Integrity >= types.Critical || technicalAsset.Availability >= types.Critical { *impact = types.MediumImpact } } func getTechFlags(technicalAsset *types.TechnicalAsset, hasBuildPipeline, hasSourcecodeRepo, hasDevOpsClient *bool) { if technicalAsset.Technologies.GetAttribute(types.BuildPipeline) { *hasBuildPipeline = true } if technicalAsset.Technologies.GetAttribute(types.SourcecodeRepository) { *hasSourcecodeRepo = true } if technicalAsset.Technologies.GetAttribute(types.DevOpsClient) { *hasDevOpsClient = true } } func (r *MissingBuildInfrastructureRule) createRisk(technicalAsset *types.TechnicalAsset, impact types.RiskExploitationImpact) *types.Risk { title := "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>" + technicalAsset.Title + "</b> as an example)" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/incomplete_model_rule_test.go
pkg/risks/builtin/incomplete_model_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestIncompleteModelRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestIncompleteModelRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestIncompleteModelRuleGenerateRisksTechnicalAssetWithKnownTechnologiesAndWithoutCommunicationLinksNoRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.UnknownTechnology: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestIncompleteModelRuleGenerateRisksTechnicalAssetContainTechnologyWithoutAttributesRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "tool", }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unknown Technology</b> specified at technical asset <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestIncompleteModelRuleGenerateRisksTechnicalAssetContainUnknownTechnologiesRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "unknown", Attributes: map[string]bool{ types.UnknownTechnology: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unknown Technology</b> specified at technical asset <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestIncompleteModelRuleGenerateRisksNoTechnologySpecifiedRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unknown Technology</b> specified at technical asset <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestIncompleteModelRuleGenerateRisksKnownProtocolCommunicationLinksNoRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.UnknownTechnology: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", Protocol: types.HTTPS, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestIncompleteModelRuleGenerateRisksUnknownProtocolCommunicationLinksRisksCreated(t *testing.T) { rule := NewIncompleteModelRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.UnknownTechnology: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", Protocol: types.UnknownProtocol, }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unknown Protocol</b> specified for communication link <b>Test Communication Link</b> at technical asset <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_vault_rule.go
pkg/risks/builtin/missing_vault_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingVaultRule struct{} func NewMissingVaultRule() *MissingVaultRule { return &MissingVaultRule{} } func (*MissingVaultRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-vault", Title: "Missing Vault (Secret Storage)", Description: "In order to avoid the risk of secret leakage via config files (when attacked through vulnerabilities being able to " + "read files like Path-Traversal and others), it is best practice to use a separate hardened process with proper authentication, " + "authorization, and audit logging to access config secrets (like credentials, private keys, client certificates, etc.). " + "This component is usually some kind of Vault.", Impact: "If this risk is unmitigated, attackers might be able to easier steal config secrets (like credentials, private keys, client certificates, etc.) once " + "a vulnerability to access files is present and exploited.", ASVS: "V6 - Stored Cryptography Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html", Action: "Vault (Secret Storage)", Mitigation: "Consider using a Vault (Secret Storage) to securely store and access config secrets (like credentials, private keys, client certificates, etc.).", Check: "GetAttribute a Vault (Secret Storage) in place?", Function: types.Architecture, STRIDE: types.InformationDisclosure, DetectionLogic: "Models without a Vault (Secret Storage).", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Models where no technical assets have any kind of sensitive config data to protect " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: true, CWE: 522, } } func (*MissingVaultRule) SupportedTags() []string { return []string{} } func (r *MissingVaultRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) hasVault := false var mostRelevantAsset *types.TechnicalAsset impact := types.LowImpact for _, id := range input.SortedTechnicalAssetIDs() { // use the sorted one to always get the same tech asset with the highest sensitivity as example asset techAsset := input.TechnicalAssets[id] if techAsset.Technologies.GetAttribute(types.Vault) { hasVault = true break } if input.HighestProcessedConfidentiality(techAsset) >= types.Confidential || input.HighestProcessedIntegrity(techAsset) >= types.Critical || input.HighestProcessedAvailability(techAsset) >= types.Critical { impact = types.MediumImpact } if techAsset.Confidentiality >= types.Confidential || techAsset.Integrity >= types.Critical || techAsset.Availability >= types.Critical { impact = types.MediumImpact } // just for referencing the most interesting asset if mostRelevantAsset == nil || techAsset.HighestSensitivityScore() > mostRelevantAsset.HighestSensitivityScore() { mostRelevantAsset = techAsset } } if !hasVault { risks = append(risks, r.createRisk(mostRelevantAsset, impact)) } return risks, nil } func (r *MissingVaultRule) createRisk(technicalAsset *types.TechnicalAsset, impact types.RiskExploitationImpact) *types.Risk { title := "<b>Missing Vault (Secret Storage)</b> in the threat model" id := "no-components" if technicalAsset != nil { title += " (referencing asset <b>" + technicalAsset.Title + "</b> as an example)" id = technicalAsset.Id } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/wrong_trust_boundary_content_rule_test.go
pkg/risks/builtin/wrong_trust_boundary_content_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestWrongTrustBoundaryContentRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewWrongTrustBoundaryContentRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type WrongTrustBoundaryContentRuleTest struct { tbType types.TrustBoundaryType machine types.TechnicalAssetMachine riskCreated bool } func TestWrongTrustBoundaryContentRuleSendDataAssetRisksCreated(t *testing.T) { testCases := map[string]WrongTrustBoundaryContentRuleTest{ "NetworkOnPrem": { tbType: types.NetworkOnPrem, riskCreated: false, }, "NetworkDedicatedHoster": { tbType: types.NetworkDedicatedHoster, riskCreated: false, }, "NetworkVirtualLAN": { tbType: types.NetworkVirtualLAN, riskCreated: false, }, "NetworkCloudProvider": { tbType: types.NetworkCloudProvider, riskCreated: false, }, "NetworkCloudSecurityGroup": { tbType: types.NetworkCloudSecurityGroup, riskCreated: false, }, "ExecutionEnvironment": { tbType: types.ExecutionEnvironment, riskCreated: false, }, "container": { tbType: types.NetworkPolicyNamespaceIsolation, machine: types.Container, riskCreated: false, }, "serverless": { tbType: types.NetworkPolicyNamespaceIsolation, machine: types.Serverless, riskCreated: false, }, "virtual": { tbType: types.NetworkPolicyNamespaceIsolation, machine: types.Virtual, riskCreated: true, }, "physical": { tbType: types.NetworkPolicyNamespaceIsolation, machine: types.Physical, riskCreated: true, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewWrongTrustBoundaryContentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta": { Id: "ta", Title: "Test Technical Asset", Machine: testCase.machine, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": { Type: testCase.tbType, TechnicalAssetsInside: []string{"ta"}, }, }, }) assert.Nil(t, err) if testCase.riskCreated { assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Wrong Trust Boundary Content</b> (non-container asset inside container trust boundary) at <b>%s</b>", "Test Technical Asset") assert.Equal(t, expTitle, risks[0].Title) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/cross_site_request_forgery_rule.go
pkg/risks/builtin/cross_site_request_forgery_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type CrossSiteRequestForgeryRule struct{} func NewCrossSiteRequestForgeryRule() *CrossSiteRequestForgeryRule { return &CrossSiteRequestForgeryRule{} } func (*CrossSiteRequestForgeryRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "cross-site-request-forgery", Title: "Cross-Site Request Forgery (CSRF)", Description: "When a web application is accessed via web protocols Cross-Site Request Forgery (CSRF) risks might arise.", Impact: "If this risk remains unmitigated, attackers might be able to trick logged-in victim users into unwanted actions within the web application " + "by visiting an attacker controlled web site.", ASVS: "V4 - Access Control Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html", Action: "CSRF Prevention", Mitigation: "Try to use anti-CSRF tokens ot the double-submit patterns (at least for logged-in requests). " + "When your authentication scheme depends on cookies (like session or token cookies), consider marking them with " + "the same-site flag. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Spoofing, DetectionLogic: "In-scope web applications accessed via typical web access protocols.", RiskAssessment: "The risk rating depends on the integrity rating of the data sent across the communication link.", FalsePositives: "Web applications passing the authentication state via custom headers instead of cookies can " + "eventually be false positives. Also when the web application " + "is not accessed via a browser-like component (i.e not by a human user initiating the request that " + "gets passed through all components until it reaches the web application) this can be considered a false positive.", ModelFailurePossibleReason: false, CWE: 352, } } func (*CrossSiteRequestForgeryRule) SupportedTags() []string { return []string{} } func (r *CrossSiteRequestForgeryRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { technicalAsset := parsedModel.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } incomingFlows := parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, incomingFlow := range incomingFlows { if !incomingFlow.Protocol.IsPotentialWebAccessProtocol() { continue } risks = append(risks, r.createRisk(parsedModel, technicalAsset, incomingFlow)) } } return risks, nil } func (csrf CrossSiteRequestForgeryRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return technicalAsset.OutOfScope || !technicalAsset.Technologies.GetAttribute(types.WebApplication) } func (r *CrossSiteRequestForgeryRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset, incomingFlow *types.CommunicationLink) *types.Risk { sourceAsset := parsedModel.TechnicalAssets[incomingFlow.SourceId] title := "<b>Cross-Site Request Forgery (CSRF)</b> risk at <b>" + technicalAsset.Title + "</b> via <b>" + incomingFlow.Title + "</b> from <b>" + sourceAsset.Title + "</b>" impact := types.LowImpact if parsedModel.HighestCommunicationLinkIntegrity(incomingFlow) == types.MissionCritical { impact = types.MediumImpact } likelihood := r.likelihoodFromUsage(incomingFlow) risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: incomingFlow.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id + "@" + incomingFlow.Id return risk } func (*CrossSiteRequestForgeryRule) likelihoodFromUsage(cl *types.CommunicationLink) types.RiskExploitationLikelihood { if cl.Usage == types.DevOps { return types.Likely } return types.VeryLikely }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unencrypted_asset_rule_test.go
pkg/risks/builtin/unencrypted_asset_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnencryptedAssetRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnencryptedAssetRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type UnencryptedAssetRuleTest struct { isEmbeddedComponent bool isNoStorageAtRest bool isUsuallyStoringEndUserData bool storedAnyData bool outOfScope bool encryption types.EncryptionStyle dataConfidentiality types.Confidentiality dataIntegrity types.Criticality riskCreated bool expectedImpact types.RiskExploitationImpact expectedSuffixTitle string } func TestUnencryptedAssetRuleGenerateRisks(t *testing.T) { testCases := map[string]UnencryptedAssetRuleTest{ "out of scope": { outOfScope: true, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, riskCreated: false, }, "encryption waiver because no storage at rest": { outOfScope: false, isNoStorageAtRest: true, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, riskCreated: false, }, "encryption waiver because embedded component": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: true, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, riskCreated: false, }, "do not store any data": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: false, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, riskCreated: false, }, "confidentiality restricted and integrity operational": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.Restricted, dataIntegrity: types.Operational, riskCreated: false, }, "encrypted not very sensitive": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.Confidential, dataIntegrity: types.Critical, encryption: types.Transparent, riskCreated: false, }, "very sensitive end user individual Key": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, encryption: types.DataWithEndUserIndividualKey, riskCreated: false, }, "not very sensitive no encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.Confidential, dataIntegrity: types.Critical, encryption: types.NoneEncryption, riskCreated: true, expectedImpact: types.MediumImpact, }, "very sensitive strictly confidential no encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.Critical, encryption: types.NoneEncryption, riskCreated: true, expectedImpact: types.HighImpact, }, "very sensitive mission critical no encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, storedAnyData: true, dataConfidentiality: types.Confidential, dataIntegrity: types.MissionCritical, encryption: types.NoneEncryption, riskCreated: true, expectedImpact: types.HighImpact, }, "very sensitive transparent encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, isUsuallyStoringEndUserData: true, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, encryption: types.Transparent, riskCreated: true, expectedImpact: types.MediumImpact, expectedSuffixTitle: " missing end user individual encryption with data-with-end-user-individual-key", }, "very sensitive DataWithSymmetricSharedKey encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, isUsuallyStoringEndUserData: true, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, encryption: types.DataWithSymmetricSharedKey, riskCreated: true, expectedImpact: types.MediumImpact, expectedSuffixTitle: " missing end user individual encryption with data-with-end-user-individual-key", }, "very sensitive DataWithAsymmetricSharedKey encryption": { outOfScope: false, isNoStorageAtRest: false, isEmbeddedComponent: false, isUsuallyStoringEndUserData: true, storedAnyData: true, dataConfidentiality: types.StrictlyConfidential, dataIntegrity: types.MissionCritical, encryption: types.DataWithAsymmetricSharedKey, riskCreated: true, expectedImpact: types.MediumImpact, expectedSuffixTitle: " missing end user individual encryption with data-with-end-user-individual-key", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnencryptedAssetRule() dataAssetsStore := []string{} if testCase.storedAnyData { dataAssetsStore = append(dataAssetsStore, "da1") } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: testCase.outOfScope, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsEmbeddedComponent: testCase.isEmbeddedComponent, types.IsNoStorageAtRest: testCase.isNoStorageAtRest, types.IsUsuallyStoringEndUserData: testCase.isUsuallyStoringEndUserData, }, }, }, DataAssetsStored: dataAssetsStore, Encryption: testCase.encryption, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Confidentiality: testCase.dataConfidentiality, Integrity: testCase.dataIntegrity, }, }, }) assert.Nil(t, err) if testCase.riskCreated { assert.NotEmpty(t, risks) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expectedMessage := fmt.Sprintf("<b>Unencrypted Technical Asset</b> named <b>Test Technical Asset</b>%s", testCase.expectedSuffixTitle) assert.Equal(t, risks[0].Title, expectedMessage) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/push_instead_of_pull_deployment_rule.go
pkg/risks/builtin/push_instead_of_pull_deployment_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type PushInsteadPullDeploymentRule struct{} func NewPushInsteadPullDeploymentRule() *PushInsteadPullDeploymentRule { return &PushInsteadPullDeploymentRule{} } func (*PushInsteadPullDeploymentRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "push-instead-of-pull-deployment", Title: "Push instead of Pull Deployment", Description: "When comparing push-based vs. pull-based deployments from a security perspective, pull-based " + "deployments improve the overall security of the deployment targets. Every exposed interface of a production system to accept a deployment " + "increases the attack surface of the production system, thus a pull-based approach exposes less attack surface relevant " + "interfaces.", Impact: "If this risk is unmitigated, attackers might have more potential target vectors for attacks, as the overall attack surface is " + "unnecessarily increased.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Build Pipeline Hardening", Mitigation: "Try to prefer pull-based deployments (like GitOps scenarios offer) over push-based deployments to reduce the attack surface of the production system.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Tampering, DetectionLogic: "Models with build pipeline components accessing in-scope targets of deployment (in a non-readonly way) which " + "are not build-related components themselves.", RiskAssessment: "The risk rating depends on the highest sensitivity of the deployment targets running custom-developed parts.", FalsePositives: "Communication links that are not deployment paths " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: true, CWE: 1127, } } func (*PushInsteadPullDeploymentRule) SupportedTags() []string { return []string{} } func (r *PushInsteadPullDeploymentRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) impact := types.LowImpact for _, buildPipeline := range input.TechnicalAssets { if !buildPipeline.Technologies.GetAttribute(types.BuildPipeline) { continue } for _, deploymentLink := range buildPipeline.CommunicationLinks { targetAsset := input.TechnicalAssets[deploymentLink.TargetId] if deploymentLink.Readonly || deploymentLink.Usage != types.DevOps { continue } if targetAsset.OutOfScope { continue } if targetAsset.Technologies.GetAttribute(types.IsDevelopmentRelevant) || targetAsset.Usage == types.DevOps { continue } if input.HighestProcessedConfidentiality(targetAsset) >= types.Confidential || input.HighestProcessedIntegrity(targetAsset) >= types.Critical || input.HighestProcessedAvailability(targetAsset) >= types.Critical { impact = types.MediumImpact } risks = append(risks, r.createRisk(buildPipeline, targetAsset, deploymentLink, impact)) } } return risks, nil } func (r *PushInsteadPullDeploymentRule) createRisk(buildPipeline *types.TechnicalAsset, deploymentTarget *types.TechnicalAsset, deploymentCommLink *types.CommunicationLink, impact types.RiskExploitationImpact) *types.Risk { title := "<b>Push instead of Pull Deployment</b> at <b>" + deploymentTarget.Title + "</b> via build pipeline asset <b>" + buildPipeline.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: deploymentTarget.Id, MostRelevantCommunicationLinkId: deploymentCommLink.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{deploymentTarget.Id}, } risk.SyntheticId = risk.CategoryId + "@" + buildPipeline.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/incomplete_model_rule.go
pkg/risks/builtin/incomplete_model_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type IncompleteModelRule struct{} func NewIncompleteModelRule() *IncompleteModelRule { return &IncompleteModelRule{} } func (*IncompleteModelRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "incomplete-model", Title: "Incomplete Model", Description: "When the threat model contains unknown technologies or transfers data over unknown protocols, this is " + "an indicator for an incomplete model.", Impact: "If this risk is unmitigated, other risks might not be noticed as the model is incomplete.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html", Action: "Threat Modeling Completeness", Mitigation: "Try to find out what technology or protocol is used instead of specifying that it is unknown.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.InformationDisclosure, DetectionLogic: "All technical assets and communication links with technology type or protocol type specified as unknown.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*IncompleteModelRule) SupportedTags() []string { return []string{} } func (r *IncompleteModelRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } if technicalAsset.Technologies.IsUnknown() { risks = append(risks, r.createRiskTechAsset(technicalAsset)) } for _, commLink := range technicalAsset.CommunicationLinks { if commLink.Protocol == types.UnknownProtocol { risks = append(risks, r.createRiskCommLink(technicalAsset, commLink)) } } } return risks, nil } func (im IncompleteModelRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return technicalAsset.OutOfScope } func (r *IncompleteModelRule) createRiskTechAsset(technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Unknown Technology</b> specified at technical asset <b>" + technicalAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk } func (r *IncompleteModelRule) createRiskCommLink(technicalAsset *types.TechnicalAsset, commLink *types.CommunicationLink) *types.Risk { title := "<b>Unknown Protocol</b> specified for communication link <b>" + commLink.Title + "</b> at technical asset <b>" + technicalAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: commLink.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + commLink.Id + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unguarded_access_from_internet_rule.go
pkg/risks/builtin/unguarded_access_from_internet_rule.go
package builtin import ( "sort" "github.com/threagile/threagile/pkg/types" ) type UnguardedAccessFromInternetRule struct{} func NewUnguardedAccessFromInternetRule() *UnguardedAccessFromInternetRule { return &UnguardedAccessFromInternetRule{} } func (*UnguardedAccessFromInternetRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unguarded-access-from-internet", Title: "Unguarded Access From Internet", Description: "Internet-exposed assets must be guarded by a protecting service, application, " + "or reverse-proxy.", Impact: "If this risk is unmitigated, attackers might be able to directly attack sensitive systems without any hardening components in-between " + "due to them being directly exposed on the internet.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Encapsulation of Technical Asset", Mitigation: "Encapsulate the asset behind a guarding service, application, or reverse-proxy. " + "For admin maintenance a bastion-host should be used as a jump-server. " + "For file transfer a store-and-forward-host should be used as an indirect file exchange platform.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets (excluding " + types.LoadBalancer + ") with confidentiality rating " + "of " + types.Confidential.String() + " (or higher) or with integrity rating of " + types.Critical.String() + " (or higher) when " + "accessed directly from the internet. All " + types.WebServer + ", " + types.WebApplication + ", " + types.ReverseProxy + ", " + types.WAF + ", and " + types.Gateway + " assets are exempted from this risk when " + "they do not consist of custom developed code and " + "the data-flow only consists of HTTP or FTP protocols. Access from " + types.Monitoring + " systems " + "as well as VPN-protected connections are exempted.", RiskAssessment: "The matching technical assets are at " + types.LowSeverity.String() + " risk. When either the " + "confidentiality rating is " + types.StrictlyConfidential.String() + " or the integrity rating " + "is " + types.MissionCritical.String() + ", the risk-rating is considered " + types.MediumSeverity.String() + ". " + "For assets with RAA values higher than 40 % the risk-rating increases.", FalsePositives: "When other means of filtering client requests are applied equivalent of " + types.ReverseProxy + ", " + types.WAF + ", or " + types.Gateway + " components.", ModelFailurePossibleReason: false, CWE: 501, } } func (*UnguardedAccessFromInternetRule) SupportedTags() []string { return []string{} } func (r *UnguardedAccessFromInternetRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope { continue } commLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] sort.Sort(types.ByTechnicalCommunicationLinkIdSort(commLinks)) for _, incomingAccess := range commLinks { if technicalAsset.Technologies.GetAttribute(types.LoadBalancer) { continue } if !technicalAsset.CustomDevelopedParts && ((technicalAsset.Technologies.GetAttribute(types.IsHTTPInternetAccessOK) && (incomingAccess.Protocol == types.HTTP || incomingAccess.Protocol == types.HTTPS)) || (technicalAsset.Technologies.GetAttribute(types.IsFTPInternetAccessOK) && (incomingAccess.Protocol == types.FTP || incomingAccess.Protocol == types.FTPS || incomingAccess.Protocol == types.SFTP))) { continue } if input.TechnicalAssets[incomingAccess.SourceId].Technologies.GetAttribute(types.Monitoring) || incomingAccess.VPN { continue } if technicalAsset.Confidentiality < types.Confidential && technicalAsset.Integrity < types.Critical { continue } if !input.TechnicalAssets[incomingAccess.SourceId].Internet { continue } highRisk := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical risks = append(risks, r.createRisk(technicalAsset, incomingAccess, input.TechnicalAssets[incomingAccess.SourceId], highRisk)) } } return risks, nil } func (r *UnguardedAccessFromInternetRule) createRisk(dataStore *types.TechnicalAsset, dataFlow *types.CommunicationLink, clientFromInternet *types.TechnicalAsset, moreRisky bool) *types.Risk { impact := types.LowImpact if moreRisky || dataStore.RAA > 40 { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.VeryLikely, impact), ExploitationLikelihood: types.VeryLikely, ExploitationImpact: impact, Title: "<b>Unguarded Access from Internet</b> of <b>" + dataStore.Title + "</b> by <b>" + clientFromInternet.Title + "</b>" + " via <b>" + dataFlow.Title + "</b>", MostRelevantTechnicalAssetId: dataStore.Id, MostRelevantCommunicationLinkId: dataFlow.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: []string{dataStore.Id}, } risk.SyntheticId = risk.CategoryId + "@" + dataStore.Id + "@" + clientFromInternet.Id + "@" + dataFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/dos_risky_access_across_trust_boundary_rule_test.go
pkg/risks/builtin/dos_risky_access_across_trust_boundary_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksTechAssetNotLoadBalancerNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.LoadBalancer: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksTechAssetLessCriticalAvailabilityNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Availability: types.Important, Technologies: types.TechnologyList{ { Name: "elb", Attributes: map[string]bool{ types.LoadBalancer: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksDirectAccessDevOpsUsageNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, "ta2": { Id: "ta2", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Usage: types.DevOps, }, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": { Id: "tb1", Type: types.NetworkCloudProvider, }, "ta2": { Id: "tb2", Type: types.NetworkCloudProvider, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksDirectAccessUsingLocalProcessProtocolNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, "ta2": { Id: "ta2", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Usage: types.Business, Protocol: types.LocalFileAccess, }, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": { Id: "tb1", }, "ta2": { Id: "tb2", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksDirectAccessUsingHTTPNotAcrossTrustBoundaryNetworkProtocolNotRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, "ta2": { Id: "ta2", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Usage: types.Business, Protocol: types.HTTP, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksAcrossTrustBoundaryBusinessNonLocalProcessRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Web Application", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, }, "ta2": { Id: "ta2", Title: "Second Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Title: "Direct Call", Usage: types.Business, Protocol: types.HTTP, }, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": { Id: "tb1", }, "ta2": { Id: "tb2", }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, 1, len(risks)) assert.Equal(t, "<b>Denial-of-Service</b> risky access of <b>First Web Application</b> by <b>Second Web Application</b> via <b>Direct Call</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksMissionCriticalMediumRiskRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Web Application", Availability: types.MissionCritical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, Redundant: false, }, "ta2": { Id: "ta2", Title: "Second Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Title: "Direct Call", Usage: types.Business, Protocol: types.HTTP, }, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": { Id: "tb1", }, "ta2": { Id: "tb2", }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, 1, len(risks)) assert.Equal(t, "<b>Denial-of-Service</b> risky access of <b>First Web Application</b> by <b>Second Web Application</b> via <b>Direct Call</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestDosRiskyAccessAcrossTrustBoundaryRuleGenerateRisksWithLoadBalancerMultipleRisksCreated(t *testing.T) { rule := NewDosRiskyAccessAcrossTrustBoundaryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, }, "elb": { Id: "elb", Title: "Load balancer", Availability: types.MissionCritical, Technologies: types.TechnologyList{ { Name: "load-balancer", Attributes: map[string]bool{ types.IsTrafficForwarding: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Second Web Application", Availability: types.Critical, Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "elb": { { Id: "elb", TargetId: "elb", SourceId: "ta1", Title: "Call to load balancer", Usage: types.Business, Protocol: types.HTTP, }, }, "ta2": { { Id: "ta2", TargetId: "ta2", SourceId: "elb", Title: "Forwarded call to second web application", Usage: types.Business, Protocol: types.HTTP, }, }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": { Id: "tb1", }, "elb": { Id: "tb2", }, "ta2": { Id: "tb2", }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, 2, len(risks)) assert.Equal(t, "<b>Denial-of-Service</b> risky access of <b>Load balancer</b> by <b>First Web Application</b> via <b>Call to load balancer</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Denial-of-Service</b> risky access of <b>Second Web Application</b> by <b>First Web Application</b> via <b>Call to load balancer</b> forwarded via <b>Load balancer</b>", risks[1].Title) assert.Equal(t, types.LowImpact, risks[1].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/search_query_injection_rule_test.go
pkg/risks/builtin/search_query_injection_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestSearchQueryInjectionRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestSearchQueryInjectionRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestSearchQueryInjectionRuleGenerateRisksNotSearchRelatedNoRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestSearchQueryInjectionRuleGenerateRisksNoIncomingCommunicationLinkNoRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestSearchQueryInjectionRuleGenerateRisksCallerOutOfScopeNoRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Protocol: types.HTTP, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestSearchQueryInjectionRuleGenerateRisksNoHTTPOrBinaryCommunicationNoRisksCreated(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Protocol: types.JDBC, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type SearchQueryInjectionRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality protocol types.Protocol usage types.Usage expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood } func TestSearchQueryInjectionRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]SearchQueryInjectionRuleTest{ "medium impact": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.HTTP, usage: types.Business, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "strictly confidential medium impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, protocol: types.HTTP, usage: types.Business, expectedImpact: types.HighImpact, expectedLikelihood: types.VeryLikely, }, "mission critical integrity medium impact": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.HTTP, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "low impact": { confidentiality: types.Internal, integrity: types.Operational, protocol: types.HTTP, usage: types.Business, expectedImpact: types.LowImpact, expectedLikelihood: types.VeryLikely, }, "HTTPS protocol": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.HTTPS, usage: types.Business, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "Binary protocol": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.BINARY, usage: types.Business, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "Binary encrypted protocol": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.BinaryEncrypted, usage: types.Business, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "devops usage": { confidentiality: types.Confidential, integrity: types.Critical, protocol: types.BinaryEncrypted, usage: types.DevOps, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewSearchQueryInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsSearchRelated: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Call to ta1", SourceId: "ta2", Protocol: testCase.protocol, Usage: testCase.usage, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := "<b>Search Query Injection</b> risk at <b>Caller Technical Asset</b> against search engine server <b>Test Technical Asset</b> via <b>Call to ta1</b>" assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/dos_risky_access_across_trust_boundary_rule.go
pkg/risks/builtin/dos_risky_access_across_trust_boundary_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type DosRiskyAccessAcrossTrustBoundaryRule struct{} func NewDosRiskyAccessAcrossTrustBoundaryRule() *DosRiskyAccessAcrossTrustBoundaryRule { return &DosRiskyAccessAcrossTrustBoundaryRule{} } func (*DosRiskyAccessAcrossTrustBoundaryRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "dos-risky-access-across-trust-boundary", Title: "DoS-risky Access Across Trust-Boundary", Description: "Assets accessed across trust boundaries with critical or mission-critical availability rating " + "are more prone to Denial-of-Service (DoS) risks.", Impact: "If this risk remains unmitigated, attackers might be able to disturb the availability of important parts of the system.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html", Action: "Anti-DoS Measures", Mitigation: "Apply anti-DoS techniques like throttling and/or per-client load blocking with quotas. " + "Also for maintenance access routes consider applying a VPN instead of public reachable interfaces. " + "Generally applying redundancy on the targeted technical asset reduces the risk of DoS.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.DenialOfService, DetectionLogic: "In-scope technical assets (excluding " + types.LoadBalancer + ") with " + "availability rating of " + types.Critical.String() + " or higher which have incoming data-flows across a " + "network trust-boundary (excluding " + types.DevOps.String() + " usage).", RiskAssessment: "Matching technical assets with availability rating " + "of " + types.Critical.String() + " or higher are " + "at " + types.LowSeverity.String() + " risk. When the availability rating is " + types.MissionCritical.String() + " and neither a VPN nor IP filter for the incoming data-flow nor redundancy " + "for the asset is applied, the risk-rating is considered " + types.MediumSeverity.String() + ".", // TODO reduce also, when data-flow authenticated and encrypted? FalsePositives: "When the accessed target operations are not time- or resource-consuming.", ModelFailurePossibleReason: false, CWE: 400, } } func (*DosRiskyAccessAcrossTrustBoundaryRule) SupportedTags() []string { return []string{} } func (r *DosRiskyAccessAcrossTrustBoundaryRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } for _, incomingAccess := range input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] { sourceAsset := input.TechnicalAssets[incomingAccess.SourceId] if sourceAsset.Technologies.GetAttribute(types.IsTrafficForwarding) { // Now try to walk a call chain up (1 hop only) to find a caller's caller used by human callersCommLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[sourceAsset.Id] for _, callersCommLink := range callersCommLinks { risks = r.potentiallyAddRisk(input, technicalAsset, callersCommLink, incomingAccess.Id, sourceAsset.Title, risks) } } else { risks = r.potentiallyAddRisk(input, technicalAsset, incomingAccess, "", "", risks) } } } return risks, nil } func (asl DosRiskyAccessAcrossTrustBoundaryRule) skipAsset(techAsset *types.TechnicalAsset) bool { return techAsset.OutOfScope || !techAsset.Technologies.GetAttribute(types.LoadBalancer) && techAsset.Availability < types.Critical } func (r *DosRiskyAccessAcrossTrustBoundaryRule) potentiallyAddRisk( input *types.Model, technicalAsset *types.TechnicalAsset, incomingAccess *types.CommunicationLink, linkId string, hopBetween string, risks []*types.Risk) []*types.Risk { if !isAcrossTrustBoundaryNetworkOnly(input, incomingAccess) { return risks } if incomingAccess.Usage == types.DevOps { return risks } if incomingAccess.Protocol.IsProcessLocal() { return risks } highRisk := technicalAsset.Availability == types.MissionCritical && !incomingAccess.VPN && !incomingAccess.IpFiltered && !technicalAsset.Redundant risks = append(risks, r.createRisk(technicalAsset, incomingAccess, linkId, hopBetween, input.TechnicalAssets[incomingAccess.SourceId], highRisk)) return risks } func (r *DosRiskyAccessAcrossTrustBoundaryRule) createRisk(techAsset *types.TechnicalAsset, dataFlow *types.CommunicationLink, linkId string, hopBetween string, clientOutsideTrustBoundary *types.TechnicalAsset, moreRisky bool) *types.Risk { impact := types.LowImpact if moreRisky { impact = types.MediumImpact } if len(hopBetween) > 0 { hopBetween = " forwarded via <b>" + hopBetween + "</b>" } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: "<b>Denial-of-Service</b> risky access of <b>" + techAsset.Title + "</b> by <b>" + clientOutsideTrustBoundary.Title + "</b> via <b>" + dataFlow.Title + "</b>" + hopBetween, MostRelevantTechnicalAssetId: techAsset.Id, MostRelevantCommunicationLinkId: dataFlow.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + techAsset.Id + "@" + clientOutsideTrustBoundary.Id + "@" + dataFlow.Id if dataFlow.Id != linkId { risk.SyntheticId += "->" + linkId } return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unchecked_deployment_rule_test.go
pkg/risks/builtin/unchecked_deployment_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUncheckedDeploymentRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUncheckedDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUncheckedDeploymentRuleGenerateRisksNotDevelopmentRelevantNoRisksCreated(t *testing.T) { rule := NewUncheckedDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "development-relevant", Attributes: map[string]bool{ types.IsDevelopmentRelevant: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type UncheckedDeploymentRuleTest struct { dataAssetIntegrity types.Criticality targetAssetConfidentiality types.Confidentiality targetAssetIntegrity types.Criticality targetAssetAvailability types.Criticality usage types.Usage expectedImpact types.RiskExploitationImpact } func TestUncheckedDeploymentRuleGenerateRisks(t *testing.T) { testCases := map[string]UncheckedDeploymentRuleTest{ "not devops usage": { dataAssetIntegrity: types.Operational, targetAssetConfidentiality: types.Restricted, targetAssetIntegrity: types.Important, targetAssetAvailability: types.Important, usage: types.Business, expectedImpact: types.LowImpact, }, "operational data asset sent low impact": { dataAssetIntegrity: types.Operational, targetAssetConfidentiality: types.Restricted, targetAssetIntegrity: types.Important, targetAssetAvailability: types.Important, usage: types.DevOps, expectedImpact: types.LowImpact, }, "important data asset sent": { dataAssetIntegrity: types.Important, targetAssetConfidentiality: types.Restricted, targetAssetIntegrity: types.Important, targetAssetAvailability: types.Important, usage: types.DevOps, expectedImpact: types.LowImpact, }, "important data asset sent to confidental asset": { dataAssetIntegrity: types.Important, targetAssetConfidentiality: types.Confidential, targetAssetIntegrity: types.Important, targetAssetAvailability: types.Important, usage: types.DevOps, expectedImpact: types.MediumImpact, }, "important data asset sent to critical integrity asset": { dataAssetIntegrity: types.Important, targetAssetConfidentiality: types.Restricted, targetAssetIntegrity: types.Critical, targetAssetAvailability: types.Important, usage: types.DevOps, expectedImpact: types.MediumImpact, }, "important data asset sent to critical available asset": { dataAssetIntegrity: types.Important, targetAssetConfidentiality: types.Restricted, targetAssetIntegrity: types.Important, targetAssetAvailability: types.Critical, usage: types.DevOps, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUncheckedDeploymentRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "development-relevant", Attributes: map[string]bool{ types.IsDevelopmentRelevant: true, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "ta2", Usage: testCase.usage, DataAssetsSent: []string{"sent-data"}, }, }, }, "ta2": { Id: "ta2", Title: "Target Technical Asset", Confidentiality: testCase.targetAssetConfidentiality, Integrity: testCase.targetAssetIntegrity, Availability: testCase.targetAssetAvailability, }, }, DataAssets: map[string]*types.DataAsset{ "sent-data": { Integrity: testCase.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unchecked Deployment</b> risk at <b>Test Technical Asset</b>", risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/mixed_targets_on_shared_runtime_rule_test.go
pkg/risks/builtin/mixed_targets_on_shared_runtime_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMixedTargetsOnSharedRuntimeRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMixedTargetsOnSharedRuntimeRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMixedTargetsOnSharedRuntimeRuleGenerateRisksAllFrontendTechAssetNoRisksCreated(t *testing.T) { rule := NewMixedTargetsOnSharedRuntimeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "First Technical Asset", Technologies: types.TechnologyList{ { Name: "front-end", Attributes: map[string]bool{ types.IsExclusivelyFrontendRelated: true, }, }, }, }, "ta2": { Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "front-end", Attributes: map[string]bool{ types.IsExclusivelyFrontendRelated: true, }, }, }, }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "sr1": { Title: "Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMixedTargetsOnSharedRuntimeRuleGenerateRisksAllBackendTechAssetNoRisksCreated(t *testing.T) { rule := NewMixedTargetsOnSharedRuntimeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "First Technical Asset", Technologies: types.TechnologyList{ { Name: "back-end", Attributes: map[string]bool{ types.IsExclusivelyBackendRelated: true, }, }, }, }, "ta2": { Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "back-end", Attributes: map[string]bool{ types.IsExclusivelyBackendRelated: true, }, }, }, }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "sr1": { Title: "Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MixedTargetsOnSharedRuntimeRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality expectedImpact types.RiskExploitationImpact } func TestMixedTargetsOnSharedRuntimeRuleGenerateRisksMixedFrontendBackendTechAssetRiskCreated(t *testing.T) { testCases := map[string]MixedTargetsOnSharedRuntimeRuleTest{ "low impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMixedTargetsOnSharedRuntimeRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset", Technologies: types.TechnologyList{ { Name: "back-end", Attributes: map[string]bool{ types.IsExclusivelyBackendRelated: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "front-end", Attributes: map[string]bool{ types.IsExclusivelyFrontendRelated: true, }, }, }, }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "sr1": { Title: "Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := "<b>Mixed Targets on Shared Runtime</b> named <b>Shared Runtime</b> might enable attackers moving from one less valuable target to a more valuable one" assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMixedTargetsOnSharedRuntimeRuleGenerateRisksMixedTrustBoundaryRiskCreated(t *testing.T) { testCases := map[string]MixedTargetsOnSharedRuntimeRuleTest{ "low impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMixedTargetsOnSharedRuntimeRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta2"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "First Technical Asset", Technologies: types.TechnologyList{ { Name: "back-end", Attributes: map[string]bool{ types.IsExclusivelyBackendRelated: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "front-end", Attributes: map[string]bool{ types.IsExclusivelyBackendRelated: true, }, }, }, }, }, SharedRuntimes: map[string]*types.SharedRuntime{ "sr1": { Title: "Shared Runtime", TechnicalAssetsRunning: []string{"ta1", "ta2"}, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := "<b>Mixed Targets on Shared Runtime</b> named <b>Shared Runtime</b> might enable attackers moving from one less valuable target to a more valuable one" assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/container_baseimage_backdooring_rule_test.go
pkg/risks/builtin/container_baseimage_backdooring_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestContainerBaseImageBackdooringRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerBaseImageBackdooringRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerBaseImageBackdooringRuleMachineIsNotContainerNotRisksCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Machine: types.Virtual, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestContainerBaseImageBackdooringRuleMachineIsContainerRiskCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Machine: types.Container, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) } func TestContainerBaseImageBackdooringRuleGenerateRisksTechAssetProcessedConfidentialityStrictlyConfidentialDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Machine: types.Container, DataAssetsProcessed: []string{"confidential-data-asset", "strictly-confidential-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "confidential-data-asset": { Confidentiality: types.Confidential, }, "strictly-confidential-data-asset": { Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) } func TestContainerBaseImageBackdooringRuleGenerateRisksTechAssetProcessedIntegrityMissionCriticalDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Machine: types.Container, DataAssetsProcessed: []string{"critical-data-asset", "mission-critical-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "critical-data-asset": { Integrity: types.Critical, }, "mission-critical-data-asset": { Integrity: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) } func TestContainerBaseImageBackdooringRuleGenerateRisksTechAssetProcessedAvailabilityMissionCriticalDataAssetHighImpactRiskCreated(t *testing.T) { rule := NewContainerBaseImageBackdooringRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Machine: types.Container, DataAssetsProcessed: []string{"critical-data-asset", "mission-critical-data-asset"}, }, }, DataAssets: map[string]*types.DataAsset{ "critical-data-asset": { Availability: types.Critical, }, "mission-critical-data-asset": { Availability: types.MissionCritical, }, }, }) assert.Nil(t, err) assert.Equal(t, len(risks), 1) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unencrypted_communication_rule_test.go
pkg/risks/builtin/unencrypted_communication_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnencryptedCommunicationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnencryptedCommunicationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } type UnencryptedCommunicationRuleTest struct { sourceOutOfScope bool sourceUnprotectedCommunicationTolerated bool targetOutOfScope bool targetUnprotectedCommunicationTolerated bool protocol types.Protocol authentication types.Authentication vpnDataFlow bool sendAnyData bool receiveAnyData bool dataAssetConfidentiality types.Confidentiality dataAssetIntegrity types.Criticality isAcrossTrustBoundary bool riskCreated bool expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood expectedSuffixTitle string } func TestUnencryptedCommunicationRuleGenerateRisks(t *testing.T) { testCases := map[string]UnencryptedCommunicationRuleTest{ "out of scope": { sourceOutOfScope: true, targetOutOfScope: true, riskCreated: false, }, "unprotected communication tolerated for source": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: true, targetUnprotectedCommunicationTolerated: false, protocol: types.HTTP, riskCreated: false, }, "unprotected communication tolerated for target": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: true, protocol: types.HTTP, riskCreated: false, }, "no data sent or received": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: false, protocol: types.HTTP, riskCreated: false, }, "send not important data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.Restricted, dataAssetIntegrity: types.Operational, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: false, }, "send important data over VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: true, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: false, }, "send authentication data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.Credentials, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, expectedSuffixTitle: " transferring authentication data (like credentials, token, session-id, etc.)", }, "send authentication data over VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: true, authentication: types.Credentials, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, expectedSuffixTitle: " transferring authentication data (like credentials, token, session-id, etc.) (even VPN-protected connections need to encrypt their data in-transit when confidentiality is rated strictly-confidential or integrity is rated mission-critical)", }, "send high sensitive data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, }, "send important data without VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: true, expectedImpact: types.MediumImpact, }, "send high sensitive data across trust boundary": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: true, receiveAnyData: false, dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, isAcrossTrustBoundary: true, riskCreated: true, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "receive not important data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.Restricted, dataAssetIntegrity: types.Operational, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: false, }, "receive important data over VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: true, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: false, }, "receive important data without VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: true, expectedImpact: types.MediumImpact, }, "receive authentication data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.Credentials, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, expectedSuffixTitle: " transferring authentication data (like credentials, token, session-id, etc.)", }, "receive authentication data over VPN": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, vpnDataFlow: true, authentication: types.Credentials, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, expectedSuffixTitle: " transferring authentication data (like credentials, token, session-id, etc.) (even VPN-protected connections need to encrypt their data in-transit when confidentiality is rated strictly-confidential or integrity is rated mission-critical)", }, "receive high sensitive data": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, riskCreated: true, expectedImpact: types.HighImpact, }, "receive high sensitive data across trust boundary": { sourceOutOfScope: false, targetOutOfScope: false, sourceUnprotectedCommunicationTolerated: false, targetUnprotectedCommunicationTolerated: false, sendAnyData: false, receiveAnyData: true, dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, vpnDataFlow: false, authentication: types.NoneAuthentication, protocol: types.HTTP, isAcrossTrustBoundary: true, riskCreated: true, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, }, "HTTPS": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.HTTPS, riskCreated: false, }, "WSS": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.WSS, riskCreated: false, }, "JdbcEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.JdbcEncrypted, riskCreated: false, }, "OdbcEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.OdbcEncrypted, riskCreated: false, }, "NosqlAccessProtocolEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.NosqlAccessProtocolEncrypted, riskCreated: false, }, "SqlAccessProtocolEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SqlAccessProtocolEncrypted, riskCreated: false, }, "BinaryEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.BinaryEncrypted, riskCreated: false, }, "TextEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.TextEncrypted, riskCreated: false, }, "SSH": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SSH, riskCreated: false, }, "SshTunnel": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SshTunnel, riskCreated: false, }, "FTPS": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.FTPS, riskCreated: false, }, "SFTP": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SFTP, riskCreated: false, }, "SCP": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SCP, riskCreated: false, }, "LDAPS": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.LDAPS, riskCreated: false, }, "ReverseProxyWebProtocolEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.ReverseProxyWebProtocolEncrypted, riskCreated: false, }, "IiopEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.IiopEncrypted, riskCreated: false, }, "JrmpEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.JrmpEncrypted, riskCreated: false, }, "SmbEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SmbEncrypted, riskCreated: false, }, "SmtpEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.SmtpEncrypted, riskCreated: false, }, "Pop3Encrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.Pop3Encrypted, riskCreated: false, }, "ImapEncrypted": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.Pop3Encrypted, riskCreated: false, }, "InProcessLibraryCall": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.InProcessLibraryCall, riskCreated: false, }, "InterProcessCommunication": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.InterProcessCommunication, riskCreated: false, }, "LocalFileAccess": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.LocalFileAccess, riskCreated: false, }, "ContainerSpawning": { sourceOutOfScope: false, targetOutOfScope: false, protocol: types.ContainerSpawning, riskCreated: false, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnencryptedCommunicationRule() dataAssetsSend := []string{} if testCase.sendAnyData { dataAssetsSend = append(dataAssetsSend, "da1") } dataAssetsReceived := []string{} if testCase.receiveAnyData { dataAssetsReceived = append(dataAssetsReceived, "da1") } tb1 := &types.TrustBoundary{ Id: "tb1", Title: "First Trust Boundary", TechnicalAssetsInside: []string{"source", "target"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Second Trust Boundary", Type: types.NetworkCloudProvider, } if testCase.isAcrossTrustBoundary { tb1.TechnicalAssetsInside = []string{"source"} tb2.TechnicalAssetsInside = []string{"target"} } directContainingTrustBoundaryMappedByTechnicalAssetId := map[string]*types.TrustBoundary{ "source": tb1, "target": tb1, } if testCase.isAcrossTrustBoundary { directContainingTrustBoundaryMappedByTechnicalAssetId["target"] = tb2 } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: testCase.sourceOutOfScope, CommunicationLinks: []*types.CommunicationLink{ { Title: "Test Communication Link", SourceId: "source", TargetId: "target", Authentication: testCase.authentication, Protocol: testCase.protocol, DataAssetsSent: dataAssetsSend, DataAssetsReceived: dataAssetsReceived, VPN: testCase.vpnDataFlow, }, }, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: testCase.sourceUnprotectedCommunicationTolerated, }, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: testCase.targetOutOfScope, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: testCase.targetUnprotectedCommunicationTolerated, }, }, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Confidentiality: testCase.dataAssetConfidentiality, Integrity: testCase.dataAssetIntegrity, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: directContainingTrustBoundaryMappedByTechnicalAssetId, }) assert.Nil(t, err) if testCase.riskCreated { assert.NotEmpty(t, risks) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) expectedMessage := fmt.Sprintf("<b>Unencrypted Communication</b> named <b>Test Communication Link</b> between <b>Source Technical Asset</b> and <b>Target Technical Asset</b>%s", testCase.expectedSuffixTitle) assert.Equal(t, risks[0].Title, expectedMessage) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_communication_link_rule.go
pkg/risks/builtin/unnecessary_communication_link_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UnnecessaryCommunicationLinkRule struct{} func NewUnnecessaryCommunicationLinkRule() *UnnecessaryCommunicationLinkRule { return &UnnecessaryCommunicationLinkRule{} } func (*UnnecessaryCommunicationLinkRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unnecessary-communication-link", Title: "Unnecessary Communication Link", Description: "When a technical communication link does not send or receive any data assets, this is " + "an indicator for an unnecessary communication link (or for an incomplete model).", Impact: "If this risk is unmitigated, attackers might be able to target unnecessary communication links.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Attack Surface Reduction", Mitigation: "Try to avoid using technical communication links that do not send or receive anything.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets' technical communication links not sending or receiving any data assets.", RiskAssessment: types.LowSeverity.String(), FalsePositives: "Usually no false positives as this looks like an incomplete model.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*UnnecessaryCommunicationLinkRule) SupportedTags() []string { return []string{} } func (r *UnnecessaryCommunicationLinkRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] for _, commLink := range technicalAsset.CommunicationLinks { if len(commLink.DataAssetsSent) != 0 || len(commLink.DataAssetsReceived) != 0 { continue } if technicalAsset.OutOfScope && input.TechnicalAssets[commLink.TargetId].OutOfScope { continue } risks = append(risks, r.createRisk(technicalAsset, commLink)) } } return risks, nil } func (r *UnnecessaryCommunicationLinkRule) createRisk(technicalAsset *types.TechnicalAsset, commLink *types.CommunicationLink) *types.Risk { title := "<b>Unnecessary Communication Link</b> titled <b>" + commLink.Title + "</b> at technical asset <b>" + technicalAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, types.LowImpact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: types.LowImpact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: commLink.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + commLink.Id + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/cross_site_scripting_rule.go
pkg/risks/builtin/cross_site_scripting_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type CrossSiteScriptingRule struct{} func NewCrossSiteScriptingRule() *CrossSiteScriptingRule { return &CrossSiteScriptingRule{} } func (*CrossSiteScriptingRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "cross-site-scripting", Title: "Cross-Site Scripting (XSS)", Description: "For each web application Cross-Site Scripting (XSS) risks might arise. In terms " + "of the overall risk level take other applications running on the same domain into account as well.", Impact: "If this risk remains unmitigated, attackers might be able to access individual victim sessions and steal or modify user data.", ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html", Action: "XSS Prevention", Mitigation: "Try to encode all values sent back to the browser and also handle DOM-manipulations in a safe way " + "to avoid DOM-based XSS. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Tampering, DetectionLogic: "In-scope web applications.", RiskAssessment: "The risk rating depends on the sensitivity of the data processed in the web application.", FalsePositives: "When the technical asset " + "is not accessed via a browser-like component (i.e not by a human user initiating the request that " + "gets passed through all components until it reaches the web application) this can be considered a false positive.", ModelFailurePossibleReason: false, CWE: 79, } } func (*CrossSiteScriptingRule) SupportedTags() []string { return []string{} } func (r *CrossSiteScriptingRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset) { continue } risks = append(risks, r.createRisk(input, technicalAsset)) } return risks, nil } func (asl CrossSiteScriptingRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return technicalAsset.OutOfScope || !technicalAsset.Technologies.GetAttribute(types.WebApplication) // TODO: also mobile clients or rich-clients as long as they use web-view... } func (r *CrossSiteScriptingRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Cross-Site Scripting (XSS)</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.MediumImpact if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.HighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Likely, impact), ExploitationLikelihood: types.Likely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/sql_nosql_injection_rule.go
pkg/risks/builtin/sql_nosql_injection_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type SqlNoSqlInjectionRule struct{} func NewSqlNoSqlInjectionRule() *SqlNoSqlInjectionRule { return &SqlNoSqlInjectionRule{} } func (*SqlNoSqlInjectionRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "sql-nosql-injection", Title: "SQL/NoSQL-Injection", Description: "When a database is accessed via database access protocols SQL/NoSQL-Injection risks might arise. " + "The risk rating depends on the sensitivity technical asset itself and of the data assets processed.", Impact: "If this risk is unmitigated, attackers might be able to modify SQL/NoSQL queries to steal and modify data and eventually further escalate towards a deeper system penetration via code executions.", ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html", Action: "SQL/NoSQL-Injection Prevention", Mitigation: "Try to use parameter binding to be safe from injection vulnerabilities. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.Tampering, DetectionLogic: "Database accessed via typical database access protocols by in-scope clients.", RiskAssessment: "The risk rating depends on the sensitivity of the data stored inside the database.", FalsePositives: "Database accesses by queries not consisting of parts controllable by the caller can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 89, } } func (*SqlNoSqlInjectionRule) SupportedTags() []string { return []string{} } func (r *SqlNoSqlInjectionRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope || technicalAsset.Type != types.Datastore { continue } incomingFlows := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, incomingFlow := range incomingFlows { potentialDatabaseAccessProtocol := incomingFlow.Protocol.IsPotentialDatabaseAccessProtocol() isVulnerableToQueryInjection := technicalAsset.Technologies.GetAttribute(types.IsVulnerableToQueryInjection) potentialLaxDatabaseAccessProtocol := incomingFlow.Protocol.IsPotentialLaxDatabaseAccessProtocol() if potentialDatabaseAccessProtocol && isVulnerableToQueryInjection || potentialLaxDatabaseAccessProtocol { risks = append(risks, r.createRisk(input, technicalAsset, incomingFlow)) } } } return risks, nil } func (r *SqlNoSqlInjectionRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingFlow *types.CommunicationLink) *types.Risk { caller := input.TechnicalAssets[incomingFlow.SourceId] title := "<b>SQL/NoSQL-Injection</b> risk at <b>" + caller.Title + "</b> against database <b>" + technicalAsset.Title + "</b>" + " via <b>" + incomingFlow.Title + "</b>" impact := types.MediumImpact if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { impact = types.HighImpact } likelihood := types.VeryLikely if incomingFlow.Usage == types.DevOps { likelihood = types.Likely } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: caller.Id, MostRelevantCommunicationLinkId: incomingFlow.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + caller.Id + "@" + technicalAsset.Id + "@" + incomingFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_waf_rule_test.go
pkg/risks/builtin/missing_waf_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingWafRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingWafRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingWafRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingWafRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "not-web-application", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingWafRuleGenerateRisksNotWebApplicationOrServiceNoRisksCreated(t *testing.T) { rule := NewMissingWafRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "not-web-application", Attributes: map[string]bool{ types.WebApplication: false, types.IsWebService: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingWafRuleGenerateRisksNotAccrossBoundaryNetworkNoRisksCreated(t *testing.T) { rule := NewMissingWafRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WAF: false, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Protocol: types.HTTP, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingWafRuleGenerateRisksWebApplicationFirewallCallNoRisksCreated(t *testing.T) { rule := NewMissingWafRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta2"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WAF: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Protocol: types.HTTP, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingWafRuleGenerateRisksNotWebAccessProtocolNoRisksCreated(t *testing.T) { rule := NewMissingWafRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta2"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WAF: false, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Protocol: types.SqlAccessProtocol, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingWafRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality expectedImpact types.RiskExploitationImpact } func TestMissingWafSegmentationRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]MissingWafRuleTest{ "low impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.LowImpact, }, // "strictly confidential medium impact": { // confidentiality: types.StrictlyConfidential, // integrity: types.Critical, // availability: types.Critical, // expectedImpact: types.MediumImpact, // }, // "mission critical integrity medium impact": { // confidentiality: types.Confidential, // integrity: types.MissionCritical, // availability: types.Critical, // expectedImpact: types.MediumImpact, // }, // "mission critical availability medium impact": { // confidentiality: types.Confidential, // integrity: types.Critical, // availability: types.MissionCritical, // expectedImpact: types.MediumImpact, // }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingWafRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta2"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "web-application", Attributes: map[string]bool{ types.WAF: false, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { TargetId: "ta1", SourceId: "ta2", Protocol: types.HTTPS, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := "<b>Missing Web Application Firewall (WAF)</b> risk at <b>First Technical Asset</b>" assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_technical_asset_rule_test.go
pkg/risks/builtin/unnecessary_technical_asset_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnnecessaryTechnicalAssetRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnnecessaryTechnicalAssetRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryTechnicalAssetRuleGenerateRisksNoDataProcessedOrStoreNotRisksCreated(t *testing.T) { rule := NewUnnecessaryTechnicalAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Technical Asset", Id: "ta1", DataAssetsProcessed: []string{}, DataAssetsStored: []string{}, CommunicationLinks: []*types.CommunicationLink{}, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Unnecessary Technical Asset</b> named <b>Technical Asset</b>", risks[0].Title) } func TestUnnecessaryTechnicalAssetRuleSomeDataStoredAndSomeOutgoingCommunicationNotRisksCreated(t *testing.T) { rule := NewUnnecessaryTechnicalAssetRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "First Technical Asset", Id: "ta1", DataAssetsProcessed: []string{}, DataAssetsStored: []string{"data"}, CommunicationLinks: []*types.CommunicationLink{ { DataAssetsSent: []string{"data"}, TargetId: "ta2", SourceId: "ta1", }, }, }, "ta2": { Title: "Second Technical Asset", Id: "ta2", DataAssetsProcessed: []string{"data"}, DataAssetsStored: []string{}, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Title: "data", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta2": { { DataAssetsReceived: []string{"data"}, TargetId: "ta1", SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_build_infrastructure_rule_test.go
pkg/risks/builtin/missing_build_infrastructure_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingBuildInfrastructureRuleGenerateRisksEmptyModelNoRisksCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingBuildInfrastructureRuleGenerateRisksCustomDevelopedPartOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingBuildInfrastructureRuleGenerateRisksCustomDevelopedPartWithoutBuildInfrastructureRiskCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksCustomDevelopedPartWithBuildPipelineRiskCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: false, }, "ArgoCD": { Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksCustomDevelopedPartWithBuildPipelineAndSourceCodeRepoRiskCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, }, "ArgoCD": { Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, }, "GitLab": { Technologies: types.TechnologyList{ { Name: "source-code-repository", Attributes: map[string]bool{ types.SourcecodeRepository: true, }, }, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksCustomDevelopedPartWithBuildPipelineAndSourceCodeRepoAndDevOpsClientNoRiskCreated(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, }, "ArgoCD": { Technologies: types.TechnologyList{ { Name: "build-pipeline", Attributes: map[string]bool{ types.BuildPipeline: true, }, }, }, }, "GitLab": { Technologies: types.TechnologyList{ { Name: "source-code-repository", Attributes: map[string]bool{ types.SourcecodeRepository: true, }, }, }, }, "DevOpsClient": { Technologies: types.TechnologyList{ { Name: "source-code-repository", Attributes: map[string]bool{ types.DevOpsClient: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingBuildInfrastructureRuleGenerateRisksProcessingConfidentialDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksProcessingCriticalIntegrityDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksProcessingCriticalAvailabilityDataRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Availability: types.Critical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksConfidentialTechnicalAssetRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksTechnicalAssetCriticalIntegrityRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, Integrity: types.Critical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) } func TestMissingBuildInfrastructureRuleGenerateRisksTechnicalAssetCriticalAvailabilityRisksCreatedWithMediumImpact(t *testing.T) { rule := NewMissingBuildInfrastructureRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, Availability: types.Critical, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_store_rule.go
pkg/risks/builtin/missing_identity_store_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingIdentityStoreRule struct{} func NewMissingIdentityStoreRule() *MissingIdentityStoreRule { return &MissingIdentityStoreRule{} } func (*MissingIdentityStoreRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-identity-store", Title: "Missing Identity Store", Description: "The modeled architecture does not contain an identity store, which might be the risk of a model missing " + "critical assets (and thus not seeing their risks).", Impact: "If this risk is unmitigated, attackers might be able to exploit risks unseen in this threat model in the identity provider/store " + "that is currently missing in the model.", ASVS: "V2 - Authentication Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html", Action: "Identity Store", Mitigation: "Include an identity store in the model if the application has a login.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Spoofing, DetectionLogic: "Models with authenticated data-flows authorized via end user identity missing an in-scope identity store.", RiskAssessment: "The risk rating depends on the sensitivity of the end user-identity authorized technical assets and " + "their data assets processed.", FalsePositives: "Models only offering data/services without any real authentication need " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: true, CWE: 287, } } func (*MissingIdentityStoreRule) SupportedTags() []string { return []string{} } func (r *MissingIdentityStoreRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if r.skipAsset(technicalAsset) { // everything fine, no risk, as we have an in-scope identity store in the model return risks, nil } } // now check if we have end user identity authorized communication links, then it's a risk riskIdentified := false var mostRelevantAsset *types.TechnicalAsset impact := types.LowImpact for _, id := range input.SortedTechnicalAssetIDs() { // use the sorted one to always get the same tech asset with the highest sensitivity as example asset technicalAsset := input.TechnicalAssets[id] for _, commLink := range technicalAsset.CommunicationLinksSorted() { // use the sorted one to always get the same tech asset with the highest sensitivity as example asset if commLink.Authorization != types.EndUserIdentityPropagation { continue } riskIdentified = true targetAsset := input.TechnicalAssets[commLink.TargetId] if impact == types.LowImpact { mostRelevantAsset = targetAsset if input.HighestProcessedConfidentiality(targetAsset) >= types.Confidential || input.HighestProcessedIntegrity(targetAsset) >= types.Critical || input.HighestProcessedAvailability(targetAsset) >= types.Critical { impact = types.MediumImpact } } if targetAsset.Confidentiality >= types.Confidential || targetAsset.Integrity >= types.Critical || targetAsset.Availability >= types.Critical { impact = types.MediumImpact } // just for referencing the most interesting asset if technicalAsset.HighestSensitivityScore() > mostRelevantAsset.HighestSensitivityScore() { mostRelevantAsset = technicalAsset } } } if riskIdentified { risks = append(risks, r.createRisk(mostRelevantAsset, impact)) } return risks, nil } func (r *MissingIdentityStoreRule) skipAsset(technicalAsset *types.TechnicalAsset) bool { return !technicalAsset.OutOfScope && technicalAsset.Technologies.GetAttribute(types.IsIdentityStore) } func (r *MissingIdentityStoreRule) createRisk(technicalAsset *types.TechnicalAsset, impact types.RiskExploitationImpact) *types.Risk { title := "<b>Missing Identity Store</b> in the threat model (referencing asset <b>" + technicalAsset.Title + "</b> as an example)" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_cloud_hardening_rule.go
pkg/risks/builtin/missing_cloud_hardening_rule.go
package builtin import ( "slices" "strings" "github.com/threagile/threagile/pkg/types" ) type MissingCloudHardeningRule struct{} func NewMissingCloudHardeningRule() *MissingCloudHardeningRule { return &MissingCloudHardeningRule{} } func (*MissingCloudHardeningRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-cloud-hardening", Title: "Missing Cloud Hardening", Description: "Cloud components should be hardened according to the cloud vendor best practices. This affects their " + "configuration, auditing, and further areas.", Impact: "If this risk is unmitigated, attackers might access cloud components in an unintended way.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Cloud Hardening", Mitigation: "Apply hardening of all cloud components and services, taking special care to follow the individual risk descriptions (which " + "depend on the cloud provider tags in the model). " + "<br><br>For <b>Amazon Web Services (AWS)</b>: Follow the <i>CIS Benchmark for Amazon Web Services</i> (see also the automated checks of cloud audit tools like <i>\"PacBot\", \"CloudSploit\", \"CloudMapper\", \"ScoutSuite\", or \"Prowler AWS CIS Benchmark Tool\"</i>). " + "<br>For EC2 and other servers running Amazon Linux, follow the <i>CIS Benchmark for Amazon Linux</i> and switch to IMDSv2. " + "<br>For S3 buckets follow the <i>Security Best Practices for Amazon S3</i> at <a href=\"https://docs.aws.amazon.com/AmazonS3/latest/dev/security-best-practices.html\">https://docs.aws.amazon.com/AmazonS3/latest/dev/security-best-practices.html</a> to avoid accidental leakage. " + "<br>Also take a look at some of these tools: <a href=\"https://github.com/toniblyx/my-arsenal-of-aws-security-tools\">https://github.com/toniblyx/my-arsenal-of-aws-security-tools</a> " + "<br><br>For <b>Microsoft Azure</b>: Follow the <i>CIS Benchmark for Microsoft Azure</i> (see also the automated checks of cloud audit tools like <i>\"CloudSploit\" or \"ScoutSuite\"</i>)." + "<br><br>For <b>Google Cloud Platform</b>: Follow the <i>CIS Benchmark for Google Cloud Computing Platform</i> (see also the automated checks of cloud audit tools like <i>\"CloudSploit\" or \"ScoutSuite\"</i>). " + "<br><br>For <b>Oracle Cloud Platform</b>: Follow the hardening best practices (see also the automated checks of cloud audit tools like <i>\"CloudSploit\"</i>).", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.Tampering, DetectionLogic: "In-scope cloud components (either residing in cloud trust boundaries or more specifically tagged with cloud provider types).", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Cloud components not running parts of the target architecture can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 1008, } } var specificSubTagsAWS = []string{"aws:vpc", "aws:ec2", "aws:s3", "aws:ebs", "aws:apigateway", "aws:lambda", "aws:dynamodb", "aws:rds", "aws:sqs", "aws:iam"} var providers = []string{"AWS", "Azure", "GCP", "OCP"} func (*MissingCloudHardeningRule) SupportedTags() []string { res := []string{ "aws", // Amazon AWS "azure", // Microsoft Azure "gcp", // Google Cloud Platform "ocp", // Oracle Cloud Platform } res = append(res, specificSubTagsAWS...) return res } type CloudAssets struct { SharedRuntimeIDs map[string]struct{} TrustBoundaryIDs map[string]struct{} TechAssetIDs map[string]struct{} } func (r *MissingCloudHardeningRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { cloudAssets := initCloudAssets([]string{"AWS", "Azure", "GCP", "OCP", "Unspecified"}) techAssetIDsWithSubtagSpecificCloudRisks := make(map[string]struct{}) risks := make([]*types.Risk, 0) addedFlags := map[string]*bool{ "AWS": new(bool), "Azure": new(bool), "GCP": new(bool), "OCP": new(bool), } r.collectCloudAssets(input, cloudAssets, techAssetIDsWithSubtagSpecificCloudRisks) r.deduplicateUnspecifiedAssets(cloudAssets) risks = append(risks, r.generateSharedRuntimeRisks(input, cloudAssets, addedFlags)...) risks = append(risks, r.generateTrustBoundaryRisks(input, cloudAssets, addedFlags)...) risks = append(risks, r.addFallbackAssetRisks(input, cloudAssets, addedFlags)...) risks = append(risks, r.addSubtagSpecificRisks(input, techAssetIDsWithSubtagSpecificCloudRisks)...) return risks, nil } func (r *MissingCloudHardeningRule) collectCloudAssets(input *types.Model, cloudAssets map[string]*CloudAssets, techAssetIDsWithSubtagSpecificCloudRisks map[string]struct{}) { for _, trustBoundary := range input.TrustBoundaries { if !trustBoundary.IsTaggedWithAny(r.SupportedTags()...) && !trustBoundary.Type.IsWithinCloud() { continue } r.addTrustBoundaryAccordingToBaseTag(trustBoundary, cloudAssets) for _, techAssetID := range input.RecursivelyAllTechnicalAssetIDsInside(trustBoundary) { tA := input.TechnicalAssets[techAssetID] switch { case tA.IsTaggedWithAny(r.SupportedTags()...): addAccordingToBaseTag(tA, tA.Tags, techAssetIDsWithSubtagSpecificCloudRisks, cloudAssets) case trustBoundary.IsTaggedWithAny(r.SupportedTags()...): addAccordingToBaseTag(tA, trustBoundary.Tags, techAssetIDsWithSubtagSpecificCloudRisks, cloudAssets) default: cloudAssets["Unspecified"].TechAssetIDs[techAssetID] = struct{}{} } } } for _, tA := range input.TechnicalAssetsTaggedWithAny(r.SupportedTags()...) { addAccordingToBaseTag(tA, tA.Tags, techAssetIDsWithSubtagSpecificCloudRisks, cloudAssets) } for _, tB := range input.TrustBoundariesTaggedWithAny(r.SupportedTags()...) { for _, techAssetID := range input.RecursivelyAllTechnicalAssetIDsInside(tB) { tA := input.TechnicalAssets[techAssetID] tagsToUse := tB.Tags if tA.IsTaggedWithAny(r.SupportedTags()...) { tagsToUse = tA.Tags } addAccordingToBaseTag(tA, tagsToUse, techAssetIDsWithSubtagSpecificCloudRisks, cloudAssets) } } for _, sR := range input.SharedRuntimes { r.addSharedRuntimeAccordingToBaseTag(sR, cloudAssets) for _, techAssetID := range sR.TechnicalAssetsRunning { tA := input.TechnicalAssets[techAssetID] addAccordingToBaseTag(tA, sR.Tags, techAssetIDsWithSubtagSpecificCloudRisks, cloudAssets) } } } func (r *MissingCloudHardeningRule) deduplicateUnspecifiedAssets(cloudAssets map[string]*CloudAssets) { providers := []string{"AWS", "Azure", "GCP", "OCP"} for _, provider := range providers { for id := range cloudAssets[provider].SharedRuntimeIDs { delete(cloudAssets["Unspecified"].SharedRuntimeIDs, id) } for id := range cloudAssets[provider].TrustBoundaryIDs { delete(cloudAssets["Unspecified"].TrustBoundaryIDs, id) } for id := range cloudAssets[provider].TechAssetIDs { delete(cloudAssets["Unspecified"].TechAssetIDs, id) } } } func (r *MissingCloudHardeningRule) generateSharedRuntimeRisks(input *types.Model, cloudAssets map[string]*CloudAssets, addedFlags map[string]*bool) []*types.Risk { risks := []*types.Risk{} for _, cfg := range r.cloudConfigs(addedFlags) { for id := range cloudAssets[cfg.Provider].SharedRuntimeIDs { risks = append(risks, r.createRiskForSharedRuntime(input, input.SharedRuntimes[id], cfg.Provider, cfg.Benchmark)) *cfg.AddedFlag = true } } for id := range cloudAssets["Unspecified"].SharedRuntimeIDs { risks = append(risks, r.createRiskForSharedRuntime(input, input.SharedRuntimes[id], "", "")) } return risks } func (r *MissingCloudHardeningRule) generateTrustBoundaryRisks(input *types.Model, cloudAssets map[string]*CloudAssets, addedFlags map[string]*bool) []*types.Risk { risks := []*types.Risk{} for _, cfg := range r.cloudConfigs(addedFlags) { for id := range cloudAssets[cfg.Provider].TrustBoundaryIDs { risks = append(risks, r.createRiskForTrustBoundary(input, input.TrustBoundaries[id], cfg.Provider, cfg.Benchmark)) *cfg.AddedFlag = true } } for id := range cloudAssets["Unspecified"].TrustBoundaryIDs { risks = append(risks, r.createRiskForTrustBoundary(input, input.TrustBoundaries[id], "", "")) } return risks } func (r *MissingCloudHardeningRule) addFallbackAssetRisks(input *types.Model, cloudAssets map[string]*CloudAssets, addedFlags map[string]*bool) []*types.Risk { risks := []*types.Risk{} for _, cfg := range r.cloudConfigs(addedFlags) { if !*cfg.AddedFlag { mostRelevant := findMostSensitiveTechnicalAsset(input, cloudAssets[cfg.Provider].TechAssetIDs) if mostRelevant != nil { risks = append(risks, r.createRiskForTechnicalAsset(input, mostRelevant, cfg.Provider, cfg.Benchmark)) } } } return risks } func (r *MissingCloudHardeningRule) addSubtagSpecificRisks(input *types.Model, ids map[string]struct{}) []*types.Risk { risks := []*types.Risk{} for id := range ids { tA := input.TechnicalAssets[id] if isTechnicalAssetTaggedWithAnyTraversingUp(input, tA, "aws:ec2") { risks = append(risks, r.createRiskForTechnicalAsset(input, tA, "EC2", "CIS Benchmark for Amazon Linux")) } if isTechnicalAssetTaggedWithAnyTraversingUp(input, tA, "aws:s3") { risks = append(risks, r.createRiskForTechnicalAsset(input, tA, "S3", "Security Best Practices for AWS S3")) } // TODO: add more subtag-specific risks } return risks } func (r *MissingCloudHardeningRule) cloudConfigs(added map[string]*bool) []struct { Provider string Benchmark string AddedFlag *bool } { return []struct { Provider string Benchmark string AddedFlag *bool }{ {"AWS", "CIS Benchmark for AWS", added["AWS"]}, {"Azure", "CIS Benchmark for Microsoft Azure", added["Azure"]}, {"GCP", "CIS Benchmark for Google Cloud Computing Platform", added["GCP"]}, {"OCP", "Vendor Best Practices for Oracle Cloud Platform", added["OCP"]}, } } func initCloudAssets(providers []string) map[string]*CloudAssets { assets := make(map[string]*CloudAssets, len(providers)) for _, provider := range providers { assets[provider] = &CloudAssets{ SharedRuntimeIDs: make(map[string]struct{}), TrustBoundaryIDs: make(map[string]struct{}), TechAssetIDs: make(map[string]struct{}), } } return assets } func isTechnicalAssetTaggedWithAnyTraversingUp(model *types.Model, ta *types.TechnicalAsset, tags ...string) bool { if containsCaseInsensitiveAny(ta.Tags, tags...) { return true } if tbID := model.GetTechnicalAssetTrustBoundaryId(ta); tbID != "" { if isTrustedBoundaryTaggedWithAnyTraversingUp(model, model.TrustBoundaries[tbID], tags...) { return true } } for _, sr := range model.SharedRuntimes { if sr.IsTaggedWithAny(tags...) && contains(sr.TechnicalAssetsRunning, ta.Id) { return true } } return false } func isTrustedBoundaryTaggedWithAnyTraversingUp(model *types.Model, tb *types.TrustBoundary, tags ...string) bool { if tb.IsTaggedWithAny(tags...) { return true } parentTb := model.FindParentTrustBoundary(tb) if parentTb != nil && isTrustedBoundaryTaggedWithAnyTraversingUp(model, parentTb, tags...) { return true } return false } func (r *MissingCloudHardeningRule) addTrustBoundaryAccordingToBaseTag( trustBoundary *types.TrustBoundary, cloudAssets map[string]*CloudAssets, ) { if trustBoundary.IsTaggedWithAny(r.SupportedTags()...) { added := false for _, provider := range providers { if isTaggedWithBaseTag(trustBoundary.Tags, strings.ToLower(provider)) { cloudAssets[provider].TrustBoundaryIDs[trustBoundary.Id] = struct{}{} added = true } } if !added { cloudAssets["Unspecified"].TrustBoundaryIDs[trustBoundary.Id] = struct{}{} } } else { cloudAssets["Unspecified"].TrustBoundaryIDs[trustBoundary.Id] = struct{}{} } } func (r *MissingCloudHardeningRule) addSharedRuntimeAccordingToBaseTag( sharedRuntime *types.SharedRuntime, cloudAssets map[string]*CloudAssets,) { if sharedRuntime.IsTaggedWithAny(r.SupportedTags()...) { for _, provider := range providers { if isTaggedWithBaseTag(sharedRuntime.Tags, strings.ToLower(provider)) { cloudAssets[provider].SharedRuntimeIDs[sharedRuntime.Id] = struct{}{} } } } else { cloudAssets["Unspecified"].SharedRuntimeIDs[sharedRuntime.Id] = struct{}{} } } func addAccordingToBaseTag( techAsset *types.TechnicalAsset, tags []string, techAssetIDsWithTagSpecificCloudRisks map[string]struct{}, cloudAssets map[string]*CloudAssets, ) { if techAsset.IsTaggedWithAny(specificSubTagsAWS...) { techAssetIDsWithTagSpecificCloudRisks[techAsset.Id] = struct{}{} } for _, provider := range providers { if isTaggedWithBaseTag(tags, strings.ToLower(provider)) { cloudAssets[provider].TechAssetIDs[techAsset.Id] = struct{}{} } } } func isTaggedWithBaseTag(tags []string, baseTag string) bool { normalizedBase := strings.ToLower(strings.TrimSpace(baseTag)) prefix := normalizedBase + ":" for _, tag := range tags { normalizedTag := strings.ToLower(strings.TrimSpace(tag)) if normalizedTag == normalizedBase || strings.HasPrefix(normalizedTag, prefix) { return true } } return false } func findMostSensitiveTechnicalAsset(input *types.Model, techAssets map[string]struct{}) *types.TechnicalAsset { var candidates []*types.TechnicalAsset for id := range techAssets { candidates = append(candidates, input.TechnicalAssets[id]) } if len(candidates) == 0 { return nil } return slices.MaxFunc(candidates, func(a, b *types.TechnicalAsset) int { return int(a.HighestSensitivityScore() - b.HighestSensitivityScore()) }) } func (r *MissingCloudHardeningRule) createCloudHardeningRisk(id, title, prefix, details string, confidentiality types.Confidentiality, integrity types.Criticality, availability types.Criticality, relatedAssets []string) *types.Risk { suffix := "" if len(prefix) > 0 { suffix = "@" + strings.ToLower(prefix) prefix = " (" + prefix + ")" } fullTitle := "<b>Missing Cloud Hardening" + prefix + "</b> risk at <b>" + title + "</b>" if len(details) > 0 { fullTitle += ": <u>" + details + "</u>" } impact := types.MediumImpact if confidentiality >= types.Confidential || integrity >= types.Critical || availability >= types.Critical { impact = types.HighImpact } if confidentiality == types.StrictlyConfidential || integrity == types.MissionCritical || availability == types.MissionCritical { impact = types.VeryHighImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: fullTitle, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: relatedAssets, SyntheticId: r.Category().ID + "@" + id + suffix, } return risk } func (r *MissingCloudHardeningRule) createRiskForSharedRuntime( input *types.Model, sharedRuntime *types.SharedRuntime, prefix, details string) *types.Risk { return r.createCloudHardeningRisk( sharedRuntime.Id, sharedRuntime.Title, prefix, details, input.FindSharedRuntimeHighestConfidentiality(sharedRuntime), input.FindSharedRuntimeHighestIntegrity(sharedRuntime), input.FindSharedRuntimeHighestAvailability(sharedRuntime), sharedRuntime.TechnicalAssetsRunning, ) } func (r *MissingCloudHardeningRule) createRiskForTrustBoundary( input *types.Model, trustBoundary *types.TrustBoundary, prefix, details string) *types.Risk { return r.createCloudHardeningRisk( trustBoundary.Id, trustBoundary.Title, prefix, details, input.FindTrustBoundaryHighestConfidentiality(trustBoundary), input.FindTrustBoundaryHighestIntegrity(trustBoundary), input.FindTrustBoundaryHighestAvailability(trustBoundary), input.RecursivelyAllTechnicalAssetIDsInside(trustBoundary), ) } func (r *MissingCloudHardeningRule) createRiskForTechnicalAsset( input *types.Model, technicalAsset *types.TechnicalAsset, prefix, details string) *types.Risk { return r.createCloudHardeningRisk( technicalAsset.Id, technicalAsset.Title, prefix, details, input.HighestProcessedConfidentiality(technicalAsset), input.HighestProcessedIntegrity(technicalAsset), input.HighestProcessedAvailability(technicalAsset), []string{technicalAsset.Id}, ) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/ldap_injection_rule_test.go
pkg/risks/builtin/ldap_injection_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestLdapInjectionRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestLdapInjectionRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestLdapInjectionRuleGenerateRisksNoIncomingFlowsNotRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestLdapInjectionRuleIncomingFlowFromOutOfScopeAssetNotRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", }, "ta2": { Id: "ta2", Title: "LDAP Server", OutOfScope: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", Protocol: types.LDAP, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestLdapInjectionRuleIncomingLdapFlowRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", }, "ta2": { Id: "ta2", Title: "LDAP Server", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "LDAP Communication", SourceId: "ta2", Protocol: types.LDAP, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, "<b>LDAP-Injection</b> risk at <b>LDAP Server</b> against LDAP server <b>Test Technical Asset</b> via <b>LDAP Communication</b>", risks[0].Title) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestLdapInjectionRuleIncomingLdapFlowDevOpsUsageRisksCreated_WithUnlikelyLikelihood(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", }, "ta2": { Id: "ta2", Title: "LDAP Server", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "LDAP Communication", SourceId: "ta2", Protocol: types.LDAP, Usage: types.DevOps, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, "<b>LDAP-Injection</b> risk at <b>LDAP Server</b> against LDAP server <b>Test Technical Asset</b> via <b>LDAP Communication</b>", risks[0].Title) assert.Equal(t, types.Unlikely, risks[0].ExploitationLikelihood) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestLdapInjectionRuleIncomingLdapFlowProcessStrictlyConfidentialDataAssetsRisksCreated(t *testing.T) { rule := NewLdapInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", DataAssetsProcessed: []string{"da1"}, }, "ta2": { Id: "ta2", Title: "LDAP Server", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "LDAP Communication", SourceId: "ta2", Protocol: types.LDAP, }, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Id: "da1", Title: "Strictly Confidential Data Asset", Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Len(t, risks, 1) assert.Equal(t, "<b>LDAP-Injection</b> risk at <b>LDAP Server</b> against LDAP server <b>Test Technical Asset</b> via <b>LDAP Communication</b>", risks[0].Title) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_network_segmentation_rule_test.go
pkg/risks/builtin/missing_network_segmentation_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingNetworkSegmentationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", CustomDevelopedParts: true, OutOfScope: true, RAA: 55, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksNoNetworkSegmentationRequiredNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, RAA: 55, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksLowRAANoNetworkSegmentationRequired(t *testing.T) { rule := NewMissingNetworkSegmentationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, RAA: 45, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksNotDataStoreAndLowCIABNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, RAA: 55, Type: types.Process, Confidentiality: types.Restricted, Integrity: types.Important, Availability: types.Important, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingNetworkSegmentationRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality expectedImpact types.RiskExploitationImpact } func TestMissingNetworkSegmentationRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]MissingNetworkSegmentationRuleTest{ "low impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integrity medium impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical availability medium impact": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingNetworkSegmentationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "artifact-registry", Attributes: map[string]bool{ types.IsLessProtectedType: true, types.IsCloseToHighValueTargetsTolerated: false, }, }, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) expTitle := fmt.Sprintf("<b>Missing Network Segmentation</b> to further encapsulate and protect <b>%s</b> against unrelated "+ "lower protected assets in the same network segment, which might be easier to compromise by attackers", "First Technical Asset") assert.Equal(t, expTitle, risks[0].Title) }) } } func TestMissingNetworkSegmentationRuleGenerateRisksSparringAssetIsNotLessProtectedNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, Type: types.Datastore, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "artifact-registry", Attributes: map[string]bool{ types.IsLessProtectedType: false, types.IsCloseToHighValueTargetsTolerated: false, }, }, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksSparringAssetCloseToHighValueTargetsToleratedNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, Type: types.Datastore, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "artifact-registry", Attributes: map[string]bool{ types.IsLessProtectedType: true, types.IsCloseToHighValueTargetsTolerated: true, }, }, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationRuleGenerateRisksNotSameTrustBoundaryNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } tb2 := &types.TrustBoundary{ Id: "tb2", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta2"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, Type: types.Datastore, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "artifact-registry", Attributes: map[string]bool{ types.IsLessProtectedType: true, types.IsCloseToHighValueTargetsTolerated: false, }, }, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingNetworkSegmentationHasDirectConnectionNoRisksCreated(t *testing.T) { rule := NewMissingNetworkSegmentationRule() tb1 := &types.TrustBoundary{ Id: "tb1", Title: "Test Trust Boundary", TechnicalAssetsInside: []string{"ta1"}, Type: types.NetworkCloudProvider, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsNoNetworkSegmentationRequired: true, }, }, }, Type: types.Datastore, RAA: 55, Title: "First Technical Asset", }, "ta2": { Id: "ta2", Title: "Second Technical Asset", Technologies: types.TechnologyList{ { Name: "artifact-registry", Attributes: map[string]bool{ types.IsLessProtectedType: true, types.IsCloseToHighValueTargetsTolerated: false, }, }, }, }, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", TargetId: "ta1", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_data_transfer_rule_test.go
pkg/risks/builtin/unnecessary_data_transfer_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestUnnecessaryDataTransferRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksIsUnnecessaryDataToleratedNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { TargetId: "target", }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.IsUnnecessaryDataTolerated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksIsUnnecessaryDataToleratedForSourceNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { SourceId: "source", TargetId: "target", }, }, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.IsUnnecessaryDataTolerated: true, }, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.IsUnnecessaryDataTolerated: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { SourceId: "source", TargetId: "target", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksSentDataAssetProcessedNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, Technologies: types.TechnologyList{ { Attributes: map[string]bool{ types.IsUnnecessaryDataTolerated: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksSentDataAssetWithLowConfidentialityAndIntegrityNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: types.Restricted, Integrity: types.Important, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestUnnecessaryDataTransferRuleGenerateRisksReceivedDataAssetProcessedNotRisksCreated(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, CommunicationLinks: []*types.CommunicationLink{ { SourceId: "source", TargetId: "target", DataAssetsReceived: []string{"data"}, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { SourceId: "source", TargetId: "target", DataAssetsReceived: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type UnnecessaryDataTransferRuleTest struct { dataAssetConfidentiality types.Confidentiality dataAssetIntegrity types.Criticality expectedImpact types.RiskExploitationImpact } func TestUnnecessaryDataTransferRuleSendDataAssetRisksCreated(t *testing.T) { testCases := map[string]UnnecessaryDataTransferRuleTest{ "low impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integriyt medium impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCases := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { Title: "Data Transfer", SourceId: "source", TargetId: "target", DataAssetsSent: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: testCases.dataAssetConfidentiality, Integrity: testCases.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCases.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unnecessary Data Transfer</b> of <b></b> data at <b>Source Technical Asset</b> from/to <b>Target Technical Asset</b>", risks[0].Title) }) } } func TestUnnecessaryDataTransferRuleReceivedDataAssetRisksCreated(t *testing.T) { testCases := map[string]UnnecessaryDataTransferRuleTest{ "low impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integriyt medium impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCases := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "source", TargetId: "target", DataAssetsReceived: []string{"data"}, }, }, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "target": { { Title: "Data Transfer", SourceId: "source", TargetId: "target", DataAssetsReceived: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: testCases.dataAssetConfidentiality, Integrity: testCases.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCases.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unnecessary Data Transfer</b> of <b></b> data at <b>Source Technical Asset</b> from/to <b>Target Technical Asset</b>", risks[0].Title) }) } } func TestUnnecessaryDataTransferRuleSendDataAssetInverseDirectionRisksCreated(t *testing.T) { testCases := map[string]UnnecessaryDataTransferRuleTest{ "low impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integriyt medium impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCases := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsSent: []string{"data"}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "source": { { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsSent: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: testCases.dataAssetConfidentiality, Integrity: testCases.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCases.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unnecessary Data Transfer</b> of <b></b> data at <b>Source Technical Asset</b> from/to <b>Target Technical Asset</b>", risks[0].Title) }) } } func TestUnnecessaryDataTransferRuleReceivedDataAssetInverseDirectionRisksCreated(t *testing.T) { testCases := map[string]UnnecessaryDataTransferRuleTest{ "low impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integriyt medium impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCases := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "source": { { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: testCases.dataAssetConfidentiality, Integrity: testCases.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCases.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unnecessary Data Transfer</b> of <b></b> data at <b>Source Technical Asset</b> from/to <b>Target Technical Asset</b>", risks[0].Title) }) } } func TestUnnecessaryDataTransferRuleGenerateRisksNoDuplicatedRisksCreated(t *testing.T) { testCases := map[string]UnnecessaryDataTransferRuleTest{ "low impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.Critical, expectedImpact: types.LowImpact, }, "strictly confidential medium impact": { dataAssetConfidentiality: types.StrictlyConfidential, dataAssetIntegrity: types.Critical, expectedImpact: types.MediumImpact, }, "mission critical integriyt medium impact": { dataAssetConfidentiality: types.Confidential, dataAssetIntegrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCases := range testCases { t.Run(name, func(t *testing.T) { rule := NewUnnecessaryDataTransferRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "source": { Id: "source", Title: "Source Technical Asset", OutOfScope: false, }, "target": { Id: "target", Title: "Target Technical Asset", OutOfScope: false, DataAssetsProcessed: []string{"data"}, CommunicationLinks: []*types.CommunicationLink{ { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, { Title: "Duplication Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "source": { { Title: "Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, { Title: "Duplication Data Transfer", SourceId: "target", TargetId: "source", DataAssetsReceived: []string{"data"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "data": { Id: "data", Confidentiality: testCases.dataAssetConfidentiality, Integrity: testCases.dataAssetIntegrity, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCases.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Unnecessary Data Transfer</b> of <b></b> data at <b>Source Technical Asset</b> from/to <b>Target Technical Asset</b>", risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_vault_rule_test.go
pkg/risks/builtin/missing_vault_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingVaultRuleGenerateRisksEmptyModelRiskCreated(t *testing.T) { rule := NewMissingVaultRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Vault (Secret Storage)</b> in the threat model", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestMissingVaultRuleGenerateRisksHasVaultNoRisksCreated(t *testing.T) { rule := NewMissingVaultRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Vault", Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingVaultRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality expectedImpact types.RiskExploitationImpact } func TestMissingVaultRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]MissingVaultRuleTest{ "low impact": { confidentiality: types.Restricted, integrity: types.Important, availability: types.Important, expectedImpact: types.LowImpact, }, "confidential data processed medium impact": { confidentiality: types.Confidential, integrity: types.Important, availability: types.Important, expectedImpact: types.MediumImpact, }, "critical integrity data processed medium impact": { confidentiality: types.Restricted, integrity: types.Critical, availability: types.Important, expectedImpact: types.MediumImpact, }, "critical availability data processed medium impact": { confidentiality: types.Restricted, integrity: types.Important, availability: types.Critical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingVaultRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Vault (Secret Storage)</b> in the threat model (referencing asset <b>Test Technical Asset</b> as an example)", risks[0].Title) }) } } func TestMissingVaultRuleGenerateRisksRiskCreatedWithMoreSensitiveAsset(t *testing.T) { rule := NewMissingVaultRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Confidentiality: types.Restricted, Integrity: types.Important, Availability: types.Important, Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: false, }, }, }, }, "ta2": { Title: "More Relevant Technical Asset", Confidentiality: types.Confidential, Integrity: types.Important, Availability: types.Important, Technologies: types.TechnologyList{ { Name: "vault", Attributes: map[string]bool{ types.Vault: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Vault (Secret Storage)</b> in the threat model (referencing asset <b>More Relevant Technical Asset</b> as an example)", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_provider_isolation_rule.go
pkg/risks/builtin/missing_identity_provider_isolation_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingIdentityProviderIsolationRule struct{} func NewMissingIdentityProviderIsolationRule() *MissingIdentityProviderIsolationRule { return &MissingIdentityProviderIsolationRule{} } func (*MissingIdentityProviderIsolationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-identity-provider-isolation", Title: "Missing Identity Provider Isolation", Description: "Highly sensitive identity provider assets and their identity data stores should be isolated from other assets " + "by their own network segmentation trust-boundary (" + types.ExecutionEnvironment.String() + " boundaries do not count as network isolation).", Impact: "If this risk is unmitigated, attackers successfully attacking other components of the system might have an easy path towards " + "highly sensitive identity provider assets and their identity data stores, as they are not separated by network segmentation.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Network Segmentation", Mitigation: "Apply a network segmentation trust-boundary around the highly sensitive identity provider assets and their identity data stores.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope identity provider assets and their identity data stores " + "when surrounded by other (not identity-related) assets (without a network trust-boundary in-between). " + "This risk is especially prevalent when other non-identity related assets are within the same execution environment (i.e. same database or same application server).", RiskAssessment: "Default is " + types.HighImpact.String() + " impact. The impact is increased to " + types.VeryHighImpact.String() + " when the asset missing the " + "trust-boundary protection is rated as " + types.StrictlyConfidential.String() + " or " + types.MissionCritical.String() + ".", FalsePositives: "When all assets within the network segmentation trust-boundary are hardened and protected to the same extend as if all were " + "identity providers with data of highest sensitivity.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*MissingIdentityProviderIsolationRule) SupportedTags() []string { return []string{} } func (r *MissingIdentityProviderIsolationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if technicalAsset.OutOfScope || !technicalAsset.Technologies.GetAttribute(types.IsIdentityRelated) { continue } moreImpact := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical || technicalAsset.Availability == types.MissionCritical sameExecutionEnv := false createRiskEntry := false // now check for any other same-network assets of non-identity-related types for sparringAssetCandidateId := range input.TechnicalAssets { // so inner loop again over all assets if technicalAsset.Id == sparringAssetCandidateId { continue } sparringAssetCandidate := input.TechnicalAssets[sparringAssetCandidateId] if sparringAssetCandidate.Technologies.GetAttribute(types.IsIdentityRelated) || sparringAssetCandidate.Technologies.GetAttribute(types.IsCloseToHighValueTargetsTolerated) { continue } if isSameExecutionEnvironment(input, technicalAsset, sparringAssetCandidateId) { createRiskEntry = true sameExecutionEnv = true } else if isSameTrustBoundaryNetworkOnly(input, technicalAsset, sparringAssetCandidateId) { createRiskEntry = true } } if createRiskEntry { risks = append(risks, r.createRisk(technicalAsset, moreImpact, sameExecutionEnv)) } } return risks, nil } func (r *MissingIdentityProviderIsolationRule) createRisk(techAsset *types.TechnicalAsset, moreImpact bool, sameExecutionEnv bool) *types.Risk { impact := types.HighImpact likelihood := types.Unlikely others := "<b>in the same network segment</b>" if moreImpact { impact = types.VeryHighImpact } if sameExecutionEnv { likelihood = types.Likely others = "<b>in the same execution environment</b>" } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: "<b>Missing Identity Provider Isolation</b> to further encapsulate and protect identity-related asset <b>" + techAsset.Title + "</b> against unrelated " + "lower protected assets " + others + ", which might be easier to compromise by attackers", MostRelevantTechnicalAssetId: techAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{techAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + techAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unnecessary_data_transfer_rule.go
pkg/risks/builtin/unnecessary_data_transfer_rule.go
package builtin import ( "sort" "github.com/threagile/threagile/pkg/types" ) type UnnecessaryDataTransferRule struct{} func NewUnnecessaryDataTransferRule() *UnnecessaryDataTransferRule { return &UnnecessaryDataTransferRule{} } func (*UnnecessaryDataTransferRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unnecessary-data-transfer", Title: "Unnecessary Data Transfer", Description: "When a technical asset sends or receives data assets, which it neither processes or stores this is " + "an indicator for unnecessarily transferred data (or for an incomplete model). When the unnecessarily " + "transferred data assets are sensitive, this poses an unnecessary risk of an increased attack surface.", Impact: "If this risk is unmitigated, attackers might be able to target unnecessarily transferred data.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Attack Surface Reduction", Mitigation: "Try to avoid sending or receiving sensitive data assets which are not required (i.e. neither " + "processed) by the involved technical asset.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets sending or receiving sensitive data assets which are neither processed nor " + "stored by the technical asset are flagged with this risk. The risk rating (low or medium) depends on the " + "confidentiality, integrity, and availability rating of the technical asset. Monitoring data is exempted from this risk.", RiskAssessment: "The risk assessment is depending on the confidentiality and integrity rating of the transferred data asset " + "either " + types.LowSeverity.String() + " or " + types.MediumSeverity.String() + ".", FalsePositives: "Technical assets missing the model entries of either processing or storing the mentioned data assets " + "can be considered as false positives (incomplete models) after individual review. These should then be addressed by " + "completing the model so that all necessary data assets are processed by the technical asset involved.", ModelFailurePossibleReason: true, CWE: 1008, } } func (*UnnecessaryDataTransferRule) SupportedTags() []string { return []string{} } func (r *UnnecessaryDataTransferRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope { continue } // outgoing data flows for _, outgoingDataFlow := range technicalAsset.CommunicationLinks { targetAsset := input.TechnicalAssets[outgoingDataFlow.TargetId] if targetAsset.Technologies.GetAttribute(types.IsUnnecessaryDataTolerated) { continue } risks = r.checkRisksAgainstTechnicalAsset(input, risks, technicalAsset, outgoingDataFlow, false) } // incoming data flows commLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] sort.Sort(types.ByTechnicalCommunicationLinkIdSort(commLinks)) for _, incomingDataFlow := range commLinks { targetAsset := input.TechnicalAssets[incomingDataFlow.SourceId] if targetAsset.Technologies.GetAttribute(types.IsUnnecessaryDataTolerated) { continue } risks = r.checkRisksAgainstTechnicalAsset(input, risks, technicalAsset, incomingDataFlow, true) } } return risks, nil } func (r *UnnecessaryDataTransferRule) checkRisksAgainstTechnicalAsset(input *types.Model, risks []*types.Risk, technicalAsset *types.TechnicalAsset, dataFlow *types.CommunicationLink, inverseDirection bool) []*types.Risk { for _, transferredDataAssetId := range dataFlow.DataAssetsSent { if !processesOrStoresDataAsset(technicalAsset, transferredDataAssetId) { transferredDataAsset := input.DataAssets[transferredDataAssetId] //fmt.Print("--->>> Checking "+technicalAsset.ID+": "+transferredDataAsset.ID+" sent via "+dataFlow.ID+"\n") if transferredDataAsset.Confidentiality >= types.Confidential || transferredDataAsset.Integrity >= types.Critical { commPartnerId := dataFlow.TargetId if inverseDirection { commPartnerId = dataFlow.SourceId } commPartnerAsset := input.TechnicalAssets[commPartnerId] risk := r.createRisk(technicalAsset, transferredDataAsset, commPartnerAsset) if isNewRisk(risks, risk) { risks = append(risks, risk) } } } } for _, transferredDataAssetId := range dataFlow.DataAssetsReceived { if !processesOrStoresDataAsset(technicalAsset, transferredDataAssetId) { transferredDataAsset := input.DataAssets[transferredDataAssetId] //fmt.Print("--->>> Checking "+technicalAsset.ID+": "+transferredDataAsset.ID+" received via "+dataFlow.ID+"\n") if transferredDataAsset.Confidentiality >= types.Confidential || transferredDataAsset.Integrity >= types.Critical { commPartnerId := dataFlow.TargetId if inverseDirection { commPartnerId = dataFlow.SourceId } commPartnerAsset := input.TechnicalAssets[commPartnerId] risk := r.createRisk(technicalAsset, transferredDataAsset, commPartnerAsset) if isNewRisk(risks, risk) { risks = append(risks, risk) } } } } return risks } func processesOrStoresDataAsset(ta *types.TechnicalAsset, dataAssetId string) bool { return contains(ta.DataAssetsProcessed, dataAssetId) || contains(ta.DataAssetsStored, dataAssetId) } func isNewRisk(risks []*types.Risk, risk *types.Risk) bool { for _, check := range risks { if check.SyntheticId == risk.SyntheticId { return false } } return true } func (r *UnnecessaryDataTransferRule) createRisk(technicalAsset *types.TechnicalAsset, dataAssetTransferred *types.DataAsset, commPartnerAsset *types.TechnicalAsset) *types.Risk { moreRisky := dataAssetTransferred.Confidentiality == types.StrictlyConfidential || dataAssetTransferred.Integrity == types.MissionCritical impact := types.LowImpact if moreRisky { impact = types.MediumImpact } title := "<b>Unnecessary Data Transfer</b> of <b>" + dataAssetTransferred.Title + "</b> data at <b>" + technicalAsset.Title + "</b> " + "from/to <b>" + commPartnerAsset.Title + "</b>" risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantDataAssetId: dataAssetTransferred.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + dataAssetTransferred.Id + "@" + technicalAsset.Id + "@" + commPartnerAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/service_registry_poisoning_rule.go
pkg/risks/builtin/service_registry_poisoning_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type ServiceRegistryPoisoningRule struct{} func NewServiceRegistryPoisoningRule() *ServiceRegistryPoisoningRule { return &ServiceRegistryPoisoningRule{} } func (*ServiceRegistryPoisoningRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "service-registry-poisoning", Title: "Service Registry Poisoning", Description: "When a service registry used for discovery of trusted service endpoints Service Registry Poisoning risks might arise.", Impact: "If this risk remains unmitigated, attackers might be able to poison the service registry with malicious service endpoints or " + "malicious lookup and config data leading to breach of sensitive data.", ASVS: "V10 - Malicious Code Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Access_Control_Cheat_Sheet.html", Action: "Service Registry Integrity Check", Mitigation: "Try to strengthen the access control of the service registry and apply cross-checks to detect maliciously poisoned lookup data.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Spoofing, DetectionLogic: "In-scope service registries.", RiskAssessment: "The risk rating depends on the sensitivity of the technical assets accessing the service registry " + "as well as the data assets processed.", FalsePositives: "Service registries not used for service discovery " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 693, } } func (*ServiceRegistryPoisoningRule) SupportedTags() []string { return []string{} } func (r *ServiceRegistryPoisoningRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if !technicalAsset.OutOfScope && technicalAsset.Technologies.GetAttribute(types.ServiceRegistry) { incomingFlows := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] risks = append(risks, r.createRisk(input, technicalAsset, incomingFlows)) } } return risks, nil } func (r *ServiceRegistryPoisoningRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, incomingFlows []*types.CommunicationLink) *types.Risk { title := "<b>Service Registry Poisoning</b> risk at <b>" + technicalAsset.Title + "</b>" impact := types.LowImpact for _, incomingFlow := range incomingFlows { caller := input.TechnicalAssets[incomingFlow.SourceId] if input.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || input.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || input.HighestProcessedAvailability(technicalAsset) == types.MissionCritical || input.HighestProcessedConfidentiality(caller) == types.StrictlyConfidential || input.HighestProcessedIntegrity(caller) == types.MissionCritical || input.HighestProcessedAvailability(caller) == types.MissionCritical || input.HighestCommunicationLinkConfidentiality(incomingFlow) == types.StrictlyConfidential || input.HighestCommunicationLinkIntegrity(incomingFlow) == types.MissionCritical || input.HighestCommunicationLinkAvailability(incomingFlow) == types.MissionCritical { impact = types.MediumImpact break } } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, // TODO: find all service-lookup-using tech assets, which then might use spoofed lookups? } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/cross_site_request_forgery_rule_test.go
pkg/risks/builtin/cross_site_request_forgery_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestCrossSiteRequestForgeryRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteRequestForgeryRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetNotWebApplicationNotRisksCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.WebApplication: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetWebApplicationWithoutIncomingCommunicationNotRisksCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetWebApplicationIncomingRequestNotWebAccessProtocolNotRiskCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "web-app": { Id: "web-app", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "file-scrapper": { Technologies: types.TechnologyList{ { Name: "tool", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "web-app": { { Protocol: types.LocalFileAccess, SourceId: "file-scrapper", TargetId: "web-app", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetWebApplicationIncomingRequestWebAccessProtocolRiskCreated(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "web-app": { Id: "web-app", Title: "Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "user": { Title: "user", Technologies: types.TechnologyList{ { Name: "user", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "web-app": { { Title: "HTTP", Protocol: types.HTTP, SourceId: "user", TargetId: "web-app", }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Cross-Site Request Forgery (CSRF)</b> risk at <b>Web Application</b> via <b>HTTP</b> from <b>user</b>", risks[0].Title) assert.Equal(t, types.VeryLikely, risks[0].ExploitationLikelihood) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetWebApplicationIncomingRequestWebAccessProtocolViaDevOpsRiskCreatedWithLikelyLikelihood(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "web-app": { Id: "web-app", Title: "Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "ci/cd": { Title: "ci/cd", Technologies: types.TechnologyList{ { Name: "ci/cd", }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "web-app": { { Title: "HTTP", Protocol: types.HTTP, SourceId: "ci/cd", TargetId: "web-app", Usage: types.DevOps, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Cross-Site Request Forgery (CSRF)</b> risk at <b>Web Application</b> via <b>HTTP</b> from <b>ci/cd</b>", risks[0].Title) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestCrossSiteRequestForgeryRuleGenerateRisksTechAssetWebApplicationIncomingRequestWebAccessProtocolRiskCreatedWithMediumImpactWhenIntegrityIsMissionCritical(t *testing.T) { rule := NewCrossSiteRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "web-app": { Id: "web-app", Title: "Web Application", Technologies: types.TechnologyList{ { Name: "web-app", Attributes: map[string]bool{ types.WebApplication: true, }, }, }, }, "user": { Title: "user", Technologies: types.TechnologyList{ { Name: "user", }, }, }, }, DataAssets: map[string]*types.DataAsset{ "mission-critical-data": { Id: "mission-critical-data", Title: "Mission Critical Data", Integrity: types.MissionCritical, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "web-app": { { Title: "HTTP", Protocol: types.HTTP, SourceId: "user", TargetId: "web-app", DataAssetsReceived: []string{"mission-critical-data"}, }, }, }, }) assert.Nil(t, err) assert.NotEmpty(t, risks) assert.Equal(t, "<b>Cross-Site Request Forgery (CSRF)</b> risk at <b>Web Application</b> via <b>HTTP</b> from <b>user</b>", risks[0].Title) assert.Equal(t, types.VeryLikely, risks[0].ExploitationLikelihood) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_hardening_rule_test.go
pkg/risks/builtin/missing_hardening_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingHardeningRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingHardeningRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingHardeningRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingHardeningRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, RAA: 100, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingHardeningRuleNoRisksTest struct { raa int technicalAssetType types.TechnicalAssetType enabledAttribute string } func TestMissingHardeningRuleNoRisksCreated(t *testing.T) { testCases := map[string]MissingHardeningRuleNoRisksTest{ "raa less limit for data store": { raa: 39, technicalAssetType: types.Datastore, enabledAttribute: types.IsDevelopmentRelevant, }, "raa less limit for high value target": { raa: 39, technicalAssetType: types.Process, enabledAttribute: types.IsHighValueTarget, }, "raa less reduced limit for not data store or high value target": { raa: 54, technicalAssetType: types.Process, enabledAttribute: "any other", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingHardeningRule() input := &types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Type: testCase.technicalAssetType, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, }, }, } input.TechnicalAssets["ta1"].RAA = float64(testCase.raa) input.TechnicalAssets["ta1"].Technologies[0].Attributes[testCase.enabledAttribute] = true risks, err := rule.GenerateRisks(input) assert.Nil(t, err) assert.Empty(t, risks) }) } } type MissingHardeningRuleRisksCreatedTest struct { raa int technicalAssetType types.TechnicalAssetType enabledAttribute string confidentiality types.Confidentiality integrity types.Criticality expectedImpact types.RiskExploitationImpact } func TestMissingHardeningRuleRisksCreated(t *testing.T) { testCases := map[string]MissingHardeningRuleRisksCreatedTest{ "raa higher reduced limit for data store": { raa: 40, technicalAssetType: types.Datastore, enabledAttribute: types.IsDevelopmentRelevant, expectedImpact: types.LowImpact, }, "raa higher reduced limit for high value target": { raa: 40, technicalAssetType: types.Process, enabledAttribute: types.IsHighValueTarget, expectedImpact: types.LowImpact, }, "raa higher limit for not high value target or data store": { raa: 55, technicalAssetType: types.Process, enabledAttribute: types.IsDevelopmentRelevant, expectedImpact: types.LowImpact, }, "process strictly confidential data": { raa: 55, technicalAssetType: types.Datastore, enabledAttribute: types.IsHighValueTarget, confidentiality: types.StrictlyConfidential, integrity: types.Critical, expectedImpact: types.MediumImpact, }, "process mission critical integrity data": { raa: 55, technicalAssetType: types.Datastore, enabledAttribute: types.IsHighValueTarget, confidentiality: types.Confidential, integrity: types.MissionCritical, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingHardeningRule() input := &types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", Type: types.Datastore, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{}, }, }, DataAssetsProcessed: []string{"da1"}, }, }, DataAssets: map[string]*types.DataAsset{ "da1": { Title: "Test Data Asset", Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, }, } input.TechnicalAssets["ta1"].RAA = float64(testCase.raa) tech := input.TechnicalAssets["ta1"].Technologies[0] tech.Attributes[testCase.enabledAttribute] = true risks, err := rule.GenerateRisks(input) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, "<b>Missing Hardening</b> risk at <b>Test Technical Asset</b>", risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_network_segmentation_rule.go
pkg/risks/builtin/missing_network_segmentation_rule.go
package builtin import ( "sort" "github.com/threagile/threagile/pkg/types" ) type MissingNetworkSegmentationRule struct { raaLimit int } func NewMissingNetworkSegmentationRule() *MissingNetworkSegmentationRule { return &MissingNetworkSegmentationRule{raaLimit: 50} } func (*MissingNetworkSegmentationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-network-segmentation", Title: "Missing Network Segmentation", Description: "Highly sensitive assets and/or data stores residing in the same network segment than other " + "lower sensitive assets (like webservers or content management systems etc.) should be better protected " + "by a network segmentation trust-boundary.", Impact: "If this risk is unmitigated, attackers successfully attacking other components of the system might have an easy path towards " + "more valuable targets, as they are not separated by network segmentation.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Network Segmentation", Mitigation: "Apply a network segmentation trust-boundary around the highly sensitive assets and/or data stores.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets with high sensitivity and RAA values as well as data stores " + "when surrounded by assets (without a network trust-boundary in-between) which are of type " + types.ClientSystem + ", " + types.WebServer + ", " + types.WebApplication + ", " + types.CMS + ", " + types.WebServiceREST + ", " + types.WebServiceSOAP + ", " + types.BuildPipeline + ", " + types.SourcecodeRepository + ", " + types.Monitoring + ", or similar and there is no direct connection between these " + "(hence no requirement to be so close to each other).", RiskAssessment: "Default is " + types.LowSeverity.String() + " risk. The risk is increased to " + types.MediumSeverity.String() + " when the asset missing the " + "trust-boundary protection is rated as " + types.StrictlyConfidential.String() + " or " + types.MissionCritical.String() + ".", FalsePositives: "When all assets within the network segmentation trust-boundary are hardened and protected to the same extend as if all were " + "containing/processing highly sensitive data.", ModelFailurePossibleReason: false, CWE: 1008, } } func (*MissingNetworkSegmentationRule) SupportedTags() []string { return []string{} } func (r *MissingNetworkSegmentationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) // first create them in memory (see the link replacement below for nested trust boundaries) - otherwise in Go ranging over map is random order // range over them in sorted (hence re-producible) way: keys := make([]string, 0) for k := range input.TechnicalAssets { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { technicalAsset := input.TechnicalAssets[key] if technicalAsset.OutOfScope { continue } if !technicalAsset.Technologies.GetAttribute(types.IsNoNetworkSegmentationRequired) { continue } if technicalAsset.RAA < float64(r.raaLimit) { continue } if technicalAsset.Type != types.Datastore && technicalAsset.Confidentiality < types.Confidential && technicalAsset.Integrity < types.Critical && technicalAsset.Availability < types.Critical { continue } // now check for any other same-network assets of certain types which have no direct connection for _, sparringAssetCandidateId := range keys { // so inner loop again over all assets if technicalAsset.Id == sparringAssetCandidateId { continue } sparringAssetCandidate := input.TechnicalAssets[sparringAssetCandidateId] if sparringAssetCandidate.Technologies.GetAttribute(types.IsLessProtectedType) && isSameTrustBoundaryNetworkOnly(input, technicalAsset, sparringAssetCandidateId) && !input.HasDirectConnection(technicalAsset, sparringAssetCandidateId) && !sparringAssetCandidate.Technologies.GetAttribute(types.IsCloseToHighValueTargetsTolerated) { highRisk := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical || technicalAsset.Availability == types.MissionCritical risks = append(risks, r.createRisk(technicalAsset, highRisk)) break } } } return risks, nil } func (r *MissingNetworkSegmentationRule) createRisk(techAsset *types.TechnicalAsset, moreRisky bool) *types.Risk { impact := types.LowImpact if moreRisky { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: "<b>Missing Network Segmentation</b> to further encapsulate and protect <b>" + techAsset.Title + "</b> against unrelated " + "lower protected assets in the same network segment, which might be easier to compromise by attackers", MostRelevantTechnicalAssetId: techAsset.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{techAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + techAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/server_side_request_forgery_rule_test.go
pkg/risks/builtin/server_side_request_forgery_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestServerSideRequestForgeryRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestServerSideRequestForgeryRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestServerSideRequestForgeryRuleGenerateRisksLoadBalancerNoRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestServerSideRequestForgeryRuleGenerateRisksIsClientNoRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: true, types.LoadBalancer: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestServerSideRequestForgeryRuleGenerateRisksNotWebAccessCommunicationNoRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Protocol: types.SqlAccessProtocol, TargetId: "ta2", }, }, }, "ta2": { Title: "Test Target Asset", OutOfScope: false, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestServerSideRequestForgeryRuleGenerateRisksLowImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", }, }, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksStrictlyConfidentialMediumImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", }, }, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksTrustBoundaryWithinCloudMediumImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() tb1 := &types.TrustBoundary{ Id: "tb1", Type: types.NetworkCloudProvider, TechnicalAssetsInside: []string{"ta1", "ta2"}, } comm := &types.CommunicationLink{ Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{comm}, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta2": {comm}, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksStrictlyConfidentialTrustBoundaryNotCloudMediumImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() tb1 := &types.TrustBoundary{ Id: "tb1", Type: types.NetworkVirtualLAN, TechnicalAssetsInside: []string{"ta1", "ta2"}, } comm := &types.CommunicationLink{ Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{comm}, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, Confidentiality: types.StrictlyConfidential, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta2": {comm}, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb1, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksStrictlyConfidentialDifferentTrustBoundaryNotCloudLowImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() tb1 := &types.TrustBoundary{ Id: "tb1", Type: types.NetworkVirtualLAN, TechnicalAssetsInside: []string{"ta1"}, } tb2 := &types.TrustBoundary{ Id: "tb2", Type: types.NetworkVirtualLAN, TechnicalAssetsInside: []string{"ta2"}, } comm := &types.CommunicationLink{ Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{comm}, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, Confidentiality: types.Confidential, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta2": {comm}, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksWithinDevopsUnlikelyLikelihoodRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{ { Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", Usage: types.DevOps, }, }, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Unlikely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) } func TestServerSideRequestForgeryRuleGenerateRisksStrictlyConfidentialNotHttpAccessDifferentTrustBoundaryNotCloudLowImpactRisksCreated(t *testing.T) { rule := NewServerSideRequestForgeryRule() tb1 := &types.TrustBoundary{ Id: "tb1", Type: types.NetworkVirtualLAN, TechnicalAssetsInside: []string{"ta1"}, } tb2 := &types.TrustBoundary{ Id: "tb2", Type: types.NetworkVirtualLAN, TechnicalAssetsInside: []string{"ta2", "ta3"}, } comm := &types.CommunicationLink{ Protocol: types.HTTP, TargetId: "ta2", Title: "Test Communication Link", } comm2 := &types.CommunicationLink{ Protocol: types.SqlAccessProtocol, TargetId: "ta1", Title: "Test Communication Link 2", } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsClient: false, types.LoadBalancer: false, }, }, }, CommunicationLinks: []*types.CommunicationLink{comm, comm2}, }, "ta2": { Id: "ta2", Title: "Test Target Asset", OutOfScope: false, Confidentiality: types.Confidential, }, "ta3": { Id: "ta3", Title: "Test Source Asset", OutOfScope: false, Confidentiality: types.StrictlyConfidential, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta2": {comm}, "ta1": {comm2}, }, TrustBoundaries: map[string]*types.TrustBoundary{ "tb1": tb1, "tb2": tb2, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, "ta3": tb2, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) assert.Equal(t, types.Likely, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>Test Technical Asset</b> server-side web-requesting the target <b>Test Target Asset</b> via <b>Test Communication Link</b>", risks[0].Title) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_identity_provider_isolation_rule_test.go
pkg/risks/builtin/missing_identity_provider_isolation_rule_test.go
package builtin import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingIdentityProviderIsolationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityProviderIsolationRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityProviderIsolationRuleGenerateRisksNotIdentityRelatedNoRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityProviderIsolationRuleGenerateRisksSparringAssetIsIdentityRelatedRelatedNoRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Test Sparring Technical Asset", Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityProviderIsolationRuleGenerateRisksSparringAssetIsCloseToHighValueTargetsToleratedNoRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Test Sparring Technical Asset", Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsCloseToHighValueTargetsTolerated: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingIdentityProviderIsolationRuleGenerateRisksSparringAssetNotInTheSameTrustBoundaryOrExecutionEnvironmentNoRisksCreated(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() tb1 := &types.TrustBoundary{ Id: "tb1", } tb2 := &types.TrustBoundary{ Id: "tb2", } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "some-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Test Sparring Technical Asset", }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb1, "ta2": tb2, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type MissingIdentityProviderIsolationRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality availability types.Criticality tbType types.TrustBoundaryType expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood expectedTrustBoundaryMessage string } func TestMissingIdentityProviderIsolationRule(t *testing.T) { testCases := map[string]MissingIdentityProviderIsolationRuleTest{ "same execution environment": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, tbType: types.ExecutionEnvironment, expectedImpact: types.HighImpact, expectedLikelihood: types.Likely, expectedTrustBoundaryMessage: "execution environment", }, "more impact for strictly confidential asset": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, availability: types.Critical, tbType: types.ExecutionEnvironment, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, expectedTrustBoundaryMessage: "execution environment", }, "more impact for mission critical integrity asset": { confidentiality: types.Confidential, integrity: types.MissionCritical, availability: types.Critical, tbType: types.ExecutionEnvironment, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, expectedTrustBoundaryMessage: "execution environment", }, "more impact for mission critical availability asset": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.MissionCritical, tbType: types.ExecutionEnvironment, expectedImpact: types.VeryHighImpact, expectedLikelihood: types.Likely, expectedTrustBoundaryMessage: "execution environment", }, "same network trust boundary": { confidentiality: types.Confidential, integrity: types.Critical, availability: types.Critical, tbType: types.NetworkOnPrem, expectedImpact: types.HighImpact, expectedLikelihood: types.Unlikely, expectedTrustBoundaryMessage: "network segment", }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewMissingIdentityProviderIsolationRule() tb := &types.TrustBoundary{ Id: "tb1", Type: testCase.tbType, } risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, Availability: testCase.availability, Technologies: types.TechnologyList{ { Name: "some-identity-related-technology", Attributes: map[string]bool{ types.IsIdentityRelated: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Test Sparring Technical Asset", }, }, DirectContainingTrustBoundaryMappedByTechnicalAssetId: map[string]*types.TrustBoundary{ "ta1": tb, "ta2": tb, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) expTitle := fmt.Sprintf("<b>Missing Identity Provider Isolation</b> to further encapsulate and protect identity-related asset <b>Test Technical Asset</b> against unrelated lower protected assets <b>in the same %s</b>, which might be easier to compromise by attackers", testCase.expectedTrustBoundaryMessage) assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_authentication_second_factor_rule.go
pkg/risks/builtin/missing_authentication_second_factor_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type MissingAuthenticationSecondFactorRule struct { missingAuthenticationRule *MissingAuthenticationRule } func NewMissingAuthenticationSecondFactorRule(missingAuthenticationRule *MissingAuthenticationRule) *MissingAuthenticationSecondFactorRule { return &MissingAuthenticationSecondFactorRule{missingAuthenticationRule: missingAuthenticationRule} } func (*MissingAuthenticationSecondFactorRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "missing-authentication-second-factor", Title: "Missing Two-Factor Authentication (2FA)", Description: "Technical assets (especially multi-tenant systems) should authenticate incoming requests with " + "two-factor (2FA) authentication when the asset processes or stores highly sensitive data (in terms of confidentiality, integrity, and availability) and is accessed by humans.", Impact: "If this risk is unmitigated, attackers might be able to access or modify highly sensitive data without strong authentication.", ASVS: "V2 - Authentication Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html", Action: "Authentication with Second Factor (2FA)", Mitigation: "Apply an authentication method to the technical asset protecting highly sensitive data via " + "two-factor authentication for human users.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.BusinessSide, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets (except " + types.LoadBalancer + ", " + types.ReverseProxy + ", " + types.WAF + ", " + types.IDS + ", and " + types.IPS + ") should authenticate incoming requests via two-factor authentication (2FA) " + "when the asset processes or stores highly sensitive data (in terms of confidentiality, integrity, and availability) and is accessed by a client used by a human user.", RiskAssessment: types.MediumSeverity.String(), FalsePositives: "Technical assets which do not process requests regarding functionality or data linked to end-users (customers) " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 308, } } func (*MissingAuthenticationSecondFactorRule) SupportedTags() []string { return []string{} } func (r *MissingAuthenticationSecondFactorRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if r.skipAsset(technicalAsset, input) { continue } // check each incoming data flow commLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, commLink := range commLinks { caller := input.TechnicalAssets[commLink.SourceId] if caller.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) || caller.Type == types.Datastore { continue } if caller.UsedAsClientByHuman { risks = appendRisk(input, risks, r, technicalAsset, commLink, commLink, "") } else if caller.Technologies.GetAttribute(types.IsTrafficForwarding) { // Now try to walk a call chain up (1 hop only) to find a caller's caller used by human callersCommLinks := input.IncomingTechnicalCommunicationLinksMappedByTargetId[caller.Id] for _, callersCommLink := range callersCommLinks { callersCaller := input.TechnicalAssets[callersCommLink.SourceId] if callersCaller.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) || callersCaller.Type == types.Datastore || !callersCaller.UsedAsClientByHuman { continue } risks = appendRisk(input, risks, r, technicalAsset, commLink, callersCommLink, caller.Title) } } } } return risks, nil } func appendRisk( input *types.Model, risks []*types.Risk, r *MissingAuthenticationSecondFactorRule, technicalAsset *types.TechnicalAsset, commLink *types.CommunicationLink, callersCommLink *types.CommunicationLink, title string) []*types.Risk { moreRisky := input.HighestCommunicationLinkConfidentiality(callersCommLink) >= types.Confidential || input.HighestCommunicationLinkIntegrity(callersCommLink) >= types.Critical if moreRisky && callersCommLink.Authentication != types.TwoFactor { risks = append(risks, r.missingAuthenticationRule.createRisk(input, technicalAsset, commLink, callersCommLink, title, types.MediumImpact, types.Unlikely, true, r.Category())) } return risks } func (masf *MissingAuthenticationSecondFactorRule) skipAsset(technicalAsset *types.TechnicalAsset, input *types.Model) bool { if technicalAsset.OutOfScope || technicalAsset.Technologies.GetAttribute(types.IsTrafficForwarding) || technicalAsset.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) { return true } if input.HighestProcessedConfidentiality(technicalAsset) < types.Confidential && input.HighestProcessedIntegrity(technicalAsset) < types.Critical && input.HighestProcessedAvailability(technicalAsset) < types.Critical && !technicalAsset.MultiTenant { return true } return false }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unguarded_direct_datastore_access_rule.go
pkg/risks/builtin/unguarded_direct_datastore_access_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UnguardedDirectDatastoreAccessRule struct{} func NewUnguardedDirectDatastoreAccessRule() *UnguardedDirectDatastoreAccessRule { return &UnguardedDirectDatastoreAccessRule{} } func (*UnguardedDirectDatastoreAccessRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unguarded-direct-datastore-access", Title: "Unguarded Direct Datastore Access", Description: "Data stores accessed across trust boundaries must be guarded by some protecting service or application.", Impact: "If this risk is unmitigated, attackers might be able to directly attack sensitive data stores without any protecting components in-between.", ASVS: "V1 - Architecture, Design and Threat Modeling Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Encapsulation of Datastore", Mitigation: "Encapsulate the datastore access behind a guarding service or application.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.ElevationOfPrivilege, DetectionLogic: "In-scope technical assets of type " + types.Datastore.String() + " (except " + types.IdentityStoreLDAP + " when accessed from " + types.IdentityProvider + " and " + types.FileServer + " when accessed via file transfer protocols) with confidentiality rating " + "of " + types.Confidential.String() + " (or higher) or with integrity rating of " + types.Critical.String() + " (or higher) " + "which have incoming data-flows from assets outside across a network trust-boundary. DevOps config and deployment access is excluded from this risk.", // TODO new rule "missing bastion host"? RiskAssessment: "The matching technical assets are at " + types.LowSeverity.String() + " risk. When either the " + "confidentiality rating is " + types.StrictlyConfidential.String() + " or the integrity rating " + "is " + types.MissionCritical.String() + ", the risk-rating is considered " + types.MediumSeverity.String() + ". " + "For assets with RAA values higher than 40 % the risk-rating increases.", FalsePositives: "When the caller is considered fully trusted as if it was part of the datastore itself.", ModelFailurePossibleReason: false, CWE: 501, } } func (*UnguardedDirectDatastoreAccessRule) SupportedTags() []string { return []string{} } // check for data stores that should not be accessed directly across trust boundaries func (r *UnguardedDirectDatastoreAccessRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope || technicalAsset.Type != types.Datastore { continue } for _, incomingAccess := range input.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] { sourceAsset := input.TechnicalAssets[incomingAccess.SourceId] if technicalAsset.Technologies.GetAttribute(types.IsIdentityStore) && sourceAsset.Technologies.GetAttribute(types.IdentityProvider) { continue } if technicalAsset.Confidentiality < types.Confidential && technicalAsset.Integrity < types.Critical { continue } if incomingAccess.Usage == types.DevOps { continue } if !isAcrossTrustBoundaryNetworkOnly(input, incomingAccess) || fileServerAccessViaFTP(technicalAsset, incomingAccess) || isSharingSameParentTrustBoundary(input, technicalAsset, sourceAsset) { continue } highRisk := technicalAsset.Confidentiality == types.StrictlyConfidential || technicalAsset.Integrity == types.MissionCritical risks = append(risks, r.createRisk(technicalAsset, incomingAccess, input.TechnicalAssets[incomingAccess.SourceId], highRisk)) } } return risks, nil } func isSharingSameParentTrustBoundary(input *types.Model, left, right *types.TechnicalAsset) bool { tbIDLeft, tbIDRight := input.GetTechnicalAssetTrustBoundaryId(left), input.GetTechnicalAssetTrustBoundaryId(right) if len(tbIDLeft) == 0 && len(tbIDRight) > 0 { return false } if len(tbIDLeft) > 0 && len(tbIDRight) == 0 { return false } if len(tbIDLeft) == 0 && len(tbIDRight) == 0 { return true } if tbIDLeft == tbIDRight { return true } tbLeft, tbRight := input.TrustBoundaries[tbIDLeft], input.TrustBoundaries[tbIDRight] tbParentsLeft, tbParentsRight := input.AllParentTrustBoundaryIDs(tbLeft), input.AllParentTrustBoundaryIDs(tbRight) for _, parentLeft := range tbParentsLeft { for _, parentRight := range tbParentsRight { if parentLeft == parentRight { return true } } } return false } func fileServerAccessViaFTP(technicalAsset *types.TechnicalAsset, incomingAccess *types.CommunicationLink) bool { return technicalAsset.Technologies.GetAttribute(types.FileServer) && (incomingAccess.Protocol == types.FTP || incomingAccess.Protocol == types.FTPS || incomingAccess.Protocol == types.SFTP) } func (r *UnguardedDirectDatastoreAccessRule) createRisk(dataStore *types.TechnicalAsset, dataFlow *types.CommunicationLink, clientOutsideTrustBoundary *types.TechnicalAsset, moreRisky bool) *types.Risk { impact := types.LowImpact if moreRisky || dataStore.RAA > 40 { impact = types.MediumImpact } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Likely, impact), ExploitationLikelihood: types.Likely, ExploitationImpact: impact, Title: "<b>Unguarded Direct Datastore Access</b> of <b>" + dataStore.Title + "</b> by <b>" + clientOutsideTrustBoundary.Title + "</b> via <b>" + dataFlow.Title + "</b>", MostRelevantTechnicalAssetId: dataStore.Id, MostRelevantCommunicationLinkId: dataFlow.Id, DataBreachProbability: types.Improbable, DataBreachTechnicalAssetIDs: []string{dataStore.Id}, } risk.SyntheticId = risk.CategoryId + "@" + dataFlow.Id + "@" + clientOutsideTrustBoundary.Id + "@" + dataStore.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unencrypted_communication_rule.go
pkg/risks/builtin/unencrypted_communication_rule.go
package builtin import ( "slices" "github.com/threagile/threagile/pkg/types" ) type UnencryptedCommunicationRule struct{} func NewUnencryptedCommunicationRule() *UnencryptedCommunicationRule { return &UnencryptedCommunicationRule{} } func (*UnencryptedCommunicationRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unencrypted-communication", Title: "Unencrypted Communication", Description: "Due to the confidentiality and/or integrity rating of the data assets transferred over the " + "communication link this connection must be encrypted.", Impact: "If this risk is unmitigated, network attackers might be able to to eavesdrop on unencrypted sensitive data sent between components.", ASVS: "V9 - Communication Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html", Action: "Encryption of Communication Links", Mitigation: "Apply transport layer encryption to the communication link.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.InformationDisclosure, DetectionLogic: "Unencrypted technical communication links of in-scope technical assets (excluding " + types.Monitoring + " traffic as well as " + types.LocalFileAccess.String() + ", " + types.InProcessLibraryCall.String() + " and " + types.InterProcessCommunication.String() + ") " + "transferring sensitive data.", // TODO more detailed text required here RiskAssessment: "Depending on the confidentiality rating of the transferred data-assets either medium or high risk.", FalsePositives: "When all sensitive data sent over the communication link is already fully encrypted on document or data level. " + "Also intra-container/pod communication can be considered false positive when container orchestration platform handles encryption.", ModelFailurePossibleReason: false, CWE: 319, } } func (*UnencryptedCommunicationRule) SupportedTags() []string { return []string{} } // check for communication links that should be encrypted due to their confidentiality and/or integrity func (r *UnencryptedCommunicationRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { for _, dataFlow := range technicalAsset.CommunicationLinks { sourceAsset := input.TechnicalAssets[dataFlow.SourceId] targetAsset := input.TechnicalAssets[dataFlow.TargetId] if sourceAsset.OutOfScope && targetAsset.OutOfScope { continue } if dataFlow.Protocol.IsEncrypted() || dataFlow.Protocol.IsProcessLocal() { continue } if sourceAsset.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) || targetAsset.Technologies.GetAttribute(types.IsUnprotectedCommunicationsTolerated) { continue } transferringAuthData := dataFlow.Authentication != types.NoneAuthentication dataAssetIds := append(dataFlow.DataAssetsSent, dataFlow.DataAssetsReceived...) slices.Sort(dataAssetIds) // ensure deterministic order for _, sentDataAsset := range dataAssetIds { dataAsset := input.DataAssets[sentDataAsset] if isHighSensitivity(dataAsset) || transferringAuthData { risks = append(risks, r.createRisk(input, technicalAsset, dataFlow, true, transferringAuthData)) break } if !dataFlow.VPN && isMediumSensitivity(dataAsset) { risks = append(risks, r.createRisk(input, technicalAsset, dataFlow, false, transferringAuthData)) break } } } } return risks, nil } func (r *UnencryptedCommunicationRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, dataFlow *types.CommunicationLink, highRisk bool, transferringAuthData bool) *types.Risk { impact := types.MediumImpact if highRisk { impact = types.HighImpact } target := input.TechnicalAssets[dataFlow.TargetId] title := "<b>Unencrypted Communication</b> named <b>" + dataFlow.Title + "</b> between <b>" + technicalAsset.Title + "</b> and <b>" + target.Title + "</b>" if transferringAuthData { title += " transferring authentication data (like credentials, token, session-id, etc.)" } if dataFlow.VPN { title += " (even VPN-protected connections need to encrypt their data in-transit when confidentiality is " + "rated " + types.StrictlyConfidential.String() + " or integrity is rated " + types.MissionCritical.String() + ")" } likelihood := types.Unlikely if isAcrossTrustBoundaryNetworkOnly(input, dataFlow) { likelihood = types.Likely } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: dataFlow.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: []string{target.Id}, } risk.SyntheticId = risk.CategoryId + "@" + dataFlow.Id + "@" + technicalAsset.Id + "@" + target.Id return risk } func isHighSensitivity(dataAsset *types.DataAsset) bool { return dataAsset.Confidentiality == types.StrictlyConfidential || dataAsset.Integrity == types.MissionCritical } func isMediumSensitivity(dataAsset *types.DataAsset) bool { return dataAsset.Confidentiality == types.Confidential || dataAsset.Integrity == types.Critical }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/accidental_secret_leak_rule.go
pkg/risks/builtin/accidental_secret_leak_rule.go
package builtin import ( "fmt" "strings" "github.com/threagile/threagile/pkg/types" ) type AccidentalSecretLeakRule struct{} func NewAccidentalSecretLeakRule() *AccidentalSecretLeakRule { return &AccidentalSecretLeakRule{} } func (*AccidentalSecretLeakRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "accidental-secret-leak", Title: "Accidental Secret Leak", Description: "Sourcecode repositories (including their histories) as well as artifact registries can accidentally contain secrets like " + "checked-in or packaged-in passwords, API tokens, certificates, crypto keys, etc.", Impact: "If this risk is unmitigated, attackers which have access to affected sourcecode repositories or artifact registries might " + "find secrets accidentally checked-in.", ASVS: "V14 - Configuration Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html", Action: "Build Pipeline Hardening", Mitigation: "Establish measures preventing accidental check-in or package-in of secrets into sourcecode repositories " + "and artifact registries. This starts by using good .gitignore and .dockerignore files, but does not stop there. " + "See for example tools like <i>\"git-secrets\" or \"Talisman\"</i> to have check-in preventive measures for secrets. " + "Consider also to regularly scan your repositories for secrets accidentally checked-in using scanning tools like <i>\"gitleaks\" or \"gitrob\"</i>.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Operations, STRIDE: types.InformationDisclosure, DetectionLogic: "In-scope sourcecode repositories and artifact registries.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed.", FalsePositives: "Usually no false positives.", ModelFailurePossibleReason: false, CWE: 200, } } func (*AccidentalSecretLeakRule) SupportedTags() []string { // todo: how is 'nexus' being used? return []string{"git", "nexus"} } func (r *AccidentalSecretLeakRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { techAsset := parsedModel.TechnicalAssets[id] if r.skipAsset(techAsset) { continue } var risk *types.Risk if techAsset.IsTaggedWithAny("git") { risk = r.createRisk(parsedModel, techAsset, "Git", "Git Leak Prevention") } else { risk = r.createRisk(parsedModel, techAsset, "", "") } risks = append(risks, risk) } return risks, nil } func (asl AccidentalSecretLeakRule) skipAsset(techAsset *types.TechnicalAsset) bool { return techAsset.OutOfScope || !techAsset.Technologies.GetAttribute(types.MayContainSecrets) } func (r *AccidentalSecretLeakRule) createRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset, prefix, details string) *types.Risk { if len(prefix) > 0 { prefix = " (" + prefix + ")" } title := "<b>Accidental Secret Leak" + prefix + "</b> risk at <b>" + technicalAsset.Title + "</b>" if len(details) > 0 { title += ": <u>" + details + "</u>" } impact := types.LowImpact highestProcessedConfidentiality := parsedModel.HighestProcessedConfidentiality(technicalAsset) highestProcessedIntegrity := parsedModel.HighestProcessedIntegrity(technicalAsset) highestProcessedAvailability := parsedModel.HighestProcessedAvailability(technicalAsset) if highestProcessedConfidentiality >= types.Confidential || highestProcessedIntegrity >= types.Critical || highestProcessedAvailability >= types.Critical { impact = types.MediumImpact } if highestProcessedConfidentiality == types.StrictlyConfidential || highestProcessedIntegrity == types.MissionCritical || highestProcessedAvailability == types.MissionCritical { impact = types.HighImpact } // create risk risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk } func (r *AccidentalSecretLeakRule) MatchRisk(parsedModel *types.Model, risk string) bool { categoryId := r.Category().ID for _, id := range parsedModel.SortedTechnicalAssetIDs() { techAsset := parsedModel.TechnicalAssets[id] if strings.EqualFold(risk, categoryId+"@"+techAsset.Id) || strings.EqualFold(risk, categoryId+"@*") { return true } } return false } func (r *AccidentalSecretLeakRule) ExplainRisk(parsedModel *types.Model, risk string) []string { categoryId := r.Category().ID explanation := make([]string, 0) for _, id := range parsedModel.SortedTechnicalAssetIDs() { techAsset := parsedModel.TechnicalAssets[id] if strings.EqualFold(risk, categoryId+"@"+techAsset.Id) || strings.EqualFold(risk, categoryId+"@*") { if !techAsset.OutOfScope && (techAsset.Technologies.GetAttribute(types.SourcecodeRepository) || techAsset.Technologies.GetAttribute(types.ArtifactRegistry)) { riskExplanation := r.explainRisk(parsedModel, techAsset) if riskExplanation != nil { if len(explanation) > 0 { explanation = append(explanation, "") } explanation = append(explanation, []string{ fmt.Sprintf("technical asset %q", techAsset.Id), fmt.Sprintf(" - out of scope: %v (=false)", techAsset.OutOfScope), fmt.Sprintf(" - technology: %v (has either [%q, %q])", techAsset.Technologies.String(), types.SourcecodeRepository, types.ArtifactRegistry), }...) if techAsset.IsTaggedWithAny("git") { explanation = append(explanation, " is tagged with 'git'") } explanation = append(explanation, riskExplanation...) } } } } return explanation } func (r *AccidentalSecretLeakRule) explainRisk(parsedModel *types.Model, technicalAsset *types.TechnicalAsset) []string { explanation := make([]string, 0) impact := types.LowImpact if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential || parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical || parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { impact = types.HighImpact explanation = append(explanation, fmt.Sprintf(" - impact is %v because", impact), ) if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential { explanation = append(explanation, fmt.Sprintf(" => highest confidentiality: %v (==%v)", parsedModel.HighestProcessedConfidentiality(technicalAsset), types.StrictlyConfidential), ) } if parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { explanation = append(explanation, fmt.Sprintf(" => highest integrity: %v (==%v)", parsedModel.HighestProcessedIntegrity(technicalAsset), types.MissionCritical), ) } if parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { explanation = append(explanation, fmt.Sprintf(" => highest availability: %v (==%v)", parsedModel.HighestProcessedAvailability(technicalAsset), types.MissionCritical), ) } } else if parsedModel.HighestProcessedConfidentiality(technicalAsset) >= types.Confidential || parsedModel.HighestProcessedIntegrity(technicalAsset) >= types.Critical || parsedModel.HighestProcessedAvailability(technicalAsset) >= types.Critical { impact = types.MediumImpact explanation = append(explanation, fmt.Sprintf(" - impact is %v because", impact), ) if parsedModel.HighestProcessedConfidentiality(technicalAsset) == types.StrictlyConfidential { explanation = append(explanation, fmt.Sprintf(" => highest confidentiality: %v (>=%v)", parsedModel.HighestProcessedConfidentiality(technicalAsset), types.Confidential), ) } if parsedModel.HighestProcessedIntegrity(technicalAsset) == types.MissionCritical { explanation = append(explanation, fmt.Sprintf(" => highest integrity: %v (==%v)", parsedModel.HighestProcessedIntegrity(technicalAsset), types.Critical), ) } if parsedModel.HighestProcessedAvailability(technicalAsset) == types.MissionCritical { explanation = append(explanation, fmt.Sprintf(" => highest availability: %v (==%v)", parsedModel.HighestProcessedAvailability(technicalAsset), types.Critical), ) } } else { explanation = append(explanation, fmt.Sprintf(" - impact is %v (default)", impact), ) } return explanation }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/server_side_request_forgery_rule.go
pkg/risks/builtin/server_side_request_forgery_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type ServerSideRequestForgeryRule struct{} func NewServerSideRequestForgeryRule() *ServerSideRequestForgeryRule { return &ServerSideRequestForgeryRule{} } func (*ServerSideRequestForgeryRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "server-side-request-forgery", Title: "Server-Side Request Forgery (SSRF)", Description: "When a server system (i.e. not a client) is accessing other server systems via typical web protocols " + "Server-Side Request Forgery (SSRF) or Local-File-Inclusion (LFI) or Remote-File-Inclusion (RFI) risks might arise. ", Impact: "If this risk is unmitigated, attackers might be able to access sensitive services or files of network-reachable components by modifying outgoing calls of affected components.", ASVS: "V12 - File and Resources Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html", Action: "SSRF Prevention", Mitigation: "Try to avoid constructing the outgoing target URL with caller controllable values. Alternatively use a mapping (whitelist) when accessing outgoing URLs instead of creating them including caller " + "controllable values. " + "When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Development, STRIDE: types.InformationDisclosure, DetectionLogic: "In-scope non-client systems accessing (using outgoing communication links) targets with either HTTP or HTTPS protocol.", RiskAssessment: "The risk rating (low or medium) depends on the sensitivity of the data assets receivable via web protocols from " + "targets within the same network trust-boundary as well on the sensitivity of the data assets receivable via web protocols from the target asset itself. " + "Also for cloud-based environments the exploitation impact is at least medium, as cloud backend services can be attacked via SSRF.", FalsePositives: "Servers not sending outgoing web requests can be considered " + "as false positives after review.", ModelFailurePossibleReason: false, CWE: 918, } } func (*ServerSideRequestForgeryRule) SupportedTags() []string { return []string{} } func (r *ServerSideRequestForgeryRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, id := range input.SortedTechnicalAssetIDs() { technicalAsset := input.TechnicalAssets[id] if technicalAsset.OutOfScope || technicalAsset.Technologies.GetAttribute(types.IsClient) || technicalAsset.Technologies.GetAttribute(types.LoadBalancer) { continue } for _, outgoingFlow := range technicalAsset.CommunicationLinks { if outgoingFlow.Protocol.IsPotentialWebAccessProtocol() { risks = append(risks, r.createRisk(input, technicalAsset, outgoingFlow)) } } } return risks, nil } func (r *ServerSideRequestForgeryRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset, outgoingFlow *types.CommunicationLink) *types.Risk { target := input.TechnicalAssets[outgoingFlow.TargetId] title := "<b>Server-Side Request Forgery (SSRF)</b> risk at <b>" + technicalAsset.Title + "</b> server-side web-requesting " + "the target <b>" + target.Title + "</b> via <b>" + outgoingFlow.Title + "</b>" impact := types.LowImpact // check by the target itself (can be in another trust-boundary) if input.HighestProcessedConfidentiality(target) == types.StrictlyConfidential { impact = types.MediumImpact } // check all potential attack targets within the same trust boundary (accessible via web protocols) uniqueDataBreachTechnicalAssetIDs := make(map[string]interface{}) uniqueDataBreachTechnicalAssetIDs[technicalAsset.Id] = true for _, potentialTargetAsset := range input.TechnicalAssets { if !isSameTrustBoundaryNetworkOnly(input, technicalAsset, potentialTargetAsset.Id) { continue } for _, commLinkIncoming := range input.IncomingTechnicalCommunicationLinksMappedByTargetId[potentialTargetAsset.Id] { if !commLinkIncoming.Protocol.IsPotentialWebAccessProtocol() { continue } uniqueDataBreachTechnicalAssetIDs[potentialTargetAsset.Id] = true if input.HighestProcessedConfidentiality(potentialTargetAsset) == types.StrictlyConfidential { impact = types.MediumImpact } } } // adjust for cloud-based special risks trustBoundaryId := input.GetTechnicalAssetTrustBoundaryId(technicalAsset) if impact == types.LowImpact && len(trustBoundaryId) > 0 && input.TrustBoundaries[input.GetTechnicalAssetTrustBoundaryId(technicalAsset)].Type.IsWithinCloud() { impact = types.MediumImpact } dataBreachTechnicalAssetIDs := make([]string, 0) for key := range uniqueDataBreachTechnicalAssetIDs { dataBreachTechnicalAssetIDs = append(dataBreachTechnicalAssetIDs, key) } likelihood := types.Likely if outgoingFlow.Usage == types.DevOps { likelihood = types.Unlikely } risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: outgoingFlow.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: dataBreachTechnicalAssetIDs, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id + "@" + target.Id + "@" + outgoingFlow.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/sql_nosql_injection_rule_test.go
pkg/risks/builtin/sql_nosql_injection_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestSqlNoSqlInjectionRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewSqlNoSqlInjectionRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestSqlNoSqlInjectionRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewSqlNoSqlInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.ServiceRegistry: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type SqlNoSqlInjectionRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality usage types.Usage assetType types.TechnicalAssetType protocol types.Protocol isVulnerableToQueryInjection bool expectRiskCreated bool expectedLikelihood types.RiskExploitationLikelihood expectedImpact types.RiskExploitationImpact } func TestSqlNoSqlInjectionRuleCreateRisks(t *testing.T) { testCases := map[string]SqlNoSqlInjectionRuleTest{ "not database protocol": { assetType: types.Datastore, protocol: types.SmbEncrypted, expectRiskCreated: false, isVulnerableToQueryInjection: true, }, "not vulnerable to query injection not lax": { assetType: types.Datastore, protocol: types.JdbcEncrypted, expectRiskCreated: false, isVulnerableToQueryInjection: false, }, "lax database always vulnerable to query injection": { assetType: types.Datastore, protocol: types.HTTP, isVulnerableToQueryInjection: false, expectRiskCreated: true, expectedLikelihood: types.VeryLikely, expectedImpact: types.MediumImpact, }, "no datastore": { assetType: types.Process, protocol: types.JdbcEncrypted, isVulnerableToQueryInjection: true, expectRiskCreated: false, }, "database protocol and vulnerable to query injection": { assetType: types.Datastore, protocol: types.JdbcEncrypted, expectRiskCreated: true, isVulnerableToQueryInjection: true, expectedLikelihood: types.VeryLikely, expectedImpact: types.MediumImpact, }, "strictly confidential tech asset high impact": { assetType: types.Datastore, protocol: types.JdbcEncrypted, expectRiskCreated: true, isVulnerableToQueryInjection: true, confidentiality: types.StrictlyConfidential, integrity: types.Critical, expectedLikelihood: types.VeryLikely, expectedImpact: types.HighImpact, }, "mission critical integrity tech asset high impact": { assetType: types.Datastore, protocol: types.JdbcEncrypted, expectRiskCreated: true, isVulnerableToQueryInjection: true, confidentiality: types.Confidential, integrity: types.MissionCritical, expectedLikelihood: types.VeryLikely, expectedImpact: types.HighImpact, }, "devops usage likely likelihood": { assetType: types.Datastore, protocol: types.JdbcEncrypted, expectRiskCreated: true, isVulnerableToQueryInjection: true, usage: types.DevOps, confidentiality: types.Confidential, integrity: types.Critical, expectedLikelihood: types.Likely, expectedImpact: types.MediumImpact, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewSqlNoSqlInjectionRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Type: testCase.assetType, Technologies: types.TechnologyList{ { Name: "service-registry", Attributes: map[string]bool{ types.IsVulnerableToQueryInjection: testCase.isVulnerableToQueryInjection, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: false, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Incoming Flow", TargetId: "ta1", SourceId: "ta2", Protocol: testCase.protocol, Usage: testCase.usage, }, }, }, }) assert.Nil(t, err) if testCase.expectRiskCreated { assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) assert.Equal(t, "<b>SQL/NoSQL-Injection</b> risk at <b>Caller Technical Asset</b> against database <b>Test Technical Asset</b> via <b>Incoming Flow</b>", risks[0].Title) } else { assert.Empty(t, risks) } }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/unchecked_deployment_rule.go
pkg/risks/builtin/unchecked_deployment_rule.go
package builtin import ( "github.com/threagile/threagile/pkg/types" ) type UncheckedDeploymentRule struct{} func NewUncheckedDeploymentRule() *UncheckedDeploymentRule { return &UncheckedDeploymentRule{} } func (*UncheckedDeploymentRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "unchecked-deployment", Title: "Unchecked Deployment", Description: "For each build-pipeline component Unchecked Deployment risks might arise when the build-pipeline " + "does not include established DevSecOps best-practices. DevSecOps best-practices scan as part of CI/CD pipelines for " + "vulnerabilities in source- or byte-code, dependencies, container layers, and dynamically against running test systems. " + "There are several open-source and commercial tools existing in the categories DAST, SAST, and IAST.", Impact: "If this risk remains unmitigated, vulnerabilities in custom-developed software or their dependencies " + "might not be identified during continuous deployment cycles.", ASVS: "V14 - Configuration Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Vulnerable_Dependency_Management_Cheat_Sheet.html", Action: "Build Pipeline Hardening", Mitigation: "Apply DevSecOps best-practices and use scanning tools to identify vulnerabilities in source- or byte-code," + "dependencies, container layers, and optionally also via dynamic scans against running test systems.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: types.Architecture, STRIDE: types.Tampering, DetectionLogic: "All development-relevant technical assets.", RiskAssessment: "The risk rating depends on the highest rating of the technical assets and data assets processed by deployment-receiving targets.", FalsePositives: "When the build-pipeline does not build any software components it can be considered a false positive " + "after individual review.", ModelFailurePossibleReason: false, CWE: 1127, } } func (*UncheckedDeploymentRule) SupportedTags() []string { return []string{} } func (r *UncheckedDeploymentRule) GenerateRisks(input *types.Model) ([]*types.Risk, error) { risks := make([]*types.Risk, 0) for _, technicalAsset := range input.TechnicalAssets { if technicalAsset.Technologies.GetAttribute(types.IsDevelopmentRelevant) { risks = append(risks, r.createRisk(input, technicalAsset)) } } return risks, nil } func (r *UncheckedDeploymentRule) createRisk(input *types.Model, technicalAsset *types.TechnicalAsset) *types.Risk { title := "<b>Unchecked Deployment</b> risk at <b>" + technicalAsset.Title + "</b>" // impact is depending on highest rating impact := types.LowImpact // data breach at all deployment targets uniqueDataBreachTechnicalAssetIDs := make(map[string]interface{}) uniqueDataBreachTechnicalAssetIDs[technicalAsset.Id] = true for _, codeDeploymentTargetCommLink := range technicalAsset.CommunicationLinks { if codeDeploymentTargetCommLink.Usage != types.DevOps { continue } for _, dataAssetID := range codeDeploymentTargetCommLink.DataAssetsSent { // it appears to be code when elevated integrity rating of sent data asset if input.DataAssets[dataAssetID].Integrity >= types.Important { // here we've got a deployment target which has its data assets at risk via deployment of backdoored code uniqueDataBreachTechnicalAssetIDs[codeDeploymentTargetCommLink.TargetId] = true targetTechAsset := input.TechnicalAssets[codeDeploymentTargetCommLink.TargetId] if input.HighestProcessedConfidentiality(targetTechAsset) >= types.Confidential || input.HighestProcessedIntegrity(targetTechAsset) >= types.Critical || input.HighestProcessedAvailability(targetTechAsset) >= types.Critical { impact = types.MediumImpact } break } } } dataBreachTechnicalAssetIDs := make([]string, 0) for key := range uniqueDataBreachTechnicalAssetIDs { dataBreachTechnicalAssetIDs = append(dataBreachTechnicalAssetIDs, key) } // create risk risk := &types.Risk{ CategoryId: r.Category().ID, Severity: types.CalculateSeverity(types.Unlikely, impact), ExploitationLikelihood: types.Unlikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: dataBreachTechnicalAssetIDs, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/path_traversal_rule_test.go
pkg/risks/builtin/path_traversal_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestPathTraversalRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestPathTraversalRuleGenerateRisksOutOfScopeNoRisksCreated(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, Technologies: types.TechnologyList{ { Name: "file-storage", Attributes: map[string]bool{ types.IsFileStorage: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPathTraversalRuleGenerateRisksNotFileStorageNoRisksCreated(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "file-storage", Attributes: map[string]bool{ types.IsFileStorage: false, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPathTraversalRuleGenerateRisksFileStorageWithoutIncomingCommunicationLinksNoRisksCreated(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "file-storage", Attributes: map[string]bool{ types.IsFileStorage: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestPathTraversalRuleGenerateRisksCallerOutOfScopeNoRisksCreated(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "file-storage", Attributes: map[string]bool{ types.IsFileStorage: true, }, }, }, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", OutOfScope: true, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } type PathTraversalRuleTest struct { confidentiality types.Confidentiality integrity types.Criticality communicationUsage types.Usage expectedImpact types.RiskExploitationImpact expectedLikelihood types.RiskExploitationLikelihood } func TestPathTraversalRuleGenerateRisksRiskCreated(t *testing.T) { testCases := map[string]PathTraversalRuleTest{ "medium impact": { confidentiality: types.Confidential, integrity: types.Critical, communicationUsage: types.Business, expectedImpact: types.MediumImpact, expectedLikelihood: types.VeryLikely, }, "strictly confidential high impact": { confidentiality: types.StrictlyConfidential, integrity: types.Critical, communicationUsage: types.Business, expectedImpact: types.HighImpact, expectedLikelihood: types.VeryLikely, }, "mission critical integrity high impact": { confidentiality: types.Confidential, integrity: types.MissionCritical, communicationUsage: types.Business, expectedImpact: types.HighImpact, expectedLikelihood: types.VeryLikely, }, "devops usage likelihood likely": { confidentiality: types.Confidential, integrity: types.Critical, communicationUsage: types.DevOps, expectedImpact: types.MediumImpact, expectedLikelihood: types.Likely, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { rule := NewPathTraversalRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", OutOfScope: false, Technologies: types.TechnologyList{ { Name: "file-storage", Attributes: map[string]bool{ types.IsFileStorage: true, }, }, }, Confidentiality: testCase.confidentiality, Integrity: testCase.integrity, }, "ta2": { Id: "ta2", Title: "Caller Technical Asset", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Call File Storage", SourceId: "ta2", Usage: testCase.communicationUsage, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, testCase.expectedImpact, risks[0].ExploitationImpact) assert.Equal(t, testCase.expectedLikelihood, risks[0].ExploitationLikelihood) expTitle := "<b>Path-Traversal</b> risk at <b>Caller Technical Asset</b> against filesystem <b>Test Technical Asset</b> via <b>Call File Storage</b>" assert.Equal(t, expTitle, risks[0].Title) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/risks/builtin/missing_authentication_rule_test.go
pkg/risks/builtin/missing_authentication_rule_test.go
package builtin import ( "testing" "github.com/stretchr/testify/assert" "github.com/threagile/threagile/pkg/types" ) func TestMissingAuthenticationRuleGenerateRisksEmptyModelNotRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{}) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksOutOfScopeNotRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", OutOfScope: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksTechnicalAssetWithoutCommunicationLinksNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksTechnicalAssetWithoutAuthenticationRequiredNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", Technologies: types.TechnologyList{ { Name: "tool", Attributes: map[string]bool{ types.NoAuthenticationRequired: true, }, }, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksTechnicalAssetMultiTenantWithoutCommunicationLinksNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Title: "Test Technical Asset", MultiTenant: true, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksCallerFromDatastoreNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Test Datastore", Type: types.Datastore, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksCallerTechnologyToleratesUnprotectedCommunicationsNoRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Test Monitoring", Technologies: types.TechnologyList{ { Name: "monitoring", Attributes: map[string]bool{ types.IsUnprotectedCommunicationsTolerated: true, }, }, }, }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { SourceId: "ta2", }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) } func TestMissingAuthenticationRuleGenerateRisksWithParameterisedAuthenticationAndProtocolNoRisksCreated(t *testing.T) { tests := []struct { name string authentication types.Authentication protocol types.Protocol expected bool }{ {"Authentication: none, Local: true", types.NoneAuthentication, types.LocalFileAccess, false}, {"Authentication: provided, Local: true", types.ClientCertificate, types.LocalFileAccess, false}, {"Authentication: provided, Local: false", types.ClientCertificate, types.HTTPS, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset 1", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "Test Technical Asset 2", MultiTenant: true, // require less code instead of adding processed data }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "Communication Link", SourceId: "ta2", Authentication: tt.authentication, Protocol: tt.protocol, }, }, }, }) assert.Nil(t, err) assert.Empty(t, risks) }) } } func TestMissingAuthenticationRuleGenerateRisksNoneAuthenticationNonLocalProcessRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "User Interface", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "User Access via Browser", SourceId: "ta2", Authentication: types.NoneAuthentication, Protocol: types.HTTPS, }, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Authentication</b> covering communication link <b>User Access via Browser</b> from <b>User Interface</b> to <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) } func TestMissingAuthenticationRuleGenerateRisksSendStrictlyConfidentialDataAssetRisksCreatedWithHighImpact(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "User Interface", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "User Access via Browser", SourceId: "ta2", Authentication: types.NoneAuthentication, Protocol: types.HTTPS, DataAssetsSent: []string{"strictly-confidential"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "strictly-confidential": { Id: "strictly-confidential", Title: "Strictly Confidential Data", Confidentiality: types.StrictlyConfidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Authentication</b> covering communication link <b>User Access via Browser</b> from <b>User Interface</b> to <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.HighImpact, risks[0].ExploitationImpact) } func TestMissingAuthenticationRuleGenerateRisksOperationalIntegrityRisksCreatedWithLowImpact(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", MultiTenant: true, // require less code instead of adding processed data }, "ta2": { Id: "ta2", Title: "User Interface", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "User Access via Browser", SourceId: "ta2", Authentication: types.NoneAuthentication, Protocol: types.HTTPS, DataAssetsSent: []string{"operational"}, }, }, }, DataAssets: map[string]*types.DataAsset{ "operational": { Id: "operational", Title: "Operational Data", Integrity: types.Operational, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Authentication</b> covering communication link <b>User Access via Browser</b> from <b>User Interface</b> to <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.LowImpact, risks[0].ExploitationImpact) } func TestMissingAuthenticationRuleGenerateRisksProcessingConfidentialDataRisksCreated(t *testing.T) { rule := NewMissingAuthenticationRule() risks, err := rule.GenerateRisks(&types.Model{ TechnicalAssets: map[string]*types.TechnicalAsset{ "ta1": { Id: "ta1", Title: "Test Technical Asset", DataAssetsProcessed: []string{"confidential"}, }, "ta2": { Id: "ta2", Title: "User Interface", }, }, IncomingTechnicalCommunicationLinksMappedByTargetId: map[string][]*types.CommunicationLink{ "ta1": { { Title: "User Access via Browser", SourceId: "ta2", Authentication: types.NoneAuthentication, Protocol: types.HTTPS, }, }, }, DataAssets: map[string]*types.DataAsset{ "confidential": { Id: "confidential", Title: "Confidential Data", Confidentiality: types.Confidential, }, }, }) assert.Nil(t, err) assert.Len(t, risks, 1) assert.Equal(t, "<b>Missing Authentication</b> covering communication link <b>User Access via Browser</b> from <b>User Interface</b> to <b>Test Technical Asset</b>", risks[0].Title) assert.Equal(t, types.MediumImpact, risks[0].ExploitationImpact) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/examples/examples.go
pkg/examples/examples.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package examples import ( "fmt" "io" "os" "path/filepath" ) func CreateExampleModelFile(appFolder, outputDir, inputFile string) error { _, err := copyFile(filepath.Join(appFolder, "threagile-example-model.yaml"), filepath.Join(outputDir, "threagile-example-model.yaml")) if err == nil { return nil } _, altError := copyFile(filepath.Join(appFolder, inputFile), filepath.Join(outputDir, "threagile-example-model.yaml")) if altError != nil { return err } return nil } func CreateStubModelFile(appFolder, outputDir, inputFile string) error { _, err := copyFile(filepath.Join(appFolder, "threagile-stub-model.yaml"), filepath.Join(outputDir, "threagile-stub-model.yaml")) if err == nil { return nil } _, altError := copyFile(filepath.Join(appFolder, inputFile), filepath.Join(outputDir, "threagile-stub-model.yaml")) if altError != nil { return err } return nil } func CreateEditingSupportFiles(appFolder, outputDir string) error { _, schemaError := copyFile(filepath.Join(appFolder, "schema.json"), filepath.Join(outputDir, "schema.json")) if schemaError != nil { return schemaError } _, templateError := copyFile(filepath.Join(appFolder, "live-templates.txt"), filepath.Join(outputDir, "live-templates.txt")) return templateError } func copyFile(src, dst string) (int64, error) { sourceFileStat, err := os.Stat(src) if err != nil { return 0, err } if !sourceFileStat.Mode().IsRegular() { return 0, fmt.Errorf("%s is not a regular file", src) } source, err := os.Open(filepath.Clean(src)) if err != nil { return 0, err } defer func() { _ = source.Close() }() destination, err := os.Create(filepath.Clean(dst)) if err != nil { return 0, err } defer func() { _ = destination.Close() }() nBytes, err := io.Copy(destination, source) return nBytes, err }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/server.go
pkg/server/server.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "fmt" "log" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "sync" "github.com/gin-gonic/gin" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/types" ) type serverConfigReader interface { GetBuildTimestamp() string GetVerbose() bool GetInteractive() bool GetAppFolder() string GetPluginFolder() string GetDataFolder() string GetOutputFolder() string GetServerFolder() string GetTempFolder() string GetKeyFolder() string GetInputFile() string GetImportedInputFile() string GetDataFlowDiagramFilenamePNG() string GetDataAssetDiagramFilenamePNG() string GetDataFlowDiagramFilenameDOT() string GetDataAssetDiagramFilenameDOT() string GetReportFilename() string GetExcelRisksFilename() string GetRiskExcelConfigHideColumns() []string GetRiskExcelConfigSortByColumns() []string GetRiskExcelConfigWidthOfColumns() map[string]float64 GetExcelTagsFilename() string GetJsonRisksFilename() string GetJsonTechnicalAssetsFilename() string GetJsonStatsFilename() string GetTemplateFilename() string GetTechnologyFilename() string GetRiskRulePlugins() []string GetSkipRiskRules() []string GetExecuteModelMacro() string GetServerMode() bool GetDiagramDPI() int GetServerPort() int GetGraphvizDPI() int GetMaxGraphvizDPI() int GetBackupHistoryFilesToKeep() int GetAddModelTitle() bool GetAddLegend() bool GetKeepDiagramSourceFiles() bool GetIgnoreOrphanedRiskTracking() bool GetThreagileVersion() string GetProgressReporter() types.ProgressReporter } type server struct { config serverConfigReader successCount int errorCount int globalLock sync.Mutex throttlerLock sync.Mutex createdObjectsThrottler map[string][]int64 mapTokenHashToTimeoutStruct map[string]timeoutStruct mapFolderNameToTokenHash map[string]string extremeShortTimeoutsForTesting bool locksByFolderName map[string]*sync.Mutex builtinRiskRules types.RiskRules customRiskRules types.RiskRules } func RunServer(config serverConfigReader, builtinRiskRules types.RiskRules) { s := &server{ config: config, createdObjectsThrottler: make(map[string][]int64), mapTokenHashToTimeoutStruct: make(map[string]timeoutStruct), mapFolderNameToTokenHash: make(map[string]string), extremeShortTimeoutsForTesting: false, locksByFolderName: make(map[string]*sync.Mutex), builtinRiskRules: builtinRiskRules, } router := gin.Default() router.LoadHTMLGlob(filepath.Join(s.config.GetServerFolder(), "static", "*.html")) // <== router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{}) }) router.HEAD("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{}) }) router.GET("/edit-model", func(c *gin.Context) { c.HTML(http.StatusOK, "edit-model.html", gin.H{}) }) router.HEAD("/edit-model", func(c *gin.Context) { c.HTML(http.StatusOK, "edit-model.html", gin.H{}) }) router.StaticFile("/css/edit-model.css", filepath.Join(s.config.GetServerFolder(), "static", "css", "edit-model.css")) // <== router.StaticFile("/js/edit-model.js", filepath.Join(s.config.GetServerFolder(), "static", "js", "edit-model.js")) // <== router.StaticFile("/js/property-editor.js", filepath.Join(s.config.GetServerFolder(), "static", "js", "property-editor.js")) // <== router.StaticFile("/js/schema.js", filepath.Join(s.config.GetServerFolder(), "static", "js", "schema.js")) // <== router.StaticFile("/threagile.png", filepath.Join(s.config.GetServerFolder(), "static", "threagile.png")) // <== router.StaticFile("/site.webmanifest", filepath.Join(s.config.GetServerFolder(), "static", "site.webmanifest")) router.StaticFile("/favicon.ico", filepath.Join(s.config.GetServerFolder(), "static", "favicon.ico")) router.StaticFile("/favicon-32x32.png", filepath.Join(s.config.GetServerFolder(), "static", "favicon-32x32.png")) router.StaticFile("/favicon-16x16.png", filepath.Join(s.config.GetServerFolder(), "static", "favicon-16x16.png")) router.StaticFile("/apple-touch-icon.png", filepath.Join(s.config.GetServerFolder(), "static", "apple-touch-icon.png")) router.StaticFile("/android-chrome-512x512.png", filepath.Join(s.config.GetServerFolder(), "static", "android-chrome-512x512.png")) router.StaticFile("/android-chrome-192x192.png", filepath.Join(s.config.GetServerFolder(), "static", "android-chrome-192x192.png")) router.StaticFile("/schema.json", filepath.Join(s.config.GetAppFolder(), "schema.json")) router.StaticFile("/live-templates.txt", filepath.Join(s.config.GetAppFolder(), "live-templates.txt")) router.StaticFile("/openapi.yaml", filepath.Join(s.config.GetAppFolder(), "openapi.yaml")) router.GET("/threagile-example-model.yaml", s.exampleFile) router.GET("/threagile-stub-model.yaml", s.stubFile) router.GET("/meta/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) router.GET("/meta/version", func(c *gin.Context) { c.JSON(200, gin.H{ "version": config.GetThreagileVersion(), "build_timestamp": s.config.GetBuildTimestamp(), }) }) router.GET("/meta/types", func(c *gin.Context) { c.JSON(200, gin.H{ "quantity": arrayOfStringValues(types.QuantityValues()), "confidentiality": arrayOfStringValues(types.ConfidentialityValues()), "criticality": arrayOfStringValues(types.CriticalityValues()), "technical_asset_type": arrayOfStringValues(types.TechnicalAssetTypeValues()), "technical_asset_size": arrayOfStringValues(types.TechnicalAssetSizeValues()), "authorization": arrayOfStringValues(types.AuthorizationValues()), "authentication": arrayOfStringValues(types.AuthenticationValues()), "usage": arrayOfStringValues(types.UsageValues()), "encryption": arrayOfStringValues(types.EncryptionStyleValues()), "data_format": arrayOfStringValues(types.DataFormatValues()), "protocol": arrayOfStringValues(types.ProtocolValues()), "technical_asset_technology": arrayOfStringValues(types.TechnicalAssetTechnologyValues(config)), "technical_asset_machine": arrayOfStringValues(types.TechnicalAssetMachineValues()), "trust_boundary_type": arrayOfStringValues(types.TrustBoundaryTypeValues()), "data_breach_probability": arrayOfStringValues(types.DataBreachProbabilityValues()), "risk_severity": arrayOfStringValues(types.RiskSeverityValues()), "risk_exploitation_likelihood": arrayOfStringValues(types.RiskExploitationLikelihoodValues()), "risk_exploitation_impact": arrayOfStringValues(types.RiskExploitationImpactValues()), "risk_function": arrayOfStringValues(types.RiskFunctionValues()), "risk_status": arrayOfStringValues(types.RiskStatusValues()), "stride": arrayOfStringValues(types.STRIDEValues()), }) }) // TODO router.GET("/meta/risk-rules", listRiskRules) // TODO router.GET("/meta/model-macros", listModelMacros) router.GET("/meta/stats", s.stats) router.POST("/edit-model/analyze", s.editModelAnalyze) router.POST("/direct/analyze", s.analyze) router.POST("/direct/check", s.check) router.GET("/direct/stub", s.stubFile) router.POST("/auth/keys", s.createKey) router.DELETE("/auth/keys", s.deleteKey) router.POST("/auth/tokens", s.createToken) router.DELETE("/auth/tokens", s.deleteToken) router.POST("/models", s.createNewModel) router.GET("/models", s.listModels) router.DELETE("/models/:model-id", s.deleteModel) router.GET("/models/:model-id", s.getModel) router.PUT("/models/:model-id", s.importModel) router.GET("/models/:model-id/data-flow-diagram", s.streamDataFlowDiagram) router.GET("/models/:model-id/data-asset-diagram", s.streamDataAssetDiagram) router.GET("/models/:model-id/report-pdf", s.streamReportPDF) router.GET("/models/:model-id/risks-excel", s.streamRisksExcel) router.GET("/models/:model-id/tags-excel", s.streamTagsExcel) router.GET("/models/:model-id/risks", s.streamRisksJSON) router.GET("/models/:model-id/technical-assets", s.streamTechnicalAssetsJSON) router.GET("/models/:model-id/stats", s.streamStatsJSON) router.GET("/models/:model-id/analysis", s.analyzeModelOnServerDirectly) router.GET("/models/:model-id/cover", s.getCover) router.PUT("/models/:model-id/cover", s.setCover) router.GET("/models/:model-id/overview", s.getOverview) router.PUT("/models/:model-id/overview", s.setOverview) //router.GET("/models/:model-id/questions", getQuestions) //router.PUT("/models/:model-id/questions", setQuestions) router.GET("/models/:model-id/abuse-cases", s.getAbuseCases) router.PUT("/models/:model-id/abuse-cases", s.setAbuseCases) router.GET("/models/:model-id/security-requirements", s.getSecurityRequirements) router.PUT("/models/:model-id/security-requirements", s.setSecurityRequirements) //router.GET("/models/:model-id/tags", getTags) //router.PUT("/models/:model-id/tags", setTags) router.GET("/models/:model-id/data-assets", s.getDataAssets) router.POST("/models/:model-id/data-assets", s.createNewDataAsset) router.GET("/models/:model-id/data-assets/:data-asset-id", s.getDataAsset) router.PUT("/models/:model-id/data-assets/:data-asset-id", s.setDataAsset) router.DELETE("/models/:model-id/data-assets/:data-asset-id", s.deleteDataAsset) router.GET("/models/:model-id/trust-boundaries", s.getTrustBoundaries) // router.POST("/models/:model-id/trust-boundaries", createNewTrustBoundary) // router.GET("/models/:model-id/trust-boundaries/:trust-boundary-id", getTrustBoundary) // router.PUT("/models/:model-id/trust-boundaries/:trust-boundary-id", setTrustBoundary) // router.DELETE("/models/:model-id/trust-boundaries/:trust-boundary-id", deleteTrustBoundary) router.GET("/models/:model-id/shared-runtimes", s.getSharedRuntimes) router.POST("/models/:model-id/shared-runtimes", s.createNewSharedRuntime) router.GET("/models/:model-id/shared-runtimes/:shared-runtime-id", s.getSharedRuntime) router.PUT("/models/:model-id/shared-runtimes/:shared-runtime-id", s.setSharedRuntime) router.DELETE("/models/:model-id/shared-runtimes/:shared-runtime-id", s.deleteSharedRuntime) s.customRiskRules = model.LoadCustomRiskRules(s.config.GetPluginFolder(), s.config.GetRiskRulePlugins(), config.GetProgressReporter()) fmt.Println("Threagile is running...") _ = router.Run(":" + strconv.Itoa(s.config.GetServerPort())) // listen and serve on 0.0.0.0:8080 or whatever port was specified } func (s *server) exampleFile(ginContext *gin.Context) { example, err := os.ReadFile(filepath.Join(s.config.GetAppFolder(), "threagile-example-model.yaml")) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.Data(http.StatusOK, gin.MIMEYAML, example) } func (s *server) stubFile(ginContext *gin.Context) { stub, err := os.ReadFile(filepath.Join(s.config.GetAppFolder(), "threagile-stub-model.yaml")) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.Data(http.StatusOK, gin.MIMEYAML, s.addSupportedTags(stub)) // TODO use also the MIMEYAML way of serving YAML in model export? } func (s *server) addSupportedTags(input []byte) []byte { // add distinct tags as "tags_available" supportedTags := make(map[string]bool) for _, customRule := range s.customRiskRules { for _, tag := range customRule.SupportedTags() { supportedTags[strings.ToLower(tag)] = true } } for _, rule := range s.builtinRiskRules { for _, tag := range rule.SupportedTags() { supportedTags[strings.ToLower(tag)] = true } } tags := make([]string, 0, len(supportedTags)) for t := range supportedTags { tags = append(tags, t) } if len(tags) == 0 { return input } sort.Strings(tags) if s.config.GetVerbose() { fmt.Print("Supported tags of all risk rules: ") for i, tag := range tags { if i > 0 { fmt.Print(", ") } fmt.Print(tag) } fmt.Println() } replacement := "tags_available:" for _, tag := range tags { replacement += "\n - " + tag } return []byte(strings.Replace(string(input), "tags_available:", replacement, 1)) } func arrayOfStringValues(values []types.TypeEnum) []string { result := make([]string, 0) for _, value := range values { result = append(result, value.String()) } return result } func (s *server) stats(ginContext *gin.Context) { keyCount, modelCount := 0, 0 keyFolders, err := os.ReadDir(filepath.Join(s.config.GetServerFolder(), s.config.GetKeyFolder())) if err != nil { log.Println(err) ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to collect stats", }) return } for _, keyFolder := range keyFolders { if len(keyFolder.Name()) == 128 { // it's a sha512 token hash probably, so count it as token folder for the stats keyCount++ if keyFolder.Name() != filepath.Clean(keyFolder.Name()) { ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "weird file path", }) return } modelFolders, err := os.ReadDir(filepath.Join(s.config.GetServerFolder(), s.config.GetKeyFolder(), keyFolder.Name())) if err != nil { log.Println(err) ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to collect stats", }) return } for _, modelFolder := range modelFolders { if len(modelFolder.Name()) == 36 { // it's a uuid model folder probably, so count it as model folder for the stats modelCount++ } } } } // TODO collect and deliver more stats (old model count?) and health info ginContext.JSON(http.StatusOK, gin.H{ "key_count": keyCount, "model_count": modelCount, "success_count": s.successCount, "error_count": s.errorCount, }) } func handleErrorInServiceCall(err error, ginContext *gin.Context) { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": strings.TrimSpace(err.Error()), }) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/hash.go
pkg/server/hash.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "crypto/sha512" "encoding/hex" "fmt" "hash/fnv" ) func xor(key []byte, xor []byte) []byte { if len(key) != len(xor) { panic(fmt.Errorf("key length not matching XOR length")) } result := make([]byte, len(xor)) for i, b := range key { result[i] = b ^ xor[i] } return result } func hashSHA256(key []byte) string { hasher := sha512.New() hasher.Write(key) return hex.EncodeToString(hasher.Sum(nil)) } func hash(s string) string { h := fnv.New32a() _, _ = h.Write([]byte(s)) return fmt.Sprintf("%v", h.Sum32()) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/zip.go
pkg/server/zip.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "archive/zip" "fmt" "io" "os" "path/filepath" "strings" ) // ZipFiles compresses one or many files into a single zip archive file. // Param 1: filename is the output zip file's name. // Param 2: files is a list of files to add to the zip. func zipFiles(filename string, files []string) error { newZipFile, err := os.Create(filepath.Clean(filename)) if err != nil { return err } defer func() { _ = newZipFile.Close() }() zipWriter := zip.NewWriter(newZipFile) defer func() { _ = zipWriter.Close() }() // Add files to zip for _, file := range files { if err = addFileToZip(zipWriter, file); err != nil { return err } } return nil } // Unzip will decompress a zip archive, moving all files and folders // within the zip file (parameter 1) to an output directory (parameter 2). func unzip(src string, dest string) ([]string, error) { var filenames []string r, err := zip.OpenReader(src) if err != nil { return filenames, err } defer func() { _ = r.Close() }() for _, f := range r.File { // Store filename/path for returning and using later on path := filepath.Clean(filepath.Join(dest, filepath.Clean(f.Name))) // Check for ZipSlip. More Info: http://bit.ly/2MsjAWE if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) { return filenames, fmt.Errorf("%s: illegal file path", path) } filenames = append(filenames, path) if f.FileInfo().IsDir() { // Make Folder _ = os.MkdirAll(path, 0700) continue } // Make File if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { return filenames, err } if path != filepath.Clean(path) { return filenames, fmt.Errorf("weird file path %v", path) } outFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return filenames, err } if f.FileInfo().Size() == 0 { _ = outFile.Close() continue } rc, err := f.Open() if err != nil { return filenames, err } _, err = io.CopyN(outFile, rc, f.FileInfo().Size()) // Close the file without defer to close before next iteration of loop _ = outFile.Close() _ = rc.Close() if err != nil { return filenames, err } } return filenames, nil } func addFileToZip(zipWriter *zip.Writer, filename string) error { fileToZip, err := os.Open(filepath.Clean(filename)) if err != nil { return err } defer func() { _ = fileToZip.Close() }() // Get the file information info, err := fileToZip.Stat() if err != nil { return err } header, err := zip.FileInfoHeader(info) if err != nil { return err } // Using FileInfoHeader() above only uses the basename of the file. If we want // to preserve the folder structure we can overwrite this with the full path. //header.Title = filename // Change to deflate to gain better compression // see http://golang.org/pkg/archive/zip/#pkg-constants header.Method = zip.Deflate writer, err := zipWriter.CreateHeader(header) if err != nil { return err } _, err = io.Copy(writer, fileToZip) return err }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/execute.go
pkg/server/execute.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "fmt" "io" "log" "net/http" "os" "os/exec" "path/filepath" "strconv" "strings" "github.com/gin-gonic/gin" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/risks" ) func (s *server) analyze(ginContext *gin.Context) { s.execute(ginContext, false) } func (s *server) check(ginContext *gin.Context) { _, ok := s.execute(ginContext, true) if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "model is ok", }) } } func (s *server) execute(ginContext *gin.Context, dryRun bool) (yamlContent []byte, ok bool) { defer func() { var err error if r := recover(); r != nil { s.errorCount++ err = r.(error) log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": strings.TrimSpace(err.Error()), }) ok = false } }() dpi, err := strconv.Atoi(ginContext.DefaultQuery("dpi", strconv.Itoa(s.config.GetGraphvizDPI()))) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } fileUploaded, header, err := ginContext.Request.FormFile("file") if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } if header.Size > 50000000 { msg := "maximum model upload file size exceeded (denial-of-service protection)" log.Println(msg) ginContext.JSON(http.StatusRequestEntityTooLarge, gin.H{ "error": msg, }) return yamlContent, false } filenameUploaded := strings.TrimSpace(header.Filename) tmpInputDir, err := os.MkdirTemp(s.config.GetTempFolder(), "threagile-input-") if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } defer func() { _ = os.RemoveAll(tmpInputDir) }() tmpModelFile, err := os.CreateTemp(tmpInputDir, "threagile-model-*") if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } defer func() { _ = os.Remove(tmpModelFile.Name()) }() _, err = io.Copy(tmpModelFile, fileUploaded) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } yamlFile := tmpModelFile.Name() if strings.ToLower(filepath.Ext(filenameUploaded)) == ".zip" { // unzip first (including the resources like images etc.) if s.config.GetVerbose() { fmt.Println("Decompressing uploaded archive") } filenamesUnzipped, err := unzip(tmpModelFile.Name(), tmpInputDir) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } found := false for _, name := range filenamesUnzipped { if strings.ToLower(filepath.Ext(name)) == ".yaml" { yamlFile = name found = true break } } if !found { panic(fmt.Errorf("no yaml file found in uploaded archive")) } } tmpOutputDir, err := os.MkdirTemp(s.config.GetTempFolder(), "threagile-output-") if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } defer func() { _ = os.RemoveAll(tmpOutputDir) }() tmpResultFile, err := os.CreateTemp(s.config.GetTempFolder(), "threagile-result-*.zip") if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } defer func() { _ = os.Remove(tmpResultFile.Name()) }() if dryRun { s.doItViaRuntimeCall(yamlFile, tmpOutputDir, false, false, false, false, false, true, true, true, 40) } else { s.doItViaRuntimeCall(yamlFile, tmpOutputDir, true, true, true, true, true, true, true, true, dpi) } yamlContent, err = os.ReadFile(filepath.Clean(yamlFile)) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } err = os.WriteFile(filepath.Join(tmpOutputDir, s.config.GetInputFile()), yamlContent, 0400) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } if !dryRun { files := []string{ filepath.Join(tmpOutputDir, s.config.GetInputFile()), filepath.Join(tmpOutputDir, s.config.GetDataFlowDiagramFilenamePNG()), filepath.Join(tmpOutputDir, s.config.GetDataAssetDiagramFilenamePNG()), filepath.Join(tmpOutputDir, s.config.GetReportFilename()), filepath.Join(tmpOutputDir, s.config.GetExcelRisksFilename()), filepath.Join(tmpOutputDir, s.config.GetExcelTagsFilename()), filepath.Join(tmpOutputDir, s.config.GetJsonRisksFilename()), filepath.Join(tmpOutputDir, s.config.GetJsonTechnicalAssetsFilename()), filepath.Join(tmpOutputDir, s.config.GetJsonStatsFilename()), } if s.config.GetKeepDiagramSourceFiles() { files = append(files, filepath.Join(tmpOutputDir, s.config.GetDataAssetDiagramFilenamePNG())) files = append(files, filepath.Join(tmpOutputDir, s.config.GetDataAssetDiagramFilenameDOT())) } err = zipFiles(tmpResultFile.Name(), files) if err != nil { handleErrorInServiceCall(err, ginContext) return yamlContent, false } if s.config.GetVerbose() { log.Println("Streaming back result file: " + tmpResultFile.Name()) } ginContext.FileAttachment(tmpResultFile.Name(), "threagile-result.zip") } s.successCount++ return yamlContent, true } // ultimately to avoid any in-process memory and/or data leaks by the used third party libs like PDF generation: exec and quit func (s *server) doItViaRuntimeCall(modelFile string, outputDir string, generateDataFlowDiagram, generateDataAssetDiagram, generateReportPdf, generateRisksExcel, generateTagsExcel, generateRisksJSON, generateTechnicalAssetsJSON, generateStatsJSON bool, dpi int) { // Remember to also add the same args to the exec based sub-process calls! var cmd *exec.Cmd args := []string{"analyze-model", "--model", modelFile, "--output", outputDir, "--execute-model-macro", s.config.GetExecuteModelMacro(), "--custom-risk-rules-plugin", strings.Join(s.config.GetRiskRulePlugins(), ","), "--skip-risk-rules", strings.Join(s.config.GetSkipRiskRules(), ","), "--diagram-dpi", strconv.Itoa(dpi), } if s.config.GetVerbose() { args = append(args, "--verbose") } if s.config.GetIgnoreOrphanedRiskTracking() { // TODO why add all them as arguments, when they are also variables on outer level? args = append(args, "--ignore-orphaned-risk-tracking") } if generateDataFlowDiagram { args = append(args, "--generate-data-flow-diagram") } if generateDataAssetDiagram { args = append(args, "--generate-data-asset-diagram") } if generateReportPdf { args = append(args, "--generate-report-pdf") } if generateRisksExcel { args = append(args, "--generate-risks-excel") } if generateTagsExcel { args = append(args, "--generate-tags-excel") } if generateRisksJSON { args = append(args, "--generate-risks-json") } if generateTechnicalAssetsJSON { args = append(args, "--generate-technical-assets-json") } if generateStatsJSON { args = append(args, "--generate-stats-json") } self, nameError := os.Executable() if nameError != nil { panic(nameError) } cmd = exec.Command(self, args...) // #nosec G204 out, err := cmd.CombinedOutput() if err != nil { panic(fmt.Errorf("%v", string(out))) } else { if s.config.GetVerbose() && len(out) > 0 { fmt.Println("---") fmt.Print(string(out)) fmt.Println("---") } } } func (s *server) editModelAnalyze(ginContext *gin.Context) { defer func() { var err error if r := recover(); r != nil { s.errorCount++ err = r.(error) log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": strings.TrimSpace(err.Error()), }) } }() var modelInput input.Model if err := ginContext.ShouldBindJSON(&modelInput); err != nil { ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid JSON provided", }) return } log.Printf("Received JSON: %+v\n", modelInput) progressReporter := DefaultProgressReporter{ Verbose: s.config.GetVerbose(), SuppressError: true, } customRiskRules := model.LoadCustomRiskRules(s.config.GetPluginFolder(), s.config.GetRiskRulePlugins(), progressReporter) builtinRiskRules := risks.GetBuiltInRiskRules() result, err := model.AnalyzeModel(&modelInput, s.config, builtinRiskRules, customRiskRules, progressReporter) if err != nil { ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "Unable to analyze model: " + err.Error(), }) return } ginContext.JSON(http.StatusOK, gin.H{ "message": "Analyzed successfully", "data": result, }) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/progress-reporter.go
pkg/server/progress-reporter.go
package server import ( "fmt" "log" ) type DefaultProgressReporter struct { Verbose bool SuppressError bool } func (r DefaultProgressReporter) Info(a ...any) { if r.Verbose { fmt.Println(a...) } } func (DefaultProgressReporter) Warn(a ...any) { fmt.Println(a...) } func (r DefaultProgressReporter) Error(v ...any) { if r.SuppressError { r.Warn(v...) return } log.Fatal(v...) } func (r DefaultProgressReporter) Infof(format string, a ...any) { if r.Verbose { fmt.Printf(format, a...) fmt.Println() } } func (DefaultProgressReporter) Warnf(format string, a ...any) { fmt.Print("WARNING: ") fmt.Printf(format, a...) fmt.Println() } func (r DefaultProgressReporter) Errorf(format string, v ...any) { if r.SuppressError { r.Warnf(format, v...) return } log.Fatalf(format, v...) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/report.go
pkg/server/report.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "log" "net/http" "os" "path/filepath" "strconv" "strings" "github.com/gin-gonic/gin" ) type responseType int const ( dataFlowDiagram responseType = iota dataAssetDiagram reportPDF risksExcel tagsExcel risksJSON technicalAssetsJSON statsJSON ) func (s *server) streamDataFlowDiagram(ginContext *gin.Context) { s.streamResponse(ginContext, dataFlowDiagram) } func (s *server) streamDataAssetDiagram(ginContext *gin.Context) { s.streamResponse(ginContext, dataAssetDiagram) } func (s *server) streamReportPDF(ginContext *gin.Context) { s.streamResponse(ginContext, reportPDF) } func (s *server) streamRisksExcel(ginContext *gin.Context) { s.streamResponse(ginContext, risksExcel) } func (s *server) streamTagsExcel(ginContext *gin.Context) { s.streamResponse(ginContext, tagsExcel) } func (s *server) streamRisksJSON(ginContext *gin.Context) { s.streamResponse(ginContext, risksJSON) } func (s *server) streamTechnicalAssetsJSON(ginContext *gin.Context) { s.streamResponse(ginContext, technicalAssetsJSON) } func (s *server) streamStatsJSON(ginContext *gin.Context) { s.streamResponse(ginContext, statsJSON) } func (s *server) streamResponse(ginContext *gin.Context, responseType responseType) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer func() { s.unlockFolder(folderNameOfKey) var err error if r := recover(); r != nil { err = r.(error) if s.config.GetVerbose() { log.Println(err) } log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": strings.TrimSpace(err.Error()), }) ok = false } }() dpi, err := strconv.Atoi(ginContext.DefaultQuery("dpi", strconv.Itoa(s.config.GetGraphvizDPI()))) if err != nil { handleErrorInServiceCall(err, ginContext) return } _, yamlText, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if !ok { return } tmpModelFile, err := os.CreateTemp(s.config.GetTempFolder(), "threagile-render-*") if err != nil { handleErrorInServiceCall(err, ginContext) return } defer func() { _ = os.Remove(tmpModelFile.Name()) }() tmpOutputDir, err := os.MkdirTemp(s.config.GetTempFolder(), "threagile-render-") if err != nil { handleErrorInServiceCall(err, ginContext) return } defer func() { _ = os.RemoveAll(tmpOutputDir) }() err = os.WriteFile(tmpModelFile.Name(), []byte(yamlText), 0400) switch responseType { case dataFlowDiagram: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, true, false, false, false, false, false, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.File(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetDataFlowDiagramFilenamePNG()))) case dataAssetDiagram: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, true, false, false, false, false, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.File(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetDataAssetDiagramFilenamePNG()))) case reportPDF: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, true, false, false, false, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.FileAttachment(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetReportFilename())), s.config.GetReportFilename()) case risksExcel: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, false, true, false, false, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.FileAttachment(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetExcelRisksFilename())), s.config.GetExcelRisksFilename()) case tagsExcel: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, false, false, true, false, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.FileAttachment(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetExcelTagsFilename())), s.config.GetExcelTagsFilename()) case risksJSON: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, false, false, false, true, false, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } jsonData, err := os.ReadFile(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetJsonRisksFilename()))) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.Data(http.StatusOK, "application/json", jsonData) // stream directly with JSON content-type in response instead of file download case technicalAssetsJSON: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, false, false, false, true, true, false, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } jsonData, err := os.ReadFile(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetJsonTechnicalAssetsFilename()))) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.Data(http.StatusOK, "application/json", jsonData) // stream directly with JSON content-type in response instead of file download case statsJSON: s.doItViaRuntimeCall(tmpModelFile.Name(), tmpOutputDir, false, false, false, false, false, false, false, true, dpi) if err != nil { handleErrorInServiceCall(err, ginContext) return } jsonData, err := os.ReadFile(filepath.Clean(filepath.Join(tmpOutputDir, s.config.GetJsonStatsFilename()))) if err != nil { handleErrorInServiceCall(err, ginContext) return } ginContext.Data(http.StatusOK, "application/json", jsonData) // stream directly with JSON content-type in response instead of file download } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/model.go
pkg/server/model.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "bytes" "compress/gzip" "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" "log" "net/http" "os" "path/filepath" "sort" "strconv" "strings" "sync" "time" "gopkg.in/yaml.v3" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" "golang.org/x/crypto/argon2" ) // creates a sub-folder (named by a new UUID) inside the token folder func (s *server) createNewModel(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } ok = s.checkObjectCreationThrottler(ginContext, "MODEL") if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aUuid := uuid.New().String() err := os.Mkdir(folderNameForModel(folderNameOfKey, aUuid), 0700) if err != nil { ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to create model", }) return } aYaml := `title: New Threat Model threagile_version: ` + s.config.GetThreagileVersion() + ` author: name: "" homepage: "" date: business_overview: description: "" images: [] technical_overview: description: "" images: [] business_criticality: "" management_summary_comment: "" questions: {} abuse_cases: {} security_requirements: {} tags_available: [] data_assets: {} technical_assets: {} trust_boundaries: {} shared_runtimes: {} individual_risk_categories: {} risk_tracking: {} diagram_tweak_nodesep: "" diagram_tweak_ranksep: "" diagram_tweak_edge_layout: "" diagram_tweak_suppress_edge_labels: false diagram_tweak_invisible_connections_between_assets: [] diagram_tweak_same_rank_assets: []` ok = s.writeModelYAML(ginContext, aYaml, key, folderNameForModel(folderNameOfKey, aUuid), "New Model Creation", true) if ok { ginContext.JSON(http.StatusCreated, gin.H{ "message": "model created", "id": aUuid, }) } } type payloadModels struct { ID string `yaml:"id" json:"id"` Title string `yaml:"title" json:"title"` TimestampCreated time.Time `yaml:"timestamp_created" json:"timestamp_created"` TimestampModified time.Time `yaml:"timestamp_modified" json:"timestamp_modified"` } func (s *server) listModels(ginContext *gin.Context) { // TODO currently returns error when any model is no longer valid in syntax, so eventually have some fallback to not just bark on an invalid model... folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) result := make([]payloadModels, 0) modelFolders, err := os.ReadDir(folderNameOfKey) if err != nil { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return } for _, dirEntry := range modelFolders { if dirEntry.IsDir() { modelStat, err := os.Stat(filepath.Join(folderNameOfKey, dirEntry.Name(), s.config.GetInputFile())) if err != nil { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "unable to list model", }) return } aModel, _, ok := s.readModel(ginContext, dirEntry.Name(), key, folderNameOfKey) if !ok { return } fileInfo, err := dirEntry.Info() if err != nil { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "unable to get file info", }) return } result = append(result, payloadModels{ ID: dirEntry.Name(), Title: aModel.Title, TimestampCreated: fileInfo.ModTime(), TimestampModified: modelStat.ModTime(), }) } } ginContext.JSON(http.StatusOK, result) } func (s *server) deleteModel(ginContext *gin.Context) { folderNameOfKey, _, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) folder, ok := s.checkModelFolder(ginContext, ginContext.Param("model-id"), folderNameOfKey) if ok { if folder != filepath.Clean(folder) { ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "model-id is weird", }) return } err := os.RemoveAll(folder) if err != nil { ginContext.JSON(http.StatusNotFound, gin.H{ "error": "model not found", }) return } ginContext.JSON(http.StatusOK, gin.H{ "message": "model deleted", }) } } type payloadCover struct { Title string `yaml:"title" json:"title"` Date time.Time `yaml:"date" json:"date"` Author input.Author `yaml:"author" json:"author"` } func (s *server) setCover(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadCover{} err := ginContext.BindJSON(&payload) if err != nil { ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } modelInput.Title = payload.Title if !payload.Date.IsZero() { modelInput.Date = payload.Date.Format("2006-01-02") } modelInput.Author.Name = payload.Author.Name modelInput.Author.Homepage = payload.Author.Homepage ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Cover Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "model updated", }) } } } func (s *server) getCover(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, gin.H{ "title": aModel.Title, "date": aModel.Date, "author": aModel.Author, }) } } type payloadOverview struct { ManagementSummaryComment string `yaml:"management_summary_comment" json:"management_summary_comment"` BusinessCriticality string `yaml:"business_criticality" json:"business_criticality"` BusinessOverview input.Overview `yaml:"business_overview" json:"business_overview"` TechnicalOverview input.Overview `yaml:"technical_overview" json:"technical_overview"` } func (s *server) setOverview(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadOverview{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } criticality, err := types.ParseCriticality(payload.BusinessCriticality) if err != nil { handleErrorInServiceCall(err, ginContext) return } modelInput.ManagementSummaryComment = payload.ManagementSummaryComment modelInput.BusinessCriticality = criticality.String() modelInput.BusinessOverview.Description = payload.BusinessOverview.Description modelInput.BusinessOverview.Images = payload.BusinessOverview.Images modelInput.TechnicalOverview.Description = payload.TechnicalOverview.Description modelInput.TechnicalOverview.Images = payload.TechnicalOverview.Images ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Overview Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "model updated", }) } } } func (s *server) getOverview(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, gin.H{ "management_summary_comment": aModel.ManagementSummaryComment, "business_criticality": aModel.BusinessCriticality, "business_overview": aModel.BusinessOverview, "technical_overview": aModel.TechnicalOverview, }) } } type payloadAbuseCases map[string]string func (s *server) setAbuseCases(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadAbuseCases{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } modelInput.AbuseCases = payload ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Abuse Cases Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "model updated", }) } } } func (s *server) getAbuseCases(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, aModel.AbuseCases) } } type payloadSecurityRequirements map[string]string func (s *server) setSecurityRequirements(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadSecurityRequirements{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } modelInput.SecurityRequirements = payload ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Security Requirements Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "model updated", }) } } } func (s *server) getSecurityRequirements(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, aModel.SecurityRequirements) } } type payloadDataAsset struct { Title string `yaml:"title" json:"title"` Id string `yaml:"id" json:"id"` Description string `yaml:"description" json:"description"` Usage string `yaml:"usage" json:"usage"` Tags []string `yaml:"tags" json:"tags"` Origin string `yaml:"origin" json:"origin"` Owner string `yaml:"owner" json:"owner"` Quantity string `yaml:"quantity" json:"quantity"` Confidentiality string `yaml:"confidentiality" json:"confidentiality"` Integrity string `yaml:"integrity" json:"integrity"` Availability string `yaml:"availability" json:"availability"` JustificationCiaRating string `yaml:"justification_cia_rating" json:"justification_cia_rating"` } func (s *server) getDataAssets(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, aModel.DataAssets) } } func (s *server) getDataAsset(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { // yes, here keyed by title in YAML for better readability in the YAML file itself for title, dataAsset := range modelInput.DataAssets { if dataAsset.ID == ginContext.Param("data-asset-id") { ginContext.JSON(http.StatusOK, gin.H{ title: dataAsset, }) return } } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "data asset not found", }) } } func (s *server) deleteDataAsset(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { referencesDeleted := false // yes, here keyed by title in YAML for better readability in the YAML file itself for title, dataAsset := range modelInput.DataAssets { if dataAsset.ID == ginContext.Param("data-asset-id") { // also remove all usages of this data asset !! for _, techAsset := range modelInput.TechnicalAssets { if techAsset.DataAssetsProcessed != nil { for i, parsedChangeCandidateAsset := range techAsset.DataAssetsProcessed { referencedAsset := fmt.Sprintf("%v", parsedChangeCandidateAsset) if referencedAsset == dataAsset.ID { // apply the removal referencesDeleted = true // Remove the element at index i // TODO needs more testing copy(techAsset.DataAssetsProcessed[i:], techAsset.DataAssetsProcessed[i+1:]) // Shift a[i+1:] left one index. techAsset.DataAssetsProcessed[len(techAsset.DataAssetsProcessed)-1] = "" // Erase last element (write zero value). techAsset.DataAssetsProcessed = techAsset.DataAssetsProcessed[:len(techAsset.DataAssetsProcessed)-1] // Truncate slice. } } } if techAsset.DataAssetsStored != nil { for i, parsedChangeCandidateAsset := range techAsset.DataAssetsStored { referencedAsset := fmt.Sprintf("%v", parsedChangeCandidateAsset) if referencedAsset == dataAsset.ID { // apply the removal referencesDeleted = true // Remove the element at index i // TODO needs more testing copy(techAsset.DataAssetsStored[i:], techAsset.DataAssetsStored[i+1:]) // Shift a[i+1:] left one index. techAsset.DataAssetsStored[len(techAsset.DataAssetsStored)-1] = "" // Erase last element (write zero value). techAsset.DataAssetsStored = techAsset.DataAssetsStored[:len(techAsset.DataAssetsStored)-1] // Truncate slice. } } } if techAsset.CommunicationLinks != nil { for title, commLink := range techAsset.CommunicationLinks { for i, dataAssetSent := range commLink.DataAssetsSent { referencedAsset := fmt.Sprintf("%v", dataAssetSent) if referencedAsset == dataAsset.ID { // apply the removal referencesDeleted = true // Remove the element at index i // TODO needs more testing copy(techAsset.CommunicationLinks[title].DataAssetsSent[i:], techAsset.CommunicationLinks[title].DataAssetsSent[i+1:]) // Shift a[i+1:] left one index. techAsset.CommunicationLinks[title].DataAssetsSent[len(techAsset.CommunicationLinks[title].DataAssetsSent)-1] = "" // Erase last element (write zero value). x := techAsset.CommunicationLinks[title] x.DataAssetsSent = techAsset.CommunicationLinks[title].DataAssetsSent[:len(techAsset.CommunicationLinks[title].DataAssetsSent)-1] // Truncate slice. techAsset.CommunicationLinks[title] = x } } for i, dataAssetReceived := range commLink.DataAssetsReceived { referencedAsset := fmt.Sprintf("%v", dataAssetReceived) if referencedAsset == dataAsset.ID { // apply the removal referencesDeleted = true // Remove the element at index i // TODO needs more testing copy(techAsset.CommunicationLinks[title].DataAssetsReceived[i:], techAsset.CommunicationLinks[title].DataAssetsReceived[i+1:]) // Shift a[i+1:] left one index. techAsset.CommunicationLinks[title].DataAssetsReceived[len(techAsset.CommunicationLinks[title].DataAssetsReceived)-1] = "" // Erase last element (write zero value). x := techAsset.CommunicationLinks[title] x.DataAssetsReceived = techAsset.CommunicationLinks[title].DataAssetsReceived[:len(techAsset.CommunicationLinks[title].DataAssetsReceived)-1] // Truncate slice. techAsset.CommunicationLinks[title] = x } } } } } for _, individualRiskCat := range modelInput.CustomRiskCategories { if individualRiskCat.RisksIdentified != nil { for individualRiskInstanceTitle, individualRiskInstance := range individualRiskCat.RisksIdentified { if individualRiskInstance.MostRelevantDataAsset == dataAsset.ID { // apply the removal referencesDeleted = true x := individualRiskCat.RisksIdentified[individualRiskInstanceTitle] x.MostRelevantDataAsset = "" // TODO needs more testing individualRiskCat.RisksIdentified[individualRiskInstanceTitle] = x } } } } // remove it itself delete(modelInput.DataAssets, title) ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Data Asset Deletion") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "data asset deleted", "id": dataAsset.ID, "references_deleted": referencesDeleted, // in order to signal to clients, that other model parts might've been deleted as well }) } return } } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "data asset not found", }) } } func (s *server) setDataAsset(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { // yes, here keyed by title in YAML for better readability in the YAML file itself for title, dataAsset := range modelInput.DataAssets { if dataAsset.ID == ginContext.Param("data-asset-id") { payload := payloadDataAsset{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } dataAssetInput, ok := s.populateDataAsset(ginContext, payload) if !ok { return } // in order to also update the title, remove the asset from the map and re-insert it (with new key) delete(modelInput.DataAssets, title) modelInput.DataAssets[payload.Title] = dataAssetInput idChanged := dataAssetInput.ID != dataAsset.ID if idChanged { // ID-CHANGE-PROPAGATION // also update all usages to point to the new (changed) ID !! for techAssetTitle, techAsset := range modelInput.TechnicalAssets { if techAsset.DataAssetsProcessed != nil { for i, parsedChangeCandidateAsset := range techAsset.DataAssetsProcessed { referencedAsset := fmt.Sprintf("%v", parsedChangeCandidateAsset) if referencedAsset == dataAsset.ID { // apply the ID change modelInput.TechnicalAssets[techAssetTitle].DataAssetsProcessed[i] = dataAssetInput.ID } } } if techAsset.DataAssetsStored != nil { for i, parsedChangeCandidateAsset := range techAsset.DataAssetsStored { referencedAsset := fmt.Sprintf("%v", parsedChangeCandidateAsset) if referencedAsset == dataAsset.ID { // apply the ID change modelInput.TechnicalAssets[techAssetTitle].DataAssetsStored[i] = dataAssetInput.ID } } } if techAsset.CommunicationLinks != nil { for title, commLink := range techAsset.CommunicationLinks { for i, dataAssetSent := range commLink.DataAssetsSent { referencedAsset := fmt.Sprintf("%v", dataAssetSent) if referencedAsset == dataAsset.ID { // apply the ID change modelInput.TechnicalAssets[techAssetTitle].CommunicationLinks[title].DataAssetsSent[i] = dataAssetInput.ID } } for i, dataAssetReceived := range commLink.DataAssetsReceived { referencedAsset := fmt.Sprintf("%v", dataAssetReceived) if referencedAsset == dataAsset.ID { // apply the ID change modelInput.TechnicalAssets[techAssetTitle].CommunicationLinks[title].DataAssetsReceived[i] = dataAssetInput.ID } } } } } for _, individualRiskCat := range modelInput.CustomRiskCategories { if individualRiskCat.RisksIdentified != nil { for individualRiskInstanceTitle, individualRiskInstance := range individualRiskCat.RisksIdentified { if individualRiskInstance.MostRelevantDataAsset == dataAsset.ID { // apply the ID change x := individualRiskCat.RisksIdentified[individualRiskInstanceTitle] x.MostRelevantDataAsset = dataAssetInput.ID // TODO needs more testing individualRiskCat.RisksIdentified[individualRiskInstanceTitle] = x } } } } } ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Data Asset Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "data asset updated", "id": dataAssetInput.ID, "id_changed": idChanged, // in order to signal to clients, that other model parts might've received updates as well and should be reloaded }) } return } } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "data asset not found", }) } } func (s *server) createNewDataAsset(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadDataAsset{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } // yes, here keyed by title in YAML for better readability in the YAML file itself if _, exists := modelInput.DataAssets[payload.Title]; exists { ginContext.JSON(http.StatusConflict, gin.H{ "error": "data asset with this title already exists", }) return } // but later it will in memory keyed by its "id", so do this uniqueness check also for _, asset := range modelInput.DataAssets { if asset.ID == payload.Id { ginContext.JSON(http.StatusConflict, gin.H{ "error": "data asset with this id already exists", }) return } } dataAssetInput, ok := s.populateDataAsset(ginContext, payload) if !ok { return } if modelInput.DataAssets == nil { modelInput.DataAssets = make(map[string]input.DataAsset) } modelInput.DataAssets[payload.Title] = dataAssetInput ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Data Asset Creation") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "data asset created", "id": dataAssetInput.ID, }) } } } func (s *server) populateDataAsset(ginContext *gin.Context, payload payloadDataAsset) (dataAssetInput input.DataAsset, ok bool) { usage, err := types.ParseUsage(payload.Usage) if err != nil { handleErrorInServiceCall(err, ginContext) return dataAssetInput, false } quantity, err := types.ParseQuantity(payload.Quantity) if err != nil { handleErrorInServiceCall(err, ginContext) return dataAssetInput, false } confidentiality, err := types.ParseConfidentiality(payload.Confidentiality) if err != nil { handleErrorInServiceCall(err, ginContext) return dataAssetInput, false } integrity, err := types.ParseCriticality(payload.Integrity) if err != nil { handleErrorInServiceCall(err, ginContext) return dataAssetInput, false } availability, err := types.ParseCriticality(payload.Availability) if err != nil { handleErrorInServiceCall(err, ginContext) return dataAssetInput, false } dataAssetInput = input.DataAsset{ ID: payload.Id, Description: payload.Description, Usage: usage.String(), Tags: lowerCaseAndTrim(payload.Tags), Origin: payload.Origin, Owner: payload.Owner, Quantity: quantity.String(), Confidentiality: confidentiality.String(), Integrity: integrity.String(), Availability: availability.String(), JustificationCiaRating: payload.JustificationCiaRating, } return dataAssetInput, true } func (s *server) getTrustBoundaries(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) aModel, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { ginContext.JSON(http.StatusOK, aModel.TrustBoundaries) } } type payloadSharedRuntime struct { Title string `yaml:"title" json:"title"` Id string `yaml:"id" json:"id"` Description string `yaml:"description" json:"description"` Tags []string `yaml:"tags" json:"tags"` TechnicalAssetsRunning []string `yaml:"technical_assets_running" json:"technical_assets_running"` } func (s *server) setSharedRuntime(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { // yes, here keyed by title in YAML for better readability in the YAML file itself for title, sharedRuntime := range modelInput.SharedRuntimes { if sharedRuntime.ID == ginContext.Param("shared-runtime-id") { payload := payloadSharedRuntime{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } sharedRuntimeInput, ok := populateSharedRuntime(ginContext, payload) if !ok { return } // in order to also update the title, remove the shared runtime from the map and re-insert it (with new key) delete(modelInput.SharedRuntimes, title) modelInput.SharedRuntimes[payload.Title] = sharedRuntimeInput idChanged := sharedRuntimeInput.ID != sharedRuntime.ID if idChanged { // ID-CHANGE-PROPAGATION for _, individualRiskCat := range modelInput.CustomRiskCategories { if individualRiskCat.RisksIdentified != nil { for individualRiskInstanceTitle, individualRiskInstance := range individualRiskCat.RisksIdentified { if individualRiskInstance.MostRelevantSharedRuntime == sharedRuntime.ID { // apply the ID change x := individualRiskCat.RisksIdentified[individualRiskInstanceTitle] x.MostRelevantSharedRuntime = sharedRuntimeInput.ID // TODO needs more testing individualRiskCat.RisksIdentified[individualRiskInstanceTitle] = x } } } } } ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Shared Runtime Update") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "shared runtime updated", "id": sharedRuntimeInput.ID, "id_changed": idChanged, // in order to signal to clients, that other model parts might've received updates as well and should be reloaded }) } return } } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "shared runtime not found", }) } } func (s *server) getSharedRuntime(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { // yes, here keyed by title in YAML for better readability in the YAML file itself for title, sharedRuntime := range modelInput.SharedRuntimes { if sharedRuntime.ID == ginContext.Param("shared-runtime-id") { ginContext.JSON(http.StatusOK, gin.H{ title: sharedRuntime, }) return } } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "shared runtime not found", }) } } func (s *server) createNewSharedRuntime(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { payload := payloadSharedRuntime{} err := ginContext.BindJSON(&payload) if err != nil { log.Println(err) ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "unable to parse request payload", }) return } // yes, here keyed by title in YAML for better readability in the YAML file itself if _, exists := modelInput.SharedRuntimes[payload.Title]; exists { ginContext.JSON(http.StatusConflict, gin.H{ "error": "shared runtime with this title already exists", }) return } // but later it will in memory keyed by its "id", so do this uniqueness check also for _, sharedRuntime := range modelInput.SharedRuntimes { if sharedRuntime.ID == payload.Id { ginContext.JSON(http.StatusConflict, gin.H{ "error": "shared runtime with this id already exists", }) return } } if !checkTechnicalAssetsExisting(modelInput, payload.TechnicalAssetsRunning) { ginContext.JSON(http.StatusBadRequest, gin.H{ "error": "referenced technical asset does not exist", }) return } sharedRuntimeInput, ok := populateSharedRuntime(ginContext, payload) if !ok { return } if modelInput.SharedRuntimes == nil { modelInput.SharedRuntimes = make(map[string]input.SharedRuntime) } modelInput.SharedRuntimes[payload.Title] = sharedRuntimeInput ok = s.writeModel(ginContext, key, folderNameOfKey, &modelInput, "Shared Runtime Creation") if ok { ginContext.JSON(http.StatusOK, gin.H{ "message": "shared runtime created", "id": sharedRuntimeInput.ID, }) } } } func checkTechnicalAssetsExisting(modelInput input.Model, techAssetIDs []string) (ok bool) { for _, techAssetID := range techAssetIDs { exists := false for _, val := range modelInput.TechnicalAssets { if val.ID == techAssetID { exists = true break } } if !exists { return false } } return true } func populateSharedRuntime(_ *gin.Context, payload payloadSharedRuntime) (sharedRuntimeInput input.SharedRuntime, ok bool) { sharedRuntimeInput = input.SharedRuntime{ ID: payload.Id, Description: payload.Description, Tags: lowerCaseAndTrim(payload.Tags), TechnicalAssetsRunning: payload.TechnicalAssetsRunning, } return sharedRuntimeInput, true } func (s *server) deleteSharedRuntime(ginContext *gin.Context) { folderNameOfKey, key, ok := s.checkTokenToFolderName(ginContext) if !ok { return } s.lockFolder(folderNameOfKey) defer s.unlockFolder(folderNameOfKey) modelInput, _, ok := s.readModel(ginContext, ginContext.Param("model-id"), key, folderNameOfKey) if ok { referencesDeleted := false // yes, here keyed by title in YAML for better readability in the YAML file itself for title, sharedRuntime := range modelInput.SharedRuntimes { if sharedRuntime.ID == ginContext.Param("shared-runtime-id") { // also remove all usages of this shared runtime !! for _, individualRiskCat := range modelInput.CustomRiskCategories { if individualRiskCat.RisksIdentified != nil { for individualRiskInstanceTitle, individualRiskInstance := range individualRiskCat.RisksIdentified { if individualRiskInstance.MostRelevantSharedRuntime == sharedRuntime.ID { // apply the removal referencesDeleted = true
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/server/token.go
pkg/server/token.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package server import ( "crypto/rand" "encoding/base64" "fmt" "log" "net/http" "os" "path/filepath" "strings" "time" "github.com/gin-gonic/gin" ) const keySize = 32 type keyHeader struct { Key string `header:"key"` } type timeoutStruct struct { xorRand []byte createdNanoTime, lastAccessedNanoTime int64 } func (s *server) createKey(ginContext *gin.Context) { ok := s.checkObjectCreationThrottler(ginContext, "KEY") if !ok { return } s.globalLock.Lock() defer s.globalLock.Unlock() keyBytesArr := make([]byte, keySize) n, err := rand.Read(keyBytesArr[:]) if n != keySize || err != nil { log.Println(err) ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to create key", }) return } err = os.MkdirAll(s.folderNameFromKey(keyBytesArr), 0700) if err != nil { log.Println(err) ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to create key", }) return } ginContext.JSON(http.StatusCreated, gin.H{ "key": base64.RawURLEncoding.EncodeToString(keyBytesArr[:]), }) } func (s *server) checkObjectCreationThrottler(ginContext *gin.Context, typeName string) bool { s.throttlerLock.Lock() defer s.throttlerLock.Unlock() // remove all elements older than 3 minutes (= 180000000000 ns) now := time.Now().UnixNano() cutoff := now - 180000000000 for keyCheck := range s.createdObjectsThrottler { for i := 0; i < len(s.createdObjectsThrottler[keyCheck]); i++ { if s.createdObjectsThrottler[keyCheck][i] < cutoff { // Remove the element at index i from slice (safe while looping using i as iterator) s.createdObjectsThrottler[keyCheck] = append(s.createdObjectsThrottler[keyCheck][:i], s.createdObjectsThrottler[keyCheck][i+1:]...) i-- // Since we just deleted a[i], we must redo that index } } length := len(s.createdObjectsThrottler[keyCheck]) if length == 0 { delete(s.createdObjectsThrottler, keyCheck) } /* if *verbose { log.Println("Throttling count: "+strconv.Itoa(length)) } */ } // check current request keyHash := hash(typeName) // getting the real client ip is not easy inside fully encapsulated containerized runtime if _, ok := s.createdObjectsThrottler[keyHash]; !ok { s.createdObjectsThrottler[keyHash] = make([]int64, 0) } // check the limit of 20 creations for this type per 3 minutes withinLimit := len(s.createdObjectsThrottler[keyHash]) < 20 if withinLimit { s.createdObjectsThrottler[keyHash] = append(s.createdObjectsThrottler[keyHash], now) return true } ginContext.JSON(http.StatusTooManyRequests, gin.H{ "error": "object creation throttling exceeded (denial-of-service protection): please wait some time and try again", }) return false } func (s *server) deleteKey(ginContext *gin.Context) { folderName, _, ok := s.checkKeyToFolderName(ginContext) if !ok { return } s.globalLock.Lock() defer s.globalLock.Unlock() err := os.RemoveAll(folderName) if err != nil { log.Println("error during key delete: " + err.Error()) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "key not found", }) return } ginContext.JSON(http.StatusOK, gin.H{ "message": "key deleted", }) } func (s *server) createToken(ginContext *gin.Context) { folderName, key, ok := s.checkKeyToFolderName(ginContext) if !ok { return } s.globalLock.Lock() defer s.globalLock.Unlock() if tokenHash, exists := s.mapFolderNameToTokenHash[folderName]; exists { // invalidate previous token delete(s.mapTokenHashToTimeoutStruct, tokenHash) } // create a strong random 256 bit value (used to xor) xorBytesArr := make([]byte, keySize) n, err := rand.Read(xorBytesArr[:]) if n != keySize || err != nil { log.Println(err) ginContext.JSON(http.StatusInternalServerError, gin.H{ "error": "unable to create token", }) return } now := time.Now().UnixNano() token := xor(key, xorBytesArr) tokenHash := hashSHA256(token) s.housekeepingTokenMaps() s.mapTokenHashToTimeoutStruct[tokenHash] = timeoutStruct{ xorRand: xorBytesArr, createdNanoTime: now, lastAccessedNanoTime: now, } s.mapFolderNameToTokenHash[folderName] = tokenHash ginContext.JSON(http.StatusCreated, gin.H{ "token": base64.RawURLEncoding.EncodeToString(token[:]), }) } type tokenHeader struct { Token string `header:"token"` } func (s *server) deleteToken(ginContext *gin.Context) { header := tokenHeader{} if err := ginContext.ShouldBindHeader(&header); err != nil { ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return } token, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(header.Token)) if len(token) == 0 || err != nil { if err != nil { log.Println(err) } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return } s.globalLock.Lock() defer s.globalLock.Unlock() s.deleteTokenHashFromMaps(hashSHA256(token)) ginContext.JSON(http.StatusOK, gin.H{ "message": "token deleted", }) } func (s *server) checkKeyToFolderName(ginContext *gin.Context) (folderNameOfKey string, key []byte, ok bool) { header := keyHeader{} if err := ginContext.ShouldBindHeader(&header); err != nil { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "key not found", }) return folderNameOfKey, key, false } key, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(header.Key)) if len(key) == 0 || err != nil { if err != nil { log.Println(err) } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "key not found", }) return folderNameOfKey, key, false } folderNameOfKey = s.folderNameFromKey(key) if _, err := os.Stat(folderNameOfKey); os.IsNotExist(err) { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "key not found", }) return folderNameOfKey, key, false } return folderNameOfKey, key, true } func (s *server) checkTokenToFolderName(ginContext *gin.Context) (folderNameOfKey string, key []byte, ok bool) { header := tokenHeader{} if err := ginContext.ShouldBindHeader(&header); err != nil { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return folderNameOfKey, key, false } token, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(header.Token)) if len(token) == 0 || err != nil { if err != nil { log.Println(err) } ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return folderNameOfKey, key, false } s.globalLock.Lock() defer s.globalLock.Unlock() s.housekeepingTokenMaps() // to remove timed-out ones tokenHash := hashSHA256(token) if timeoutStruct, exists := s.mapTokenHashToTimeoutStruct[tokenHash]; exists { // re-create the key from token key := xor(token, timeoutStruct.xorRand) folderNameOfKey := s.folderNameFromKey(key) if _, err := os.Stat(folderNameOfKey); os.IsNotExist(err) { log.Println(err) ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return folderNameOfKey, key, false } timeoutStruct.lastAccessedNanoTime = time.Now().UnixNano() return folderNameOfKey, key, true } else { ginContext.JSON(http.StatusNotFound, gin.H{ "error": "token not found", }) return folderNameOfKey, key, false } } func (s *server) folderNameFromKey(key []byte) string { sha512Hash := hashSHA256(key) return filepath.Join(s.config.GetServerFolder(), s.config.GetKeyFolder(), sha512Hash) } func (s *server) housekeepingTokenMaps() { now := time.Now().UnixNano() for tokenHash, val := range s.mapTokenHashToTimeoutStruct { if s.extremeShortTimeoutsForTesting { // remove all elements older than 1 minute (= 60000000000 ns) soft // and all elements older than 3 minutes (= 180000000000 ns) hard if now-val.lastAccessedNanoTime > 60000000000 || now-val.createdNanoTime > 180000000000 { fmt.Println("About to remove a token hash from maps") s.deleteTokenHashFromMaps(tokenHash) } } else { // remove all elements older than 30 minutes (= 1800000000000 ns) soft // and all elements older than 10 hours (= 36000000000000 ns) hard if now-val.lastAccessedNanoTime > 1800000000000 || now-val.createdNanoTime > 36000000000000 { s.deleteTokenHashFromMaps(tokenHash) } } } } func (s *server) deleteTokenHashFromMaps(tokenHash string) { delete(s.mapTokenHashToTimeoutStruct, tokenHash) for folderName, check := range s.mapFolderNameToTokenHash { if check == tokenHash { delete(s.mapFolderNameToTokenHash, folderName) break } } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/technical-asset.go
pkg/input/technical-asset.go
package input import "fmt" type TechnicalAsset struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Type string `yaml:"type,omitempty" json:"type,omitempty"` Usage string `yaml:"usage,omitempty" json:"usage,omitempty"` UsedAsClientByHuman bool `yaml:"used_as_client_by_human,omitempty" json:"used_as_client_by_human,omitempty"` OutOfScope bool `yaml:"out_of_scope,omitempty" json:"out_of_scope,omitempty"` JustificationOutOfScope string `yaml:"justification_out_of_scope,omitempty" json:"justification_out_of_scope,omitempty"` Size string `yaml:"size,omitempty" json:"size,omitempty"` Technology string `yaml:"technology,omitempty" json:"technology,omitempty"` Technologies []string `yaml:"technologies,omitempty" json:"technologies,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"` Internet bool `yaml:"internet,omitempty" json:"internet,omitempty"` Machine string `yaml:"machine,omitempty" json:"machine,omitempty"` Encryption string `yaml:"encryption,omitempty" json:"encryption,omitempty"` Owner string `yaml:"owner,omitempty" json:"owner,omitempty"` Confidentiality string `yaml:"confidentiality,omitempty" json:"confidentiality,omitempty"` Integrity string `yaml:"integrity,omitempty" json:"integrity,omitempty"` Availability string `yaml:"availability,omitempty" json:"availability,omitempty"` JustificationCiaRating string `yaml:"justification_cia_rating,omitempty" json:"justification_cia_rating,omitempty"` MultiTenant bool `yaml:"multi_tenant,omitempty" json:"multi_tenant,omitempty"` Redundant bool `yaml:"redundant,omitempty" json:"redundant,omitempty"` CustomDevelopedParts bool `yaml:"custom_developed_parts,omitempty" json:"custom_developed_parts,omitempty"` DataAssetsProcessed []string `yaml:"data_assets_processed,omitempty" json:"data_assets_processed,omitempty"` DataAssetsStored []string `yaml:"data_assets_stored,omitempty" json:"data_assets_stored,omitempty"` DataFormatsAccepted []string `yaml:"data_formats_accepted,omitempty" json:"data_formats_accepted,omitempty"` DiagramTweakOrder int `yaml:"diagram_tweak_order,omitempty" json:"diagram_tweak_order,omitempty"` CommunicationLinks map[string]CommunicationLink `yaml:"communication_links,omitempty" json:"communication_links,omitempty"` } func (what *TechnicalAsset) Merge(other TechnicalAsset) error { var mergeError error what.ID, mergeError = new(Strings).MergeSingleton(what.ID, other.ID) if mergeError != nil { return fmt.Errorf("failed to merge id: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Type, mergeError = new(Strings).MergeSingleton(what.Type, other.Type) if mergeError != nil { return fmt.Errorf("failed to merge type: %w", mergeError) } what.Usage, mergeError = new(Strings).MergeSingleton(what.Usage, other.Usage) if mergeError != nil { return fmt.Errorf("failed to merge usage: %w", mergeError) } if !what.UsedAsClientByHuman { what.UsedAsClientByHuman = other.UsedAsClientByHuman } if !what.OutOfScope { what.OutOfScope = other.OutOfScope } what.JustificationOutOfScope = new(Strings).MergeMultiline(what.JustificationOutOfScope, other.JustificationOutOfScope) what.Size, mergeError = new(Strings).MergeSingleton(what.Size, other.Size) if mergeError != nil { return fmt.Errorf("failed to merge size: %w", mergeError) } what.Technology, mergeError = new(Strings).MergeSingleton(what.Technology, other.Technology) if mergeError != nil { return fmt.Errorf("failed to merge technology: %w", mergeError) } what.Tags = new(Strings).MergeUniqueSlice(what.Tags, other.Tags) if !what.Internet { what.Internet = other.Internet } what.Machine, mergeError = new(Strings).MergeSingleton(what.Machine, other.Machine) if mergeError != nil { return fmt.Errorf("failed to merge machine: %w", mergeError) } what.Encryption, mergeError = new(Strings).MergeSingleton(what.Encryption, other.Encryption) if mergeError != nil { return fmt.Errorf("failed to merge encryption: %w", mergeError) } what.Owner, mergeError = new(Strings).MergeSingleton(what.Owner, other.Owner) if mergeError != nil { return fmt.Errorf("failed to merge owner: %w", mergeError) } what.Confidentiality, mergeError = new(Strings).MergeSingleton(what.Confidentiality, other.Confidentiality) if mergeError != nil { return fmt.Errorf("failed to merge confidentiality: %w", mergeError) } what.Integrity, mergeError = new(Strings).MergeSingleton(what.Integrity, other.Integrity) if mergeError != nil { return fmt.Errorf("failed to merge integrity: %w", mergeError) } what.Availability, mergeError = new(Strings).MergeSingleton(what.Availability, other.Availability) if mergeError != nil { return fmt.Errorf("failed to merge availability: %w", mergeError) } what.JustificationCiaRating = new(Strings).MergeMultiline(what.JustificationCiaRating, other.JustificationCiaRating) if !what.MultiTenant { what.MultiTenant = other.MultiTenant } if !what.Redundant { what.Redundant = other.Redundant } if !what.CustomDevelopedParts { what.CustomDevelopedParts = other.CustomDevelopedParts } what.DataAssetsProcessed = new(Strings).MergeUniqueSlice(what.DataAssetsProcessed, other.DataAssetsProcessed) what.DataAssetsStored = new(Strings).MergeUniqueSlice(what.DataAssetsStored, other.DataAssetsStored) what.DataFormatsAccepted = new(Strings).MergeUniqueSlice(what.DataFormatsAccepted, other.DataFormatsAccepted) if what.DiagramTweakOrder == 0 { what.DiagramTweakOrder = other.DiagramTweakOrder } what.CommunicationLinks, mergeError = new(CommunicationLink).MergeMap(what.CommunicationLinks, other.CommunicationLinks) if mergeError != nil { return fmt.Errorf("failed to merge communication_links: %w", mergeError) } return nil } func (what *TechnicalAsset) MergeMap(first map[string]TechnicalAsset, second map[string]TechnicalAsset) (map[string]TechnicalAsset, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge technical asset %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/communication-link.go
pkg/input/communication-link.go
package input import "fmt" type CommunicationLink struct { Target string `yaml:"target,omitempty" json:"target,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Protocol string `yaml:"protocol,omitempty" json:"protocol,omitempty"` Authentication string `yaml:"authentication,omitempty" json:"authentication,omitempty"` Authorization string `yaml:"authorization,omitempty" json:"authorization,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"` VPN bool `yaml:"vpn,omitempty" json:"vpn,omitempty"` IpFiltered bool `yaml:"ip_filtered,omitempty" json:"ip_filtered,omitempty"` Readonly bool `yaml:"readonly,omitempty" json:"readonly,omitempty"` Usage string `yaml:"usage,omitempty" json:"usage,omitempty"` DataAssetsSent []string `yaml:"data_assets_sent,omitempty" json:"data_assets_sent,omitempty"` DataAssetsReceived []string `yaml:"data_assets_received,omitempty" json:"data_assets_received,omitempty"` DiagramTweakWeight int `yaml:"diagram_tweak_weight,omitempty" json:"diagram_tweak_weight,omitempty"` DiagramTweakConstraint bool `yaml:"diagram_tweak_constraint,omitempty" json:"diagram_tweak_constraint,omitempty"` } func (what *CommunicationLink) Merge(other CommunicationLink) error { var mergeError error what.Target, mergeError = new(Strings).MergeSingleton(what.Target, other.Target) if mergeError != nil { return fmt.Errorf("failed to merge target: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Protocol, mergeError = new(Strings).MergeSingleton(what.Protocol, other.Protocol) if mergeError != nil { return fmt.Errorf("failed to merge protocol: %w", mergeError) } what.Authentication, mergeError = new(Strings).MergeSingleton(what.Authentication, other.Authentication) if mergeError != nil { return fmt.Errorf("failed to merge authentication: %w", mergeError) } what.Authorization, mergeError = new(Strings).MergeSingleton(what.Authorization, other.Authorization) if mergeError != nil { return fmt.Errorf("failed to merge authorization: %w", mergeError) } what.Tags = new(Strings).MergeUniqueSlice(what.Tags, other.Tags) if !what.VPN { what.VPN = other.VPN } if !what.IpFiltered { what.IpFiltered = other.IpFiltered } if !what.Readonly { what.Readonly = other.Readonly } what.Usage, mergeError = new(Strings).MergeSingleton(what.Usage, other.Usage) if mergeError != nil { return fmt.Errorf("failed to merge usage: %w", mergeError) } what.DataAssetsSent = new(Strings).MergeUniqueSlice(what.DataAssetsSent, other.DataAssetsSent) what.DataAssetsReceived = new(Strings).MergeUniqueSlice(what.DataAssetsReceived, other.DataAssetsReceived) if what.DiagramTweakWeight == 0 { what.DiagramTweakWeight = other.DiagramTweakWeight } if !what.DiagramTweakConstraint { what.DiagramTweakConstraint = other.DiagramTweakConstraint } return nil } func (what *CommunicationLink) MergeMap(first map[string]CommunicationLink, second map[string]CommunicationLink) (map[string]CommunicationLink, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge commuinication link %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/risk.go
pkg/input/risk.go
package input import "fmt" type RiskIdentified struct { Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` ExploitationLikelihood string `yaml:"exploitation_likelihood,omitempty" json:"exploitation_likelihood,omitempty"` ExploitationImpact string `yaml:"exploitation_impact,omitempty" json:"exploitation_impact,omitempty"` DataBreachProbability string `yaml:"data_breach_probability,omitempty" json:"data_breach_probability,omitempty"` DataBreachTechnicalAssets []string `yaml:"data_breach_technical_assets,omitempty" json:"data_breach_technical_assets,omitempty"` MostRelevantDataAsset string `yaml:"most_relevant_data_asset,omitempty" json:"most_relevant_data_asset,omitempty"` MostRelevantTechnicalAsset string `yaml:"most_relevant_technical_asset,omitempty" json:"most_relevant_technical_asset,omitempty"` MostRelevantCommunicationLink string `yaml:"most_relevant_communication_link,omitempty" json:"most_relevant_communication_link,omitempty"` MostRelevantTrustBoundary string `yaml:"most_relevant_trust_boundary,omitempty" json:"most_relevant_trust_boundary,omitempty"` MostRelevantSharedRuntime string `yaml:"most_relevant_shared_runtime,omitempty" json:"most_relevant_shared_runtime,omitempty"` } func (what *RiskIdentified) Merge(other RiskIdentified) error { var mergeError error what.Severity, mergeError = new(Strings).MergeSingleton(what.Severity, other.Severity) if mergeError != nil { return fmt.Errorf("failed to merge severity: %w", mergeError) } what.ExploitationLikelihood, mergeError = new(Strings).MergeSingleton(what.ExploitationLikelihood, other.ExploitationLikelihood) if mergeError != nil { return fmt.Errorf("failed to merge exploitation_likelihood: %w", mergeError) } what.ExploitationImpact, mergeError = new(Strings).MergeSingleton(what.ExploitationImpact, other.ExploitationImpact) if mergeError != nil { return fmt.Errorf("failed to merge exploitation_impact: %w", mergeError) } what.DataBreachProbability, mergeError = new(Strings).MergeSingleton(what.DataBreachProbability, other.DataBreachProbability) if mergeError != nil { return fmt.Errorf("failed to merge date: %w", mergeError) } what.DataBreachTechnicalAssets = new(Strings).MergeUniqueSlice(what.DataBreachTechnicalAssets, other.DataBreachTechnicalAssets) what.MostRelevantDataAsset, mergeError = new(Strings).MergeSingleton(what.MostRelevantDataAsset, other.MostRelevantDataAsset) if mergeError != nil { return fmt.Errorf("failed to merge most_relevant_data_asset: %w", mergeError) } what.MostRelevantTechnicalAsset, mergeError = new(Strings).MergeSingleton(what.MostRelevantTechnicalAsset, other.MostRelevantTechnicalAsset) if mergeError != nil { return fmt.Errorf("failed to merge most_relevant_technical_asset: %w", mergeError) } what.MostRelevantCommunicationLink, mergeError = new(Strings).MergeSingleton(what.MostRelevantCommunicationLink, other.MostRelevantCommunicationLink) if mergeError != nil { return fmt.Errorf("failed to merge most_relevant_communication_link: %w", mergeError) } what.MostRelevantTrustBoundary, mergeError = new(Strings).MergeSingleton(what.MostRelevantTrustBoundary, other.MostRelevantTrustBoundary) if mergeError != nil { return fmt.Errorf("failed to merge most_relevant_trust_boundary: %w", mergeError) } what.MostRelevantSharedRuntime, mergeError = new(Strings).MergeSingleton(what.MostRelevantSharedRuntime, other.MostRelevantSharedRuntime) if mergeError != nil { return fmt.Errorf("failed to merge most_relevant_shared_runtime: %w", mergeError) } return nil } func (what *RiskIdentified) MergeMap(first map[string]RiskIdentified, second map[string]RiskIdentified) (map[string]RiskIdentified, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge risk %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/shared-runtime.go
pkg/input/shared-runtime.go
package input import "fmt" type SharedRuntime struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tag,omitempty"` TechnicalAssetsRunning []string `yaml:"technical_assets_running,omitempty" json:"technical_assets_running,omitempty"` } func (what *SharedRuntime) Merge(other SharedRuntime) error { var mergeError error what.ID, mergeError = new(Strings).MergeSingleton(what.ID, other.ID) if mergeError != nil { return fmt.Errorf("failed to merge id: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Tags = new(Strings).MergeUniqueSlice(what.Tags, other.Tags) what.TechnicalAssetsRunning = new(Strings).MergeUniqueSlice(what.TechnicalAssetsRunning, other.TechnicalAssetsRunning) return nil } func (what *SharedRuntime) MergeMap(first map[string]SharedRuntime, second map[string]SharedRuntime) (map[string]SharedRuntime, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge shared runtime %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/risk-category.go
pkg/input/risk-category.go
package input import ( "fmt" "strings" ) type RiskCategory struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Title string `json:"title,omitempty" yaml:"title,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Impact string `yaml:"impact,omitempty" json:"impact,omitempty"` ASVS string `yaml:"asvs,omitempty" json:"asvs,omitempty"` CheatSheet string `yaml:"cheat_sheet,omitempty" json:"cheat_sheet,omitempty"` Action string `yaml:"action,omitempty" json:"action,omitempty"` Mitigation string `yaml:"mitigation,omitempty" json:"mitigation,omitempty"` Check string `yaml:"check,omitempty" json:"check,omitempty"` Function string `yaml:"function,omitempty" json:"function,omitempty"` STRIDE string `yaml:"stride,omitempty" json:"stride,omitempty"` DetectionLogic string `yaml:"detection_logic,omitempty" json:"detection_logic,omitempty"` RiskAssessment string `yaml:"risk_assessment,omitempty" json:"risk_assessment,omitempty"` FalsePositives string `yaml:"false_positives,omitempty" json:"false_positives,omitempty"` ModelFailurePossibleReason bool `yaml:"model_failure_possible_reason,omitempty" json:"model_failure_possible_reason,omitempty"` CWE int `yaml:"cwe,omitempty" json:"cwe,omitempty"` RisksIdentified map[string]RiskIdentified `yaml:"risks_identified,omitempty" json:"risks_identified,omitempty"` } type RiskCategories []*RiskCategory func (what *RiskCategory) Merge(other RiskCategory) error { var mergeError error what.ID, mergeError = new(Strings).MergeSingleton(what.ID, other.ID) if mergeError != nil { return fmt.Errorf("failed to merge id: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Impact, mergeError = new(Strings).MergeSingleton(what.Impact, other.Impact) if mergeError != nil { return fmt.Errorf("failed to merge impact: %w", mergeError) } what.ASVS, mergeError = new(Strings).MergeSingleton(what.ASVS, other.ASVS) if mergeError != nil { return fmt.Errorf("failed to merge asvs: %w", mergeError) } what.CheatSheet, mergeError = new(Strings).MergeSingleton(what.CheatSheet, other.CheatSheet) if mergeError != nil { return fmt.Errorf("failed to merge cheat_sheet: %w", mergeError) } what.Action, mergeError = new(Strings).MergeSingleton(what.Action, other.Action) if mergeError != nil { return fmt.Errorf("failed to merge action: %w", mergeError) } what.Mitigation, mergeError = new(Strings).MergeSingleton(what.Mitigation, other.Mitigation) if mergeError != nil { return fmt.Errorf("failed to merge mitigation: %w", mergeError) } what.Check, mergeError = new(Strings).MergeSingleton(what.Check, other.Check) if mergeError != nil { return fmt.Errorf("failed to merge check: %w", mergeError) } what.Function, mergeError = new(Strings).MergeSingleton(what.Function, other.Function) if mergeError != nil { return fmt.Errorf("failed to merge function: %w", mergeError) } what.STRIDE, mergeError = new(Strings).MergeSingleton(what.STRIDE, other.STRIDE) if mergeError != nil { return fmt.Errorf("failed to merge STRIDE: %w", mergeError) } what.DetectionLogic, mergeError = new(Strings).MergeSingleton(what.DetectionLogic, other.DetectionLogic) if mergeError != nil { return fmt.Errorf("failed to merge detection_logic: %w", mergeError) } what.RiskAssessment, mergeError = new(Strings).MergeSingleton(what.RiskAssessment, other.RiskAssessment) if mergeError != nil { return fmt.Errorf("failed to merge risk_assessment: %w", mergeError) } what.FalsePositives, mergeError = new(Strings).MergeSingleton(what.FalsePositives, other.FalsePositives) if mergeError != nil { return fmt.Errorf("failed to merge false_positives: %w", mergeError) } if !what.ModelFailurePossibleReason { what.ModelFailurePossibleReason = other.ModelFailurePossibleReason } if what.CWE == 0 { what.CWE = other.CWE } what.RisksIdentified, mergeError = new(RiskIdentified).MergeMap(what.RisksIdentified, other.RisksIdentified) if mergeError != nil { return fmt.Errorf("failed to merge identified risks: %w", mergeError) } return nil } func (what *RiskCategories) Add(items ...*RiskCategory) error { for _, item := range items { for _, value := range *what { if strings.EqualFold(value.ID, item.ID) { return fmt.Errorf("duplicate item %q in risk category list", value.ID) } } *what = append(*what, item) } return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/overview.go
pkg/input/overview.go
package input type Overview struct { Description string `yaml:"description,omitempty" json:"description,omitempty"` Images []map[string]string `yaml:"images,omitempty" json:"images,omitempty"` // yes, array of map here, as array keeps the order of the image keys } func (what *Overview) Merge(other Overview) error { if len(what.Description) > 0 { if len(other.Description) > 0 { what.Description += lineSeparator + other.Description } } else { what.Description = other.Description } what.Images = append(what.Images, other.Images...) return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/risk-tracking.go
pkg/input/risk-tracking.go
package input import "fmt" type RiskTracking struct { Status string `yaml:"status,omitempty" json:"status,omitempty"` Justification string `yaml:"justification,omitempty" json:"justification,omitempty"` Ticket string `yaml:"ticket,omitempty" json:"ticket,omitempty"` Date string `yaml:"date,omitempty" json:"date,omitempty"` CheckedBy string `yaml:"checked_by,omitempty" json:"checked_by,omitempty"` } func (what *RiskTracking) Merge(other RiskTracking) error { var mergeError error what.Status, mergeError = new(Strings).MergeSingleton(what.Status, other.Status) if mergeError != nil { return fmt.Errorf("failed to merge status: %w", mergeError) } what.Justification, mergeError = new(Strings).MergeSingleton(what.Justification, other.Justification) if mergeError != nil { return fmt.Errorf("failed to merge justification: %w", mergeError) } what.Ticket, mergeError = new(Strings).MergeSingleton(what.Ticket, other.Ticket) if mergeError != nil { return fmt.Errorf("failed to merge ticket: %w", mergeError) } what.Date, mergeError = new(Strings).MergeSingleton(what.Date, other.Date) if mergeError != nil { return fmt.Errorf("failed to merge date: %w", mergeError) } what.CheckedBy, mergeError = new(Strings).MergeSingleton(what.CheckedBy, other.CheckedBy) if mergeError != nil { return fmt.Errorf("failed to merge checked_by: %w", mergeError) } return nil } func (what *RiskTracking) MergeMap(first map[string]RiskTracking, second map[string]RiskTracking) (map[string]RiskTracking, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge risk tracking %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/model.go
pkg/input/model.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package input import ( "fmt" "log" "os" "path/filepath" "slices" "sort" "strings" "github.com/mpvl/unique" "gopkg.in/yaml.v3" ) // === Model Type Stuff ====================================== type Model struct { // TODO: Eventually remove this and directly use ParsedModelRoot? But then the error messages for model errors are not quite as good anymore... ThreagileVersion string `yaml:"threagile_version,omitempty" json:"threagile_version,omitempty"` Includes []string `yaml:"includes,omitempty" json:"includes,omitempty"` Title string `yaml:"title,omitempty" json:"title,omitempty"` Author Author `yaml:"author,omitempty" json:"author,omitempty"` Contributors []Author `yaml:"contributors,omitempty" json:"contributors,omitempty"` Date string `yaml:"date,omitempty" json:"date,omitempty"` AppDescription Overview `yaml:"application_description,omitempty" json:"application_description,omitempty"` BusinessOverview Overview `yaml:"business_overview,omitempty" json:"business_overview,omitempty"` TechnicalOverview Overview `yaml:"technical_overview,omitempty" json:"technical_overview,omitempty"` BusinessCriticality string `yaml:"business_criticality,omitempty" json:"business_criticality,omitempty"` ManagementSummaryComment string `yaml:"management_summary_comment,omitempty" json:"management_summary_comment,omitempty"` SecurityRequirements map[string]string `yaml:"security_requirements,omitempty" json:"security_requirements,omitempty"` Questions map[string]string `yaml:"questions,omitempty" json:"questions,omitempty"` AbuseCases map[string]string `yaml:"abuse_cases,omitempty" json:"abuse_cases,omitempty"` TagsAvailable []string `yaml:"tags_available,omitempty" json:"tags_available,omitempty"` DataAssets map[string]DataAsset `yaml:"data_assets,omitempty" json:"data_assets,omitempty"` TechnicalAssets map[string]TechnicalAsset `yaml:"technical_assets,omitempty" json:"technical_assets,omitempty"` TrustBoundaries map[string]TrustBoundary `yaml:"trust_boundaries,omitempty" json:"trust_boundaries,omitempty"` SharedRuntimes map[string]SharedRuntime `yaml:"shared_runtimes,omitempty" json:"shared_runtimes,omitempty"` CustomRiskCategories RiskCategories `yaml:"custom_risk_categories,omitempty" json:"custom_risk_categories,omitempty"` RiskTracking map[string]RiskTracking `yaml:"risk_tracking,omitempty" json:"risk_tracking,omitempty"` DiagramTweakNodesep int `yaml:"diagram_tweak_nodesep,omitempty" json:"diagram_tweak_nodesep,omitempty"` DiagramTweakRanksep int `yaml:"diagram_tweak_ranksep,omitempty" json:"diagram_tweak_ranksep,omitempty"` DiagramTweakEdgeLayout string `yaml:"diagram_tweak_edge_layout,omitempty" json:"diagram_tweak_edge_layout,omitempty"` DiagramTweakSuppressEdgeLabels bool `yaml:"diagram_tweak_suppress_edge_labels,omitempty" json:"diagram_tweak_suppress_edge_labels,omitempty"` DiagramTweakLayoutLeftToRight bool `yaml:"diagram_tweak_layout_left_to_right,omitempty" json:"diagram_tweak_layout_left_to_right,omitempty"` DiagramTweakInvisibleConnectionsBetweenAssets []string `yaml:"diagram_tweak_invisible_connections_between_assets,omitempty" json:"diagram_tweak_invisible_connections_between_assets,omitempty"` DiagramTweakSameRankAssets []string `yaml:"diagram_tweak_same_rank_assets,omitempty" json:"diagram_tweak_same_rank_assets,omitempty"` } func (model *Model) Defaults() *Model { *model = Model{ Questions: make(map[string]string), AbuseCases: make(map[string]string), SecurityRequirements: make(map[string]string), DataAssets: make(map[string]DataAsset), TechnicalAssets: make(map[string]TechnicalAsset), TrustBoundaries: make(map[string]TrustBoundary), SharedRuntimes: make(map[string]SharedRuntime), CustomRiskCategories: make(RiskCategories, 0), RiskTracking: make(map[string]RiskTracking), } return model } func (model *Model) Load(inputFilename string) error { modelYaml, readError := os.ReadFile(filepath.Clean(inputFilename)) if readError != nil { log.Fatal("Unable to read model file: ", readError) } unmarshalError := yaml.Unmarshal(modelYaml, &model) if unmarshalError != nil { log.Fatal("Unable to parse model yaml: ", unmarshalError) } for _, includeFile := range model.Includes { mergeError := model.Merge(filepath.Dir(inputFilename), includeFile) if mergeError != nil { log.Fatalf("Unable to merge model include %q: %v", includeFile, mergeError) } } return nil } func (model *Model) Merge(dir string, includeFilename string) error { modelYaml, readError := os.ReadFile(filepath.Clean(filepath.Join(dir, includeFilename))) if readError != nil { return fmt.Errorf("unable to read model file: %w", readError) } var fileStructure map[string]any unmarshalStructureError := yaml.Unmarshal(modelYaml, &fileStructure) if unmarshalStructureError != nil { return fmt.Errorf("unable to parse model structure: %w", unmarshalStructureError) } var includedModel Model unmarshalError := yaml.Unmarshal(modelYaml, &includedModel) if unmarshalError != nil { return fmt.Errorf("unable to parse model yaml: %w", unmarshalError) } var mergeError error for item := range fileStructure { switch strings.ToLower(item) { case strings.ToLower("includes"): for _, includeFile := range includedModel.Includes { mergeError = model.Merge(filepath.Join(dir, filepath.Dir(includeFilename)), includeFile) if mergeError != nil { return fmt.Errorf("failed to merge model include %q: %w", includeFile, mergeError) } } case strings.ToLower("threagile_version"): model.ThreagileVersion, mergeError = new(Strings).MergeSingleton(model.ThreagileVersion, includedModel.ThreagileVersion) if mergeError != nil { return fmt.Errorf("failed to merge threagile version: %w", mergeError) } case strings.ToLower("title"): model.Title, mergeError = new(Strings).MergeSingleton(model.Title, includedModel.Title) if mergeError != nil { return fmt.Errorf("failed to merge title: %w", mergeError) } case strings.ToLower("author"): mergeError = model.Author.Merge(includedModel.Author) if mergeError != nil { return fmt.Errorf("failed to merge author: %w", mergeError) } case strings.ToLower("contributors"): model.Contributors, mergeError = new(Author).MergeList(append(model.Contributors, includedModel.Author)) if mergeError != nil { return fmt.Errorf("failed to merge contributors: %w", mergeError) } case strings.ToLower("date"): model.Date, mergeError = new(Strings).MergeSingleton(model.Date, includedModel.Date) if mergeError != nil { return fmt.Errorf("failed to merge date: %w", mergeError) } case strings.ToLower("application_description"): mergeError = model.AppDescription.Merge(includedModel.AppDescription) if mergeError != nil { return fmt.Errorf("failed to merge application description: %w", mergeError) } case strings.ToLower("business_overview"): mergeError = model.BusinessOverview.Merge(includedModel.BusinessOverview) if mergeError != nil { return fmt.Errorf("failed to merge business overview: %w", mergeError) } case strings.ToLower("technical_overview"): mergeError = model.TechnicalOverview.Merge(includedModel.TechnicalOverview) if mergeError != nil { return fmt.Errorf("failed to merge technical overview: %w", mergeError) } case strings.ToLower("business_criticality"): model.BusinessCriticality, mergeError = new(Strings).MergeSingleton(model.BusinessCriticality, includedModel.BusinessCriticality) if mergeError != nil { return fmt.Errorf("failed to merge business criticality: %w", mergeError) } case strings.ToLower("management_summary_comment"): model.ManagementSummaryComment = new(Strings).MergeMultiline(model.ManagementSummaryComment, includedModel.ManagementSummaryComment) case strings.ToLower("security_requirements"): model.SecurityRequirements, mergeError = new(Strings).MergeMap(model.SecurityRequirements, includedModel.SecurityRequirements) if mergeError != nil { return fmt.Errorf("failed to merge security requirements: %w", mergeError) } case strings.ToLower("questions"): model.Questions, mergeError = new(Strings).MergeMap(model.Questions, includedModel.Questions) if mergeError != nil { return fmt.Errorf("failed to merge questions: %w", mergeError) } case strings.ToLower("abuse_cases"): model.AbuseCases, mergeError = new(Strings).MergeMap(model.AbuseCases, includedModel.AbuseCases) if mergeError != nil { return fmt.Errorf("failed to merge abuse cases: %w", mergeError) } case strings.ToLower("tags_available"): model.TagsAvailable = new(Strings).MergeUniqueSlice(model.TagsAvailable, includedModel.TagsAvailable) case strings.ToLower("data_assets"): model.DataAssets, mergeError = new(DataAsset).MergeMap(model.DataAssets, includedModel.DataAssets) if mergeError != nil { return fmt.Errorf("failed to merge data assets: %w", mergeError) } case strings.ToLower("technical_assets"): model.TechnicalAssets, mergeError = new(TechnicalAsset).MergeMap(model.TechnicalAssets, includedModel.TechnicalAssets) if mergeError != nil { return fmt.Errorf("failed to merge technical assets: %w", mergeError) } case strings.ToLower("trust_boundaries"): model.TrustBoundaries, mergeError = new(TrustBoundary).MergeMap(model.TrustBoundaries, includedModel.TrustBoundaries) if mergeError != nil { return fmt.Errorf("failed to merge trust boundaries: %w", mergeError) } case strings.ToLower("shared_runtimes"): model.SharedRuntimes, mergeError = new(SharedRuntime).MergeMap(model.SharedRuntimes, includedModel.SharedRuntimes) if mergeError != nil { return fmt.Errorf("failed to merge shared runtimes: %w", mergeError) } case strings.ToLower("custom_risk_categories"): mergeError = model.CustomRiskCategories.Add(includedModel.CustomRiskCategories...) if mergeError != nil { return fmt.Errorf("failed to merge risk categories: %w", mergeError) } case strings.ToLower("risk_tracking"): model.RiskTracking, mergeError = new(RiskTracking).MergeMap(model.RiskTracking, includedModel.RiskTracking) if mergeError != nil { return fmt.Errorf("failed to merge risk tracking: %w", mergeError) } case "diagram_tweak_nodesep": model.DiagramTweakNodesep = includedModel.DiagramTweakNodesep case "diagram_tweak_ranksep": model.DiagramTweakRanksep = includedModel.DiagramTweakRanksep case "diagram_tweak_edge_layout": model.DiagramTweakEdgeLayout = includedModel.DiagramTweakEdgeLayout case "diagram_tweak_suppress_edge_labels": model.DiagramTweakSuppressEdgeLabels = includedModel.DiagramTweakSuppressEdgeLabels case "diagram_tweak_layout_left_to_right": model.DiagramTweakLayoutLeftToRight = includedModel.DiagramTweakLayoutLeftToRight case "diagram_tweak_invisible_connections_between_assets": model.DiagramTweakInvisibleConnectionsBetweenAssets = append(model.DiagramTweakInvisibleConnectionsBetweenAssets, includedModel.DiagramTweakInvisibleConnectionsBetweenAssets...) sort.Strings(model.DiagramTweakInvisibleConnectionsBetweenAssets) unique.Strings(&model.DiagramTweakInvisibleConnectionsBetweenAssets) case "diagram_tweak_same_rank_assets": model.DiagramTweakSameRankAssets = append(model.DiagramTweakSameRankAssets, includedModel.DiagramTweakSameRankAssets...) sort.Strings(model.DiagramTweakSameRankAssets) unique.Strings(&model.DiagramTweakSameRankAssets) } } return nil } func (model *Model) AddTagToModelInput(tag string, dryRun bool, changes *[]string) { tag = NormalizeTag(tag) if !slices.Contains(model.TagsAvailable, tag) { *changes = append(*changes, "adding tag: "+tag) if !dryRun { model.TagsAvailable = append(model.TagsAvailable, tag) } } } func NormalizeTag(tag string) string { return strings.TrimSpace(strings.ToLower(tag)) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/strings.go
pkg/input/strings.go
package input import ( "fmt" "gopkg.in/yaml.v3" "slices" "strings" ) const ( lineSeparator = "\n<br><br>\n" ) type Strings struct { } func (what *Strings) MergeSingleton(first string, second string) (string, error) { if len(first) > 0 { if len(second) > 0 { if !strings.EqualFold(first, second) { return first, fmt.Errorf("conflicting string values: %q versus %q", first, second) } } return first, nil } return second, nil } func (what *Strings) MergeMultiline(first string, second string) string { text := first if len(first) > 0 { if len(second) > 0 && !strings.EqualFold(first, second) { text = text + lineSeparator + second } } else { text = second } return text } func (what *Strings) MergeMap(first map[string]string, second map[string]string) (map[string]string, error) { for mapKey, mapValue := range second { _, ok := first[mapKey] if ok { return nil, fmt.Errorf("duplicate item %q", mapKey) } first[mapKey] = mapValue } return first, nil } func (what *Strings) MergeUniqueSlice(first []string, second []string) []string { for _, item := range second { if !slices.Contains(first, item) { first = append(first, item) } } return first } func (what *Strings) AddLineNumbers(script any) string { text, isString := script.(string) if !isString { data, _ := yaml.Marshal(script) text = string(data) } lines := strings.Split(text, "\n") for n, line := range lines { lines[n] = fmt.Sprintf("%3d:\t%v", n+1, line) } return strings.Join(lines, "\n") } func (what *Strings) IndentPrintf(level int, script any) string { text, isString := script.(string) if !isString { data, _ := yaml.Marshal(script) text = string(data) } lines := strings.Split(text, "\n") for n, line := range lines { lines[n] = strings.Repeat(" ", level) + line } return strings.Join(lines, "\n") } func (what *Strings) IndentLine(level int, format string, params ...any) string { return strings.Repeat(" ", level) + fmt.Sprintf(format, params...) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/author.go
pkg/input/author.go
package input import ( "fmt" "sort" "strings" ) type Author struct { Name string `yaml:"name,omitempty" json:"name,omitempty"` Contact string `yaml:"contact,omitempty" json:"contact,omitempty"` Homepage string `yaml:"homepage,omitempty" json:"homepage,omitempty"` } func (what *Author) Merge(other Author) error { if len(what.Name) > 0 && !strings.EqualFold(what.Name, other.Name) { return fmt.Errorf("author name mismatch") } if len(what.Contact) > 0 && !strings.EqualFold(what.Contact, other.Contact) { return fmt.Errorf("author contact mismatch") } if len(what.Homepage) > 0 && !strings.EqualFold(what.Homepage, other.Homepage) { return fmt.Errorf("author homepage mismatch") } what.Name = other.Name what.Contact = other.Contact what.Homepage = other.Homepage return nil } func (what *Author) MergeList(list []Author) ([]Author, error) { sort.Slice(list, func(i int, j int) bool { return strings.Compare(list[i].Name, list[j].Name) < 0 }) if len(list) < 2 { return list, nil } first := list[0] tail, mergeError := what.MergeList(list[1:]) if mergeError != nil { return nil, mergeError } newList := make([]Author, 1) newList[0] = first for _, second := range tail { if first.Match(second) { mergeError = first.Merge(second) if mergeError != nil { return nil, mergeError } } else { newList = append(newList, second) } } return newList, nil } func (what *Author) Match(other Author) bool { return strings.EqualFold(what.Name, other.Name) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/trust-boundary.go
pkg/input/trust-boundary.go
package input import "fmt" type TrustBoundary struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Type string `yaml:"type,omitempty" json:"type,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"` TechnicalAssetsInside []string `yaml:"technical_assets_inside,omitempty" json:"technical_assets_inside,omitempty"` TrustBoundariesNested []string `yaml:"trust_boundaries_nested,omitempty" json:"trust_boundaries_nested,omitempty"` } func (what *TrustBoundary) Merge(other TrustBoundary) error { var mergeError error what.ID, mergeError = new(Strings).MergeSingleton(what.ID, other.ID) if mergeError != nil { return fmt.Errorf("failed to merge id: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Type, mergeError = new(Strings).MergeSingleton(what.Type, other.Type) if mergeError != nil { return fmt.Errorf("failed to merge type: %w", mergeError) } what.Tags = new(Strings).MergeUniqueSlice(what.Tags, other.Tags) what.TechnicalAssetsInside = new(Strings).MergeUniqueSlice(what.TechnicalAssetsInside, other.TechnicalAssetsInside) what.TrustBoundariesNested = new(Strings).MergeUniqueSlice(what.TrustBoundariesNested, other.TrustBoundariesNested) return nil } func (what *TrustBoundary) MergeMap(first map[string]TrustBoundary, second map[string]TrustBoundary) (map[string]TrustBoundary, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge trust boundary %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/input/data-asset.go
pkg/input/data-asset.go
package input import "fmt" type DataAsset struct { ID string `yaml:"id,omitempty" json:"id,omitempty"` Description string `yaml:"description,omitempty" json:"description,omitempty"` Usage string `yaml:"usage,omitempty" json:"usage,omitempty"` Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"` Origin string `yaml:"origin,omitempty" json:"origin,omitempty"` Owner string `yaml:"owner,omitempty" json:"owner,omitempty"` Quantity string `yaml:"quantity,omitempty" json:"quantity,omitempty"` Confidentiality string `yaml:"confidentiality,omitempty" json:"confidentiality,omitempty"` Integrity string `yaml:"integrity,omitempty" json:"integrity,omitempty"` Availability string `yaml:"availability,omitempty" json:"availability,omitempty"` JustificationCiaRating string `yaml:"justification_cia_rating,omitempty" json:"justification_cia_rating,omitempty"` } func (what *DataAsset) Merge(other DataAsset) error { var mergeError error what.ID, mergeError = new(Strings).MergeSingleton(what.ID, other.ID) if mergeError != nil { return fmt.Errorf("failed to merge id: %w", mergeError) } what.Description, mergeError = new(Strings).MergeSingleton(what.Description, other.Description) if mergeError != nil { return fmt.Errorf("failed to merge description: %w", mergeError) } what.Usage, mergeError = new(Strings).MergeSingleton(what.Usage, other.Usage) if mergeError != nil { return fmt.Errorf("failed to merge usage: %w", mergeError) } what.Tags = new(Strings).MergeUniqueSlice(what.Tags, other.Tags) what.Origin, mergeError = new(Strings).MergeSingleton(what.Origin, other.Origin) if mergeError != nil { return fmt.Errorf("failed to merge origin: %w", mergeError) } what.Owner, mergeError = new(Strings).MergeSingleton(what.Owner, other.Owner) if mergeError != nil { return fmt.Errorf("failed to merge owner: %w", mergeError) } what.Quantity, mergeError = new(Strings).MergeSingleton(what.Quantity, other.Quantity) if mergeError != nil { return fmt.Errorf("failed to merge quantity: %w", mergeError) } what.Confidentiality, mergeError = new(Strings).MergeSingleton(what.Confidentiality, other.Confidentiality) if mergeError != nil { return fmt.Errorf("failed to merge confidentiality: %w", mergeError) } what.Integrity, mergeError = new(Strings).MergeSingleton(what.Integrity, other.Integrity) if mergeError != nil { return fmt.Errorf("failed to merge integrity: %w", mergeError) } what.Availability, mergeError = new(Strings).MergeSingleton(what.Availability, other.Availability) if mergeError != nil { return fmt.Errorf("failed to merge availability: %w", mergeError) } what.JustificationCiaRating = new(Strings).MergeMultiline(what.JustificationCiaRating, other.JustificationCiaRating) return nil } func (what *DataAsset) MergeMap(first map[string]DataAsset, second map[string]DataAsset) (map[string]DataAsset, error) { for mapKey, mapValue := range second { mapItem, ok := first[mapKey] if ok { mergeError := mapItem.Merge(mapValue) if mergeError != nil { return first, fmt.Errorf("failed to merge data asset %q: %w", mapKey, mergeError) } first[mapKey] = mapItem } else { first[mapKey] = mapValue } } return first, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/seed-tags-macro.go
pkg/macros/seed-tags-macro.go
package macros import ( "sort" "strconv" "github.com/mpvl/unique" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type SeedTagsMacro struct { } func NewSeedTags() *SeedTagsMacro { return &SeedTagsMacro{} } func (*SeedTagsMacro) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "seed-tags", Title: "Seed Tags", Description: "This model macro simply seeds the model file with supported tags from all risk rules.", } } func (*SeedTagsMacro) GetNextQuestion(parsedModel *types.Model) (nextQuestion MacroQuestion, err error) { return NoMoreQuestions(), nil } func (*SeedTagsMacro) ApplyAnswer(_ string, _ ...string) (message string, validResult bool, err error) { return "Answer processed", true, nil } func (*SeedTagsMacro) GoBack() (message string, validResult bool, err error) { return "Cannot go back further", false, nil } func (*SeedTagsMacro) GetFinalChangeImpact(_ *input.Model, _ *types.Model) (changes []string, message string, validResult bool, err error) { return []string{"seed the model file with supported tags from all risk rules"}, "Changeset valid", true, err } func (*SeedTagsMacro) Execute(modelInput *input.Model, parsedModel *types.Model) (message string, validResult bool, err error) { modelInput.TagsAvailable = parsedModel.TagsAvailable for tag := range parsedModel.AllSupportedTags { modelInput.TagsAvailable = append(modelInput.TagsAvailable, tag) } unique.Strings(&modelInput.TagsAvailable) sort.Strings(modelInput.TagsAvailable) return "Model file seeding with " + strconv.Itoa(len(parsedModel.AllSupportedTags)) + " tags successful", true, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/macros.go
pkg/macros/macros.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package macros import ( "bufio" "fmt" "io" "os" "path/filepath" "strconv" "strings" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" "gopkg.in/yaml.v3" ) type Macros interface { GetMacroDetails() MacroDetails GetNextQuestion(model *types.Model) (nextQuestion MacroQuestion, err error) ApplyAnswer(questionID string, answer ...string) (message string, validResult bool, err error) GoBack() (message string, validResult bool, err error) GetFinalChangeImpact(modelInput *input.Model, model *types.Model) (changes []string, message string, validResult bool, err error) Execute(modelInput *input.Model, model *types.Model) (message string, validResult bool, err error) } func ListBuiltInMacros() []Macros { return []Macros{ NewBuildPipeline(), NewAddVault(), NewPrettyPrint(), newRemoveUnusedTags(), NewSeedRiskTracking(), NewSeedTags(), } } func ListCustomMacros() []Macros { // TODO: implement return []Macros{} } func GetMacroByID(id string) (Macros, error) { builtinMacros := ListBuiltInMacros() customMacros := ListCustomMacros() allMacros := append(builtinMacros, customMacros...) for _, macro := range allMacros { if macro.GetMacroDetails().ID == id { return macro, nil } } return nil, fmt.Errorf("unknown macro id: %v", id) } func ExecuteModelMacro(modelInput *input.Model, inputFile string, parsedModel *types.Model, macroID string) error { macros, err := GetMacroByID(macroID) if err != nil { return err } macroDetails := macros.GetMacroDetails() fmt.Println("Executing model macro:", macroDetails.ID) fmt.Println() fmt.Println() printBorder(len(macroDetails.Title), true) fmt.Println(macroDetails.Title) printBorder(len(macroDetails.Title), true) if len(macroDetails.Description) > 0 { fmt.Println(macroDetails.Description) } fmt.Println() reader := bufio.NewReader(os.Stdin) for { nextQuestion, err := macros.GetNextQuestion(parsedModel) if err != nil { return err } if nextQuestion.NoMoreQuestions() { break } fmt.Println() printBorder(len(nextQuestion.Title), false) fmt.Println(nextQuestion.Title) printBorder(len(nextQuestion.Title), false) if len(nextQuestion.Description) > 0 { fmt.Println(nextQuestion.Description) } resultingMultiValueSelection := make([]string, 0) if nextQuestion.IsValueConstrained() { if nextQuestion.MultiSelect { selectedValues := make(map[string]bool) for { fmt.Println("Please select (multiple executions possible) from the following values (use number to select/deselect):") fmt.Println(" 0:", "SELECTION PROCESS FINISHED: CONTINUE TO NEXT QUESTION") for i, val := range nextQuestion.PossibleAnswers { number := i + 1 padding, selected := "", " " if number < 10 { padding = " " } if val, exists := selectedValues[val]; exists && val { selected = "*" } fmt.Println(" "+selected+" "+padding+strconv.Itoa(number)+":", val) } fmt.Println() fmt.Print("Enter number to select/deselect (or 0 when finished): ") answer, err := reader.ReadString('\n') // convert CRLF to LF answer = strings.TrimSpace(strings.ReplaceAll(answer, "\n", "")) if err != nil { return err } if val, err := strconv.Atoi(answer); err == nil { // flip selection if val == 0 { for key, selected := range selectedValues { if selected { resultingMultiValueSelection = append(resultingMultiValueSelection, key) } } break } else if val > 0 && val <= len(nextQuestion.PossibleAnswers) { selectedValues[nextQuestion.PossibleAnswers[val-1]] = !selectedValues[nextQuestion.PossibleAnswers[val-1]] } } } } else { fmt.Println("Please choose from the following values (enter value directly or use number):") for i, val := range nextQuestion.PossibleAnswers { number := i + 1 padding := "" if number < 10 { padding = " " } fmt.Println(" "+padding+strconv.Itoa(number)+":", val) } } } message := "" validResult := true if !nextQuestion.IsValueConstrained() || !nextQuestion.MultiSelect { fmt.Println() fmt.Println("Enter your answer (use 'BACK' to go one step back or 'QUIT' to quit without executing the model macro)") fmt.Print("Answer") if len(nextQuestion.DefaultAnswer) > 0 { fmt.Print(" (default '" + nextQuestion.DefaultAnswer + "')") } fmt.Print(": ") answer, err := reader.ReadString('\n') // convert CRLF to LF answer = strings.TrimSpace(strings.ReplaceAll(answer, "\n", "")) if err != nil { return err } if len(answer) == 0 && len(nextQuestion.DefaultAnswer) > 0 { // accepting the default answer = nextQuestion.DefaultAnswer } else if nextQuestion.IsValueConstrained() { // convert number to value if val, err := strconv.Atoi(answer); err == nil { if val > 0 && val <= len(nextQuestion.PossibleAnswers) { answer = nextQuestion.PossibleAnswers[val-1] } } } if strings.ToLower(answer) == "quit" { fmt.Println("Quitting without executing the model macro") return nil } else if strings.ToLower(answer) == "back" { message, validResult, _ = macros.GoBack() } else if len(answer) > 0 { // individual answer if nextQuestion.IsValueConstrained() { if !nextQuestion.IsMatchingValueConstraint(answer) { fmt.Println() fmt.Println(">>> INVALID <<<") fmt.Println("Answer does not match any allowed value. Please try again:") continue } } message, validResult, _ = macros.ApplyAnswer(nextQuestion.ID, answer) } } else { message, validResult, _ = macros.ApplyAnswer(nextQuestion.ID, resultingMultiValueSelection...) } if err != nil { return err } if !validResult { fmt.Println() fmt.Println(">>> INVALID <<<") } fmt.Println(message) fmt.Println() } for { fmt.Println() fmt.Println() fmt.Println("#################################################################") fmt.Println("Do you want to execute the model macro (updating the model file)?") fmt.Println("#################################################################") fmt.Println() fmt.Println("The following changes will be applied:") var changes []string message := "" changes, message, validResult, err := macros.GetFinalChangeImpact(modelInput, parsedModel) if err != nil { return err } for _, change := range changes { fmt.Println(" -", change) } if !validResult { fmt.Println() fmt.Println(">>> INVALID <<<") } fmt.Println() fmt.Println(message) fmt.Println() fmt.Print("Apply these changes to the model file?\nType Yes or No: ") answer, err := reader.ReadString('\n') // convert CRLF to LF answer = strings.TrimSpace(strings.ReplaceAll(answer, "\n", "")) if err != nil { return err } answer = strings.ToLower(answer) fmt.Println() switch answer { case "yes", "y": message, validResult, err = macros.Execute(modelInput, parsedModel) if err != nil { return err } if !validResult { fmt.Println() fmt.Println(">>> INVALID <<<") } fmt.Println(message) fmt.Println() backupFilename := inputFile + ".backup" fmt.Println("Creating backup model file:", backupFilename) // TODO add random files in /dev/shm space? _, err = copyFile(inputFile, backupFilename) if err != nil { return err } fmt.Println("Updating model") yamlBytes, err := yaml.Marshal(modelInput) if err != nil { return err } /* yamlBytes = model.ReformatYAML(yamlBytes) */ fmt.Println("Writing model file:", inputFile) err = os.WriteFile(inputFile, yamlBytes, 0400) if err != nil { return err } fmt.Println("Model file successfully updated") return nil case "no", "n": fmt.Println("Quitting without executing the model macro") return nil } } } func printBorder(length int, bold bool) { char := "-" if bold { char = "=" } for i := 1; i <= length; i++ { fmt.Print(char) } fmt.Println() } func copyFile(src, dst string) (int64, error) { sourceFileStat, err := os.Stat(src) if err != nil { return 0, err } if !sourceFileStat.Mode().IsRegular() { return 0, fmt.Errorf("%s is not a regular file", src) } source, err := os.Open(filepath.Clean(src)) if err != nil { return 0, err } defer func() { _ = source.Close() }() destination, err := os.Create(filepath.Clean(dst)) if err != nil { return 0, err } defer func() { _ = destination.Close() }() nBytes, err := io.Copy(destination, source) return nBytes, err } type MacroDetails struct { ID, Title, Description string } type MacroQuestion struct { ID, Title, Description string PossibleAnswers []string MultiSelect bool DefaultAnswer string } const NoMoreQuestionsID = "" func NoMoreQuestions() MacroQuestion { return MacroQuestion{ ID: NoMoreQuestionsID, Title: "", Description: "", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "", } } func (what MacroQuestion) NoMoreQuestions() bool { return what.ID == NoMoreQuestionsID } func (what MacroQuestion) IsValueConstrained() bool { return len(what.PossibleAnswers) > 0 } func (what MacroQuestion) IsMatchingValueConstraint(answer string) bool { if what.IsValueConstrained() { for _, val := range what.PossibleAnswers { if strings.EqualFold(val, answer) { return true } } return false } return true }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/pretty-print-macro.go
pkg/macros/pretty-print-macro.go
package macros import ( "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type PrettyPrintMacro struct { } func NewPrettyPrint() *PrettyPrintMacro { return &PrettyPrintMacro{} } func (*PrettyPrintMacro) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "pretty-print", Title: "Pretty Print", Description: "This model macro simply reformats the model file in a pretty-print style.", } } func (*PrettyPrintMacro) GetNextQuestion(_ *types.Model) (nextQuestion MacroQuestion, err error) { return NoMoreQuestions(), nil } func (*PrettyPrintMacro) ApplyAnswer(_ string, _ ...string) (message string, validResult bool, err error) { return "Answer processed", true, nil } func (*PrettyPrintMacro) GoBack() (message string, validResult bool, err error) { return "Cannot go back further", false, nil } func (*PrettyPrintMacro) GetFinalChangeImpact(_ *input.Model, _ *types.Model) (changes []string, message string, validResult bool, err error) { return []string{"pretty-printing the model file"}, "Changeset valid", true, err } func (*PrettyPrintMacro) Execute(_ *input.Model, _ *types.Model) (message string, validResult bool, err error) { return "Model pretty printing successful", true, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/add-vault-macro.go
pkg/macros/add-vault-macro.go
package macros import ( "fmt" "sort" "strings" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type AddVaultMacro struct { macroState map[string][]string questionsAnswered []string withinTrustBoundary bool createNewTrustBoundary bool } const createNewTrustBoundaryLabel = "CREATE NEW TRUST BOUNDARY" var storageTypes = []string{ "Cloud Provider (storage buckets or similar)", "Container Platform (orchestration platform managed storage)", "Database (SQL-DB, NoSQL-DB, object store or similar)", // TODO let user choose to reuse existing technical asset when shared storage (which would be bad) "Filesystem (local or remote)", "In-Memory (no persistent storage of secrets)", "Service Registry", // TODO let user choose which technical asset the registry is (for comm link) } var authenticationTypes = []string{ "Certificate", "Cloud Provider (relying on cloud provider instance authentication)", "Container Platform (orchestration platform managed authentication)", "Credentials (username/password, API-key, secret token, etc.)", } func NewAddVault() *AddVaultMacro { return &AddVaultMacro{ macroState: make(map[string][]string), questionsAnswered: make([]string, 0), } } func (m *AddVaultMacro) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "add-vault", Title: "Add Vault", Description: "This model macro adds a vault (secret storage) to the model.", } } func (m *AddVaultMacro) GetNextQuestion(parsedModel *types.Model) (nextQuestion MacroQuestion, err error) { counter := len(m.questionsAnswered) if counter > 5 && !m.withinTrustBoundary { counter++ } if counter > 6 && !m.createNewTrustBoundary { counter++ } switch counter { case 0: return MacroQuestion{ ID: "vault-name", Title: "What product is used as the vault?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "", }, nil case 1: return MacroQuestion{ ID: "storage-type", Title: "What type of storage is used for the vault?", Description: "This selection affects the type of technical asset for the persistence.", PossibleAnswers: storageTypes, MultiSelect: false, DefaultAnswer: "", }, nil case 2: return MacroQuestion{ ID: "authentication-type", Title: "What type of authentication is used for accessing the vault?", Description: "This selection affects the type of communication links.", PossibleAnswers: authenticationTypes, MultiSelect: false, DefaultAnswer: "", }, nil case 3: return MacroQuestion{ ID: "multi-tenant", Title: "Is the vault used by multiple tenants?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "No", }, nil case 4: possibleAnswers := make([]string, 0) for id := range parsedModel.TechnicalAssets { possibleAnswers = append(possibleAnswers, id) } sort.Strings(possibleAnswers) if len(possibleAnswers) > 0 { return MacroQuestion{ ID: "clients", Title: "Select all technical assets that make use of the vault and access it:", Description: "This affects the communication links being generated.", PossibleAnswers: possibleAnswers, MultiSelect: true, DefaultAnswer: "", }, nil } case 5: return MacroQuestion{ ID: "within-trust-boundary", Title: "Is the vault placed within a network trust boundary?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "Yes", }, nil case 6: possibleAnswers := []string{createNewTrustBoundaryLabel} for id, trustBoundary := range parsedModel.TrustBoundaries { if trustBoundary.Type.IsNetworkBoundary() { possibleAnswers = append(possibleAnswers, id) } } sort.Strings(possibleAnswers) return MacroQuestion{ ID: "selected-trust-boundary", Title: "Choose from the list of existing network trust boundaries or create a new one?", Description: "", PossibleAnswers: possibleAnswers, MultiSelect: false, DefaultAnswer: "", }, nil case 7: return MacroQuestion{ ID: "new-trust-boundary-type", Title: "Of which type shall the new trust boundary be?", Description: "", PossibleAnswers: []string{types.NetworkOnPrem.String(), types.NetworkDedicatedHoster.String(), types.NetworkVirtualLAN.String(), types.NetworkCloudProvider.String(), types.NetworkCloudSecurityGroup.String(), types.NetworkPolicyNamespaceIsolation.String()}, MultiSelect: false, DefaultAnswer: types.NetworkOnPrem.String(), }, nil } return NoMoreQuestions(), nil } func (m *AddVaultMacro) ApplyAnswer(questionID string, answer ...string) (message string, validResult bool, err error) { m.macroState[questionID] = answer m.questionsAnswered = append(m.questionsAnswered, questionID) switch questionID { case "within-trust-boundary": m.withinTrustBoundary = strings.EqualFold(m.macroState["within-trust-boundary"][0], "yes") case "selected-trust-boundary": m.createNewTrustBoundary = strings.EqualFold(m.macroState["selected-trust-boundary"][0], createNewTrustBoundaryLabel) } return "Answer processed", true, nil } func (m *AddVaultMacro) GoBack() (message string, validResult bool, err error) { if len(m.questionsAnswered) == 0 { return "Cannot go back further", false, nil } lastQuestionID := m.questionsAnswered[len(m.questionsAnswered)-1] m.questionsAnswered = m.questionsAnswered[:len(m.questionsAnswered)-1] delete(m.macroState, lastQuestionID) return "Undo successful", true, nil } func (m *AddVaultMacro) GetFinalChangeImpact(modelInput *input.Model, parsedModel *types.Model) (changes []string, message string, validResult bool, err error) { changeLogCollector := make([]string, 0) message, validResult, err = m.applyChange(modelInput, parsedModel, &changeLogCollector, true) return changeLogCollector, message, validResult, err } func (m *AddVaultMacro) Execute(modelInput *input.Model, parsedModel *types.Model) (message string, validResult bool, err error) { changeLogCollector := make([]string, 0) message, validResult, err = m.applyChange(modelInput, parsedModel, &changeLogCollector, false) return message, validResult, err } func (m *AddVaultMacro) applyChange(modelInput *input.Model, parsedModel *types.Model, changeLogCollector *[]string, dryRun bool) (message string, validResult bool, err error) { modelInput.AddTagToModelInput(m.macroState["vault-name"][0], dryRun, changeLogCollector) var serverSideTechAssets = make([]string, 0) if _, exists := parsedModel.DataAssets["Configuration Secrets"]; !exists { dataAsset := input.DataAsset{ ID: "configuration-secrets", Description: "Configuration secrets (like credentials, keys, certificates, etc.) secured and managed by a vault", Usage: types.DevOps.String(), Tags: []string{}, Origin: "", Owner: "", Quantity: types.VeryFew.String(), Confidentiality: types.StrictlyConfidential.String(), Integrity: types.Critical.String(), Availability: types.Critical.String(), JustificationCiaRating: "Configuration secrets are rated as being 'strictly-confidential'.", } *changeLogCollector = append(*changeLogCollector, "adding data asset: configuration-secrets") if !dryRun { modelInput.DataAssets["Configuration Secrets"] = dataAsset } } databaseUsed := m.macroState["storage-type"][0] == storageTypes[2] filesystemUsed := m.macroState["storage-type"][0] == storageTypes[3] inMemoryUsed := m.macroState["storage-type"][0] == storageTypes[4] storageID := "vault-storage" if databaseUsed || filesystemUsed { tech := types.FileServer // TODO ask for local or remote and only local use execution-environment (and add separate tech type LocalFilesystem?) if databaseUsed { tech = types.Database } if _, exists := parsedModel.TechnicalAssets[storageID]; !exists { serverSideTechAssets = append(serverSideTechAssets, storageID) techAsset := input.TechnicalAsset{ ID: storageID, Description: "Vault Storage", Type: types.Datastore.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: false, OutOfScope: false, JustificationOutOfScope: "", Size: types.Component.String(), Technology: tech, Tags: []string{}, // TODO: let user enter or too detailed for a wizard? Internet: false, Machine: types.Virtual.String(), // TODO: let user enter or too detailed for a wizard? Encryption: types.DataWithSymmetricSharedKey.String(), // can be assumed for a vault product as at least having some good encryption Owner: "", Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Critical.String(), JustificationCiaRating: "Vault components are only rated as 'confidential' as vaults usually apply a trust barrier to encrypt all data-at-rest with a vault key.", MultiTenant: strings.EqualFold(m.macroState["multi-tenant"][0], "yes"), Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: nil, DataAssetsStored: []string{"configuration-secrets"}, DataFormatsAccepted: nil, CommunicationLinks: nil, } *changeLogCollector = append(*changeLogCollector, "adding technical asset: "+storageID) if !dryRun { modelInput.TechnicalAssets["Vault Storage"] = techAsset } } } vaultID := types.MakeID(m.macroState["vault-name"][0]) + "-vault" if _, exists := parsedModel.TechnicalAssets[vaultID]; !exists { serverSideTechAssets = append(serverSideTechAssets, vaultID) commLinks := make(map[string]input.CommunicationLink) if databaseUsed || filesystemUsed { accessLink := input.CommunicationLink{ Target: storageID, Description: "Vault Storage Access", Protocol: types.LocalFileAccess.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"configuration-secrets"}, DataAssetsReceived: []string{"configuration-secrets"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } if databaseUsed { accessLink.Protocol = types.SqlAccessProtocol.String() // TODO ask if encrypted and ask if NoSQL? or to detailed for a wizard? } commLinks["Vault Storage Access"] = accessLink } authentication := types.NoneAuthentication.String() switch m.macroState["authentication-type"][0] { case authenticationTypes[0]: authentication = types.ClientCertificate.String() case authenticationTypes[1]: authentication = types.Externalized.String() case authenticationTypes[2]: authentication = types.Externalized.String() case authenticationTypes[3]: authentication = types.Credentials.String() } for _, clientID := range m.macroState["clients"] { // add a connection from each client clientAccessCommLink := input.CommunicationLink{ Target: vaultID, Description: "Vault Access Traffic (by " + clientID + ")", Protocol: types.HTTPS.String(), Authentication: authentication, Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"configuration-secrets"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } clientAssetTitle := parsedModel.TechnicalAssets[clientID].Title if !dryRun { client := modelInput.TechnicalAssets[clientAssetTitle] client.CommunicationLinks["Vault Access ("+clientID+")"] = clientAccessCommLink modelInput.TechnicalAssets[clientAssetTitle] = client } // don't forget to also add the "configuration-secrets" data asset as processed on the client assetsProcessed := make([]string, 0) if modelInput.TechnicalAssets[clientAssetTitle].DataAssetsProcessed != nil { for _, val := range modelInput.TechnicalAssets[clientAssetTitle].DataAssetsProcessed { assetsProcessed = append(assetsProcessed, fmt.Sprintf("%v", val)) } } mergedArrays := make([]string, 0) for _, val := range assetsProcessed { mergedArrays = append(mergedArrays, fmt.Sprintf("%v", val)) } mergedArrays = append(mergedArrays, "configuration-secrets") if !dryRun { x := modelInput.TechnicalAssets[clientAssetTitle] x.DataAssetsProcessed = mergedArrays modelInput.TechnicalAssets[clientAssetTitle] = x } } techAsset := input.TechnicalAsset{ ID: vaultID, Description: m.macroState["vault-name"][0] + " Vault", Type: types.Process.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: false, OutOfScope: false, JustificationOutOfScope: "", Size: types.Service.String(), Technology: types.Vault, Tags: []string{input.NormalizeTag(m.macroState["vault-name"][0])}, Internet: false, Machine: types.Virtual.String(), Encryption: types.Transparent.String(), Owner: "", Confidentiality: types.StrictlyConfidential.String(), Integrity: types.Critical.String(), Availability: types.Critical.String(), JustificationCiaRating: "Vault components are rated as 'strictly-confidential'.", MultiTenant: strings.EqualFold(m.macroState["multi-tenant"][0], "yes"), Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: []string{"configuration-secrets"}, DataAssetsStored: nil, DataFormatsAccepted: nil, CommunicationLinks: commLinks, } if inMemoryUsed { techAsset.DataAssetsStored = []string{"configuration-secrets"} } *changeLogCollector = append(*changeLogCollector, "adding technical asset (including communication links): "+vaultID) if !dryRun { modelInput.TechnicalAssets[m.macroState["vault-name"][0]+" Vault"] = techAsset } } vaultEnvID := "vault-environment" if filesystemUsed { title := "Vault Environment" trustBoundary := input.TrustBoundary{ ID: vaultEnvID, Description: "Vault Environment", Type: types.ExecutionEnvironment.String(), Tags: []string{}, TechnicalAssetsInside: []string{vaultID, storageID}, TrustBoundariesNested: nil, } *changeLogCollector = append(*changeLogCollector, "adding trust boundary: "+vaultEnvID) if !dryRun { modelInput.TrustBoundaries[title] = trustBoundary } } if m.withinTrustBoundary { if m.createNewTrustBoundary { trustBoundaryType := m.macroState["new-trust-boundary-type"][0] title := "Vault Network" trustBoundary := input.TrustBoundary{ ID: "vault-network", Description: "Vault Network", Type: trustBoundaryType, Tags: []string{}, } if filesystemUsed { trustBoundary.TrustBoundariesNested = []string{vaultEnvID} } else { trustBoundary.TechnicalAssetsInside = serverSideTechAssets } *changeLogCollector = append(*changeLogCollector, "adding trust boundary: vault-network") if !dryRun { modelInput.TrustBoundaries[title] = trustBoundary } } else { // adding to existing trust boundary existingTrustBoundaryToAddTo := m.macroState["selected-trust-boundary"][0] title := parsedModel.TrustBoundaries[existingTrustBoundaryToAddTo].Title if filesystemUsed { // ---------------------- nest as execution-environment trust boundary ---------------------- boundariesNested := make([]string, 0) if modelInput.TrustBoundaries[title].TrustBoundariesNested != nil { values := modelInput.TrustBoundaries[title].TrustBoundariesNested for _, val := range values { boundariesNested = append(boundariesNested, fmt.Sprintf("%v", val)) } } mergedArrays := make([]string, 0) for _, val := range boundariesNested { mergedArrays = append(mergedArrays, fmt.Sprintf("%v", val)) } mergedArrays = append(mergedArrays, vaultEnvID) *changeLogCollector = append(*changeLogCollector, "filling existing trust boundary: "+existingTrustBoundaryToAddTo) if !dryRun { tb := modelInput.TrustBoundaries[title] tb.TrustBoundariesNested = mergedArrays modelInput.TrustBoundaries[title] = tb } } else { // ---------------------- place assets inside directly ---------------------- assetsInside := make([]string, 0) if modelInput.TrustBoundaries[title].TechnicalAssetsInside != nil { values := modelInput.TrustBoundaries[title].TechnicalAssetsInside for _, val := range values { assetsInside = append(assetsInside, fmt.Sprintf("%v", val)) } } mergedArrays := make([]string, 0) for _, val := range assetsInside { mergedArrays = append(mergedArrays, fmt.Sprintf("%v", val)) } mergedArrays = append(mergedArrays, serverSideTechAssets...) *changeLogCollector = append(*changeLogCollector, "filling existing trust boundary: "+existingTrustBoundaryToAddTo) if !dryRun { tb := modelInput.TrustBoundaries[title] tb.TechnicalAssetsInside = mergedArrays modelInput.TrustBoundaries[title] = tb } } } } return "Changeset valid", true, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/add-build-pipeline-macro.go
pkg/macros/add-build-pipeline-macro.go
package macros import ( "fmt" "sort" "strings" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type AddBuildPipeline struct { macroState map[string][]string questionsAnswered []string codeInspectionUsed bool containerTechUsed bool withinTrustBoundary bool createNewTrustBoundary bool } func NewBuildPipeline() *AddBuildPipeline { return &AddBuildPipeline{ macroState: make(map[string][]string), questionsAnswered: make([]string, 0), } } var pushOrPull = []string{ "Push-based Deployment (build pipeline deploys towards target asset)", "Pull-based Deployment (deployment target asset fetches deployment from registry)", } func (m *AddBuildPipeline) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "add-build-pipeline", Title: "Add Build Pipeline", Description: "This model macro adds a build pipeline (development client, build pipeline, artifact registry, container image registry, " + "source code repository, etc.) to the model.", } } // TODO add question for type of machine (either physical, virtual, container, etc.) func (m *AddBuildPipeline) GetNextQuestion(model *types.Model) (nextQuestion MacroQuestion, err error) { counter := len(m.questionsAnswered) if counter > 3 && !m.codeInspectionUsed { counter++ } if counter > 5 && !m.containerTechUsed { counter += 2 } if counter > 12 && !m.withinTrustBoundary { counter++ } if counter > 13 && !m.createNewTrustBoundary { counter++ } switch counter { case 0: return MacroQuestion{ ID: "source-repository", Title: "What product is used as the sourcecode repository?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "Git", }, nil case 1: return MacroQuestion{ ID: "build-pipeline", Title: "What product is used as the build pipeline?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "Jenkins", }, nil case 2: return MacroQuestion{ ID: "artifact-registry", Title: "What product is used as the artifact registry?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "Nexus", }, nil case 3: return MacroQuestion{ ID: "code-inspection-used", Title: "Are code inspection platforms (like SonarQube) used?", Description: "This affects whether code inspection platform are added.", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "Yes", }, nil case 4: return MacroQuestion{ ID: types.CodeInspectionPlatform, Title: "What product is used as the code inspection platform?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "SonarQube", }, nil case 5: return MacroQuestion{ ID: "container-technology-used", Title: "Is container technology (like Docker) used?", Description: "This affects whether container registries are added.", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "Yes", }, nil case 6: return MacroQuestion{ ID: "container-registry", Title: "What product is used as the container registry?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "Docker", }, nil case 7: return MacroQuestion{ ID: "container-platform", Title: "What product is used as the container platform (for orchestration and runtime)?", Description: "This name affects the technical asset's title and ID plus also the tags used.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "Kubernetes", }, nil case 8: return MacroQuestion{ ID: "internet", Title: "Are build pipeline components exposed on the internet?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "No", }, nil case 9: return MacroQuestion{ ID: "multi-tenant", Title: "Are build pipeline components used by multiple tenants?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "No", }, nil case 10: return MacroQuestion{ ID: "encryption", Title: "Are build pipeline components encrypted?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "No", }, nil case 11: possibleAnswers := make([]string, 0) for id := range model.TechnicalAssets { possibleAnswers = append(possibleAnswers, id) } sort.Strings(possibleAnswers) if len(possibleAnswers) > 0 { return MacroQuestion{ ID: "deploy-targets", Title: "Select all technical assets where the build pipeline deploys to:", Description: "This affects the communication links being generated.", PossibleAnswers: possibleAnswers, MultiSelect: true, DefaultAnswer: "", }, nil } case 12: return MacroQuestion{ ID: "within-trust-boundary", Title: "Are the server-side components of the build pipeline components within a network trust boundary?", Description: "", PossibleAnswers: []string{"Yes", "No"}, MultiSelect: false, DefaultAnswer: "Yes", }, nil case 13: possibleAnswers := []string{createNewTrustBoundaryLabel} for id, trustBoundary := range model.TrustBoundaries { if trustBoundary.Type.IsNetworkBoundary() { possibleAnswers = append(possibleAnswers, id) } } sort.Strings(possibleAnswers) return MacroQuestion{ ID: "selected-trust-boundary", Title: "Choose from the list of existing network trust boundaries or create a new one?", Description: "", PossibleAnswers: possibleAnswers, MultiSelect: false, DefaultAnswer: "", }, nil case 14: return MacroQuestion{ ID: "new-trust-boundary-type", Title: "Of which type shall the new trust boundary be?", Description: "", PossibleAnswers: []string{types.NetworkOnPrem.String(), types.NetworkDedicatedHoster.String(), types.NetworkVirtualLAN.String(), types.NetworkCloudProvider.String(), types.NetworkCloudSecurityGroup.String(), types.NetworkPolicyNamespaceIsolation.String()}, MultiSelect: false, DefaultAnswer: types.NetworkOnPrem.String(), }, nil case 15: return MacroQuestion{ ID: "push-or-pull", Title: "What type of deployment strategy is used?", Description: "Push-based deployments are more classic ones and pull-based are more GitOps-like ones.", PossibleAnswers: pushOrPull, MultiSelect: false, DefaultAnswer: "", }, nil case 16: return MacroQuestion{ ID: "owner", Title: "Who is the owner of the build pipeline and runtime assets?", Description: "This name affects the technical asset's and data asset's owner.", PossibleAnswers: nil, MultiSelect: false, DefaultAnswer: "", }, nil } return NoMoreQuestions(), nil } func (m *AddBuildPipeline) ApplyAnswer(questionID string, answer ...string) (message string, validResult bool, err error) { m.macroState[questionID] = answer m.questionsAnswered = append(m.questionsAnswered, questionID) switch questionID { case "code-inspection-used": m.codeInspectionUsed = strings.EqualFold(m.macroState["code-inspection-used"][0], "yes") case "container-technology-used": m.containerTechUsed = strings.EqualFold(m.macroState["container-technology-used"][0], "yes") case "within-trust-boundary": m.withinTrustBoundary = strings.EqualFold(m.macroState["within-trust-boundary"][0], "yes") case "selected-trust-boundary": m.createNewTrustBoundary = strings.EqualFold(m.macroState["selected-trust-boundary"][0], createNewTrustBoundaryLabel) } return "Answer processed", true, nil } func (m *AddBuildPipeline) GoBack() (message string, validResult bool, err error) { if len(m.questionsAnswered) == 0 { return "Cannot go back further", false, nil } lastQuestionID := m.questionsAnswered[len(m.questionsAnswered)-1] m.questionsAnswered = m.questionsAnswered[:len(m.questionsAnswered)-1] delete(m.macroState, lastQuestionID) return "Undo successful", true, nil } func (m *AddBuildPipeline) GetFinalChangeImpact(modelInput *input.Model, model *types.Model) (changes []string, message string, validResult bool, err error) { changeLogCollector := make([]string, 0) message, validResult, err = m.applyChange(modelInput, model, &changeLogCollector, true) return changeLogCollector, message, validResult, err } func (m *AddBuildPipeline) Execute(modelInput *input.Model, model *types.Model) (message string, validResult bool, err error) { changeLogCollector := make([]string, 0) message, validResult, err = m.applyChange(modelInput, model, &changeLogCollector, false) return message, validResult, err } func (m *AddBuildPipeline) applyChange(modelInput *input.Model, parsedModel *types.Model, changeLogCollector *[]string, dryRun bool) (message string, validResult bool, err error) { var serverSideTechAssets = make([]string, 0) // ################################################ modelInput.AddTagToModelInput(m.macroState["source-repository"][0], dryRun, changeLogCollector) modelInput.AddTagToModelInput(m.macroState["build-pipeline"][0], dryRun, changeLogCollector) modelInput.AddTagToModelInput(m.macroState["artifact-registry"][0], dryRun, changeLogCollector) if m.containerTechUsed { modelInput.AddTagToModelInput(m.macroState["container-registry"][0], dryRun, changeLogCollector) modelInput.AddTagToModelInput(m.macroState["container-platform"][0], dryRun, changeLogCollector) } if m.codeInspectionUsed { modelInput.AddTagToModelInput(m.macroState[types.CodeInspectionPlatform][0], dryRun, changeLogCollector) } sourceRepoID := types.MakeID(m.macroState["source-repository"][0]) + "-sourcecode-repository" buildPipelineID := types.MakeID(m.macroState["build-pipeline"][0]) + "-build-pipeline" artifactRegistryID := types.MakeID(m.macroState["artifact-registry"][0]) + "-artifact-registry" containerRepoID, containerPlatformID, containerSharedRuntimeID := "", "", "" if m.containerTechUsed { containerRepoID = types.MakeID(m.macroState["container-registry"][0]) + "-container-registry" containerPlatformID = types.MakeID(m.macroState["container-platform"][0]) + "-container-platform" containerSharedRuntimeID = types.MakeID(m.macroState["container-platform"][0]) + "-container-runtime" } codeInspectionPlatformID := "" if m.codeInspectionUsed { codeInspectionPlatformID = types.MakeID(m.macroState[types.CodeInspectionPlatform][0]) + "-code-inspection-platform" } owner := m.macroState["owner"][0] if _, exists := parsedModel.DataAssets["Sourcecode"]; !exists { //fmt.Println("Adding data asset:", "sourcecode") // ################################################ dataAsset := input.DataAsset{ ID: "sourcecode", Description: "Sourcecode to build the application components from", Usage: types.DevOps.String(), Tags: []string{}, Origin: "", Owner: owner, Quantity: types.Few.String(), Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Important.String(), JustificationCiaRating: "Sourcecode is at least rated as 'critical' in terms of integrity, because any " + "malicious modification of it might lead to a backdoored production system.", } *changeLogCollector = append(*changeLogCollector, "adding data asset: sourcecode") if !dryRun { modelInput.DataAssets["Sourcecode"] = dataAsset } } if _, exists := parsedModel.DataAssets["Deployment"]; !exists { //fmt.Println("Adding data asset:", "deployment") // ################################################ dataAsset := input.DataAsset{ ID: "deployment", Description: "Deployment unit being installed/shipped", Usage: types.DevOps.String(), Tags: []string{}, Origin: "", Owner: owner, Quantity: types.VeryFew.String(), Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Important.String(), JustificationCiaRating: "Deployment units are at least rated as 'critical' in terms of integrity, because any " + "malicious modification of it might lead to a backdoored production system.", } *changeLogCollector = append(*changeLogCollector, "adding data asset: deployment") if !dryRun { modelInput.DataAssets["Deployment"] = dataAsset } } id := "development-client" if _, exists := parsedModel.TechnicalAssets[id]; !exists { //fmt.Println("Adding technical asset:", id) // ################################################ encryption := types.NoneEncryption.String() if strings.EqualFold(m.macroState["encryption"][0], "yes") { encryption = types.Transparent.String() } commLinks := make(map[string]input.CommunicationLink) commLinks["Sourcecode Repository Traffic"] = input.CommunicationLink{ Target: sourceRepoID, Description: "Sourcecode Repository Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"sourcecode"}, DataAssetsReceived: []string{"sourcecode"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } commLinks["Build Pipeline Traffic"] = input.CommunicationLink{ Target: buildPipelineID, Description: "Build Pipeline Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } commLinks["Artifact Registry Traffic"] = input.CommunicationLink{ Target: artifactRegistryID, Description: "Artifact Registry Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } if m.containerTechUsed { commLinks["Container Registry Traffic"] = input.CommunicationLink{ Target: containerRepoID, Description: "Container Registry Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } commLinks["Container Platform Traffic"] = input.CommunicationLink{ Target: containerPlatformID, Description: "Container Platform Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } } if m.codeInspectionUsed { commLinks["Code Inspection Platform Traffic"] = input.CommunicationLink{ Target: codeInspectionPlatformID, Description: "Code Inspection Platform Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.EndUserIdentityPropagation.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"sourcecode"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } } techAsset := input.TechnicalAsset{ ID: id, Description: "Development Client", Type: types.ExternalEntity.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: true, OutOfScope: true, JustificationOutOfScope: "Development client is not directly in-scope of the application.", Size: types.System.String(), Technology: types.DevOpsClient, Tags: []string{}, Internet: strings.EqualFold(m.macroState["internet"][0], "yes"), Machine: types.Physical.String(), Encryption: encryption, Owner: owner, Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Important.String(), JustificationCiaRating: "Sourcecode processing components are at least rated as 'critical' in terms of integrity, because any " + "malicious modification of it might lead to a backdoored production system.", MultiTenant: false, Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: []string{"sourcecode", "deployment"}, DataAssetsStored: []string{"sourcecode", "deployment"}, DataFormatsAccepted: []string{"file"}, CommunicationLinks: commLinks, } *changeLogCollector = append(*changeLogCollector, "adding technical asset (including communication links): "+id) if !dryRun { modelInput.TechnicalAssets["Development Client"] = techAsset } } id = sourceRepoID if _, exists := parsedModel.TechnicalAssets[id]; !exists { //fmt.Println("Adding technical asset:", id) // ################################################ serverSideTechAssets = append(serverSideTechAssets, id) encryption := types.NoneEncryption.String() if strings.EqualFold(m.macroState["encryption"][0], "yes") { encryption = types.Transparent.String() } techAsset := input.TechnicalAsset{ ID: id, Description: m.macroState["source-repository"][0] + " Sourcecode Repository", Type: types.Process.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: false, OutOfScope: false, JustificationOutOfScope: "", Size: types.Service.String(), Technology: types.SourcecodeRepository, Tags: []string{input.NormalizeTag(m.macroState["source-repository"][0])}, Internet: strings.EqualFold(m.macroState["internet"][0], "yes"), Machine: types.Virtual.String(), Encryption: encryption, Owner: owner, Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Important.String(), JustificationCiaRating: "Sourcecode processing components are at least rated as 'critical' in terms of integrity, because any " + "malicious modification of it might lead to a backdoored production system.", MultiTenant: strings.EqualFold(m.macroState["multi-tenant"][0], "yes"), Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: []string{"sourcecode"}, DataAssetsStored: []string{"sourcecode"}, DataFormatsAccepted: []string{"file"}, CommunicationLinks: nil, } *changeLogCollector = append(*changeLogCollector, "adding technical asset (including communication links): "+id) if !dryRun { modelInput.TechnicalAssets[m.macroState["source-repository"][0]+" Sourcecode Repository"] = techAsset } } if m.containerTechUsed { id = containerRepoID if _, exists := parsedModel.TechnicalAssets[id]; !exists { //fmt.Println("Adding technical asset:", id) // ################################################ serverSideTechAssets = append(serverSideTechAssets, id) encryption := types.NoneEncryption.String() if strings.EqualFold(m.macroState["encryption"][0], "yes") { encryption = types.Transparent.String() } techAsset := input.TechnicalAsset{ ID: id, Description: m.macroState["container-registry"][0] + " Container Registry", Type: types.Process.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: false, OutOfScope: false, JustificationOutOfScope: "", Size: types.Service.String(), Technology: types.ArtifactRegistry, Tags: []string{input.NormalizeTag(m.macroState["container-registry"][0])}, Internet: strings.EqualFold(m.macroState["internet"][0], "yes"), Machine: types.Virtual.String(), Encryption: encryption, Owner: owner, Confidentiality: types.Confidential.String(), Integrity: types.Critical.String(), Availability: types.Important.String(), JustificationCiaRating: "Container registry components are at least rated as 'critical' in terms of integrity, because any " + "malicious modification of it might lead to a backdoored production system.", MultiTenant: strings.EqualFold(m.macroState["multi-tenant"][0], "yes"), Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: []string{"deployment"}, DataAssetsStored: []string{"deployment"}, DataFormatsAccepted: []string{"file"}, CommunicationLinks: nil, } *changeLogCollector = append(*changeLogCollector, "adding technical asset (including communication links): "+id) if !dryRun { modelInput.TechnicalAssets[m.macroState["container-registry"][0]+" Container Registry"] = techAsset } } id = containerPlatformID if _, exists := parsedModel.TechnicalAssets[id]; !exists { //fmt.Println("Adding technical asset:", id) // ################################################ serverSideTechAssets = append(serverSideTechAssets, id) encryption := types.NoneEncryption.String() if strings.EqualFold(m.macroState["encryption"][0], "yes") { encryption = types.Transparent.String() } techAsset := input.TechnicalAsset{ ID: id, Description: m.macroState["container-platform"][0] + " Container Platform", Type: types.Process.String(), Usage: types.DevOps.String(), UsedAsClientByHuman: false, OutOfScope: false, JustificationOutOfScope: "", Size: types.System.String(), Technology: types.ContainerPlatform, Tags: []string{input.NormalizeTag(m.macroState["container-platform"][0])}, Internet: strings.EqualFold(m.macroState["internet"][0], "yes"), Machine: types.Virtual.String(), Encryption: encryption, Owner: owner, Confidentiality: types.Confidential.String(), Integrity: types.MissionCritical.String(), Availability: types.MissionCritical.String(), JustificationCiaRating: "Container platform components are rated as 'mission-critical' in terms of integrity and availability, because any " + "malicious modification of it might lead to a backdoored production system.", MultiTenant: strings.EqualFold(m.macroState["multi-tenant"][0], "yes"), Redundant: false, CustomDevelopedParts: false, DataAssetsProcessed: []string{"deployment"}, DataAssetsStored: []string{"deployment"}, DataFormatsAccepted: []string{"file"}, CommunicationLinks: nil, } *changeLogCollector = append(*changeLogCollector, "adding technical asset (including communication links): "+id) if !dryRun { modelInput.TechnicalAssets[m.macroState["container-platform"][0]+" Container Platform"] = techAsset } } } id = buildPipelineID if _, exists := parsedModel.TechnicalAssets[id]; !exists { //fmt.Println("Adding technical asset:", id) // ################################################ serverSideTechAssets = append(serverSideTechAssets, id) encryption := types.NoneEncryption.String() if strings.EqualFold(m.macroState["encryption"][0], "yes") { encryption = types.Transparent.String() } commLinks := make(map[string]input.CommunicationLink) commLinks["Sourcecode Repository Traffic"] = input.CommunicationLink{ Target: sourceRepoID, Description: "Sourcecode Repository Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"sourcecode"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } commLinks["Artifact Registry Traffic"] = input.CommunicationLink{ Target: artifactRegistryID, Description: "Artifact Registry Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } if m.containerTechUsed { commLinks["Container Registry Traffic"] = input.CommunicationLink{ Target: containerRepoID, Description: "Container Registry Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } if m.macroState["push-or-pull"][0] == pushOrPull[0] { // Push commLinks["Container Platform Push"] = input.CommunicationLink{ Target: containerPlatformID, Description: "Container Platform Push", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } } else { // Pull commLinkPull := input.CommunicationLink{ Target: containerRepoID, Description: "Container Platform Pull", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: true, Usage: types.DevOps.String(), DataAssetsSent: nil, DataAssetsReceived: []string{"deployment"}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } if !dryRun { titleOfTargetAsset := m.macroState["container-platform"][0] + " Container Platform" containerPlatform := modelInput.TechnicalAssets[titleOfTargetAsset] if containerPlatform.CommunicationLinks == nil { containerPlatform.CommunicationLinks = make(map[string]input.CommunicationLink) } containerPlatform.CommunicationLinks["Container Platform Pull"] = commLinkPull modelInput.TechnicalAssets[titleOfTargetAsset] = containerPlatform } } } if m.codeInspectionUsed { commLinks["Code Inspection Platform Traffic"] = input.CommunicationLink{ Target: codeInspectionPlatformID, Description: "Code Inspection Platform Traffic", Protocol: types.HTTPS.String(), Authentication: types.Credentials.String(), Authorization: types.TechnicalUser.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"sourcecode"}, DataAssetsReceived: []string{}, DiagramTweakWeight: 0, DiagramTweakConstraint: false, } } // The individual deployments for _, deployTargetID := range m.macroState["deploy-targets"] { // add a connection to each deployment target //fmt.Println("Adding deployment flow to:", deployTargetID) if m.containerTechUsed { if !dryRun { containerPlatform := modelInput.TechnicalAssets[m.macroState["container-platform"][0]+" Container Platform"] if containerPlatform.CommunicationLinks == nil { containerPlatform.CommunicationLinks = make(map[string]input.CommunicationLink) } containerPlatform.CommunicationLinks["Container Spawning ("+deployTargetID+")"] = input.CommunicationLink{ Target: deployTargetID, Description: "Container Spawning " + deployTargetID, Protocol: types.ContainerSpawning.String(), Authentication: types.NoneAuthentication.String(), Authorization: types.NoneAuthorization.String(), Tags: []string{}, VPN: false, IpFiltered: false, Readonly: false, Usage: types.DevOps.String(), DataAssetsSent: []string{"deployment"}, DataAssetsReceived: nil, DiagramTweakWeight: 0, DiagramTweakConstraint: false,
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/remove-unused-tags-macro.go
pkg/macros/remove-unused-tags-macro.go
package macros import ( "sort" "strconv" "github.com/mpvl/unique" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type removeUnusedTagsMacro struct { } func newRemoveUnusedTags() *removeUnusedTagsMacro { return &removeUnusedTagsMacro{} } func (*removeUnusedTagsMacro) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "remove-unused-tags", Title: "Remove Unused Tags", Description: "This model macro simply removes all unused tags from the model file.", } } func (*removeUnusedTagsMacro) GetNextQuestion(*types.Model) (nextQuestion MacroQuestion, err error) { return NoMoreQuestions(), nil } func (*removeUnusedTagsMacro) ApplyAnswer(_ string, _ ...string) (message string, validResult bool, err error) { return "Answer processed", true, nil } func (*removeUnusedTagsMacro) GoBack() (message string, validResult bool, err error) { return "Cannot go back further", false, nil } func (*removeUnusedTagsMacro) GetFinalChangeImpact(_ *input.Model, _ *types.Model) (changes []string, message string, validResult bool, err error) { return []string{"remove unused tags from the model file"}, "Changeset valid", true, err } func (*removeUnusedTagsMacro) Execute(modelInput *input.Model, parsedModel *types.Model) (message string, validResult bool, err error) { modelInput.TagsAvailable = parsedModel.TagsAvailable for _, asset := range parsedModel.DataAssets { modelInput.TagsAvailable = append(modelInput.TagsAvailable, asset.Tags...) } for _, asset := range parsedModel.TechnicalAssets { modelInput.TagsAvailable = append(modelInput.TagsAvailable, asset.Tags...) for _, link := range asset.CommunicationLinks { modelInput.TagsAvailable = append(modelInput.TagsAvailable, link.Tags...) } } for _, boundary := range parsedModel.TrustBoundaries { modelInput.TagsAvailable = append(modelInput.TagsAvailable, boundary.Tags...) } for _, runtime := range parsedModel.SharedRuntimes { modelInput.TagsAvailable = append(modelInput.TagsAvailable, runtime.Tags...) } count := len(modelInput.TagsAvailable) unique.Strings(&modelInput.TagsAvailable) sort.Strings(modelInput.TagsAvailable) return "Model file removal of " + strconv.Itoa(count-len(modelInput.TagsAvailable)) + " unused tags successful", true, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/macros/seed-risk-tracking-macro.go
pkg/macros/seed-risk-tracking-macro.go
package macros import ( "sort" "strconv" "github.com/threagile/threagile/pkg/input" "github.com/threagile/threagile/pkg/types" ) type SeedRiskTrackingMacro struct { } func NewSeedRiskTracking() *SeedRiskTrackingMacro { return &SeedRiskTrackingMacro{} } func (*SeedRiskTrackingMacro) GetMacroDetails() MacroDetails { return MacroDetails{ ID: "seed-risk-tracking", Title: "Seed Risk Tracking", Description: "This model macro simply seeds the model file with initial risk tracking entries for all untracked risks.", } } func (*SeedRiskTrackingMacro) GetNextQuestion(*types.Model) (nextQuestion MacroQuestion, err error) { return NoMoreQuestions(), nil } func (*SeedRiskTrackingMacro) ApplyAnswer(_ string, _ ...string) (message string, validResult bool, err error) { return "Answer processed", true, nil } func (*SeedRiskTrackingMacro) GoBack() (message string, validResult bool, err error) { return "Cannot go back further", false, nil } func (*SeedRiskTrackingMacro) GetFinalChangeImpact(_ *input.Model, _ *types.Model) (changes []string, message string, validResult bool, err error) { return []string{"seed the model file with with initial risk tracking entries for all untracked risks"}, "Changeset valid", true, err } func (*SeedRiskTrackingMacro) Execute(modelInput *input.Model, parsedModel *types.Model) (message string, validResult bool, err error) { syntheticRiskIDsToCreateTrackingFor := make([]string, 0) for id, risk := range parsedModel.GeneratedRisksBySyntheticId { if !parsedModel.IsRiskTracked(risk) { syntheticRiskIDsToCreateTrackingFor = append(syntheticRiskIDsToCreateTrackingFor, id) } } sort.Strings(syntheticRiskIDsToCreateTrackingFor) if modelInput.RiskTracking == nil { modelInput.RiskTracking = make(map[string]input.RiskTracking) } for _, id := range syntheticRiskIDsToCreateTrackingFor { modelInput.RiskTracking[id] = input.RiskTracking{ Status: types.Unchecked.String(), Justification: "", Ticket: "", Date: "", CheckedBy: "", } } return "Model file seeding with " + strconv.Itoa(len(syntheticRiskIDsToCreateTrackingFor)) + " initial risk tracking successful", true, nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/helpers.go
pkg/types/helpers.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "regexp" "strings" ) func MakeID(val string) string { reg, _ := regexp.Compile("[^A-Za-z0-9]+") return strings.Trim(reg.ReplaceAllString(strings.ToLower(val), "-"), "- ") } func contains(a []string, x string) bool { for _, n := range a { if x == n { return true } } return false } func containsCaseInsensitiveAny(a []string, x ...string) bool { for _, n := range a { for _, c := range x { if strings.TrimSpace(strings.ToLower(c)) == strings.TrimSpace(strings.ToLower(n)) { return true } } } return false } type byDataAssetTitleSort []*DataAsset func (what byDataAssetTitleSort) Len() int { return len(what) } func (what byDataAssetTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what byDataAssetTitleSort) Less(i, j int) bool { return what[i].Title < what[j].Title }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/protocol_test.go
pkg/types/protocol_test.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type ParseProtocolTest struct { input string expected Protocol expectedError error } func TestParseProtocol(t *testing.T) { testCases := map[string]ParseProtocolTest{ "unknown-protocol": { input: "unknown-protocol", expected: UnknownProtocol, }, "http": { input: "http", expected: HTTP, }, "https": { input: "https", expected: HTTPS, }, "ws": { input: "ws", expected: WS, }, "wss": { input: "wss", expected: WSS, }, "reverse-proxy-web-protocol": { input: "reverse-proxy-web-protocol", expected: ReverseProxyWebProtocol, }, "reverse-proxy-web-protocol-encrypted": { input: "reverse-proxy-web-protocol-encrypted", expected: ReverseProxyWebProtocolEncrypted, }, "mqtt": { input: "mqtt", expected: MQTT, }, "jdbc": { input: "jdbc", expected: JDBC, }, "jdbc-encrypted": { input: "jdbc-encrypted", expected: JdbcEncrypted, }, "odbc": { input: "odbc", expected: ODBC, }, "odbc-encrypted": { input: "odbc-encrypted", expected: OdbcEncrypted, }, "sql-access-protocol": { input: "sql-access-protocol", expected: SqlAccessProtocol, }, "sql-access-protocol-encrypted": { input: "sql-access-protocol-encrypted", expected: SqlAccessProtocolEncrypted, }, "nosql-access-protocol": { input: "nosql-access-protocol", expected: NosqlAccessProtocol, }, "nosql-access-protocol-encrypted": { input: "nosql-access-protocol-encrypted", expected: NosqlAccessProtocolEncrypted, }, "binary": { input: "binary", expected: BINARY, }, "binary-encrypted": { input: "binary-encrypted", expected: BinaryEncrypted, }, "text": { input: "text", expected: TEXT, }, "text-encrypted": { input: "text-encrypted", expected: TextEncrypted, }, "ssh": { input: "ssh", expected: SSH, }, "ssh-tunnel": { input: "ssh-tunnel", expected: SshTunnel, }, "smtp": { input: "smtp", expected: SMTP, }, "smtp-encrypted": { input: "smtp-encrypted", expected: SmtpEncrypted, }, "pop3": { input: "pop3", expected: POP3, }, "pop3-encrypted": { input: "pop3-encrypted", expected: Pop3Encrypted, }, "imap": { input: "imap", expected: IMAP, }, "imap-encrypted": { input: "imap-encrypted", expected: ImapEncrypted, }, "ftp": { input: "ftp", expected: FTP, }, "ftps": { input: "ftps", expected: FTPS, }, "sftp": { input: "sftp", expected: SFTP, }, "scp": { input: "scp", expected: SCP, }, "ldap": { input: "ldap", expected: LDAP, }, "ldaps": { input: "ldaps", expected: LDAPS, }, "jms": { input: "jms", expected: JMS, }, "nfs": { input: "nfs", expected: NFS, }, "smb": { input: "smb", expected: SMB, }, "smb-encrypted": { input: "smb-encrypted", expected: SmbEncrypted, }, "local-file-access": { input: "local-file-access", expected: LocalFileAccess, }, "nrpe": { input: "nrpe", expected: NRPE, }, "xmpp": { input: "xmpp", expected: XMPP, }, "iiop": { input: "iiop", expected: IIOP, }, "iiop-encrypted": { input: "iiop-encrypted", expected: IiopEncrypted, }, "jrmp": { input: "jrmp", expected: JRMP, }, "jrmp-encrypted": { input: "jrmp-encrypted", expected: JrmpEncrypted, }, "in-process-library-call": { input: "in-process-library-call", expected: InProcessLibraryCall, }, "inter-process-communication": { input: "inter-process-communication", expected: InterProcessCommunication, }, "container-spawning": { input: "container-spawning", expected: ContainerSpawning, }, "unknown": { input: "unknown", expectedError: fmt.Errorf("unable to parse into type: unknown"), }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { actual, err := ParseProtocol(testCase.input) assert.Equal(t, testCase.expected, actual) assert.Equal(t, testCase.expectedError, err) }) } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/types/risks.go
pkg/types/risks.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package types import "sort" func ReduceToOnlyStillAtRisk(risks []*Risk) []*Risk { filteredRisks := make([]*Risk, 0) for _, risk := range risks { if risk.RiskStatus.IsStillAtRisk() { filteredRisks = append(filteredRisks, risk) } } return filteredRisks } func HighestSeverityStillAtRisk(risks []*Risk) RiskSeverity { result := LowSeverity for _, risk := range risks { if risk.Severity > result && risk.RiskStatus.IsStillAtRisk() { result = risk.Severity } } return result } func SortByRiskSeverity(risks []*Risk) { sort.Slice(risks, func(i, j int) bool { if risks[i].Severity == risks[j].Severity { trackingStatusLeft := risks[i].RiskStatus trackingStatusRight := risks[j].RiskStatus if trackingStatusLeft == trackingStatusRight { impactLeft := risks[i].ExploitationImpact impactRight := risks[j].ExploitationImpact if impactLeft == impactRight { likelihoodLeft := risks[i].ExploitationLikelihood likelihoodRight := risks[j].ExploitationLikelihood if likelihoodLeft == likelihoodRight { return risks[i].Title < risks[j].Title } else { return likelihoodLeft > likelihoodRight } } else { return impactLeft > impactRight } } else { return trackingStatusLeft < trackingStatusRight } } return risks[i].Severity > risks[j].Severity }) } type ByRiskCategoryTitleSort []*RiskCategory func (what ByRiskCategoryTitleSort) Len() int { return len(what) } func (what ByRiskCategoryTitleSort) Swap(i, j int) { what[i], what[j] = what[j], what[i] } func (what ByRiskCategoryTitleSort) Less(i, j int) bool { return what[i].Title < what[j].Title }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false