Skip to content

Commit

Permalink
refactored to prepare for script integration
Browse files Browse the repository at this point in the history
  • Loading branch information
joreiche committed Apr 11, 2024
1 parent a98f0d6 commit cfaacff
Show file tree
Hide file tree
Showing 109 changed files with 2,090 additions and 1,283 deletions.
12 changes: 6 additions & 6 deletions cmd/raa/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func main() {

// _ = os.WriteFile("raa_in.json", data, 0644)

var input types.ParsedModel
var input types.Model
parseError := json.Unmarshal(data, &input)
if parseError != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to parse model: %v\n", parseError)
Expand Down Expand Up @@ -75,7 +75,7 @@ func closeFile(file io.Closer) {
_ = file.Close()
}

func CalculateRAA(input *types.ParsedModel) string {
func CalculateRAA(input *types.Model) string {
for techAssetID, techAsset := range input.TechnicalAssets {
aa := calculateAttackerAttractiveness(input, techAsset)
aa += calculatePivotingNeighbourEffectAdjustment(input, techAsset)
Expand All @@ -95,7 +95,7 @@ func CalculateRAA(input *types.ParsedModel) string {
var attackerAttractivenessMinimum, attackerAttractivenessMaximum, spread float64 = 0, 0, 0

// set the concrete value in relation to the minimum and maximum of all
func calculateRelativeAttackerAttractiveness(input *types.ParsedModel, attractiveness float64) float64 {
func calculateRelativeAttackerAttractiveness(input *types.Model, attractiveness float64) float64 {
if attackerAttractivenessMinimum == 0 || attackerAttractivenessMaximum == 0 {
attackerAttractivenessMinimum, attackerAttractivenessMaximum = 9223372036854775807, -9223372036854775808
// determine (only one time required) the min/max of all
Expand Down Expand Up @@ -130,7 +130,7 @@ func calculateRelativeAttackerAttractiveness(input *types.ParsedModel, attractiv
}

// increase the RAA (relative attacker attractiveness) by one third (1/3) of the delta to the highest outgoing neighbour (if positive delta)
func calculatePivotingNeighbourEffectAdjustment(input *types.ParsedModel, techAsset *types.TechnicalAsset) float64 {
func calculatePivotingNeighbourEffectAdjustment(input *types.Model, techAsset *types.TechnicalAsset) float64 {
if techAsset.OutOfScope {
return 0
}
Expand All @@ -141,7 +141,7 @@ func calculatePivotingNeighbourEffectAdjustment(input *types.ParsedModel, techAs
delta := calculateRelativeAttackerAttractiveness(input, calculateAttackerAttractiveness(input, outgoingNeighbour)) - calculateRelativeAttackerAttractiveness(input, calculateAttackerAttractiveness(input, techAsset))
if delta > 0 {
potentialIncrease := delta / 3
//fmt.Println("Positive delta from", techAsset.Id, "to", outgoingNeighbour.Id, "is", delta, "yields to pivoting neighbour effect of an increase of", potentialIncrease)
//fmt.Println("Positive delta from", techAsset.ID, "to", outgoingNeighbour.ID, "is", delta, "yields to pivoting neighbour effect of an increase of", potentialIncrease)
if potentialIncrease > adjustment {
adjustment = potentialIncrease
}
Expand All @@ -153,7 +153,7 @@ func calculatePivotingNeighbourEffectAdjustment(input *types.ParsedModel, techAs

// The sum of all CIAs of the asset itself (fibonacci scale) plus the sum of the comm-links' transferred CIAs
// Multiplied by the quantity values of the data asset for C and I (not A)
func calculateAttackerAttractiveness(input *types.ParsedModel, techAsset *types.TechnicalAsset) float64 {
func calculateAttackerAttractiveness(input *types.Model, techAsset *types.TechnicalAsset) float64 {
if techAsset.OutOfScope {
return 0
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/raa_dummy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {
os.Exit(-2)
}

var input types.ParsedModel
var input types.Model
inError := json.Unmarshal(inData, &input)
if inError != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to parse model: %v\n", inError)
Expand All @@ -44,7 +44,7 @@ func main() {

// used from run caller:

func CalculateRAA(input *types.ParsedModel) string {
func CalculateRAA(input *types.Model) string {
for techAssetID, techAsset := range input.TechnicalAssets {
nBig, randError := rand.Int(rand.Reader, big.NewInt(100))
if randError != nil {
Expand Down
18 changes: 8 additions & 10 deletions cmd/risk_demo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,14 @@ type customRiskRule string

// exported as symbol (here simply as variable to interface to bundle many functions under one symbol) named "RiskRule"

var CustomRiskRule customRiskRule

func main() {
getInfo := flag.Bool("get-info", false, "get rule info")
generateRisks := flag.Bool("generate-risks", false, "generate risks")
flag.Parse()

if *getInfo {
rule := new(customRiskRule)
category := rule.Category()
riskData, marshalError := json.Marshal(new(model.CustomRisk).Init(category.Id, category, rule.SupportedTags()))
riskData, marshalError := json.Marshal(new(model.CustomRiskCategory).Init(rule.Category(), rule.SupportedTags()))

if marshalError != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to print risk data: %v", marshalError)
Expand All @@ -45,7 +42,7 @@ func main() {
os.Exit(-2)
}

var input types.ParsedModel
var input types.Model
inError := json.Unmarshal(inData, &input)
if inError != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to parse model: %v\n", inError)
Expand All @@ -67,9 +64,9 @@ func main() {
os.Exit(-2)
}

func (r customRiskRule) Category() types.RiskCategory {
return types.RiskCategory{
Id: "demo",
func (r customRiskRule) Category() *types.RiskCategory {
return &types.RiskCategory{
ID: "demo",
Title: "Just a Demo",
Description: "Demo Description",
Impact: "Demo Impact",
Expand All @@ -92,7 +89,7 @@ func (r customRiskRule) SupportedTags() []string {
return []string{"demo tag"}
}

func (r customRiskRule) GenerateRisks(parsedModel *types.ParsedModel) []types.Risk {
func (r customRiskRule) GenerateRisks(parsedModel *types.Model) []types.Risk {
generatedRisks := make([]types.Risk, 0)
for _, techAsset := range parsedModel.TechnicalAssets {
generatedRisks = append(generatedRisks, createRisk(techAsset))
Expand All @@ -101,8 +98,9 @@ func (r customRiskRule) GenerateRisks(parsedModel *types.ParsedModel) []types.Ri
}

func createRisk(technicalAsset *types.TechnicalAsset) types.Risk {
category := new(customRiskRule).Category()
risk := types.Risk{
CategoryId: CustomRiskRule.Category().Id,
CategoryId: category.ID,
Severity: types.CalculateSeverity(types.VeryLikely, types.MediumImpact),
ExploitationLikelihood: types.VeryLikely,
ExploitationImpact: types.MediumImpact,
Expand Down
90 changes: 55 additions & 35 deletions cmd/script/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@ package main

import (
"fmt"
"github.com/threagile/threagile/pkg/common"
"github.com/threagile/threagile/pkg/input"
"github.com/threagile/threagile/pkg/model"
"github.com/threagile/threagile/pkg/script"
"github.com/threagile/threagile/pkg/script/common"
"github.com/threagile/threagile/pkg/security/types"
"github.com/threagile/threagile/pkg/security/risks"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
)

func main() {
riskData, riskReadError := os.ReadFile(filepath.Join("test", "risk-category.yaml"))
if riskReadError != nil {
fmt.Printf("error reading risk category: %v\n", riskReadError)
ruleData, ruleReadError := os.ReadFile(filepath.Join("test", "risk-category.yaml"))
if ruleReadError != nil {
fmt.Printf("error reading risk category: %v\n", ruleReadError)
return
}

scripts, parseError := new(script.Script).Parse(riskData)
scripts, parseError := new(script.Script).ParseScripts(ruleData)
if parseError != nil {
fmt.Printf("error parsing scripts: %v\n", parseError)
return
Expand All @@ -29,52 +31,70 @@ func main() {
return
}

model := new(types.ParsedModel)
modelUnmarshalError := yaml.Unmarshal(modelData, model)
inputModel := new(input.Model)
modelUnmarshalError := yaml.Unmarshal(modelData, inputModel)
if modelUnmarshalError != nil {
fmt.Printf("error parsing model: %v\n", modelUnmarshalError)
return
}

categoriesModel := new(types.ParsedModel)
riskUnmarshalError := yaml.Unmarshal(riskData, categoriesModel)
if riskUnmarshalError != nil {
fmt.Printf("error parsing risk category: %v\n", riskUnmarshalError)
/*
categoriesModel := new(input.Model)
riskUnmarshalError := yaml.Unmarshal(riskData, categoriesModel)
if riskUnmarshalError != nil {
fmt.Printf("error parsing risk category: %v\n", riskUnmarshalError)
return
}
*/

parsedModel, modelError := model.ParseModel(&common.Config{}, inputModel, make(risks.RiskRules), make(risks.RiskRules))
if modelError != nil {
fmt.Printf("error importing model: %v\n", modelError)
return
}

var risk types.RiskCategory
if categoriesModel.IndividualRiskCategories != nil {
for _, item := range categoriesModel.IndividualRiskCategories {
risk = item
_ = parsedModel
_ = scripts
/*
var risk types.RiskCategory
if categoriesModel.CustomRiskCategories != nil {
for _, item := range categoriesModel.CustomRiskCategories {
risk = item
}
}
}
for name, script := range scripts {
scope := new(common.Scope)
addError := scope.Init(model, &risk, script.Utils())
if addError != nil {
fmt.Printf("error adding model to scope for %q: %v\n", name, addError)
if len(categoriesModel.CustomRiskCategories) == 0 {
fmt.Printf("no risk categories\n")
return
}
risks, errorLiteral, riskError := script.GenerateRisks(scope)
if riskError != nil {
fmt.Printf("error generating risks for %q: %v\n", name, riskError)
for name, script := range scripts {
scope := new(script.Scope)
addError := scope.Init(parsedModel, &risk, script.Utils())
if addError != nil {
fmt.Printf("error adding model to scope for %q: %v\n", name, addError)
return
}
risks, errorLiteral, riskError := script.GenerateRisks(scope)
if riskError != nil {
fmt.Printf("error generating risks for %q: %v\n", name, riskError)
if len(errorLiteral) > 0 {
fmt.Printf("in:\n%v\n", script.IndentPrintf(1, errorLiteral))
if len(errorLiteral) > 0 {
fmt.Printf("in:\n%v\n", script.IndentPrintf(1, errorLiteral))
}
return
}
return
}
printedRisks, printError := yaml.Marshal(risks)
if printError != nil {
fmt.Printf("error printing risks for %q: %v\n", name, printError)
return
}
printedRisks, printError := yaml.Marshal(risks)
if printError != nil {
fmt.Printf("error printing risks for %q: %v\n", name, printError)
return
fmt.Printf("generated risks for %q: \n%v\n", name, string(printedRisks))
}
fmt.Printf("generated risks for %q: \n%v\n", name, string(printedRisks))
}
*/
}
4 changes: 2 additions & 2 deletions internal/threagile/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,15 @@ func (what *Threagile) explainRules(cmd *cobra.Command, _ []string) error {
cmd.Println("----------------------")
customRiskRules := model.LoadCustomRiskRules(strings.Split(what.flags.customRiskRulesPluginFlag, ","), common.DefaultProgressReporter{Verbose: what.flags.verboseFlag})
for _, rule := range customRiskRules {
cmd.Printf("%v: %v\n", rule.Category().Id, rule.Category().Description)
cmd.Printf("%v: %v\n", rule.Category().ID, rule.Category().Description)
}
cmd.Println()
cmd.Println("--------------------")
cmd.Println("Built-in risk rules:")
cmd.Println("--------------------")
cmd.Println()
for _, rule := range risks.GetBuiltInRiskRules() {
cmd.Printf("%v: %v\n", rule.Category().Id, rule.Category().Description)
cmd.Printf("%v: %v\n", rule.Category().ID, rule.Category().Description)
}
cmd.Println()

Expand Down
2 changes: 1 addition & 1 deletion internal/threagile/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (what *Threagile) initList() *Threagile {
cmd.Println("--------------------")
cmd.Println()
for _, rule := range risks.GetBuiltInRiskRules() {
cmd.Println(rule.Category().Id, "-->", rule.Category().Title, "--> with tags:", rule.SupportedTags())
cmd.Println(rule.Category().ID, "-->", rule.Category().Title, "--> with tags:", rule.SupportedTags())
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions internal/threagile/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (what *Threagile) initRoot() *Threagile {

what.rootCmd.PersistentFlags().StringVar(&what.flags.customRiskRulesPluginFlag, customRiskRulesPluginFlagName, strings.Join(defaultConfig.RiskRulesPlugins, ","), "comma-separated list of plugins file names with custom risk rules to load")
what.rootCmd.PersistentFlags().IntVar(&what.flags.diagramDpiFlag, diagramDpiFlagName, defaultConfig.DiagramDPI, "DPI used to render: maximum is "+fmt.Sprintf("%d", common.MaxGraphvizDPI)+"")
what.rootCmd.PersistentFlags().StringVar(&what.flags.skipRiskRulesFlag, skipRiskRulesFlagName, defaultConfig.SkipRiskRules, "comma-separated list of risk rules (by their ID) to skip")
what.rootCmd.PersistentFlags().StringVar(&what.flags.skipRiskRulesFlag, skipRiskRulesFlagName, strings.Join(defaultConfig.SkipRiskRules, ","), "comma-separated list of risk rules (by their ID) to skip")
what.rootCmd.PersistentFlags().BoolVar(&what.flags.ignoreOrphanedRiskTrackingFlag, ignoreOrphanedRiskTrackingFlagName, defaultConfig.IgnoreOrphanedRiskTracking, "ignore orphaned risk tracking (just log them) not matching a concrete risk")
what.rootCmd.PersistentFlags().StringVar(&what.flags.templateFileNameFlag, templateFileNameFlagName, defaultConfig.TemplateFilename, "background pdf file")

Expand Down Expand Up @@ -264,7 +264,7 @@ func (what *Threagile) readConfig(cmd *cobra.Command, buildTimestamp string) *co
cfg.RiskRulesPlugins = strings.Split(what.flags.customRiskRulesPluginFlag, ",")
}
if isFlagOverridden(flags, skipRiskRulesFlagName) {
cfg.SkipRiskRules = what.flags.skipRiskRulesFlag
cfg.SkipRiskRules = strings.Split(what.flags.skipRiskRulesFlag, ",")
}
if isFlagOverridden(flags, ignoreOrphanedRiskTrackingFlagName) {
cfg.IgnoreOrphanedRiskTracking = what.flags.ignoreOrphanedRiskTrackingFlag
Expand Down
4 changes: 2 additions & 2 deletions pkg/common/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type Config struct {

RAAPlugin string
RiskRulesPlugins []string
SkipRiskRules string
SkipRiskRules []string
ExecuteModelMacro string
RiskExcel RiskExcelConfig

Expand Down Expand Up @@ -92,7 +92,7 @@ func (c *Config) Defaults(buildTimestamp string) *Config {

RAAPlugin: RAAPluginName,
RiskRulesPlugins: make([]string, 0),
SkipRiskRules: "",
SkipRiskRules: make([]string, 0),
ExecuteModelMacro: "",
RiskExcel: RiskExcelConfig{
HideColumns: make([]string, 0),
Expand Down
Loading

0 comments on commit cfaacff

Please sign in to comment.