{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: .goreleaser.yaml\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\nversion: 2\nproject_name: amass\n\nbefore:\n hooks:\n - go mod tidy\n\nbuilds:\n -\n main: ./cmd/amass\n binary: amass\n env:\n - CGO_ENABLED=0\n goos:\n - windows\n - linux\n - darwin\n goarch:\n - amd64\n - 386\n - arm\n - arm64\n goarm:\n - 6\n - 7\n ignore:\n - goos: darwin\n goarch: 386\n - goos: darwin\n goarch: arm\n - goos: windows\n goarch: 386\n - goos: windows\n goarch: arm\n - goos: windows\n goarch: arm64\n\narchives:\n -\n name_template: \"{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}\"\n wrap_in_directory: true\n files:\n - LICENSE\n - README.md\n - resources/config.yaml\n - resources/datasources.yaml\n\nchecksum:\n name_template: \"{{ .ProjectName }}_checksums.txt\"\n\nchangelog:\n sort: desc\n filters:\n exclude:\n - '^MERGE'\n - \"{{ .Tag }}\"\n\nrelease:\n github:\n owner: owasp-amass\n name: amass\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: CONTRIBUTING.md\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n# Contributing\n\nThank you for considering making contributions to the OWASP Amass Project! Start by joining our [Discord server](https://discord.gg/ANTyEDUXt5), taking a look at the [Documentation](https://owasp-amass.github.io/docs/), and checking out the [open issues](https://github.com/owasp-amass/amass/issues) for things we need help with!\n\nPlease follow standard github best practices: fork the repo, branch from the tip of develop, make some commits, and submit a pull request to develop. \n\nPlease make sure to use `gofmt` before every commit - the easiest way to do this is have your editor run it for you upon saving a file. Otherwise, run the following command in the project root directory: `go fmt ./...`\n\nIt is recommended that you use the Golang Linter before every commit, to help you catch errors and to write clean code: `golangci-lint run ./...`\n\n## Forking\n\nPlease note that Go requires code to live under absolute paths, which complicates forking.\nWhile the fork for user 'foo' lives at `https://github.com/foo/amass`,\nthe code should never exist at `$GOPATH/src/github.com/foo/amass`.\nInstead, we use `git remote` to add the fork as a new remote for the original repo,\n`$GOPATH/src/github.com/owasp-amass/amass`, and do all the work there.\n\nFor instance, to create a fork and work on a branch of it, user 'foo' would:\n\n * Create the fork on github, using the fork button.\n * Go to the original repo checked out locally (ie. `$GOPATH/src/github.com/owasp-amass/amass`)\n * `git remote rename origin upstream`\n * `git remote add origin git@github.com:foo/amass.git`\n\nNow `origin` refers to the foo fork and `upstream` refers to the OWASP version.\nSo foo can `git push -u origin develop` to update his/her fork, and make pull requests to OWASP from there.\nOf course, replace `foo` with your git handle.\n\nTo pull in updates from the original repo, run\n\n * `git fetch upstream`\n * `git rebase upstream/main` (or whatever branch you want)\n\nPlease do not make pull requests to `main`.\n\n### Development Procedure:\n- the latest state of development is on `develop`\n- no --force onto `develop` (except when reverting a broken commit, which should seldom happen)\n- create a development branch on your fork (using `git add origin`)\n- before submitting a pull request, begin `git rebase` on top of `develop`\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n# [![OWASP Logo](https://raw.githubusercontent.com/owasp-amass/docs/master/images/owasp_logo.png) OWASP Amass Project](https://owasp.org/www-project-amass/)\n\n[![OWASP Flagship](https://img.shields.io/badge/owasp-flagship%20project-48A646.svg)](https://owasp.org/projects/#sec-flagships)\n[![GitHub Release](https://img.shields.io/github/release/owasp-amass/amass)](https://github.com/owasp-amass/amass/releases/latest)\n[![Go Report](https://goreportcard.com/badge/github.com/owasp-amass/amass)](https://goreportcard.com/report/github.com/owasp-amass/amass)\n[![CodeFactor](https://www.codefactor.io/repository/github/owasp-amass/amass/badge)](https://www.codefactor.io/repository/github/owasp-amass/amass)\n[![Follow on Twitter](https://img.shields.io/twitter/follow/owaspamass.svg?logo=twitter)](https://twitter.com/owaspamass)\n[![Chat on Discord](https://img.shields.io/discord/433729817918308352.svg?logo=discord)](https://discord.gg/ANTyEDUXt5)\n\nThe OWASP Amass Project performs network mapping of attack surfaces and external asset discovery using open source information gathering and active reconnaissance techniques.\n\n## Installation [![Go Version](https://img.shields.io/github/go-mod/go-version/owasp-amass/amass)](https://golang.org/dl/) [![Docker Image](https://img.shields.io/docker/pulls/owaspamass/amass.svg)](https://hub.docker.com/r/owaspamass/amass) [![GitHub Downloads](https://img.shields.io/github/downloads/owasp-amass/amass/latest/total.svg)](https://github.com/owasp-amass/amass/releases/latest)\n\n> You can find additional installation instructions and documentation in the [Amass Docs](https://owasp-amass.github.io/docs) repo.\n\n## Corporate Supporters\n\n[![WhoisXML API Logo](https://raw.githubusercontent.com/owasp-amass/docs/master/images/supporters/whoisxmlapi_logo.png)](https://www.whoisxmlapi.com/)\n\n## Contributing [![Contribute Yes](https://img.shields.io/badge/contribute-yes-brightgreen.svg)](./CONTRIBUTING.md) [![Chat on Discord](https://img.shields.io/discord/433729817918308352.svg?logo=discord)](https://discord.gg/ANTyEDUXt5)\n\nWe are always happy to get new contributors on board! Please check [CONTRIBUTING.md](CONTRIBUTING.md) to learn how to\ncontribute to our codebase, and join our [Discord Server](https://discord.gg/ANTyEDUXt5) to discuss current project goals.\n\n## Troubleshooting ![GitHub Test Status](https://github.com/owasp-amass/amass/workflows/tests/badge.svg) [![codecov](https://codecov.io/gh/owasp-amass/amass/branch/master/graph/badge.svg?token=zoPKxvLT1n)](https://codecov.io/gh/owasp-amass/amass) [![Chat on Discord](https://img.shields.io/discord/433729817918308352.svg?logo=discord)](https://discord.gg/ANTyEDUXt5)\n\nIf you need help with installation and/or usage of the tool, please join our [Discord server](https://discord.gg/ANTyEDUXt5) where community members can best help you.\n\n:stop_sign: **Please avoid opening GitHub issues for support requests or questions!**\n\n## Licensing [![License](https://img.shields.io/badge/license-apache%202-blue)](https://www.apache.org/licenses/LICENSE-2.0)\n\nThis program is free software: you can redistribute it and/or modify it under the terms of the [Apache license](LICENSE). OWASP Amass and any contributions are Copyright \u00a9 by Jeff Foley 2017-2025. Some subcomponents have separate licenses.\n\n![Network graph](https://raw.githubusercontent.com/owasp-amass/docs/master/images/network_06092018.png \"Amass Network Mapping\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/ae_isready/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\tamasshttp \"github.com/owasp-amass/amass/v5/internal/net/http\"\n)\n\nfunc main() {\n\tvar hostname string\n\tvar help1, help2 bool\n\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s %s\\n\\n\", path.Base(os.Args[0]), \"--host HOSTNAME [-h | -help]\")\n\t\treturn\n\t}\n\n\tflag.BoolVar(&help1, \"h\", false, \"Show the program usage message\")\n\tflag.BoolVar(&help2, \"help\", false, \"Show the program usage message\")\n\tflag.StringVar(&hostname, \"host\", \"\", \"Hostname or IP address of the Amass Engine\")\n\t//flag.BoolVar(&version, \"version\", false, \"Print the version number of this Amass binary\")\n\tflag.Parse()\n\n\tif (help1 || help2) || hostname == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s %s\\n\\n\", path.Base(os.Args[0]), \"--host HOSTNAME\")\n\t\tflag.PrintDefaults()\n\t\treturn\n\t}\n\t/*if version {\n\t\tfmt.Fprintf(color.Error, \"%s\\n\", format.Version)\n\t\treturn\n\t}*/\n\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tu := \"http://\" + hostname + \":4000/graphql\"\n\tif _, err := amasshttp.RequestWebPage(ctx, &amasshttp.Request{URL: u}); err != nil {\n\t\t// a failure to respond indicates that the server is not yet available\n\t\tos.Exit(1)\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/amass/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// In-depth Attack Surface Mapping and Asset Discovery\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\tae \"github.com/owasp-amass/amass/v5/internal/amass_engine\"\n\t\"github.com/owasp-amass/amass/v5/internal/assoc\"\n\t\"github.com/owasp-amass/amass/v5/internal/enum\"\n\t\"github.com/owasp-amass/amass/v5/internal/subs\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n\t\"github.com/owasp-amass/amass/v5/internal/track\"\n\t\"github.com/owasp-amass/amass/v5/internal/viz\"\n)\n\nconst (\n\tusageMsg string = \"[assoc|engine|enum|subs|track|viz] [options]\"\n)\n\ntype Args struct {\n\tHelp bool\n\tVersion bool\n}\n\ntype subDesc struct {\n\tName string\n\tDescription string\n}\n\nvar subcommands = []subDesc{\n\t{\"assoc\", assoc.Description},\n\t{\"engine\", ae.Description},\n\t{\"enum\", enum.Description},\n\t{\"subs\", subs.Description},\n\t{\"track\", track.Description},\n\t{\"viz\", viz.Description},\n}\n\nfunc main() {\n\tvar args Args\n\tfs := flag.NewFlagSet(\"amass\", flag.ContinueOnError)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Version, \"version\", false, \"Print the Amass version number\")\n\n\tdefaultBuf := new(bytes.Buffer)\n\tfs.SetOutput(defaultBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", path.Base(os.Args[0]), usageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, defaultBuf.String())\n\t\t\t_, _ = afmt.G.Fprintf(color.Error, \"Subcommands: \\n\\n\")\n\t\t\tfor _, sub := range subcommands {\n\t\t\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\t%-5s\\t%s\\n\", sub.Name, sub.Description)\n\t\t\t}\n\t\t\t_, _ = afmt.G.Fprintln(color.Error)\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and subcommands\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\tusage()\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Version {\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"%s\\n\", afmt.Version)\n\t\treturn\n\t}\n\n\t// Ensure the output directory exists\n\tif err := tools.CreateOutputDirectory(\"\"); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdir := config.OutputDirectory(\"\")\n\tif dir == \"\" {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"failed to obtain the path for the output directory\")\n\t\tos.Exit(1)\n\t}\n\n\t// Ensure the default config files exist\n\tif err := tools.CreateDefaultConfigFiles(dir); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the default config files: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tcmdName := fmt.Sprintf(\"%s %s\", path.Base(os.Args[0]), os.Args[1])\n\tswitch os.Args[1] {\n\tcase \"assoc\":\n\t\tassoc.CLIWorkflow(cmdName, os.Args[2:])\n\tcase \"engine\":\n\t\tif engineIsRunning() {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"The Amass engine is already running.\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tae.CLIWorkflow(cmdName, os.Args[2:])\n\tcase \"enum\":\n\t\t// The engine must be started before running the enum command\n\t\tif !engineIsRunning() {\n\t\t\tif err := startEngine(); err != nil {\n\t\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to start the Amass engine: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\t// Give the engine time to start\n\t\t\tif err := waitForEngineResponse(); err != nil {\n\t\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"The Amass engine did not respond: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tenum.CLIWorkflow(cmdName, os.Args[2:])\n\tcase \"subs\":\n\t\tsubs.CLIWorkflow(cmdName, os.Args[2:])\n\tcase \"track\":\n\t\ttrack.CLIWorkflow(cmdName, os.Args[2:])\n\tcase \"viz\":\n\t\tviz.CLIWorkflow(cmdName, os.Args[2:])\n\tdefault:\n\t\tusage()\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"subcommand provided but not defined: %s\\n\", os.Args[1])\n\t\tos.Exit(1)\n\t}\n}\n\nfunc waitForEngineResponse() error {\n\tt := time.NewTicker(time.Second)\n\tdefer t.Stop()\n\n\tfor range 60 {\n\t\t<-t.C\n\t\tif engineIsRunning() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"the Amass engine did not respond within the timeout period\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/amass/process.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/engine/api/graphql/client\"\n)\n\nfunc engineIsRunning() bool {\n\tc := client.NewClient(\"http://127.0.0.1:4000/graphql\")\n\n\tif _, err := c.SessionStats(uuid.New()); err != nil && err.Error() == \"invalid session token\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc startEngine() error {\n\tp, err := os.Executable()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get executable path: %w\", err)\n\t}\n\tif p == \"\" {\n\t\treturn fmt.Errorf(\"executable path is empty\")\n\t}\n\n\tcmd := initCmd(p)\n\tif cmd == nil {\n\t\treturn fmt.Errorf(\"failed to initialize command for %s\", p)\n\t}\n\tcmd.Stdout = io.Discard\n\tcmd.Stderr = io.Discard\n\tcmd.Stdin = os.Stdin\n\n\tcmd.Dir, err = os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Start()\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/amass/process_unix.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n//go:build !windows\n\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n)\n\nfunc initCmd(p string) *exec.Cmd {\n\tcmd := exec.Command(\"nohup\", p, \"engine\")\n\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\n\treturn cmd\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/amass/process_windows.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n//go:build windows\n\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"os/exec\"\n\t\"syscall\"\n)\n\nfunc initCmd(p string) *exec.Cmd {\n\tcmd := exec.Command(\"cmd\", \"/C\", \"start\", p, \"engine\")\n\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCreationFlags: syscall.CREATE_NEW_PROCESS_GROUP,\n\t}\n\n\treturn cmd\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/amass_engine/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// amass_engine: Run the Amass collection engine to populate the OAM database\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\tae \"github.com/owasp-amass/amass/v5/internal/amass_engine\"\n)\n\nfunc main() {\n\tae.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_assoc/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_assoc: Analyze collected OAM data to identify assets associated with the seed data\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/assoc\"\n)\n\nfunc main() {\n\tassoc.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_enum/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_enum: Interface with the engine that performs enumerations and network mapping\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/enum\"\n)\n\nfunc main() {\n\tenum.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_i2y/ini.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/go-ini/ini\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n)\n\n// Updater allows an object to implement a method that updates a configuration.\ntype Updater interface {\n\tOverrideConfig(*Config) error\n}\n\n// Config passes along Amass configuration settings and options.\ntype Config struct {\n\tsync.Mutex\n\n\t// The graph databases used by the system / enumerations\n\tGraphDBs []*Database\n\n\t// The IP addresses specified as in scope\n\tAddresses []string\n\n\t// CIDR that is in scope\n\tCIDRs []string\n\n\t// ASNs specified as in scope\n\tASNs []int\n\n\t// The ports that will be checked for certificates\n\tPorts []int\n\n\t// Will the enumeration including brute forcing techniques\n\tBruteForcing bool\n\n\tBruteforcelist []string\n\n\t// Will recursive brute forcing be performed?\n\tRecursive bool\n\n\t// Will discovered subdomain name alterations be generated?\n\tAlterations bool\n\n\tAlterationslist []string\n\n\t// Only access the data sources for names and return results?\n\tPassive bool\n\n\t// Determines if zone transfers will be attempted\n\tActive bool\n\n\t// A blacklist of subdomain names that will not be investigated\n\tBlacklist []string\n\n\t// The minimum number of minutes that data source responses will be reused\n\tMinimumTTL int\n\n\t// Resolver settings\n\tResolvers []string\n\n\t// The root domain names that the enumeration will target\n\tdomains []string\n\n\t// The regular expressions for the root domains added to the enumeration\n\tregexps map[string]*regexp.Regexp\n\n\t// The data source configurations\n\tdatasrcConfigs map[string]*DataSourceConfig\n}\n\n// DataSourceConfig contains the configurations specific to a data source.\ntype DataSourceConfig struct {\n\tName string\n\tTTL int `ini:\"ttl\"`\n\tcreds map[string]*Credentials\n}\n\n// Credentials contains values required for authenticating with web APIs.\ntype Credentials struct {\n\tName string\n\tUsername string `ini:\"username\"`\n\tPassword string `ini:\"password\"`\n\tKey string `ini:\"apikey\"`\n\tSecret string `ini:\"secret\"`\n}\n\n// Database contains values required for connecting with graph databases.\ntype Database struct {\n\tSystem string\n\tPrimary bool `ini:\"primary\"`\n\tURL string `ini:\"url\"`\n\tUsername string `ini:\"username\"`\n\tPassword string `ini:\"password\"`\n\tDBName string `ini:\"database\"`\n\tOptions string `ini:\"options\"`\n}\n\n// LoadSettings parses settings from an .ini file and assigns them to the Config.\nfunc (c *Config) LoadSettings(path string) error {\n\tcfg, err := ini.LoadSources(ini.LoadOptions{\n\t\tInsensitive: true,\n\t\tAllowShadows: true,\n\t}, path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load the configuration file: %v\", err)\n\t}\n\t// Get the easy ones out of the way using mapping\n\tif err = cfg.MapTo(c); err != nil {\n\t\treturn fmt.Errorf(\"error mapping configuration settings to internal values: %v\", err)\n\t}\n\t// Attempt to load a special mode of operation specified by the user\n\tif cfg.Section(ini.DefaultSection).HasKey(\"mode\") {\n\t\tmode := cfg.Section(ini.DefaultSection).Key(\"mode\").String()\n\n\t\tswitch mode {\n\t\tcase \"passive\":\n\t\t\tc.Passive = true\n\t\tcase \"active\":\n\t\t\tc.Active = true\n\t\t}\n\t}\n\n\tloads := []func(cfg *ini.File) error{\n\t\tc.loadResolverSettings,\n\t\tc.loadScopeSettings,\n\t\tc.loadAlterationSettings,\n\t\tc.loadBruteForceSettings,\n\t\tc.loadDatabaseSettings,\n\t\tc.loadDataSourceSettings,\n\t}\n\tfor _, load := range loads {\n\t\tif err := load(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Config) loadDataSourceSettings(cfg *ini.File) error {\n\tsec, err := cfg.GetSection(\"data_sources\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif sec.HasKey(\"minimum_ttl\") {\n\t\tif ttl, err := sec.Key(\"minimum_ttl\").Int(); err == nil {\n\t\t\tc.MinimumTTL = ttl\n\t\t}\n\t}\n\n\tfor _, child := range sec.ChildSections() {\n\t\tname := strings.Split(child.Name(), \".\")[1]\n\n\t\tif name == \"disabled\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tdsc := c.GetDataSourceConfig(name)\n\t\t// Parse the Database information and assign to the Config\n\t\tif err := child.MapTo(dsc); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif c.MinimumTTL > dsc.TTL {\n\t\t\tdsc.TTL = c.MinimumTTL\n\t\t}\n\t\t// Check for data source credentials\n\t\tfor _, cr := range child.ChildSections() {\n\t\t\tsetName := strings.Split(cr.Name(), \".\")[2]\n\n\t\t\tcreds := &Credentials{Name: setName}\n\t\t\tif err := cr.MapTo(creds); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := dsc.AddCredentials(creds); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *Config) loadDatabaseSettings(cfg *ini.File) error {\n\tsec, err := cfg.GetSection(\"graphdbs\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tfor _, child := range sec.ChildSections() {\n\t\tdb := new(Database)\n\t\tname := strings.Split(child.Name(), \".\")[1]\n\n\t\t// Parse the Database information and assign to the Config\n\t\tif err := child.MapTo(db); err == nil {\n\t\t\tdb.System = name\n\t\t\tc.GraphDBs = append(c.GraphDBs, db)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Config) loadResolverSettings(cfg *ini.File) error {\n\tsec, err := cfg.GetSection(\"resolvers\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tc.Resolvers = stringset.Deduplicate(sec.Key(\"resolver\").ValueWithShadows())\n\tif len(c.Resolvers) == 0 {\n\t\treturn errors.New(\"no resolver keys were found in the resolvers section\")\n\t}\n\n\treturn nil\n}\n\nfunc (c *Config) loadScopeSettings(cfg *ini.File) error {\n\tscope, err := cfg.GetSection(\"scope\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tif scope.HasKey(\"address\") {\n\t\tc.Addresses = append(c.Addresses, scope.Key(\"address\").ValueWithShadows()...)\n\t}\n\n\tif scope.HasKey(\"cidr\") {\n\t\tfor _, cidr := range scope.Key(\"cidr\").ValueWithShadows() {\n\t\t\t// Verify the CIDR is valid\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.CIDRs = append(c.CIDRs, cidr)\n\t\t}\n\t}\n\n\tif scope.HasKey(\"asn\") {\n\t\tfor _, asn := range scope.Key(\"asn\").ValueWithShadows() {\n\t\t\tc.ASNs = uniqueIntAppend(c.ASNs, asn)\n\t\t}\n\t}\n\n\tif scope.HasKey(\"port\") {\n\t\tfor _, port := range scope.Key(\"port\").ValueWithShadows() {\n\t\t\tc.Ports = uniqueIntAppend(c.Ports, port)\n\t\t}\n\t}\n\n\t// Load up all the DNS domain names\n\tif domains, err := cfg.GetSection(\"scope.domains\"); err == nil {\n\t\tfor _, domain := range domains.Key(\"domain\").ValueWithShadows() {\n\t\t\tc.AddDomain(domain)\n\t\t}\n\t}\n\n\t// Load up all the blacklisted subdomain names\n\tif blacklisted, err := cfg.GetSection(\"scope.blacklisted\"); err == nil {\n\t\tc.Blacklist = stringset.Deduplicate(blacklisted.Key(\"subdomain\").ValueWithShadows())\n\t}\n\n\treturn nil\n}\n\nfunc (c *Config) loadBruteForceSettings(cfg *ini.File) error {\n\tbruteforce, err := cfg.GetSection(\"bruteforce\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// get the list\n\tc.Bruteforcelist = bruteforce.Key(\"wordlist_file\").ValueWithShadows()\n\n\t// get the options like the worldlist somehow\n\tc.BruteForcing = bruteforce.Key(\"enabled\").MustBool(true)\n\tif !c.BruteForcing {\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc (c *Config) loadAlterationSettings(cfg *ini.File) error {\n\talterations, err := cfg.GetSection(\"alterations\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// get the list\n\tc.Alterationslist = alterations.Key(\"wordlist_file\").ValueWithShadows()\n\n\tc.Alterations = alterations.Key(\"enabled\").MustBool(true)\n\tif !c.Alterations {\n\t\treturn nil\n\t}\n\treturn nil\n}\n\n// GetDataSourceConfig returns the DataSourceConfig associated with the data source name argument.\nfunc (c *Config) GetDataSourceConfig(source string) *DataSourceConfig {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tkey := strings.TrimSpace(source)\n\tif key == \"\" {\n\t\treturn nil\n\t}\n\tif c.datasrcConfigs == nil {\n\t\tc.datasrcConfigs = make(map[string]*DataSourceConfig)\n\t}\n\tif _, found := c.datasrcConfigs[key]; !found {\n\t\tc.datasrcConfigs[key] = &DataSourceConfig{Name: key}\n\t}\n\treturn c.datasrcConfigs[key]\n}\n\n// AddCredentials adds the Credentials provided to the configuration.\nfunc (dsc *DataSourceConfig) AddCredentials(cred *Credentials) error {\n\tif cred == nil || cred.Name == \"\" {\n\t\treturn fmt.Errorf(\"AddCredentials: The Credentials argument is invalid\")\n\t}\n\n\tif dsc.creds == nil {\n\t\tdsc.creds = make(map[string]*Credentials)\n\t}\n\n\tdsc.creds[cred.Name] = cred\n\treturn nil\n}\n\n// AddDomain appends the domain name provided in the parameter to the list in the configuration.\nfunc (c *Config) AddDomain(domain string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\t// Check that the domain string is not empty\n\td := strings.TrimSpace(domain)\n\tif d == \"\" {\n\t\treturn\n\t}\n\t// Check that it is a domain with at least two labels\n\tlabels := strings.Split(d, \".\")\n\tif len(labels) < 2 {\n\t\treturn\n\t}\n\n\t// Check that none of the labels are empty\n\tfor _, label := range labels {\n\t\tif label == \"\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Check that the regular expression map has been initialized\n\tif c.regexps == nil {\n\t\tc.regexps = make(map[string]*regexp.Regexp)\n\t}\n\n\t// Create the regular expression for this domain\n\tc.regexps[d] = dns.SubdomainRegex(d)\n\tif c.regexps[d] != nil {\n\t\t// Add the domain string to the list\n\t\tc.domains = append(c.domains, d)\n\t}\n\n\tc.domains = stringset.Deduplicate(c.domains)\n}\n\nfunc uniqueIntAppend(s []int, e string) []int {\n\tif a1, err := strconv.Atoi(e); err == nil {\n\t\tvar found bool\n\n\t\tfor _, a2 := range s {\n\t\t\tif a1 == a2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\ts = append(s, a1)\n\t\t}\n\t}\n\treturn s\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_i2y/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_i2y: Converts legacy INI configuration to YAML!\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"gopkg.in/yaml.v3\"\n)\n\nconst (\n\tusageMsg = \"[options]\"\n)\n\nvar (\n\tg = color.New(color.FgHiGreen)\n\tr = color.New(color.FgHiRed)\n\tb = color.New(color.FgHiBlue)\n\tp = color.New(color.FgHiMagenta)\n)\n\nfunc main() {\n\tvar help1, help2 bool\n\tvar iniFile, configFile, datasrcFile string\n\tvar err error\n\ti2yCommand := flag.NewFlagSet(\"db\", flag.ContinueOnError)\n\n\ti2yBuf := new(bytes.Buffer)\n\ti2yCommand.SetOutput(i2yBuf)\n\n\ti2yCommand.BoolVar(&help1, \"h\", false, \"Show the program usage message\")\n\ti2yCommand.BoolVar(&help2, \"help\", false, \"Show the program usage message\")\n\ti2yCommand.StringVar(&iniFile, \"ini\", \"\", \"Path to the INI configuration file.\")\n\ti2yCommand.StringVar(&configFile, \"cf\", \"oam_config.yaml\", \"YAML configuration file name.\")\n\ti2yCommand.StringVar(&datasrcFile, \"df\", \"oam_datasources.yaml\", \"YAML data sources file name.\")\n\n\tvar usage = func() {\n\t\t_, _ = g.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", path.Base(os.Args[0]), usageMsg)\n\t\ti2yCommand.PrintDefaults()\n\t\t_, _ = g.Fprintln(color.Error, i2yBuf.String())\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := i2yCommand.Parse(os.Args[1:]); err != nil {\n\t\t_, _ = r.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif help1 || help2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif iniFile == \"\" {\n\t\tusage()\n\t\t_, _ = r.Fprintln(color.Error, \"Failed to parse the INI file: File not present, got \\\"\"+iniFile+\"\\\" as the path.\")\n\t\treturn\n\t}\n\n\t// converts the file paths to absolute paths\n\tconfigFile, err = filepath.Abs(configFile)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to get the absolute config path:\", err)\n\t}\n\tdatasrcFile, err = filepath.Abs(datasrcFile)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to get the absolute data source path:\", err)\n\t}\n\n\tiniConfig := Config{}\n\tif err := iniConfig.LoadSettings(iniFile); err != nil {\n\t\tlog.Fatal(\"Failed to load the INI file:\", err)\n\t}\n\n\t// this code below will take all the datasources specified in the ini and populate the filled ones into the yaml\n\tyamlDataSources := make([]*config.DataSource, 0)\n\n\tfor _, v := range iniConfig.datasrcConfigs {\n\t\tif len(v.creds) == 0 {\n\t\t\tcontinue // Skip to the next iteration if there are no credentials\n\t\t}\n\n\t\tcreds := make(map[string]*config.Credentials)\n\t\tfor credKey, credValue := range v.creds {\n\t\t\tcreds[credKey] = &config.Credentials{\n\t\t\t\tName: credValue.Name,\n\t\t\t\tUsername: credValue.Username,\n\t\t\t\tPassword: credValue.Password,\n\t\t\t\tApikey: credValue.Key,\n\t\t\t\tSecret: credValue.Secret,\n\t\t\t}\n\t\t}\n\n\t\tyamlDataSources = append(yamlDataSources, &config.DataSource{\n\t\t\tName: v.Name,\n\t\t\tTTL: v.TTL,\n\t\t\tCreds: creds,\n\t\t})\n\t}\n\n\t// this part of the code will populate the options only if theyre populated in the ini\n\toptions := make(map[string]interface{})\n\n\tif len(iniConfig.Resolvers) > 0 {\n\t\toptions[\"resolvers\"] = iniConfig.Resolvers\n\t}\n\n\tif iniConfig.BruteForcing {\n\t\tbruteforce := make(map[string]interface{})\n\t\tbruteforce[\"enabled\"] = iniConfig.BruteForcing\n\n\t\tif len(iniConfig.Bruteforcelist) > 0 {\n\t\t\tbruteforce[\"wordlist\"] = iniConfig.Bruteforcelist\n\t\t}\n\n\t\toptions[\"bruteforce\"] = bruteforce\n\t}\n\n\tif iniConfig.Alterations {\n\t\talterations := make(map[string]interface{})\n\t\talterations[\"enabled\"] = iniConfig.Alterations\n\n\t\tif len(iniConfig.Alterationslist) > 0 {\n\t\t\talterations[\"wordlist\"] = iniConfig.Alterationslist\n\t\t}\n\n\t\toptions[\"alterations\"] = alterations\n\t}\n\n\t// this part of the code initializes the yamlconfig file with the values\n\tyamlConfig := config.Config{\n\t\tScope: &config.Scope{\n\t\t\tDomains: iniConfig.domains,\n\t\t\tIP: iniConfig.Addresses,\n\t\t\tASNs: iniConfig.ASNs,\n\t\t\tCIDRStrings: iniConfig.CIDRs,\n\t\t\tPorts: iniConfig.Ports,\n\t\t\tBlacklist: iniConfig.Blacklist,\n\t\t},\n\t\tOptions: options,\n\t}\n\n\t// if the databse is present in the ini, then store the first url.\n\tif len(iniConfig.GraphDBs) > 0 {\n\t\tyamlConfig.Options[\"database\"] = iniConfig.GraphDBs[0].URL\n\t}\n\n\t// this part of the code initializes the yamlDataSrcConfigs file with the values\n\tyamlDataSrcConfigs := config.DataSourceConfig{\n\t\tDatasources: yamlDataSources,\n\t\tGlobalOptions: map[string]int{\n\t\t\t\"minimum_ttl\": iniConfig.MinimumTTL,\n\t\t},\n\t}\n\n\t// marshals and outputs it into a file\n\n\toutput, err := yaml.Marshal(yamlDataSrcConfigs)\n\tif err != nil {\n\t\tlog.Println(\"failed to marshal the yaml:\", err)\n\t} else {\n\t\tyamlConfig.Options[\"datasources\"] = datasrcFile\n\t\terr = os.WriteFile(datasrcFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed to write datasources file:\", err)\n\t\t} else {\n\t\t\t_, _ = fmt.Println(b.Sprint(\"Wrote data sources file successfully at: \") + p.Sprint(datasrcFile))\n\t\t}\n\t}\n\n\toutput, err = yaml.Marshal(&yamlConfig)\n\tif err != nil {\n\t\tlog.Println(\"failed to marshal the yaml:\", err)\n\t} else {\n\t\terr = os.WriteFile(configFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed to write config file:\", err)\n\t\t} else {\n\t\t\t_, _ = fmt.Println(b.Sprint(\"Wrote config file successfully at \") + p.Sprint(configFile))\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_subs/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_subs: Analyze and present collected OAM subdomains and associated data\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/subs\"\n)\n\nfunc main() {\n\tsubs.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_track/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_track: Analyze collected OAM data to identify newly discovered assets\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/track\"\n)\n\nfunc main() {\n\ttrack.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: cmd/oam_viz/main.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\n// oam_viz: Analyze collected OAM data to generate graph visualizations\n//\n//\t+----------------------------------------------------------------------------+\n//\t| \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 OWASP Amass \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 |\n//\t+----------------------------------------------------------------------------+\n//\t| .+++:. : .+++. |\n//\t| +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ |\n//\t| &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& |\n//\t| +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 |\n//\t| 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: |\n//\t| WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: |\n//\t| #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 |\n//\t| o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. |\n//\t| WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o |\n//\t| :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ |\n//\t| :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& |\n//\t| +o&&&&+. +oooo. |\n//\t+----------------------------------------------------------------------------+\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/viz\"\n)\n\nfunc main() {\n\tviz.CLIWorkflow(path.Base(os.Args[0]), os.Args[1:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/active.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport \"fmt\"\n\nfunc (c *Config) loadActiveSettings(cfg *Config) error {\n\t// Retrieve the active option from the configuration\n\tactiveinterface, ok := c.Options[\"active\"]\n\tif !ok {\n\t\t// \"active\" not found in options, so nothing to do here.\n\t\treturn nil\n\t}\n\n\tactive, ok := activeinterface.(bool)\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to parse active setting, value is not a boolean\")\n\t}\n\tc.Active = active\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/active_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nvar validyaml = []byte(`\noptions:\n active: true\n`)\n\nvar validyaml2 = []byte(`\noptions:\n active: false\n`)\n\nvar invalidyaml = []byte(`\noptions:\n active: \"true\"\n`)\n\nfunc TestActive(t *testing.T) {\n\tc := NewConfig()\n\n\terr := yaml.Unmarshal(validyaml, c)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\n\t// Test case 1: MarshalJSON returns the expected JSON bytes\n\tt.Run(\"TestActive returns the expected JSON bytes\", func(t *testing.T) {\n\t\texpected := []byte(`{\"seed\":{},\"scope\":{\"ports\":[80,443]},\"active\":true,\"rigid_boundaries\":false,\"resolvers\":null,\"datasource_config\":{},\"transformations\":{}}\n`)\n\t\t_ = c.loadActiveSettings(c)\n\t\tgot, err := c.JSON()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(got, expected) {\n\t\t\tt.Errorf(\"Unexpected JSON bytes.\\nExpected: %s\\nGot: %s\", expected, got)\n\t\t}\n\n\t})\n\n\tt.Run(\"TestActive returns the expected JSON bytes when active isnt provided\", func(t *testing.T) {\n\t\tc := NewConfig()\n\t\texpected := []byte(`{\"seed\":{},\"scope\":{\"ports\":[80,443]},\"rigid_boundaries\":false,\"resolvers\":null,\"datasource_config\":{},\"transformations\":{}}\n`)\n\n\t\tgot, err := c.JSON()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(got, expected) {\n\t\t\tt.Errorf(\"Unexpected JSON bytes.\\nExpected: %s\\nGot: %s\", expected, got)\n\t\t}\n\n\t})\n\n\tt.Run(\"TestActive returns the expected JSON bytes when active is false\", func(t *testing.T) {\n\t\terr := yaml.Unmarshal(validyaml2, c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\texpected := []byte(`{\"seed\":{},\"scope\":{\"ports\":[80,443]},\"rigid_boundaries\":false,\"resolvers\":null,\"datasource_config\":{},\"transformations\":{}}\n`)\n\n\t\t_ = c.loadActiveSettings(c)\n\t\tgot, err := c.JSON()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(got, expected) {\n\t\t\tt.Errorf(\"Unexpected JSON bytes.\\nExpected: %s\\nGot: %s\", expected, got)\n\t\t}\n\n\t})\n\n\tt.Run(\"TestActive fails to parse non-bool active setting\", func(t *testing.T) {\n\t\tc := NewConfig()\n\t\terr := yaml.Unmarshal(invalidyaml, c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\terr = c.loadActiveSettings(c)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected error, got nil\")\n\t\t}\n\t})\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/brute.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/caffix/stringset\"\n)\n\nfunc (c *Config) loadBruteForceSettings(cfg *Config) error {\n\tbruteforceRaw, ok := c.Options[\"bruteforce\"]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tbruteforce, ok := bruteforceRaw.(map[string]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"bruteforce is not a map[string]interface{}\")\n\t}\n\n\tenabled, ok := bruteforce[\"enabled\"].(bool)\n\tif !ok {\n\t\treturn fmt.Errorf(\"bruteforce enabled is not a bool\")\n\t}\n\n\tc.BruteForcing = enabled\n\tif !c.BruteForcing {\n\t\treturn nil\n\t}\n\n\tif wordlistPathRaw, ok := bruteforce[\"wordlists\"]; ok {\n\t\twordlistPaths, ok := wordlistPathRaw.([]interface{})\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"bruteforce wordlist_file is not an array\")\n\t\t}\n\n\t\tfor _, wordlistPathRaw := range wordlistPaths {\n\t\t\twordlistPath, ok := wordlistPathRaw.(string)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"bruteforce wordlist_file item is not a string\")\n\t\t\t}\n\n\t\t\tabsPath, err := c.AbsPathFromConfigDir(wordlistPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get absolute path for wordlist file: %w\", err)\n\t\t\t}\n\n\t\t\twordlist, err := GetListFromFile(absPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to load the file in the bruteforce wordlist_file setting: %s: %v\", absPath, err)\n\t\t\t}\n\n\t\t\tc.Wordlist = append(c.Wordlist, wordlist...)\n\t\t}\n\t}\n\n\tc.Wordlist = stringset.Deduplicate(c.Wordlist)\n\treturn nil\n}\n\nfunc (c *Config) loadAlterationSettings(cfg *Config) error {\n\talterationsRaw, ok := c.Options[\"alterations\"]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\talterations, ok := alterationsRaw.(map[string]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"alterations is not a map[string]interface{}\")\n\t}\n\n\tenabled, ok := alterations[\"enabled\"].(bool)\n\tif !ok {\n\t\treturn fmt.Errorf(\"alterations enabled is not a bool\")\n\t}\n\n\tc.Alterations = enabled\n\tif !c.Alterations {\n\t\treturn nil\n\t}\n\n\tif wordlistPathRaw, ok := alterations[\"wordlists\"]; ok {\n\t\twordlistPaths, ok := wordlistPathRaw.([]interface{})\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"alterations wordlist_file is not an array\")\n\t\t}\n\n\t\tfor _, wordlistPathRaw := range wordlistPaths {\n\t\t\twordlistPath, ok := wordlistPathRaw.(string)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"alterations wordlist_file item is not a string\")\n\t\t\t}\n\n\t\t\tabsPath, err := c.AbsPathFromConfigDir(wordlistPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get absolute path for wordlist file: %w\", err)\n\t\t\t}\n\n\t\t\twordlist, err := GetListFromFile(absPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to load the file in the alterations wordlist_file setting: %s: %v\", absPath, err)\n\t\t\t}\n\n\t\t\tc.AltWordlist = append(c.AltWordlist, wordlist...)\n\t\t}\n\t}\n\n\tc.AltWordlist = stringset.Deduplicate(c.AltWordlist)\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/brute_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nfunc TestConfigLoadBruteForceSettings(t *testing.T) {\n\ttype args struct {\n\t\tcfg []byte\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr bool\n\t\tassertionFunc func(*testing.T, *Config)\n\t}{\n\t\t{\n\t\t\tname: \"success - brute force enabled\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n brute_force:\n enabled: true\n wordlists: []`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tbruteForce, ok := c.Options[\"brute_force\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"BruteForce not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tenabled, ok := bruteForce[\"enabled\"].(bool)\n\t\t\t\tif !ok || !enabled {\n\t\t\t\t\tt.Errorf(\"BruteForce not enabled\")\n\t\t\t\t}\n\t\t\t\twordlist, ok := bruteForce[\"wordlists\"].([]interface{})\n\t\t\t\tif !ok || len(wordlist) != 0 {\n\t\t\t\t\tt.Errorf(\"Wordlist not correctly set\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"failure - missing brute force settings\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n something_else:\n some_setting: true`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tif _, ok := c.Options[\"brute_force\"]; ok {\n\t\t\t\t\tt.Errorf(\"BruteForce should not be found\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - brute force disabled\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n brute_force:\n enabled: false\n wordlists: []`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tbruteForce, ok := c.Options[\"brute_force\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"BruteForce not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tenabled, ok := bruteForce[\"enabled\"].(bool)\n\t\t\t\tif !ok || enabled {\n\t\t\t\t\tt.Errorf(\"BruteForce should not be enabled\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"failure - missing wordlist\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n brute_force:\n enabled: true`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tbruteForce, ok := c.Options[\"brute_force\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"BruteForce not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_, ok = bruteForce[\"wordlists\"].([]interface{})\n\t\t\t\tif ok {\n\t\t\t\t\tt.Errorf(\"Wordlist was found, but it is not in the YAML\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - minimal wordlist\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n brute_force:\n enabled: true\n wordlists: \n - \"wordlist_file\"`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tbruteForce, ok := c.Options[\"brute_force\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"BruteForce not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twordlist, ok := bruteForce[\"wordlists\"].([]interface{})\n\t\t\t\tif !ok || len(wordlist) != 1 {\n\t\t\t\t\tt.Errorf(\"Wordlist not correctly set\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := &Config{}\n\t\t\tif err := yaml.Unmarshal(tt.args.cfg, c); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"yaml.Unmarshal() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t\ttt.assertionFunc(t, c)\n\t\t})\n\t}\n}\n\nfunc TestConfigLoadAlterationSettings(t *testing.T) {\n\ttype args struct {\n\t\tcfg []byte\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr bool\n\t\tassertionFunc func(*testing.T, *Config)\n\t}{\n\t\t{\n\t\t\tname: \"success - check default for enabled\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n name_alteration:\n enabled: false\n wordlists: []\n `)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tnameAlteration, ok := c.Options[\"name_alteration\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"NameAlteration not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tenabled, ok := nameAlteration[\"enabled\"].(bool)\n\t\t\t\tif !ok || enabled {\n\t\t\t\t\tt.Errorf(\"NameAlteration should not be enabled\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - enabled, with wordlist file\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n name_alteration:\n enabled: true\n wordlists: \n - \"test_word\"\n `)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tnameAlteration, ok := c.Options[\"name_alteration\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"NameAlteration not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tenabled, ok := nameAlteration[\"enabled\"].(bool)\n\t\t\t\tif !ok || !enabled {\n\t\t\t\t\tt.Errorf(\"NameAlteration not enabled\")\n\t\t\t\t}\n\t\t\t\twordlist, ok := nameAlteration[\"wordlists\"].([]interface{})\n\t\t\t\tif !ok || len(wordlist) != 1 {\n\t\t\t\t\tt.Errorf(\"Wordlist not correctly set\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"failure - missing wordlist\",\n\t\t\targs: args{cfg: []byte(`\noptions:\n name_alteration:\n enabled: true\n `)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tnameAlteration, ok := c.Options[\"name_alteration\"].(map[string]interface{})\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"NameAlteration not found\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_, ok = nameAlteration[\"wordlists\"].([]interface{})\n\t\t\t\tif ok {\n\t\t\t\t\tt.Errorf(\"Wordlist was found, but not in YAML\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := &Config{}\n\t\t\tif err := yaml.Unmarshal(tt.args.cfg, c); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"Config.loadAlterationSettings() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t\ttt.assertionFunc(t, c)\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/config.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/google/uuid\"\n\t\"gopkg.in/yaml.v3\"\n)\n\nconst (\n\toutputDirName = \"amass\"\n\tdefaultCfgFile = \"config.yaml\"\n\tcfgEnvironVar = \"AMASS_CONFIG\"\n\tsystemCfgDir = \"/etc\"\n)\n\n// Updater allows an object to implement a method that updates a configuration.\ntype Updater interface {\n\tOverrideConfig(*Config) error\n}\n\n// Config passes along Amass configuration settings and options.\ntype Config struct {\n\tsync.Mutex `yaml:\"-\" json:\"-\"`\n\n\t// A Universally Unique Identifier (UUID) for the enumeration\n\tUUID uuid.UUID `yaml:\"-\" json:\"-\"`\n\n\t// The pseudo-random number generator\n\tRand *rand.Rand `yaml:\"-\" json:\"-\"`\n\n\t// Logger for error messages\n\tLog *log.Logger `yaml:\"-\" json:\"-\"`\n\n\t// The date/time that discoveries must be active since to be included in the findings\n\tCollectionStartTime time.Time `yaml:\"-\" json:\"-\"`\n\n\t// Seed struct that contains the provided names and CIDRs\n\tSeed *Scope `yaml:\"seed,omitempty\" json:\"seed,omitempty\"`\n\n\t// Scope struct that contains ASN, CIDR, Domain, IP, and ports in scope\n\tScope *Scope `yaml:\"scope,omitempty\" json:\"scope,omitempty\"`\n\n\t// Defines options like datasources config path and stuff like that\n\tOptions map[string]interface{} `yaml:\"options,omitempty\" json:\"-\"`\n\n\t// The global transformation settings\n\tDefaultTransformations *Transformation `yaml:\"-\" json:\"-\"`\n\n\t// Filepath of the configuration file. It is needed as a seed incase of relative paths in the config.\n\tFilepath string `yaml:\"-\" json:\"-\"`\n\n\t// Alternative directory for scripts provided by the user\n\tScriptsDirectory string `yaml:\"-\" json:\"-\"`\n\n\t// The directory that stores the bolt db and other files created\n\tDir string `yaml:\"-\" json:\"-\"`\n\n\t// The graph databases used by the system / enumerations\n\tGraphDBs []*Database `yaml:\"-\" json:\"database,omitempty\"`\n\n\t// The maximum number of concurrent DNS queries\n\tMaxDNSQueries int `yaml:\"-\" json:\"-\"`\n\n\t// The list of words to use when generating names\n\tWordlist []string `yaml:\"-\" json:\"wordlist,omitempty\"`\n\n\t// Will the enumeration including brute forcing techniques\n\tBruteForcing bool `yaml:\"-\" json:\"brute_force,omitempty\"`\n\n\t// Will recursive brute forcing be performed?\n\tRecursive bool `yaml:\"-\" json:\"-\"`\n\n\t// Minimum number of subdomain discoveries before performing recursive brute forcing\n\tMinForRecursive int `yaml:\"-\" json:\"-\"`\n\n\t// Maximum depth for bruteforcing\n\tMaxDepth int `yaml:\"-\" json:\"-\"`\n\n\t// Will discovered subdomain name alterations be generated?\n\tAlterations bool `yaml:\"-\" json:\"alterations,omitempty\"`\n\tFlipWords bool `yaml:\"-\" json:\"-\"`\n\tFlipNumbers bool `yaml:\"-\" json:\"-\"`\n\tAddWords bool `yaml:\"-\" json:\"-\"`\n\tAddNumbers bool `yaml:\"-\" json:\"-\"`\n\tMinForWordFlip int `yaml:\"-\" json:\"-\"`\n\tEditDistance int `yaml:\"-\" json:\"-\"`\n\tAltWordlist []string `yaml:\"-\" json:\"alt_worldlist,omitempty\"`\n\n\t// Only access the data sources for names and return results?\n\tPassive bool `yaml:\"-\" json:\"-\"`\n\n\t// Determines if zone transfers will be attempted\n\tActive bool `yaml:\"active,omitempty\" json:\"active,omitempty\"`\n\n\t// Determines rigidness of the enumeration\n\tRigid bool `yaml:\"rigid_boundaries\" json:\"rigid_boundaries\"`\n\n\tblacklistLock sync.Mutex `yaml:\"-\" json:\"-\"`\n\n\t// A list of data sources that should not be utilized\n\tSourceFilter struct {\n\t\tInclude bool `yaml:\"-\" json:\"-\"` // true = include, false = exclude\n\t\tSources []string `yaml:\"-\" json:\"-\"`\n\t} `yaml:\"-\" json:\"-\"`\n\n\t// The minimum number of minutes that data source responses will be reused\n\tMinimumTTL int `yaml:\"-\" json:\"-\"`\n\n\t// Type of DNS records to query for\n\tRecordTypes []string `yaml:\"-\" json:\"-\"`\n\n\t// Resolver settings\n\tResolvers []string `yaml:\"-\" json:\"resolvers\"`\n\tResolversQPS int `yaml:\"-\" json:\"-\"`\n\tTrustedResolvers []string `yaml:\"-\" json:\"trusted_resolvers,omitempty\"`\n\tTrustedQPS int `yaml:\"-\" json:\"-\"`\n\n\t// Option for verbose logging and output\n\tVerbose bool `yaml:\"-\" json:\"-\"`\n\n\t// Names provided to seed the enumeration\n\tProvidedNames []string `yaml:\"-\" json:\"-\"`\n\n\t// The regular expressions for the root domains added to the enumeration\n\tregexps map[string]*regexp.Regexp `yaml:\"-\" json:\"-\"`\n\n\t// Mode should be determined based on scripts utilized\n\tMode string `yaml:\"-\" json:\"-\"`\n\n\t// The data source configurations\n\tDataSrcConfigs *DataSourceConfig `yaml:\"-\" json:\"datasource_config\"`\n\n\t// The Transformations map will contain incoming assets, and what handlers should be called.\n\tTransformations map[string]*Transformation `yaml:\"transformations\" json:\"transformations\"`\n\n\t// The engine APIURI configuration\n\tEngineAPI *EngAPI `yaml:\"-\" json:\"-\"`\n\n\t// Map to track 'From' types that have a 'none' transformation, indicating no processing should occur.\n\tfromWithNone map[string]bool\n\n\t// Map to track 'From' types that have at least one valid transformation defined.\n\tfromWithValid map[string]bool\n}\n\n// Scope represents the configuration for the enumeration scope.\ntype Scope struct {\n\t// The root domain names that the enumeration will target\n\tDomains []string `yaml:\"domains,omitempty\" json:\"domains,omitempty\"`\n\n\t// IP Net.IP\n\tAddresses []net.IP `yaml:\"-\" json:\"ips,omitempty\"`\n\n\t// The IP addresses specified as in scope\n\tIP []string `yaml:\"ips,omitempty\" json:\"-\"`\n\n\t// ASNs specified as in scope\n\tASNs []int `yaml:\"asns,omitempty\" json:\"asns,omitempty\"`\n\n\t// CIDR IPNET\n\tCIDRs []*net.IPNet `yaml:\"-\" json:\"cidrs,omitempty\"`\n\n\t// CIDR in scope\n\tCIDRStrings []string `yaml:\"cidrs,omitempty\" json:\"-\"`\n\n\t// Ports as an interface to parse and for ranges, it is stored as an interface for easy casting\n\tPortsRaw []interface{} `yaml:\"ports,omitempty\" json:\"-\"`\n\n\t// The ports checked for certificates\n\tPorts []int `yaml:\"-\" json:\"ports,omitempty\"`\n\n\t// A blacklist of subdomain names that will not be investigated\n\tBlacklist []string `yaml:\"blacklist,omitempty\" json:\"blacklist,omitempty\"`\n}\n\n// NewConfig returns a default configuration object.\nfunc NewConfig() *Config {\n\treturn &Config{\n\t\tUUID: uuid.New(),\n\t\tRand: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),\n\t\tLog: log.New(io.Discard, \"\", 0),\n\t\tCollectionStartTime: time.Now(),\n\t\tSeed: &Scope{},\n\t\tScope: &Scope{Ports: []int{80, 443}},\n\t\tOptions: make(map[string]interface{}),\n\t\tMinForRecursive: 1,\n\t\tFlipWords: true,\n\t\tFlipNumbers: true,\n\t\tAddWords: true,\n\t\tAddNumbers: true,\n\t\tMinForWordFlip: 2,\n\t\tEditDistance: 1,\n\t\tRecursive: true,\n\t\tMinimumTTL: 1440,\n\t\tResolversQPS: DefaultQueriesPerPublicResolver,\n\t\tTrustedQPS: DefaultQueriesPerBaselineResolver,\n\t\tDataSrcConfigs: &DataSourceConfig{\n\t\t\tGlobalOptions: make(map[string]int),\n\t\t},\n\t\tTransformations: make(map[string]*Transformation),\n\t\tDefaultTransformations: &Transformation{\n\t\t\tTTL: 1440,\n\t\t\tConfidence: 50,\n\t\t\tPriority: 5,\n\t\t},\n\t}\n}\n\n// UpdateConfig allows the provided Updater to update the current configuration.\nfunc (c *Config) UpdateConfig(update Updater) error {\n\treturn update.OverrideConfig(c)\n}\n\n// CheckSettings runs some sanity checks on the configuration options selected.\nfunc (c *Config) CheckSettings() error {\n\tvar err error\n\n\tif c.BruteForcing {\n\t\tif c.Passive {\n\t\t\treturn errors.New(\"brute forcing cannot be performed without DNS resolution\")\n\t\t}\n\t}\n\tif c.Passive && c.Active {\n\t\treturn errors.New(\"active enumeration cannot be performed without DNS resolution\")\n\t}\n\n\tc.Wordlist, err = ExpandMaskWordlist(c.Wordlist)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.AltWordlist, err = ExpandMaskWordlist(c.AltWordlist)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}\n\n// LoadSettings parses settings from an .yaml file and assigns them to the Config.\nfunc (c *Config) LoadSettings(path string) error {\n\t// Determine and store the absolute path of the config file\n\tabsolutePath, err := filepath.Abs(path)\n\tif err != nil {\n\t\t_ = c.LoadDatabaseEnvSettings()\n\t\t_ = c.LoadEngineEnvSettings()\n\t\treturn fmt.Errorf(\"failed to get absolute path of the configuration file: %v\", err)\n\t}\n\tc.Filepath = absolutePath\n\n\t// Open the configuration file\n\tdata, err := os.ReadFile(c.Filepath)\n\tif err != nil {\n\t\t_ = c.LoadDatabaseEnvSettings()\n\t\t_ = c.LoadEngineEnvSettings()\n\t\treturn fmt.Errorf(\"failed to load the main configuration file: %v\", err)\n\t}\n\n\terr = yaml.Unmarshal(data, c)\n\tif err != nil {\n\t\t_ = c.LoadDatabaseEnvSettings()\n\t\t_ = c.LoadEngineEnvSettings()\n\t\treturn fmt.Errorf(\"error mapping configuration settings to internal values: %v\", err)\n\t}\n\n\tif err := c.loadSeedandScopeSettings(); err != nil {\n\t\treturn err\n\t}\n\n\tloads := []func(cfg *Config) error{\n\t\tc.loadAlterationSettings,\n\t\tc.loadBruteForceSettings,\n\t\tc.loadDatabaseSettings,\n\t\tc.loadDataSourceSettings,\n\t\tc.loadResolverSettings,\n\t\tc.loadTransformSettings,\n\t\tc.loadEngineSettings,\n\t\tc.loadActiveSettings,\n\t\tc.loadRigidSettings,\n\t}\n\tfor _, load := range loads {\n\t\tif err := load(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// AbsPathFromConfigDir Creates a file path that is relative the the configuration file location.\n// If the path is already absolute, return it as is.\nfunc (c *Config) AbsPathFromConfigDir(path string) (string, error) {\n\t// If the path is already absolute, return it as is\n\tif filepath.IsAbs(path) {\n\t\t// Check if the file exists\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\treturn \"\", fmt.Errorf(\"file does not exist: %v\", err)\n\t\t}\n\n\t\treturn path, nil\n\t}\n\t// Get the directory of the current config file\n\tcfgDir := filepath.Dir(c.Filepath)\n\t// Clean the incoming path to ensure it doesn't have any problematic elements\n\tcleanPath := filepath.Clean(path)\n\t// Construct the absolute path by joining the config directory and the relative path\n\tabsPath := filepath.Join(cfgDir, cleanPath)\n\t// Check if the file exists\n\tif _, err := os.Stat(absPath); os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"file does not exist: %v\", err)\n\t}\n\treturn absPath, nil\n}\nfunc (s *Scope) toCIDRs(strings []string) []*net.IPNet {\n\tcidrs := make([]*net.IPNet, len(strings))\n\tfor i, str := range strings {\n\t\t_, cidr, _ := net.ParseCIDR(str)\n\t\tcidrs[i] = cidr\n\t}\n\treturn cidrs\n}\n\n// AcquireConfig populates the Config struct provided by the Config argument.\nfunc AcquireConfig(dir, file string, cfg *Config) error {\n\tvar path, dircfg, syscfg string\n\n\tcfg.Dir = OutputDirectory(dir)\n\tif finfo, err := os.Stat(cfg.Dir); cfg.Dir != \"\" && !os.IsNotExist(err) && finfo.IsDir() {\n\t\tdircfg = filepath.Join(cfg.Dir, defaultCfgFile)\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\tsyscfg = filepath.Join(filepath.Join(systemCfgDir, outputDirName), defaultCfgFile)\n\t}\n\n\tif file != \"\" {\n\t\tpath = file\n\t} else if f, set := os.LookupEnv(cfgEnvironVar); set {\n\t\tpath = f\n\t} else if _, err := os.Stat(dircfg); err == nil {\n\t\tpath = dircfg\n\t} else if _, err := os.Stat(syscfg); err == nil {\n\t\tpath = syscfg\n\t}\n\n\treturn cfg.LoadSettings(path)\n}\n\n// OutputDirectory returns the file path of the Amass output directory. A suitable\n// path provided will be used as the output directory instead.\nfunc OutputDirectory(dir ...string) string {\n\tif len(dir) > 0 && dir[0] != \"\" {\n\t\treturn dir[0]\n\t}\n\n\tif path, err := os.UserConfigDir(); err == nil {\n\t\treturn filepath.Join(path, outputDirName)\n\t}\n\n\treturn \"\"\n}\n\n// GetListFromFile reads a wordlist text or gzip file and returns the slice of words.\nfunc GetListFromFile(path string) ([]string, error) {\n\tvar reader io.Reader\n\n\tabsPath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get absolute path: %v\", err)\n\t}\n\n\tfile, err := os.Open(absPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening the file %s: %v\", absPath, err)\n\t}\n\tdefer func() { _ = file.Close() }()\n\treader = file\n\n\t// We need to determine if this is a gzipped file or a plain text file, so we\n\t// first read the first 512 bytes to pass them down to http.DetectContentType\n\t// for mime detection. The file is rewinded before passing it along to the\n\t// next reader\n\thead := make([]byte, 512)\n\tif _, err = file.Read(head); err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading the first 512 bytes from %s: %s\", absPath, err)\n\t}\n\tif _, err = file.Seek(0, 0); err != nil {\n\t\treturn nil, fmt.Errorf(\"error rewinding the file %s: %s\", absPath, err)\n\t}\n\n\t// Read the file as gzip if it's actually compressed\n\tif mt := http.DetectContentType(head); mt == \"application/gzip\" || mt == \"application/x-gzip\" {\n\t\tgzReader, err := gzip.NewReader(file)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error gz-reading the file %s: %v\", absPath, err)\n\t\t}\n\t\tdefer func() { _ = gzReader.Close() }()\n\t\treader = gzReader\n\t}\n\n\ts, err := getWordList(reader)\n\treturn s, err\n}\n\nfunc getWordList(reader io.Reader) ([]string, error) {\n\tvar words []string\n\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\t// Get the next word in the list\n\t\tw := strings.TrimSpace(scanner.Text())\n\t\tif err := scanner.Err(); err == nil && w != \"\" {\n\t\t\twords = append(words, w)\n\t\t}\n\t}\n\treturn stringset.Deduplicate(words), nil\n}\n\n// JSON returns the JSON encoding of the configuration without escaping HTML characters.\nfunc (c *Config) JSON() ([]byte, error) {\n\ttype Alias Config\n\tbuffer := &bytes.Buffer{}\n\tencoder := json.NewEncoder(buffer)\n\tencoder.SetEscapeHTML(false)\n\n\terr := encoder.Encode(&struct{ *Alias }{Alias: (*Alias)(c)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/config_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nfunc TestCheckSettings(t *testing.T) {\n\tc := NewConfig()\n\n\terr := c.CheckSettings()\n\n\tif err != nil {\n\t\tt.Errorf(\"Error checking settings.\\n%v\", err)\n\t}\n\n}\nfunc TestDomainRegex(t *testing.T) {\n\tc := NewConfig()\n\tgot := c.DomainRegex(\"owasp.org\")\n\n\tif got != nil {\n\t\tt.Errorf(\"Error with DomainRegex.\\n%v\", got)\n\t}\n}\n\nfunc TestAddDomains(t *testing.T) {\n\tc := NewConfig()\n\texample := \"owasp.org/test\"\n\tlist := []string{\"owasp.org\", \"google.com\", \"yahoo.com\"}\n\tc.AddDomains(list...)\n\tgot := c.Domains()\n\tsort.Strings(list)\n\tsort.Strings(got)\n\tc.AddDomains(list...)\n\n\tif !reflect.DeepEqual(list, got) {\n\t\tt.Errorf(\"Domains do not match.\\nWanted:%v\\nGot:%v\\n\", list, got)\n\t}\n\tt.Run(\"Testing AddDomain...\", func(t *testing.T) {\n\n\t\tc.AddDomain(example)\n\t\twant := true\n\t\tgot := false\n\t\tfor _, l := range c.Scope.Domains {\n\t\t\tif example == l {\n\t\t\t\tgot = true\n\t\t\t}\n\t\t}\n\t\tif got != want {\n\t\t\tt.Errorf(\"Expected:%v\\nGot:%v\", want, got)\n\t\t}\n\t\tt.Run(\"Testing Domains...\", func(t *testing.T) {\n\t\t\tif c.Domains() == nil {\n\t\t\t\tt.Errorf(\"No domains in current configuration.\")\n\t\t\t}\n\n\t\t\tif len(c.Domains()) <= 0 {\n\t\t\t\tt.Errorf(\"Failed to populate c.domains.\\nLength:%v\", len(c.Domains()))\n\t\t\t}\n\n\t\t})\n\n\t\tt.Run(\"Testing IsDomainInScope...\", func(t *testing.T) {\n\n\t\t\tif !c.IsDomainInScope(example) {\n\t\t\t\tt.Errorf(\"Domain is considered out of scope.\\nExample:%v\\nGot:%v,\\nWant:%v\", example, got, want)\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"Testing WhichDomain...\", func(t *testing.T) {\n\n\t\t\tif example != c.WhichDomain(example) {\n\t\t\t\tt.Errorf(\"Failed to find example.\\nExample:%v\\nGot:%v\", example, got)\n\t\t\t}\n\t\t})\n\t})\n}\n\nfunc TestIsAddressInScope(t *testing.T) {\n\tc := NewConfig()\n\tvar ipNet ParseIPs\n\n\t// Example string to use to convert the appropriate data type and populate c.Scope.IP\n\texample := \"192.0.2.1\"\n\t_ = ipNet.parseRange(example)\n\tc.Scope.Addresses = ipNet\n\n\tc.Scope.IP = append(c.Scope.IP, string(c.Scope.Addresses[0]))\n\tif !c.IsAddressInScope(example) {\n\t\tt.Errorf(\"Failed to find address %v in scope.\\nAddress List:%v\", example, c.Scope.Addresses)\n\t}\n}\n\nfunc TestBlacklist(t *testing.T) {\n\tc := NewConfig()\n\texample := \"owasp.org\"\n\tc.Scope.Blacklist = append(c.Scope.Blacklist, example)\n\tgot := c.Blacklisted(example)\n\twant := true\n\n\tif got != want {\n\t\tt.Errorf(\"Failed to find %v in blacklist.\", example)\n\t}\n}\n\nfunc TestConfigCheckSettings(t *testing.T) {\n\ttype fields struct {\n\t\tc *Config\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"brute-force & passive set\",\n\t\t\tfields: fields{\n\t\t\t\t&Config{BruteForcing: true, Passive: true},\n\t\t\t},\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"brute-force & empty wordlist - load default wordlist\",\n\t\t\tfields: fields{\n\t\t\t\t&Config{BruteForcing: true, Passive: false, Wordlist: []string{}},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"active & passive enumeration set\",\n\t\t\tfields: fields{\n\t\t\t\t&Config{Passive: true, Active: true},\n\t\t\t},\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"alterations set with empty alt-wordlist - load default alt-wordlist\",\n\t\t\tfields: fields{\n\t\t\t\t&Config{Alterations: true, AltWordlist: []string{}},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif err := tt.fields.c.CheckSettings(); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"Config.CheckSettings() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar configyaml = []byte(`\noptions:\n database: \"postgres://postgres:testPasWORD123456!)*&*$@localhost:5432\"\n`)\n\nfunc TestMarshalJSON(t *testing.T) {\n\tc := NewConfig()\n\n\t// Test case 1: MarshalJSON returns the expected JSON bytes\n\tt.Run(\"MarshalJSON returns the expected JSON bytes\", func(t *testing.T) {\n\t\texpected := []byte(`{\"seed\":{},\"scope\":{\"ports\":[80,443]},\"rigid_boundaries\":false,\"resolvers\":null,\"datasource_config\":{},\"transformations\":{}}\n`)\n\t\tgot, err := c.JSON()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(got, expected) {\n\t\t\tt.Errorf(\"Unexpected JSON bytes.\\nExpected: %s\\nGot: %s\", expected, got)\n\t\t}\n\t})\n\n\tif err := yaml.Unmarshal(configyaml, c); err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\tif err := c.loadDatabaseSettings(c); err != nil {\n\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t}\n\t// Test case 2: MarshalJSON unescapes HTML entities in the JSON bytes\n\tt.Run(\"MarshalJSON unescapes HTML entities in the JSON bytes\", func(t *testing.T) {\n\t\texpected := []byte(`{\"seed\":{},\"scope\":{\"ports\":[80,443]},\"database\":[{\"system\":\"postgres\",\"primary\":true,\"url\":\"postgres://postgres:testPasWORD123456!)*&*$@localhost:5432\",\"username\":\"postgres\",\"password\":\"testPasWORD123456!)*&*$\",\"host\":\"localhost\",\"port\":\"5432\"}],\"rigid_boundaries\":false,\"resolvers\":null,\"datasource_config\":{},\"transformations\":{}}\n`)\n\t\texpectedString := string(expected)\n\t\tgot, err := c.JSON()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\tgotString := string(got)\n\t\tif !reflect.DeepEqual(got, expected) {\n\t\t\tt.Errorf(\"Unexpected JSON bytes.\\nExpected: %s\\nGot: %s\", expected, got)\n\t\t}\n\t\tif gotString != expectedString {\n\t\t\tt.Errorf(\"Unexpected JSON string.\\nExpected: %s\\nGot: %s\", expectedString, gotString)\n\t\t}\n\t})\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/datasrcs.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\n// DataSource contains the configurations specific to a data source.\ntype DataSource struct {\n\tName string `yaml:\"name,omitempty\" json:\"name,omitempty\"`\n\tTTL int `yaml:\"ttl,omitempty\" json:\"ttl,omitempty\"`\n\tCreds map[string]*Credentials `yaml:\"creds,omitempty\" json:\"creds,omitempty\"`\n}\n\n// Credentials contains values required for authenticating with web APIs.\ntype Credentials struct {\n\tName string `yaml:\"-\" json:\"-\"`\n\tUsername string `yaml:\"username,omitempty\" json:\"username,omitempty\"`\n\tPassword string `yaml:\"password,omitempty\" json:\"password,omitempty\"`\n\tApikey string `yaml:\"apikey,omitempty\" json:\"apikey,omitempty\"`\n\tSecret string `yaml:\"secret,omitempty\" json:\"secret,omitempty\"`\n}\n\n// DataSourceConfig contains the configuration for multiple data sources.\ntype DataSourceConfig struct {\n\tDatasources []*DataSource `yaml:\"datasources,omitempty\" json:\"datasources,omitempty\"`\n\tGlobalOptions map[string]int `yaml:\"global_options,omitempty\" json:\"global_options,omitempty\"`\n}\n\n// GetDataSourceConfig returns the DataSourceConfig associated with the data source name argument.\nfunc (c *Config) GetDataSourceConfig(source string) *DataSource {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tkey := strings.ToLower(strings.TrimSpace(source))\n\tif key == \"\" || c.DataSrcConfigs == nil {\n\t\treturn nil\n\t}\n\n\tvar dsc *DataSource\n\tfor _, src := range c.DataSrcConfigs.Datasources {\n\t\tif strings.ToLower(src.Name) == key {\n\t\t\tdsc = src\n\t\t\tbreak\n\t\t}\n\t}\n\treturn dsc\n}\n\n// AddCredentials adds the Credentials provided to the configuration.\nfunc (ds *DataSource) AddCredentials(accountName string, cred *Credentials) error {\n\tif accountName == \"\" || ds == nil {\n\t\treturn fmt.Errorf(\"AddCredentials: The accountName argument is invalid\")\n\t}\n\n\tif ds.Creds == nil {\n\t\tds.Creds = make(map[string]*Credentials)\n\t}\n\n\tds.Creds[accountName] = cred\n\treturn nil\n}\n\n// GetCredentials returns the first set of Credentials associated with the given DataSource name.\nfunc (dsc *DataSourceConfig) GetCredentials(dsName string) *Credentials {\n\tif dsc == nil || dsc.Datasources == nil {\n\t\treturn nil\n\t}\n\n\tfor _, src := range dsc.Datasources {\n\t\tif src.Name == dsName && src.Creds != nil {\n\t\t\tfor _, creds := range src.Creds {\n\t\t\t\treturn creds // Return the first set of credentials found\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *Config) loadDataSourceSettings(cfg *Config) error {\n\t// Retrieve the datasources file path from the options\n\tpathInterface, ok := c.Options[\"datasources\"]\n\tif !ok {\n\t\t// \"datasources\" not found in options, so nothing to do here.\n\t\treturn nil\n\t}\n\n\tpath, ok := pathInterface.(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"datasources option is not a string\")\n\t}\n\t// Construct the absolute path by joining the current working directory and the relative path\n\tabsPath, err := c.AbsPathFromConfigDir(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get absolute path: %v\", err)\n\t}\n\t// Load the datasources YAML file\n\tdata, err := os.ReadFile(absPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading datasources file: %v\", err)\n\t}\n\t// Unmarshal the YAML data into a DataSourceConfig\n\tvar dsConfig DataSourceConfig\n\terr = yaml.Unmarshal(data, &dsConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error unmarshalling datasources YAML: %v\", err)\n\t}\n\n\tdsConfig.MapNames()\n\t// Assign the unmarshalled DataSourceConfig to the Config struct\n\tc.DataSrcConfigs = &dsConfig\n\tc.DataSrcConfigs.ttlCheck()\n\treturn nil\n}\n\nfunc (dsc *DataSourceConfig) ttlCheck() {\n\t// The global minimum TTL is already loaded during the YAML unmarshalling process\n\tfor _, ds := range dsc.Datasources {\n\t\t// Ensure the TTL is not less than the global minimum\n\t\tif dsc.GlobalOptions != nil {\n\t\t\tif minTTL, ok := dsc.GlobalOptions[\"minimum_ttl\"]; ok && minTTL > ds.TTL {\n\t\t\t\tds.TTL = dsc.GlobalOptions[\"minimum_ttl\"]\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// MapNames assigns the name of the DataSource to each associated Credential's Name field.\n// This is especially useful after unmarshalling data where the relationship between a DataSource and its\n// credentials may not have been explicitly set in the source data.\nfunc (dsc *DataSourceConfig) MapNames() {\n\t// Assign the DataSource name to each Credential's Name field in the Datasource\n\tfor _, src := range dsc.Datasources {\n\t\tif src.Creds == nil {\n\t\t\tsrc.Creds = make(map[string]*Credentials)\n\t\t}\n\n\t\tfor accountName, creds := range src.Creds {\n\t\t\tcreds.Name = src.Name\n\t\t\tsrc.Creds[accountName] = creds\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/datasrcs_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nfunc TestGetDataSourceConfig(t *testing.T) {\n\tc := NewConfig()\n\n\t// Scenario 1: Empty DataSourceConfig\n\tc.DataSrcConfigs = &DataSourceConfig{\n\t\tGlobalOptions: make(map[string]int),\n\t}\n\tif dsc := c.GetDataSourceConfig(\"nonexistent\"); dsc != nil {\n\t\tt.Errorf(\"GetDataSourceConfig returned a non-nil value when provided an nonexistent argument\")\n\t}\n\n\t// Scenario 2: DataSource with no creds\n\tnameNoCreds := \"testNoCreds\"\n\tc.DataSrcConfigs.Datasources = []*DataSource{\n\t\t{\n\t\t\tName: nameNoCreds,\n\t\t},\n\t}\n\tif dsc := c.GetDataSourceConfig(nameNoCreds); dsc == nil || dsc.Name != nameNoCreds {\n\t\tt.Errorf(\"GetDataSourceConfig returned an error when provided a valid argument with no creds\")\n\t}\n\n\t// Scenario 3: DataSource with empty creds\n\tnameEmptyCreds := \"testEmptyCreds\"\n\tcreds := make(map[string]*Credentials)\n\tc.DataSrcConfigs.Datasources = []*DataSource{\n\t\t{\n\t\t\tName: nameEmptyCreds,\n\t\t\tCreds: creds,\n\t\t},\n\t}\n\tif dsc := c.GetDataSourceConfig(nameEmptyCreds); dsc == nil || dsc.Name != nameEmptyCreds {\n\t\tt.Errorf(\"GetDataSourceConfig returned an error when provided a valid argument with empty creds\")\n\t}\n\n\t// Scenario 4: DataSource with creds\n\tnameWithCreds := \"testWithCreds\"\n\tcreds[\"key\"] = &Credentials{\n\t\tUsername: \"user\",\n\t\tPassword: \"pass\",\n\t}\n\tc.DataSrcConfigs.Datasources = []*DataSource{\n\t\t{\n\t\t\tName: nameWithCreds,\n\t\t\tCreds: creds,\n\t\t},\n\t}\n\tif dsc := c.GetDataSourceConfig(nameWithCreds); dsc == nil || dsc.Name != nameWithCreds {\n\t\tt.Errorf(\"GetDataSourceConfig returned an error when provided a valid argument with creds\")\n\t}\n}\n\nfunc TestAddCredentials(t *testing.T) {\n\tname := \"test\"\n\tc := NewConfig()\n\n\t// Add a DataSource to the Config object to use it in the test\n\tc.DataSrcConfigs = &DataSourceConfig{\n\t\tDatasources: []*DataSource{\n\t\t\t{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t}\n\n\tdsc := c.GetDataSourceConfig(name)\n\n\tif err := dsc.AddCredentials(\"account1\", &Credentials{Username: \"username\", Password: \"password\"}); err != nil {\n\t\tt.Errorf(\"AddCredentials returned an error when provided an valid arguments: %v\", err)\n\t}\n\n\tif dsc.Creds[\"account1\"].Username != \"username\" {\n\t\tt.Errorf(\"AddCredentials failed to enter the new credentials into the data source configuration\")\n\t}\n}\n\nfunc TestGetCredentials(t *testing.T) {\n\tc := NewConfig()\n\n\t// Add a DataSource with credentials to the Config object to use it in the test\n\tc.DataSrcConfigs = &DataSourceConfig{\n\t\tDatasources: []*DataSource{\n\t\t\t{\n\t\t\t\tName: \"test\",\n\t\t\t\tCreds: map[string]*Credentials{\n\t\t\t\t\t\"account1\": {\n\t\t\t\t\t\tUsername: \"username\",\n\t\t\t\t\t\tPassword: \"password\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tdsc := c.DataSrcConfigs\n\n\t// Pass the name of the data source when calling GetCredentials\n\tif creds := dsc.GetCredentials(\"test\"); creds == nil || creds.Username != \"username\" {\n\t\tt.Errorf(\"GetCredentials returned an error when provided a valid argument\")\n\t}\n}\n\nfunc TestLoadDataSourceSettings(t *testing.T) {\n\tc := NewConfig()\n\tymlData := `\ndatasources:\n - name: AlienVault\n ttl: 4320\n creds:\n account1:\n username: avuser\n password: avpass\n - name: BinaryEdge\n creds:\n account2:\n username: beuser\n password: bepass\nglobal_options:\n minimum_ttl: 1440\n`\n\tvar dsConfig DataSourceConfig\n\terr := yaml.Unmarshal([]byte(ymlData), &dsConfig)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to parse the data source settings: %v\", err)\n\t}\n\n\t// Assign the unmarshalled DataSourceConfig to the Config struct\n\tc.DataSrcConfigs = &dsConfig\n\n\tdsc := c.GetDataSourceConfig(\"AlienVault\")\n\tif dsc == nil {\n\t\tt.Errorf(\"Failed to load data source settings\")\n\t}\n\n\t// Pass the name of the data source when calling GetCredentials\n\tif creds := c.DataSrcConfigs.GetCredentials(\"AlienVault\"); creds == nil || creds.Username != \"avuser\" {\n\t\tt.Errorf(\"Failed to load data source credentials\")\n\t}\n\n\tif c.DataSrcConfigs.GlobalOptions[\"minimum_ttl\"] != 1440 {\n\t\tt.Errorf(\"Failed to load global options\")\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/engineapi.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n)\n\n// EngAPI structure holds various components necessary for establishing a connection with an Engine API.\n// It includes fields for the scheme (http or https), the full API URL, authentication credentials (username, password),\n// host and port information, the specific path (name) of the API, and any extra options that may be used during the connection.\ntype EngAPI struct {\n\tScheme string // Engine API scheme (http, https)\n\tURL string // Full URI to the Engine API\n\tUsername string // Username for authentication\n\tPassword string // Password for authentication\n\tHost string // Host of the Engine API\n\tPort string // Port of the Engine API\n\tPath string // Name of the Engine API\n\tOptions string // Extra options used while connecting to the Engine API\n}\n\nconst (\n\tengineUser = \"AMASS_ENGINE_USER\"\n\tenginePass = \"AMASS_ENGINE_PASSWORD\"\n\tengineHost = \"AMASS_ENGINE_HOST\"\n\tenginePort = \"AMASS_ENGINE_PORT\"\n\tenginePath = \"AMASS_ENGINE_PATH\"\n\tengineScheme = \"AMASS_ENGINE_SCHEME\"\n)\n\n// loadEngineSettings is responsible for extracting the \"engine\" URL from the application's configuration\n// and initializing the EngAPI structure. It performs several checks such as ensuring the configuration options\n// are initialized and the \"engine\" key is present and of type string. If any of these checks fail, an error is returned.\nfunc (c *Config) loadEngineSettings(cfg *Config) error {\n\t// Check if configuration options are initialized; if not, return an error.\n\tif c.Options == nil {\n\t\treturn fmt.Errorf(\"config options are not initialized\")\n\t}\n\t// Attempt to retrieve the \"engine\" value from the configuration options.\n\tapiURIInterface, ok := c.Options[\"engine\"]\n\tif !ok {\n\t\treturn c.LoadEngineEnvSettings()\n\t}\n\t// Assert that the \"engine\" option is of type string; if not, return an error specifying the incorrect type received.\n\tapiURI, ok := apiURIInterface.(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"expected 'engine' to be a string, got %T\", apiURIInterface)\n\t}\n\t// Load the Engine API URI information into the EngAPI structure.\n\t// If there's an error during this process, it's returned to the calling function.\n\tif err := c.loadEngineURI(apiURI); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// LoadEngineEnvSettings initializes the EngAPI structure with the Environment variables.\nfunc (c *Config) LoadEngineEnvSettings() error {\n\tapiURI := \"\"\n\teng := &EngAPI{}\n\n\th := \"localhost\"\n\tif henv, set := os.LookupEnv(engineHost); set {\n\t\th = henv\n\t}\n\teng.Host = h\n\tu := \"\"\n\tif uEnv, set := os.LookupEnv(engineUser); set {\n\t\teng.Username = uEnv\n\t\tu = uEnv + \"@\"\n\t}\n\tp := \"\"\n\tif penv, set := os.LookupEnv(enginePass); set {\n\t\teng.Password = penv\n\t\tp = \":\" + penv + \"@\"\n\t}\n\tscheme := \"http\"\n\tif s, set := os.LookupEnv(engineScheme); set {\n\t\tscheme = s\n\t}\n\teng.Scheme = scheme\n\tport := \"4000\"\n\tif pEnv, set := os.LookupEnv(enginePort); set {\n\t\tport = pEnv\n\t}\n\teng.Port = port\n\tpath := \"graphql\"\n\tif pEnv, set := os.LookupEnv(enginePath); set {\n\t\tpath = pEnv\n\t}\n\teng.Path = path\n\tif p != \"\" {\n\t\tu = u[:len(u)-1]\n\t}\n\tapiURI = scheme + \"://\" + u + p + h + \":\" + port + \"/\" + path\n\teng.URL = apiURI\n\n\tc.EngineAPI = eng\n\treturn nil\n}\n\n// loadEngineURI takes the Engine API's URI as a string, parses it, and populates the EngAPI structure with the URI's components.\n// It performs validations to ensure the URI contains a valid scheme and hostname. If parsing fails or any validation check doesn't pass,\n// an error is returned. It also handles extracting authentication information and any additional options provided in the URI query.\nfunc (c *Config) loadEngineURI(apiURI string) error {\n\t// Parse the raw URI string to a url.URL object. If the URI is malformed, an error is returned.\n\tu, err := url.Parse(apiURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check for valid scheme\n\tif u.Scheme == \"\" {\n\t\treturn fmt.Errorf(\"missing scheme in database URI\")\n\t}\n\t// Check for reachable hostname\n\tif u.Hostname() == \"\" {\n\t\treturn fmt.Errorf(\"missing hostname in database URI\")\n\t}\n\t// If the path is present in the URI and is more than just a \"/\", it's trimmed and used.\n\t// If the path is empty or just a \"/\", it defaults to an empty string.\n\tapiURIPath := \"\"\n\t// Only get the api file path name if it's not empty or a single slash\n\tif u.Path != \"\" && u.Path != \"/\" {\n\t\tapiURIPath = strings.TrimPrefix(u.Path, \"/\")\n\t}\n\t// Initialize a new EngAPI object with data from the parsed URI.\n\tapi := &EngAPI{\n\t\tURL: apiURI,\n\t\tScheme: u.Scheme,\n\t\tUsername: u.User.Username(),\n\t\tPath: apiURIPath,\n\t\tHost: u.Hostname(), // Hostname without port\n\t\tPort: u.Port(), // Get port\n\t}\n\t// If a password is set in the URI, it's extracted and stored in the EngAPI object.\n\tpassword, isSet := u.User.Password()\n\tif isSet {\n\t\tapi.Password = password\n\t}\n\t// If there are query parameters present in the URI, they are parsed and encoded as a string,\n\t// then stored in the EngAPI object's Options field. If parsing fails, an error is returned.\n\tif u.RawQuery != \"\" {\n\t\tqueryParams, err := url.ParseQuery(u.RawQuery)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse engine API URI query parameters: %v\", err)\n\t\t}\n\t\tapi.Options = queryParams.Encode() // Encode url.Values to a string\n\t}\n\t// The Config's EngineAPI field is set to the newly created EngAPI object.\n\tc.EngineAPI = api\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/engineapi_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"gopkg.in/yaml.v3\"\n)\n\n// Valid mock YAML configuration for testing\nvar validMockConfigYAML = []byte(`\noptions:\n engine: \"http://username:password@127.0.0.1:80/path?option1=value1\"\n`)\n\n// Invalid mock YAML configuration (non-string engine value)\nvar invalidTypeMockConfigYAML = []byte(`\noptions:\n engine: 123\n`)\n\n// Invalid mock YAML configuration (malformed YAML)\nvar malformedMockConfigYAML = []byte(`\n\toptions\n engine \"http://username:password@127.0.0.1:80/path?option1=value1\"\n`)\n\nfunc TestLoadEngineSettings_ValidConfig(t *testing.T) {\n\tc := NewConfig()\n\n\terr := yaml.Unmarshal(validMockConfigYAML, &c)\n\trequire.NoError(t, err, \"Unmarshalling valid YAML should not produce an error\")\n\n\terr = c.loadEngineSettings(c)\n\tassert.NoError(t, err, \"loadEngineSettings should not return an error with valid config\")\n\tassert.NotNil(t, c.EngineAPI, \"EngineAPI should not be nil after loading settings\")\n}\n\nfunc TestLoadEngineSettings_InvalidType(t *testing.T) {\n\tc := NewConfig()\n\n\terr := yaml.Unmarshal(invalidTypeMockConfigYAML, &c)\n\trequire.NoError(t, err, \"Unmarshalling invalid type YAML should not produce an error\")\n\n\terr = c.loadEngineSettings(c)\n\tassert.Error(t, err, \"loadEngineSettings should return an error if 'engine' type is not string\")\n}\n\nfunc TestLoadEngineSettings_MalformedYAML(t *testing.T) {\n\tc := NewConfig()\n\n\terr := yaml.Unmarshal(malformedMockConfigYAML, &c)\n\tassert.Error(t, err, \"Unmarshalling malformed YAML should produce an error\")\n}\n\nfunc TestLoadEngineURI_ValidURI(t *testing.T) {\n\tc := NewConfig()\n\n\terr := yaml.Unmarshal(validMockConfigYAML, &c)\n\trequire.NoError(t, err, \"Unmarshalling valid YAML should not produce an error\")\n\n\t_ = c.loadEngineSettings(c)\n\n\tassert.Equal(t, \"http\", c.EngineAPI.Scheme, \"Scheme should be 'http'\")\n\tassert.Equal(t, \"username\", c.EngineAPI.Username, \"Username should be 'username'\")\n\tassert.Equal(t, \"password\", c.EngineAPI.Password, \"Password should be 'password'\")\n\tassert.Equal(t, \"127.0.0.1\", c.EngineAPI.Host, \"Host should be 'hostname'\")\n\tassert.Equal(t, \"80\", c.EngineAPI.Port, \"Port should be 'port'\")\n\tassert.Equal(t, \"path\", c.EngineAPI.Path, \"Path should be 'path'\")\n\tassert.Equal(t, \"option1=value1\", c.EngineAPI.Options, \"Options should be 'option1=value1'\")\n}\n\nfunc TestLoadEngineURI_InvalidURI(t *testing.T) {\n\tc := NewConfig()\n\n\t// Set 'engine' option to an invalid URI\n\tc.Options[\"engine\"] = \"http:://invalid-uri\"\n\n\terr := c.loadEngineSettings(c)\n\tassert.Error(t, err, \"loadEngineSettings should return an error for invalid URI\")\n}\n\nfunc TestLoadEngineURI_MissingScheme(t *testing.T) {\n\tc := NewConfig()\n\n\t// Set 'engine' option to a URI missing a scheme\n\tc.Options[\"engine\"] = \"username:password@hostname:port/path?option1=value1\"\n\n\terr := c.loadEngineSettings(c)\n\tassert.Error(t, err, \"loadEngineSettings should return an error for missing scheme in URI\")\n}\nfunc TestLoadEngineEnvSettings_ValidEnvSettings(t *testing.T) {\n\tc := NewConfig()\n\n\t// Set the required environment variables\n\t_ = os.Setenv(engineHost, \"127.0.0.1\")\n\t_ = os.Setenv(engineUser, \"username\")\n\t_ = os.Setenv(enginePass, \"password\")\n\t_ = os.Setenv(engineScheme, \"http\")\n\t_ = os.Setenv(enginePort, \"80\")\n\t_ = os.Setenv(enginePath, \"path\")\n\n\terr := c.LoadEngineEnvSettings()\n\tassert.NoError(t, err, \"LoadEngineEnvSettings should not return an error with valid environment settings\")\n\tassert.NotNil(t, c.EngineAPI, \"EngineAPI should not be nil after loading environment settings\")\n\n\t// Verify the loaded EngineAPI values\n\tassert.Equal(t, \"http\", c.EngineAPI.Scheme, \"Scheme should be 'http'\")\n\tassert.Equal(t, \"username\", c.EngineAPI.Username, \"Username should be 'username'\")\n\tassert.Equal(t, \"password\", c.EngineAPI.Password, \"Password should be 'password'\")\n\tassert.Equal(t, \"127.0.0.1\", c.EngineAPI.Host, \"Host should be '127.0.0.1'\")\n\tassert.Equal(t, \"80\", c.EngineAPI.Port, \"Port should be '80'\")\n\tassert.Equal(t, \"path\", c.EngineAPI.Path, \"Path should be 'path'\")\n}\n\nfunc TestLoadEngineEnvSettings_MissingEnvSettings(t *testing.T) {\n\tc := NewConfig()\n\n\t// Unset the required environment variables\n\t_ = os.Unsetenv(engineHost)\n\t_ = os.Unsetenv(engineUser)\n\t_ = os.Unsetenv(enginePass)\n\t_ = os.Unsetenv(engineScheme)\n\t_ = os.Unsetenv(enginePort)\n\t_ = os.Unsetenv(enginePath)\n\n\terr := c.LoadEngineEnvSettings()\n\t_ = c.loadEngineURI(c.EngineAPI.URL)\n\tassert.Nil(t, err, \"LoadEngineEnvSettings shouldn't return an error since default values are in place\")\n\tassert.NotEmpty(t, c.EngineAPI, \"EngineAPI should be properly populated\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/graphdb.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"strings\"\n)\n\n// Database contains values required for connecting with graph database.\ntype Database struct {\n\tSystem string `json:\"system,omitempty\"` // Database system type (Postgres, MySQL, etc.)\n\tPrimary bool `json:\"primary,omitempty\"` // Whether this database is the primary store\n\tURL string `json:\"url,omitempty\"` // Full URI to the database\n\tUsername string `json:\"username,omitempty\"` // Username for authentication\n\tPassword string `json:\"password,omitempty\"` // Password for authentication\n\tHost string `json:\"host,omitempty\"` // Host of the database\n\tPort string `json:\"port,omitempty\"` // Port of the database\n\tDBName string `json:\"db_name,omitempty\"` // Name of the database\n\tOptions string `json:\"options,omitempty\"` // Extra options used while connecting to the database\n}\n\nconst (\n\tamassUser = \"AMASS_DB_USER\"\n\tamassPass = \"AMASS_DB_PASSWORD\"\n\tassetDB = \"AMASS_DB_HOST\"\n\tassetPort = \"AMASS_DB_PORT\"\n\tassetDBName = \"AMASS_DB_NAME\"\n)\n\nfunc (c *Config) loadDatabaseSettings(cfg *Config) error {\n\tif c.Options == nil {\n\t\treturn fmt.Errorf(\"config options are not initialized\")\n\t}\n\n\tdbURIInterface, ok := c.Options[\"database\"]\n\tif !ok {\n\t\tif err := c.LoadDatabaseEnvSettings(); err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tdbURI, ok := dbURIInterface.(string)\n\tif !ok {\n\t\treturn fmt.Errorf(\"expected 'database' to be a string, got %T\", dbURIInterface)\n\t}\n\n\tif _, err := url.Parse(dbURI); err == nil {\n\t\tif err := c.loadDatabase(dbURI); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// LoadDatabaseEnvSettings initializes the DB structure with the Environment variables.\nfunc (c *Config) LoadDatabaseEnvSettings() error {\n\tdbURI := \"\"\n\tdb := &Database{\n\t\tPrimary: true,\n\t\tSystem: \"postgres\",\n\t}\n\n\tvar u string\n\tif uenv, set := os.LookupEnv(amassUser); set {\n\t\tu = uenv\n\t} else {\n\t\treturn fmt.Errorf(\"environment variable %s is not set\", amassUser)\n\t}\n\tdb.Username = u\n\th := \"localhost\"\n\tif dbEnv, set := os.LookupEnv(assetDB); set {\n\t\th = dbEnv\n\t}\n\tdb.Host = h\n\tport := \"5432\"\n\tif pEnv, set := os.LookupEnv(assetPort); set {\n\t\tport = pEnv\n\t}\n\tdb.Port = port\n\tn := \"assetdb\"\n\tif nEnv, set := os.LookupEnv(assetDBName); set {\n\t\tn = nEnv\n\t}\n\tdb.DBName = n\n\tif p, set := os.LookupEnv(amassPass); set {\n\t\tdb.Password = p\n\t\tdbURI = \"postgres://\" + u + \":\" + p + \"@\" + h + \":\" + port + \"/\" + n\n\t} else {\n\t\tdbURI = \"postgres://\" + u + \"@\" + h + \":\" + port + \"/\" + n\n\t}\n\tdb.URL = dbURI\n\tif c.GraphDBs == nil {\n\t\tc.GraphDBs = make([]*Database, 0)\n\t}\n\tc.GraphDBs = append(c.GraphDBs, db)\n\treturn nil\n}\n\nfunc (c *Config) loadDatabase(dbURI string) error {\n\tu, err := url.Parse(dbURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check for valid scheme (database type)\n\tif u.Scheme == \"\" {\n\t\treturn fmt.Errorf(\"missing scheme in database URI\")\n\t}\n\t// Check for non-empty username\n\tif u.User == nil || u.User.Username() == \"\" {\n\t\treturn fmt.Errorf(\"missing username in database URI\")\n\t}\n\t// Check for reachable hostname\n\tif u.Hostname() == \"\" {\n\t\treturn fmt.Errorf(\"missing hostname in database URI\")\n\t}\n\n\tdbName := \"\"\n\t// Only get the database name if it's not empty or a single slash\n\tif u.Path != \"\" && u.Path != \"/\" {\n\t\tdbName = strings.TrimPrefix(u.Path, \"/\")\n\t}\n\n\tdb := &Database{\n\t\tPrimary: true, // Set as primary, because it wouldn't be there otherwise.\n\t\tURL: dbURI,\n\t\tSystem: u.Scheme,\n\t\tUsername: u.User.Username(),\n\t\tDBName: dbName,\n\t\tHost: u.Hostname(), // Hostname without port\n\t\tPort: u.Port(), // Get port\n\t}\n\n\tpassword, isSet := u.User.Password()\n\tif isSet {\n\t\tdb.Password = password\n\t}\n\n\tif u.RawQuery != \"\" {\n\t\tqueryParams, err := url.ParseQuery(u.RawQuery)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse database URI query parameters: %v\", err)\n\t\t}\n\t\tdb.Options = queryParams.Encode() // Encode url.Values to a string\n\t}\n\n\tif c.GraphDBs == nil {\n\t\tc.GraphDBs = make([]*Database, 0)\n\t}\n\tc.GraphDBs = append(c.GraphDBs, db)\n\n\treturn nil\n}\n\n// LocalDatabaseSettings returns the Database for the local bolt store.\nfunc (c *Config) LocalDatabaseSettings(dbs []*Database) *Database {\n\tbolt := &Database{\n\t\tSystem: \"local\",\n\t\tPrimary: true,\n\t\tURL: OutputDirectory(c.Dir),\n\t}\n\n\tfor _, db := range dbs {\n\t\tif db != nil && db.Primary {\n\t\t\tbolt.Primary = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn bolt\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/graphdb_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestLoadDatabaseSettings(t *testing.T) {\n\t// Test with no database in options\n\tc := NewConfig()\n\tc.Options = make(map[string]interface{})\n\terr := c.loadDatabaseSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when no database is provided, expected nil. Error: %v\", err)\n\t}\n\n\t// Test with invalid type in database\n\tc = NewConfig()\n\tc.Options = make(map[string]interface{})\n\tc.Options[\"database\"] = 1234\n\terr = c.loadDatabaseSettings(c)\n\tif err == nil {\n\t\tt.Errorf(\"Expected an error when database is not a string or array of strings, got nil\")\n\t}\n\n\t// Test with invalid URI\n\tc = NewConfig()\n\tc.Options = make(map[string]interface{})\n\tc.Options[\"database\"] = \"not a valid URI\"\n\terr = c.loadDatabaseSettings(c)\n\tif err == nil {\n\t\tt.Errorf(\"Expected an error when database is not a valid URI, got nil\")\n\t}\n\n\t// Test with valid URI without password but with database name\n\tc = NewConfig()\n\tc.Options = make(map[string]interface{})\n\tc.Options[\"database\"] = \"mysql://username@localhost/mydatabase\"\n\terr = c.loadDatabaseSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid database is provided, expected nil. Error: %v\", err)\n\t}\n\n\tif len(c.GraphDBs) != 1 {\n\t\tt.Errorf(\"Expected GraphDBs to have one element, got %v\", len(c.GraphDBs))\n\t} else {\n\t\tdb := c.GraphDBs[0]\n\t\tif db.Username != \"username\" || db.System != \"mysql\" || db.URL != \"mysql://username@localhost/mydatabase\" {\n\t\t\tt.Errorf(\"Database struct does not match expected values after loading valid database without password and path\")\n\t\t}\n\t}\n\n\t// Test with valid URI with password and path\n\tc = NewConfig()\n\tc.Options = make(map[string]interface{})\n\tc.Options[\"database\"] = \"postgres://username:password@localhost:5432/database?sslmode=disable\"\n\terr = c.loadDatabaseSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid database is provided, expected nil. Error: %v\", err)\n\t}\n\n\tif len(c.GraphDBs) != 1 {\n\t\tt.Errorf(\"Expected GraphDBs to have one element, got %v\", len(c.GraphDBs))\n\t} else {\n\t\tdb := c.GraphDBs[0]\n\t\tif db.Username != \"username\" || db.Password != \"password\" || db.System != \"postgres\" ||\n\t\t\tdb.URL != \"postgres://username:password@localhost:5432/database?sslmode=disable\" || db.DBName != \"database\" || db.Options != \"sslmode=disable\" {\n\t\t\tt.Errorf(\"Database struct does not match expected values after loading valid database with password and path\")\n\t\t}\n\t}\n}\n\nfunc TestLocalDatabaseSettings(t *testing.T) {\n\tc := NewConfig()\n\tc.Dir = \"/tmp\" // Set the directory to a known value for testing.\n\n\t// Scenario 1: Test with no primary database in the slice.\n\tdbs := []*Database{\n\t\t{System: \"remote\", Primary: false},\n\t\t{System: \"another_remote\", Primary: false},\n\t}\n\tlocalDB := c.LocalDatabaseSettings(dbs)\n\tif localDB.Primary != true {\n\t\tt.Errorf(\"Expected localDB.Primary to be true when no primary database is in the slice, got false\")\n\t}\n\tif localDB.URL != OutputDirectory(\"/tmp\") {\n\t\tt.Errorf(\"Expected localDB.URL to be %s, got %s\", OutputDirectory(\"/tmp\"), localDB.URL)\n\t}\n\n\t// Scenario 2: Test with a primary database in the slice.\n\tdbs = []*Database{\n\t\t{System: \"remote\", Primary: false},\n\t\t{System: \"another_remote\", Primary: true},\n\t}\n\tlocalDB = c.LocalDatabaseSettings(dbs)\n\tif localDB.Primary != false {\n\t\tt.Errorf(\"Expected localDB.Primary to be false when a primary database is in the slice, got true\")\n\t}\n}\nfunc TestLoadDatabaseEnvSettings(t *testing.T) {\n\tc := NewConfig()\n\n\t// Scenario 1: Test with valid environment variables\n\t_ = os.Setenv(amassUser, \"the_inceptions\")\n\t_ = os.Setenv(amassPass, \"was_here\")\n\t_ = os.Setenv(assetDB, \"192.168.24.14\")\n\t_ = os.Setenv(assetPort, \"5432\")\n\t_ = os.Setenv(assetDBName, \"inceptionsdb\")\n\n\terr := c.LoadDatabaseEnvSettings()\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid environment variables are set, expected nil. Error: %v\", err)\n\t}\n\n\texpectedDBURI := \"postgres://the_inceptions:was_here@192.168.24.14:5432/inceptionsdb\"\n\tif c.GraphDBs[0].URL != expectedDBURI {\n\t\tt.Errorf(\"Expected DB URI to be %s, got %s\", expectedDBURI, c.GraphDBs[0].URL)\n\t}\n\n\t// Clean up environment variables\n\t_ = os.Unsetenv(amassUser)\n\t_ = os.Unsetenv(amassPass)\n\t_ = os.Unsetenv(assetDB)\n\t_ = os.Unsetenv(assetPort)\n\t_ = os.Unsetenv(assetDBName)\n\n\t// // Scenario 2: Test with just the user environment variables\n\t_ = os.Setenv(amassUser, \"the_inceptions\")\n\terr = c.LoadDatabaseEnvSettings()\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when only the user environment variable is set, expected nil. Error: %v\", err)\n\t}\n\n\texpectedDBURI = \"postgres://the_inceptions@localhost:5432/assetdb\"\n\tif c.GraphDBs[1].URL != expectedDBURI {\n\t\tt.Errorf(\"Expected DB URI to be %s, got %s\", expectedDBURI, c.GraphDBs[0].URL)\n\t}\n\n\t// Clean up environment variables\n\t_ = os.Unsetenv(amassUser)\n\n\t// // Scenario 3: Test with no environment variables\n\terr = c.LoadDatabaseEnvSettings()\n\tif err.Error() != \"environment variable AMASS_DB_USER is not set\" {\n\t\tt.Errorf(\"Expected a different error, got: %v\", err)\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/resolvers.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"context\"\n\t\"encoding/csv\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n)\n\n// DefaultQueriesPerPublicResolver is the number of queries sent to each public DNS resolver per second.\nconst DefaultQueriesPerPublicResolver = 5\n\n// DefaultQueriesPerBaselineResolver is the number of queries sent to each trusted DNS resolver per second.\nconst DefaultQueriesPerBaselineResolver = 15\nconst minResolverReliability = 0.85\n\n// DefaultBaselineResolvers is a list of trusted public DNS resolvers.\nvar DefaultBaselineResolvers = []string{\n\t\"8.8.8.8\", // Google\n\t\"1.1.1.1\", // Cloudflare\n\t\"9.9.9.9\", // Quad9\n\t\"208.67.222.222\", // Cisco OpenDNS\n\t\"84.200.69.80\", // DNS.WATCH\n\t\"64.6.64.6\", // Neustar DNS\n\t\"8.26.56.26\", // Comodo Secure DNS\n\t\"205.171.3.65\", // Level3\n\t\"134.195.4.2\", // OpenNIC\n\t\"185.228.168.9\", // CleanBrowsing\n\t\"76.76.19.19\", // Alternate DNS\n\t\"37.235.1.177\", // FreeDNS\n\t\"77.88.8.1\", // Yandex.DNS\n\t\"94.140.14.140\", // AdGuard\n\t\"38.132.106.139\", // CyberGhost\n\t\"74.82.42.42\", // Hurricane Electric\n\t\"76.76.2.0\", // ControlD\n}\n\n// PublicResolvers includes the addresses of public resolvers obtained dynamically.\nvar PublicResolvers []string\n\n// GetPublicDNSResolvers obtains the public DNS server addresses from public-dns.info and assigns them to PublicResolvers.\nfunc GetPublicDNSResolvers() error {\n\turl := \"https://public-dns.info/nameservers-all.csv\"\n\tresp, err := http.RequestWebPage(context.Background(), &http.Request{URL: url})\n\tif err != nil || resp.StatusCode < 200 || resp.StatusCode >= 400 {\n\t\treturn fmt.Errorf(\"failed to obtain the Public DNS csv file at %s: %v\", url, err)\n\t}\n\n\tvar resolvers []string\n\tvar ipIdx, reliabilityIdx int\n\tr := csv.NewReader(strings.NewReader(resp.Body))\n\tfor i := 0; ; i++ {\n\t\trecord, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tfor idx, val := range record {\n\t\t\t\tswitch val {\n\t\t\t\tcase \"ip_address\":\n\t\t\t\t\tipIdx = idx\n\t\t\t\tcase \"reliability\":\n\t\t\t\t\treliabilityIdx = idx\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif rel, err := strconv.ParseFloat(record[reliabilityIdx], 64); err == nil && rel >= minResolverReliability {\n\t\t\tresolvers = append(resolvers, record[ipIdx])\n\t\t}\n\t}\nloop:\n\tfor _, addr := range resolvers {\n\t\tfor _, br := range DefaultBaselineResolvers {\n\t\t\tif addr == br {\n\t\t\t\tcontinue loop\n\t\t\t}\n\t\t}\n\t\tPublicResolvers = append(PublicResolvers, addr)\n\t}\n\treturn nil\n}\n\n// SetResolvers assigns the untrusted resolver names provided in the parameter to the list in the configuration.\nfunc (c *Config) SetResolvers(resolvers ...string) {\n\tc.Resolvers = []string{}\n\tc.AddResolvers(resolvers...)\n}\n\n// AddResolvers appends the untrusted resolver names provided in the parameter to the list in the configuration.\nfunc (c *Config) AddResolvers(resolvers ...string) {\n\tfor _, r := range resolvers {\n\t\tc.AddResolver(r)\n\t}\n\tc.CalcMaxQPS()\n}\n\n// AddResolver appends the untrusted resolver name provided in the parameter to the list in the configuration.\nfunc (c *Config) AddResolver(resolver string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\t// Check that the domain string is not empty\n\tr := strings.TrimSpace(resolver)\n\tif r == \"\" {\n\t\treturn\n\t}\n\n\tc.Resolvers = stringset.Deduplicate(append(c.Resolvers, resolver))\n}\n\n// SetTrustedResolvers assigns the trusted resolver names provided in the parameter to the list in the configuration.\nfunc (c *Config) SetTrustedResolvers(resolvers ...string) {\n\tc.Resolvers = []string{}\n\tc.AddResolvers(resolvers...)\n}\n\n// AddTrustedResolvers appends the trusted resolver names provided in the parameter to the list in the configuration.\nfunc (c *Config) AddTrustedResolvers(resolvers ...string) {\n\tfor _, r := range resolvers {\n\t\tc.AddTrustedResolver(r)\n\t}\n\tc.CalcMaxQPS()\n}\n\n// AddTrustedResolver appends the trusted resolver name provided in the parameter to the list in the configuration.\nfunc (c *Config) AddTrustedResolver(resolver string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\t// Check that the domain string is not empty\n\tr := strings.TrimSpace(resolver)\n\tif r == \"\" {\n\t\treturn\n\t}\n\n\tc.TrustedResolvers = stringset.Deduplicate(append(c.TrustedResolvers, resolver))\n}\n\n// CalcMaxQPS updates the MaxDNSQueries field of the configuration based on current settings.\nfunc (c *Config) CalcMaxQPS() {\n\tc.MaxDNSQueries = (len(c.Resolvers) * c.ResolversQPS) + (len(c.TrustedResolvers) * c.TrustedQPS)\n}\n\nfunc (c *Config) loadResolverSettings(cfg *Config) error {\n\t// Fetch resolvers from the Options map in the Config.\n\tresolversRaw, ok := c.Options[\"resolvers\"]\n\tif !ok {\n\t\t// \"resolvers\" not found in options, so nothing to do here.\n\t\treturn nil\n\t}\n\n\t// Type assert the raw resolvers to []interface{}\n\tresolvers, ok := resolversRaw.([]interface{})\n\tif !ok {\n\t\treturn errors.New(\"resolvers section is not a list\")\n\t}\n\n\tvar resolversList []string\n\tfor _, r := range resolvers {\n\t\t// Type assert the resolver to string\n\t\trStr, ok := r.(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"resolver entry %v is not a string\", r)\n\t\t}\n\n\t\t// Check if rStr is an IP address.\n\t\tip := net.ParseIP(rStr)\n\t\tif ip != nil {\n\t\t\tresolversList = append(resolversList, rStr)\n\t\t\tcontinue\n\t\t}\n\n\t\t// rStr is not an IP address, so we assume it is a file path.\n\t\tabsPath, err := c.AbsPathFromConfigDir(rStr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get absolute path for resolver file: %w\", err)\n\t\t}\n\n\t\tfileResolvers, err := c.loadResolversFromFile(absPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load resolvers from file: %w\", err)\n\t\t}\n\n\t\tresolversList = append(resolversList, fileResolvers...)\n\n\t}\n\n\t// Deduplicate the list of resolvers and assign to c.Resolvers.\n\tresolverIPs := stringset.Deduplicate(resolversList)\n\n\tif len(resolverIPs) == 0 {\n\t\treturn errors.New(\"no valid resolvers were found\")\n\t}\n\n\tc.Resolvers = resolverIPs\n\n\treturn nil\n}\n\nfunc (c *Config) loadResolversFromFile(path string) ([]string, error) {\n\tabsPath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get absolute path: %v\", err)\n\t}\n\n\tdata, err := os.ReadFile(absPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open resolvers file: %w\", err)\n\t}\n\n\t// Split the file data by newlines to get the IP addresses.\n\tlines := strings.Split(string(data), \"\\n\")\n\n\tvar resolvers []string\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\t// Skip empty lines.\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check if each line in the file is a valid IP address.\n\t\tip := net.ParseIP(line)\n\t\tif ip == nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid IP address in resolvers file: %s\", line)\n\t\t}\n\n\t\tresolvers = append(resolvers, line)\n\t}\n\n\treturn resolvers, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/resolvers_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestConfigSetResolvers(t *testing.T) {\n\ttype fields struct {\n\t\tconfig *Config\n\t}\n\ttype args struct {\n\t\tresolvers []string\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfields fields\n\t\targs args\n\t}{\n\t\t{\n\t\t\tname: \"success\",\n\t\t\tfields: fields{config: &Config{}},\n\t\t\targs: args{\n\t\t\t\tresolvers: []string{\"127.0.0.1\", \"127.0.0.2\", \"127.0.0.3\"},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttt.fields.config.SetResolvers(tt.args.resolvers...)\n\n\t\t\tsort.Strings(tt.fields.config.Resolvers)\n\t\t\tif !reflect.DeepEqual(tt.args.resolvers, tt.fields.config.Resolvers) {\n\t\t\t\tt.Errorf(\"SetResolvers() = %v, want %v\",\n\t\t\t\t\ttt.args.resolvers, tt.fields.config.Resolvers)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLoadResolverSettings(t *testing.T) {\n\tc := NewConfig()\n\tc.Options = make(map[string]interface{})\n\n\t// Test with no resolvers in options\n\terr := c.loadResolverSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error when no resolvers are provided, got an error\")\n\t}\n\n\t// Test with incorrect type in resolvers\n\tc.Options[\"resolvers\"] = \"Not a slice\"\n\terr = c.loadResolverSettings(c)\n\tif err == nil {\n\t\tt.Errorf(\"Expected an error when resolvers are not a slice, got nil\")\n\t}\n\n\t// Test with valid resolvers\n\tc.Options[\"resolvers\"] = []interface{}{\"192.0.2.1\", \"192.0.2.2\"}\n\terr = c.loadResolverSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid resolvers are provided, expected nil. Error: %v\", err)\n\t}\n\n\t// Test with valid resolvers including duplicates\n\tc.Options[\"resolvers\"] = []interface{}{\"192.0.2.1\", \"192.0.2.2\", \"192.0.2.1\"}\n\terr = c.loadResolverSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid resolvers (including duplicates) are provided, expected nil. Error: %v\", err)\n\t}\n\n\t// Test with valid file path with resolvers\n\t_ = os.WriteFile(\"testResolvers.txt\", []byte(\"192.0.2.3\\n192.0.2.4\"), 0644)\n\tc.Options[\"resolvers\"] = []interface{}{\"192.0.2.1\", \"192.0.2.2\", \"testResolvers.txt\"}\n\terr = c.loadResolverSettings(c)\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when valid resolvers and valid file path are provided, expected nil. Error: %v\", err)\n\t}\n\tdefer func() { _ = os.Remove(\"testResolvers.txt\") }()\n}\n\nfunc TestLoadResolversFromFile(t *testing.T) {\n\tc := NewConfig()\n\n\t// Test with non-existing file\n\t_, err := c.loadResolversFromFile(\"nonExistingFile.txt\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected an error when file does not exist, got nil\")\n\t}\n\n\t// Test with invalid IPs in file\n\t_ = os.WriteFile(\"invalidResolvers.txt\", []byte(\"192.0.2.300\\ninvalidIP\"), 0644)\n\t_, err = c.loadResolversFromFile(\"invalidResolvers.txt\")\n\tif err == nil {\n\t\tt.Errorf(\"Expected an error when file contains invalid IPs, got nil\")\n\t}\n\t_ = os.Remove(\"invalidResolvers.txt\")\n\n\t// Test with valid IPs in file\n\t_ = os.WriteFile(\"validResolvers.txt\", []byte(\"192.0.2.3\\n192.0.2.4\"), 0644)\n\tresolvers, err := c.loadResolversFromFile(\"validResolvers.txt\")\n\tif err != nil {\n\t\tt.Errorf(\"Got an error when file contains valid IPs, expected nil. Error: %v\", err)\n\t}\n\n\tif len(resolvers) != 2 {\n\t\tt.Errorf(\"Expected 2 resolvers, got %v\", len(resolvers))\n\t}\n\n\tif resolvers[0] != \"192.0.2.3\" || resolvers[1] != \"192.0.2.4\" {\n\t\tt.Errorf(\"Resolvers do not match expected values. Got: %v\", resolvers)\n\t}\n\t_ = os.Remove(\"validResolvers.txt\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/rigid.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport \"fmt\"\n\nfunc (c *Config) loadRigidSettings(cfg *Config) error {\n\t// Retrieve the rigid_boundaries option from the configuration\n\trigidinterface, ok := c.Options[\"rigid_boundaries\"]\n\tif !ok {\n\t\t// \"rigid_boundaries\" not found in options, so nothing to do here.\n\t\treturn nil\n\t}\n\n\trigid, ok := rigidinterface.(bool)\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to parse rigid_boundaries setting, value is not a boolean\")\n\t}\n\tc.Rigid = rigid\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/rigid_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nfunc TestLoadRigidSettings(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\toptions string\n\t\texpectedRigid bool\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"RigidBoundariesTrue\",\n\t\t\toptions: \"rigid_boundaries: true\",\n\t\t\texpectedRigid: true,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"RigidBoundariesFalse\",\n\t\t\toptions: \"rigid_boundaries: false\",\n\t\t\texpectedRigid: false,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"RigidBoundariesNotPresent\",\n\t\t\toptions: \"\",\n\t\t\texpectedRigid: false,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"RigidBoundariesInvalidType\",\n\t\t\toptions: \"rigid_boundaries: invalid\",\n\t\t\texpectedRigid: false,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := NewConfig()\n\t\t\terr := yaml.Unmarshal([]byte(tt.options), &cfg.Options)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t\terr = cfg.loadRigidSettings(cfg)\n\t\t\tif (err != nil) != tt.expectError {\n\t\t\t\tt.Errorf(\"loadRigidSettings() error = %v, expectError %v\", err, tt.expectError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif cfg.Rigid != tt.expectedRigid {\n\t\t\t\tt.Errorf(\"loadRigidSettings() Rigid = %v, expectedRigid %v\", cfg.Rigid, tt.expectedRigid)\n\t\t\t}\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/scope.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/caffix/stringset\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n)\n\nfunc (c *Config) loadSeedandScopeSettings() error {\n\tif c.Seed == nil || c.Seed.isScopeEmpty(false) {\n\t\tif c.Scope == nil {\n\t\t\treturn fmt.Errorf(\"config seed and scope are not initialized\")\n\t\t} else {\n\t\t\tif err := c.Scope.populate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.Seed = c.Scope\n\t\t\treturn nil\n\t\t}\n\t} else if err := c.Seed.populate(); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Scope == nil || !c.Scope.isScopeEmpty(true) {\n\t\tif err := c.Seed.populate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Scope = c.Seed\n\t\tc.Scope.Ports = []int{80, 443}\n\t\treturn nil\n\t} else if err := c.Scope.populate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (s *Scope) isScopeEmpty(scopeSwitch bool) bool {\n\tif len(s.Domains) > 0 {\n\t\treturn false\n\t}\n\tif len(s.Addresses) > 0 {\n\t\treturn false\n\t}\n\tif len(s.CIDRs) > 0 {\n\t\treturn false\n\t}\n\tif len(s.ASNs) > 0 {\n\t\treturn false\n\t}\n\tif len(s.IP) > 0 {\n\t\treturn false\n\t}\n\tif scopeSwitch && portCheck(s.Ports) {\n\t\treturn false\n\t} else if len(s.Ports) > 0 {\n\t\treturn false\n\t}\n\tif len(s.Blacklist) > 0 {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (s *Scope) populate() error {\n\t// Convert string CIDRs to net.IP and net.IPNet\n\ts.CIDRs = s.toCIDRs(s.CIDRStrings)\n\n\t// Convert PortsRaw to Ports\n\tif err := s.parsePorts(); err != nil {\n\t\treturn err\n\t}\n\n\tparseIPs := ParseIPs{} // Create a new ParseIPs, which is a []net.IP under the hood\n\t// Validate IP ranges in c.Scope.IP\n\tfor _, ipRange := range s.IP {\n\t\tif err := parseIPs.parseRange(ipRange); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// append parseIPs (which is a []net.IP) to c.Scope.IP\n\ts.Addresses = append(s.Addresses, parseIPs...)\n\treturn nil\n}\n\nfunc (s *Scope) parsePorts() error {\n\n\tif len(s.PortsRaw) != 0 {\n\t\ts.Ports = []int{}\n\t}\n\n\tfor _, port := range s.PortsRaw {\n\t\tswitch p := port.(type) {\n\t\tcase int: // If it's an integer, just append\n\t\t\ts.Ports = append(s.Ports, p)\n\t\tcase string: // If it's a string, check if it's a range or a single port\n\t\t\tif strings.Contains(p, \"-\") {\n\t\t\t\t// Handle port range\n\t\t\t\tportRange, err := convertPortRangeToSlice(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.Ports = append(s.Ports, portRange...)\n\t\t\t} else {\n\t\t\t\t// Handle single port string\n\t\t\t\tportNum, err := strconv.Atoi(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"invalid port string: %v\", err)\n\t\t\t\t}\n\t\t\t\ts.Ports = append(s.Ports, portNum)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unsupported port type: %T\", p)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc convertPortRangeToSlice(portRange string) ([]int, error) {\n\tvar ports []int\n\n\tparts := strings.Split(portRange, \"-\")\n\tif len(parts) != 2 {\n\t\treturn nil, fmt.Errorf(\"invalid port range format\")\n\t}\n\n\tstart, err := strconv.Atoi(parts[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid start port: %v\", err)\n\t}\n\n\tend, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid end port: %v\", err)\n\t}\n\n\tfor i := start; i <= end; i++ {\n\t\tports = append(ports, i)\n\t}\n\n\treturn ports, nil\n}\n\n// returns true is ports match default ports (80,443), otherwise return false\nfunc portCheck(ports []int) bool {\n\tdefaultPorts := []int{80, 443}\n\n\tportSet := make(map[int]struct{}, len(ports))\n\tfor _, v := range ports {\n\t\tportSet[v] = struct{}{}\n\t}\n\tif len(portSet) > len(defaultPorts) {\n\t\treturn false\n\t}\n\tfor _, v := range defaultPorts {\n\t\tif _, found := portSet[v]; !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// DomainRegex returns the Regexp object for the domain name identified by the parameter.\nfunc (c *Config) DomainRegex(domain string) *regexp.Regexp {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif re, found := c.regexps[domain]; found {\n\t\treturn re\n\t}\n\treturn nil\n}\n\n// AddDomains appends the domain names provided in the parameter to the list in the configuration.\nfunc (c *Config) AddDomains(domains ...string) {\n\tfor _, d := range domains {\n\t\tc.AddDomain(d)\n\t}\n}\n\n// AddDomain appends the domain name provided in the parameter to the list in the configuration.\nfunc (c *Config) AddDomain(domain string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\t// Check that the domain string is not empty\n\td := strings.TrimSpace(domain)\n\tif d == \"\" {\n\t\treturn\n\t}\n\t// Check that it is a domain with at least two labels\n\tlabels := strings.Split(d, \".\")\n\tif len(labels) < 2 {\n\t\treturn\n\t}\n\n\t// Check that none of the labels are empty\n\tfor _, label := range labels {\n\t\tif label == \"\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Check that the regular expression map has been initialized\n\tif c.regexps == nil {\n\t\tc.regexps = make(map[string]*regexp.Regexp)\n\t}\n\n\t// Create the regular expression for this domain\n\tc.regexps[d] = dns.SubdomainRegex(d)\n\tif c.regexps[d] != nil {\n\t\t// Add the domain string to the list\n\t\tc.Scope.Domains = append(c.Scope.Domains, d)\n\t}\n\n\tc.Scope.Domains = stringset.Deduplicate(c.Scope.Domains)\n}\n\n// Domains returns the list of domain names currently in the configuration.\nfunc (c *Config) Domains() []string {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\treturn c.Scope.Domains\n}\n\n// IsDomainInScope returns true if the DNS name in the parameter ends with a domain in the config list.\nfunc (c *Config) IsDomainInScope(name string) bool {\n\tvar discovered bool\n\n\tif domain := c.WhichDomain(name); domain != \"\" {\n\t\tdiscovered = true\n\t}\n\n\treturn discovered\n}\n\n// WhichDomain returns the domain in the config list that the DNS name in the parameter ends with.\nfunc (c *Config) WhichDomain(name string) string {\n\tn := strings.ToLower(strings.TrimSpace(name))\n\n\tfor _, d := range c.Domains() {\n\t\tif hasPathSuffix(n, d) {\n\t\t\treturn d\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc hasPathSuffix(path, suffix string) bool {\n\tif strings.HasSuffix(path, suffix) {\n\t\tplen := len(path)\n\t\tslen := len(suffix)\n\n\t\t// Check for exact match first to guard against out of bound index\n\t\tif plen == slen || path[plen-slen-1] == '.' {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// IsAddressInScope returns true if the addr parameter matches provided network scope and when\n// no network scope has been set.\nfunc (c *Config) IsAddressInScope(addr string) bool {\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\treturn false\n\t}\n\n\tif len(c.Scope.Addresses) == 0 && len(c.Scope.CIDRs) == 0 {\n\t\treturn false\n\t}\n\tfor _, cidr := range c.Scope.CIDRs {\n\t\tif cidr.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, a := range c.Scope.Addresses {\n\t\tif a.Equal(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// BlacklistSubdomain adds a subdomain name to the config blacklist.\nfunc (c *Config) BlacklistSubdomain(name string) {\n\tc.blacklistLock.Lock()\n\tdefer c.blacklistLock.Unlock()\n\n\tset := stringset.New(c.Scope.Blacklist...)\n\tdefer set.Close()\n\tset.Insert(strings.TrimSpace(name))\n\n\tc.Scope.Blacklist = set.Slice()\n}\n\n// Blacklisted returns true is the name in the parameter ends with a subdomain name in the config blacklist.\nfunc (c *Config) Blacklisted(name string) bool {\n\tc.blacklistLock.Lock()\n\tdefer c.blacklistLock.Unlock()\n\n\tn := strings.ToLower(strings.TrimSpace(name))\n\n\tfor _, bl := range c.Scope.Blacklist {\n\t\tif hasPathSuffix(n, bl) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n// ParseIPs represents a slice of net.IP addresses.\ntype ParseIPs []net.IP\n\nfunc (p *ParseIPs) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\n\tvar ipaddrs []string\n\tfor _, ipaddr := range *p {\n\t\tipaddrs = append(ipaddrs, ipaddr.String())\n\t}\n\treturn strings.Join(ipaddrs, \",\")\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseIPs) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"IP address parsing failed\")\n\t}\n\n\tips := strings.Split(s, \",\")\n\tfor _, ip := range ips {\n\t\t// Is this an IP range?\n\t\terr := p.parseRange(ip)\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\taddr := net.ParseIP(ip)\n\t\tif addr == nil {\n\t\t\treturn fmt.Errorf(\"%s is not a valid IP address or range\", ip)\n\t\t}\n\t\t*p = append(*p, addr)\n\t}\n\treturn nil\n}\n\nfunc (p *ParseIPs) appendIPs(addrs []net.IP) error {\n\tfor _, addr := range addrs {\n\t\t*p = append(*p, addr)\n\t}\n\treturn nil\n}\n\nfunc (p *ParseIPs) parseRange(s string) error {\n\ttwoIPs := strings.Split(s, \"-\")\n\n\t// If s is not a range, try parsing it as a single IP\n\tif twoIPs[0] == s {\n\t\tip := net.ParseIP(s)\n\t\tif ip == nil {\n\t\t\treturn fmt.Errorf(\"%s is not a valid IP\", s)\n\t\t}\n\t\treturn p.appendIPs([]net.IP{ip})\n\t}\n\tstart := net.ParseIP(twoIPs[0])\n\tend := net.ParseIP(twoIPs[1])\n\tif end == nil {\n\t\tnum, err := strconv.Atoi(twoIPs[1])\n\t\tif err == nil {\n\t\t\tend = net.ParseIP(twoIPs[0])\n\t\t\tend[len(end)-1] = byte(num)\n\t\t}\n\t}\n\tif start == nil || end == nil {\n\t\treturn fmt.Errorf(\"%s is not a valid IP range\", s)\n\t}\n\n\tips := amassnet.RangeHosts(start, end)\n\tif len(ips) == 0 {\n\t\treturn fmt.Errorf(\"%s is not a valid IP range\", s)\n\t}\n\treturn p.appendIPs(ips)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/scope_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestConfigAddDomains(t *testing.T) {\n\ttype args struct {\n\t\tdomains []string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantFound bool\n\t}{\n\t\t{\n\t\t\tname: \"success\",\n\t\t\targs: args{[]string{\"utica.edu\", \"www.utica.edu\"}},\n\t\t\twantFound: true,\n\t\t},\n\t\t{\n\t\t\tname: \"empty space\",\n\t\t\targs: args{[]string{\" \"}},\n\t\t\twantFound: false,\n\t\t},\n\t\t{\n\t\t\tname: \"missing label\",\n\t\t\targs: args{[]string{\"owasp\"}},\n\t\t\twantFound: false,\n\t\t},\n\t\t{\n\t\t\tname: \"empty label\",\n\t\t\targs: args{[]string{\"owasp.\"}},\n\t\t\twantFound: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := NewConfig() // Use NewConfig() instead of new(Config)\n\t\t\tc.AddDomains(tt.args.domains...)\n\t\t\tfor _, d := range tt.args.domains {\n\t\t\t\tvar found bool\n\t\t\t\tfor _, d2 := range c.Domains() {\n\t\t\t\t\tif d == d2 {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found && tt.wantFound {\n\t\t\t\t\tt.Errorf(\"Config.AddDomains() error = domain %v missing from config.domains\", d)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigParseIPsParseRange(t *testing.T) {\n\ttype args struct {\n\t\ts string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tp *ParseIPs\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"basic success - full range\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{s: \"192.168.0.1-192.168.0.3\"},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"basic success - short-hand range\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{s: \"192.168.0.1-4\"},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"illicit split\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{s: \"192.168.0.1\"},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"illicit range\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{s: \"192.168.0.255-192.168.0.260\"},\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif err := tt.p.parseRange(tt.args.s); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"ParseIPs.parseRange() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigParseIPsString(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tp *ParseIPs\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"success\",\n\t\t\tp: &ParseIPs{net.ParseIP(\"192.168.0.1\"), net.ParseIP(\"192.168.0.2\"), net.ParseIP(\"192.168.0.3\")},\n\t\t\twant: \"192.168.0.1,192.168.0.2,192.168.0.3\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty ParseIPs\",\n\t\t\tp: new(ParseIPs),\n\t\t\twant: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"nil ParseIPs\",\n\t\t\tp: nil,\n\t\t\twant: \"\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.p.String(); got != tt.want {\n\t\t\t\tt.Errorf(\"ParseIPs.String() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigParseIPsSet(t *testing.T) {\n\ttype args struct {\n\t\ts string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tp *ParseIPs\n\t\targs args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"success\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{\n\t\t\t\ts: \"192.168.0.1,192.168.0.2,192.168.0.3\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"illicit range\",\n\t\t\tp: new(ParseIPs),\n\t\t\targs: args{\n\t\t\t\ts: \"192.168.0.4-\",\n\t\t\t},\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif err := tt.p.Set(tt.args.s); (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"ParseIPs.Set() error = %v, wantErr %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigBlacklistSubdomain(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tconfig *Config\n\t\tdomains []string\n\t}{\n\t\t{\n\t\t\tname: \"blacklist success\",\n\t\t\tconfig: NewConfig(), // Use NewConfig() instead of new(Config)\n\t\t\tdomains: []string{\"user\", \"tmp\", \"admin\"},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfor _, d := range tt.domains {\n\t\t\t\ttt.config.BlacklistSubdomain(d)\n\t\t\t}\n\n\t\t\tsort.Strings(tt.domains)\n\t\t\tsort.Strings(tt.config.Scope.Blacklist)\n\n\t\t\tif !reflect.DeepEqual(tt.domains, tt.config.Scope.Blacklist) {\n\t\t\t\tt.Errorf(\"BlacklistSubdomain() wanted %v, got %v\", tt.domains, tt.config.Scope.Blacklist)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLoadScopeSettings(t *testing.T) {\n\ttype args struct {\n\t\tcfg []byte\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twantErr bool\n\t\tassertionFunc func(*testing.T, *Config)\n\t}{\n\t\t{\n\t\t\tname: \"failure - invalid address range\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n ips:\n - 1.2.3.4-1.1.1.1`)},\n\t\t\twantErr: true,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid IPv4 addresses\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n ips:\n - 1.2.3.4\n - 0.0.0.0\n - 255.255.255.255`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tif len(c.Scope.Addresses) != 3 {\n\t\t\t\t\tt.Errorf(\"failed to load addresses\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid IPv6 addresses\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n ips:\n - '::'\n - '1111:2222:3333:4444:5555:6666:7777:8888'\n - '1:2:0001:deca:f000:00c0:ff:ee'`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tif len(c.Scope.Addresses) != 3 {\n\t\t\t\t\tt.Errorf(\"failed to load addresses %v\", c.Scope.Addresses)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid cidr\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n cidrs:\n - 1.2.3.4/8`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tif len(c.Scope.CIDRStrings) != 1 {\n\t\t\t\t\tt.Errorf(\"failed to load cidr\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid asn\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n asns:\n - 26808`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid domain in scope domains\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n domains:\n - owasp.org`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid subdomain in section scope.blacklisted\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n blacklist:\n - gopher.example.com`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"success - valid ports in section with range in scope.PortsRaw\",\n\t\t\targs: args{cfg: []byte(`\nscope:\n ports: # ports to be used when actively reaching a service\n - \"80\"\n - 443\n - 8080-8088`)},\n\t\t\twantErr: false,\n\t\t\tassertionFunc: func(t *testing.T, c *Config) {\n\t\t\t\tif len(c.Scope.Ports) != 11 {\n\t\t\t\t\tt.Errorf(\"failed to load ports\")\n\t\t\t\t}\n\t\t\t\texpected := map[int]struct{}{\n\t\t\t\t\t80: {},\n\t\t\t\t\t443: {},\n\t\t\t\t\t8080: {},\n\t\t\t\t\t8081: {},\n\t\t\t\t\t8082: {},\n\t\t\t\t\t8083: {},\n\t\t\t\t\t8084: {},\n\t\t\t\t\t8085: {},\n\t\t\t\t\t8086: {},\n\t\t\t\t\t8087: {},\n\t\t\t\t\t8088: {},\n\t\t\t\t}\n\t\t\t\tfor _, v := range c.Scope.Ports {\n\t\t\t\t\tif _, ok := expected[v]; !ok {\n\t\t\t\t\t\tt.Errorf(\"failed to load ports\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tc := NewConfig()\n\n\t\t\t// Create a temporary file and write the config data to it\n\t\t\ttmpfile, err := os.CreateTemp(\"\", \"config\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\t// Obtain the absolute path of the file\n\t\t\tabsPath, err := filepath.Abs(tmpfile.Name())\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer func() { _ = os.Remove(absPath) }() // clean up\n\n\t\t\tif _, err := tmpfile.Write(tt.args.cfg); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif err := tmpfile.Close(); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\t// Call LoadScopeSettings with the absolute file path\n\t\t\terr = c.LoadSettings(absPath)\n\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\" %v error = %v\", tt.name, err)\n\t\t\t}\n\n\t\t\ttt.assertionFunc(t, c)\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/transform.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\n// Transformation represents an individual transofmration with optional priority & confidence.\ntype Transformation struct {\n\tFrom string `yaml:\"-\" json:\"-\"`\n\tTo string `yaml:\"-\" json:\"-\"`\n\tPriority int `yaml:\"priority,omitempty\" json:\"priority,omitempty\"`\n\tConfidence int `yaml:\"confidence,omitempty\" json:\"confidence,omitempty\"`\n\tExclude []string `yaml:\"exclude,omitempty\" json:\"exclude,omitempty\"`\n\tTTL int `yaml:\"ttl,omitempty\" json:\"ttl,omitempty\"`\n}\n\n// Matches represents a collection of transform matches.\ntype Matches struct {\n\tlock sync.Mutex\n\tto map[string]struct {\n\t\tttl int\n\t\tconfidence int\n\t}\n}\n\n// loadTransformSettings processes the Transformations map from the configuration,\n// assigning structured data to each Transformation based on its key.\n// Each key is parsed into 'From' and 'To' segments, representing the origin and target\n// of the transformation, respectively, which are then stored in the corresponding Transformation struct.\nfunc (c *Config) loadTransformSettings(cfg *Config) error {\n\t// Retrieve the global options from the Options, if it's set.\n\tif err := c.loadGlobalTransformSettings(); err != nil {\n\t\treturn err\n\t}\n\t// Iterate through each transformation rule defined in the configuration.\n\tfor key, transformation := range c.Transformations {\n\t\t// Initialize transformation if nil\n\t\tif transformation == nil {\n\t\t\ttransformation = &Transformation{} // default struct\n\t\t\tc.Transformations[key] = transformation // assign it back to the map\n\t\t}\n\t\t// Spit the key into 'From' and 'To' components.\n\t\tif err := transformation.Split(key); err != nil {\n\t\t\treturn fmt.Errorf(\"error when splitting the key: %w\", err)\n\t\t}\n\t\t// Apply the global confidence if no specific confidence is set for this transformation.\n\t\tif transformation.Confidence == 0 {\n\t\t\ttransformation.Confidence = c.DefaultTransformations.Confidence\n\t\t}\n\t\tif transformation.TTL == 0 {\n\t\t\ttransformation.TTL = c.DefaultTransformations.TTL\n\t\t}\n\n\t\terr := transformation.Validate(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// If the loop completes with no conflicts, the function returns nil, indicating success.\n\treturn nil\n}\n\nfunc (c *Config) loadGlobalTransformSettings() error {\n\t// get the default_transfom_values in the config yaml\n\tif dtv, ok := c.Options[\"default_transform_values\"]; ok {\n\t\t// Assert the type to map[interface{}]interface{}\n\t\tdtvMap, ok := dtv.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"invalid type for default_transform_values\")\n\t\t}\n\t\t// Convert the map to the Transformation struct\n\t\tif ttl, ok := dtvMap[\"ttl\"].(int); ok {\n\t\t\tc.DefaultTransformations.TTL = ttl\n\t\t} else if !ok && dtvMap[\"ttl\"] != nil {\n\t\t\treturn fmt.Errorf(\"invalid type for ttl in default_transform_values\")\n\t\t}\n\t\tif confidence, ok := dtvMap[\"confidence\"].(int); ok {\n\t\t\tc.DefaultTransformations.Confidence = confidence\n\t\t} else if !ok && dtvMap[\"confidence\"] != nil {\n\t\t\treturn fmt.Errorf(\"invalid type for confidence in default_transform_values\")\n\t\t}\n\t\tif priority, ok := dtvMap[\"priority\"].(int); ok {\n\t\t\tc.DefaultTransformations.Priority = priority\n\t\t} else if !ok && dtvMap[\"priority\"] != nil {\n\t\t\treturn fmt.Errorf(\"invalid type for priority in default_transform_values\")\n\t\t}\n\n\t}\n\treturn nil\n}\n\n// Split splits the key into 'From' and 'To' components, expecting a \"->\" delimiter.\n// Requires a non-nil Transformation pointer and a valid key format. Example: FQDN->IPaddress.\nfunc (t *Transformation) Split(key string) error {\n\tif t.From != \"\" && t.To != \"\" {\n\t\tt.From = strings.ToLower(t.From)\n\t\tt.To = strings.ToLower(t.To)\n\t\treturn nil // Already split\n\t}\n\t// Split the key into 'From' and 'To' components, expecting a \"->\" delimiter.\n\tparts := strings.Split(key, \"->\")\n\tif len(parts) != 2 {\n\t\treturn fmt.Errorf(\"invalid key delimiter: %s\", key)\n\t}\n\t// Assign the 'From' and 'To' values to the Transformation struct.\n\tt.From = strings.ToLower(parts[0])\n\tt.To = strings.ToLower(parts[1])\n\treturn nil\n}\n\n// Validate checks the validity of a given transformation with respect to OAM &\n// previously registered transformations. The function ensures OAM compliance & that there are no conflicts\n// between transformations with 'none' (indicating no action) and other valid transformations\n// for the same 'From' type.\nfunc (t *Transformation) Validate(c *Config) error {\n\tif c.fromWithNone == nil {\n\t\tc.fromWithNone = make(map[string]bool)\n\t}\n\tif c.fromWithValid == nil {\n\t\tc.fromWithValid = make(map[string]bool)\n\t}\n\ttfound := false\n\tffound := false\n\t// Check if \"From\" and \"To\" is OAM compliant\n\tfor _, a := range oam.AssetList {\n\t\ta := strings.ToLower(string(a))\n\t\tif t.From == a {\n\t\t\tffound = true\n\t\t}\n\t\tif t.To == a || t.To == \"none\" || t.To == \"all\" {\n\t\t\ttfound = true\n\t\t}\n\t\t// Used to prevent unnecessary iterations\n\t\tif tfound && ffound {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !ffound {\n\t\treturn fmt.Errorf(\"invalid 'From' type: %s does not comply with OAM\", t.From)\n\t}\n\t// Check for a 'none' transformation, which indicates that no further processing is required for this 'From' type.\n\tif t.To == \"none\" {\n\t\t// Conflict arises if there's already a valid transformation for this 'From'.\n\t\tif c.fromWithValid[t.From] {\n\t\t\treturn fmt.Errorf(\"invalid config: 'none' specified after a valid transformation for 'From' type: %s. 'None' should be the only transformation\", t.From)\n\t\t}\n\t\tc.fromWithNone[t.From] = true\n\t} else { // For other valid transformations.\n\t\t// Conflict arises if a 'none' transformation is already registered for this 'From'.\n\t\tif c.fromWithNone[t.From] {\n\t\t\treturn fmt.Errorf(\"invalid config: valid transformation specified after 'none' for 'From' type: %s. 'None' should be the only transformation\", t.From)\n\t\t}\n\t\t// Mark this 'From' as having a valid transformation.\n\t\tc.fromWithValid[t.From] = true\n\t}\n\n\treturn nil\n}\n\n// CheckTransformations checks if the given 'From' type has a valid transformation to any of the given 'To' types.\nfunc (c *Config) CheckTransformations(from string, tos ...string) (*Matches, error) {\n\tlower := strings.ToLower(from)\n\ttomap := make(map[string]struct{})\n\tresults := &Matches{to: make(map[string]struct {\n\t\tttl int\n\t\tconfidence int\n\t})}\n\n\tfor _, v := range tos {\n\t\tt := strings.ToLower(v)\n\t\ttomap[t] = struct{}{}\n\t}\n\n\tfor _, transform := range c.Transformations {\n\t\tif lower == transform.From {\n\t\t\tif transform.To == \"all\" {\n\t\t\t\texcludes := make(map[string]struct{})\n\t\t\t\tfor _, e := range transform.Exclude {\n\t\t\t\t\texcludes[strings.ToLower(e)] = struct{}{}\n\t\t\t\t}\n\n\t\t\t\tfor k := range tomap {\n\t\t\t\t\tif _, ok := results.to[k]; !ok {\n\t\t\t\t\t\tif _, found := excludes[k]; !found {\n\t\t\t\t\t\t\tresults.to[k] = struct {\n\t\t\t\t\t\t\t\tttl int\n\t\t\t\t\t\t\t\tconfidence int\n\t\t\t\t\t\t\t}{ttl: transform.checkTTL(k, c), confidence: transform.Confidence}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else if _, found := tomap[transform.To]; found {\n\t\t\t\t// this only occurs if an ALL is specified\n\t\t\t\tif old, ok := results.to[transform.To]; ok {\n\t\t\t\t\tconfidence := transform.Confidence\n\t\t\t\t\tttl := transform.checkTTL(transform.To, c)\n\n\t\t\t\t\tif confidence == 0 { // if confidence is not set, use the ALL confidence\n\t\t\t\t\t\tconfidence = old.confidence\n\t\t\t\t\t}\n\n\t\t\t\t\tif ttl == 0 { // if ttl is not set, use the ALL ttl\n\t\t\t\t\t\tttl = old.ttl\n\t\t\t\t\t}\n\n\t\t\t\t\tresults.to[transform.To] = struct {\n\t\t\t\t\t\tttl int\n\t\t\t\t\t\tconfidence int\n\t\t\t\t\t}{ttl: ttl, confidence: confidence}\n\n\t\t\t\t} else {\n\t\t\t\t\tresults.to[transform.To] = struct {\n\t\t\t\t\t\tttl int\n\t\t\t\t\t\tconfidence int\n\t\t\t\t\t}{ttl: transform.checkTTL(transform.To, c), confidence: transform.Confidence}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(results.to) == 0 {\n\t\treturn nil, fmt.Errorf(\"zero transformation matches in the session config\")\n\t}\n\treturn results, nil\n}\n\n// checkTTl checks the TTL value for the given 'To' type in the given Config.\n// if the 'To' is a data source, it will return the TTL value from the data source config.\n// otherwise, it will return the default TTL value from the transformation config.\nfunc (t *Transformation) checkTTL(to string, c *Config) int {\n\tif c != nil {\n\t\tif c.DataSrcConfigs != nil {\n\t\t\tds := c.GetDataSourceConfig(to)\n\t\t\tif ds != nil && ds.TTL > 0 {\n\t\t\t\treturn ds.TTL\n\t\t\t}\n\t\t}\n\t}\n\treturn t.TTL\n}\n\n// IsMatch checks if a valid transformation to the given 'To' type is present.\nfunc (m *Matches) IsMatch(to string) bool {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\t_, found := m.to[strings.ToLower(to)]\n\treturn found\n}\n\n// Len returns the number of matches in the result set.\nfunc (m *Matches) Len() int {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\treturn len(m.to)\n}\n\n// TTL returns the ttl for a given 'To' type in the Matches struct.\n// If the 'To' type is not found, the function returns -1.\nfunc (m *Matches) TTL(to string) int {\n\tif m.IsMatch(to) {\n\t\treturn m.to[strings.ToLower(to)].ttl\n\t}\n\treturn -1\n}\n\n// Confidence returns the confidence for a given 'To' type in the Matches struct.\n// If the 'To' type is not found, the function returns -1.\nfunc (m *Matches) Confidence(to string) int {\n\tif m.IsMatch(to) {\n\t\treturn m.to[strings.ToLower(to)].confidence\n\t}\n\treturn -1\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/transform_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\n// Mock YAML inputs for various test cases\nvar validYAML = []byte(`\noptions:\n confidence: 50 # default confidence level for all transformations unless otherwise specified\n\ntransformations:\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n FQDN->DomainRecord:\n priority: 2\n FQDN->ALL: \n exclude: [NetworkEndpoint,FQDN]\n IPAddress->IPAddress:\n priority: 1\n confidence: 80\n IPAddress->Netblock:\n priority: 2\n IPAddress->SocketAddress:\n # leaving both priority and confidence out\n\n`)\n\nvar conflictingNoneYAML = []byte(`\noptions:\n confidence: 50\n\ntransformations:\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n FQDN->none:\n priority: 2\n FQDN->ALL: \n exclude: [TLS,FQDN]\n IPAddress->IPAddress:\n priority: 1\n confidence: 80\n IPAddress->Netblock:\n priority: 2\n IPAddress->TLS:\n # leaving both priority and confidence out\n`)\n\nvar conflictingNoneYAML2 = []byte(`\noptions:\n confidence: 50\n\ntransformations:\n FQDN->none:\n priority: 2\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n FQDN->ALL: \n exclude: [TLS,FQDN]\n IPAddress->IPAddress:\n priority: 1\n confidence: 80\n IPAddress->Netblock:\n priority: 2\n IPAddress->TLS:\n # leaving both priority and confidence out\n`)\n\nvar invalidKeyYAML = []byte(`\noptions:\n confidence: 50\n\ntransformations:\n FQDN-IPAddress:\n priority: 1\n`)\n\nvar nonOAMtoYAML = []byte(`\noptions:\n confidence: 50 # default confidence level for all transformations unless otherwise specified\n\ntransformations:\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n FQDN->Amass:\n priority: 2\n FQDN->ALL: \n exclude: [RIRORG,FQDN]\n`)\n\nvar nonOAMfromYAML = []byte(`\noptions:\n confidence: 50 # default confidence level for all transformations unless otherwise specified\n\ntransformations:\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n Amass->DomainRecord:\n priority: 2\n FQDN->ALL: \n exclude: [RIRORG,FQDN]\n`)\n\n// this data source info is here to test accuracy of considering data source ttl in the transformation\nvar validDataSrcYAML = []byte(`\ndatasources:\n - name: AlienVault\n ttl: 4320\n creds:\n account1:\n username: avuser\n password: avpass\n - name: BinaryEdge\n creds:\n account2:\n username: beuser\n password: bepass\nglobal_options:\n minimum_ttl: 1300\n`)\n\nvar validttlYAML = []byte(`\noptions:\n confidence: 50 # default confidence level for all transformations unless otherwise specified\n default_transform_values:\n ttl: 69 # default is 1440\n confidence: 50 # default is 50\n priority: 5 # default global priority is 5 (assuming its 1-10)\n\ntransformations:\n FQDN->IPAddress:\n priority: 1\n confidence: 80\n ttl: 770\n FQDN->DomainRecord:\n priority: 2\n FQDN->ALL: \n exclude: [TLS,FQDN]\n IPAddress->FQDN:\n priority: 1\n confidence: 80\n IPAddress->DomainRecord:\n priority: 2\n IPAddress->Netblock:\n # leaving both priority and confidence out\n`)\n\n/*\nthis blob Makes sure that the default is set as 1440 and that the FQDN->IPAddress has a ttl of 770 even if\nEven if the FQDN->ALL has a ttl of 1000\n*/\nvar validttlNoDefaultYAML = []byte(`\ntransformations:\n FQDN->IPAddress:\n priority: 1\n ttl: 770\n FQDN->DomainRecord:\n priority: 2\n FQDN->Netblock:\n ttl: 1440\n FQDN->ALL:\n ttl: 1000\n exclude: [TLS,FQDN]\n IPAddress->FQDN:\n priority: 1\n IPAddress->DomainRecord:\n priority: 2\n confidence: 80\n IPAddress->Netblock:\n # leaving both priority and confidence out\n`)\n\nvar nonvalidttlYAML = []byte(`\noptions:\n default_transform_values:\n ttl: hello # default is 1440\n confidence: 50 # default is 50\n priority: 5 # default global priority is 5 (assuming its 1-10)\n`)\n\nvar nonvalidttlYAML2 = []byte(`\noptions:\n default_transform_values:\n ttl: 1440 # default is 1440\n confidence: 50 # default is 50\n priority: hello # default global priority is 5 (assuming its 1-10)\n`)\n\nvar nonvalidttlYAML3 = []byte(`\noptions:\n default_transform_values:\n ttl: 1440 # default is 1440\n confidence: hello # default is 50\n priority: 5 # default global priority is 5 (assuming its 1-10)\n`)\n\n// Utility function to unmarshal YAML and load transformation settings\nfunc prepareConfig(yamlInput []byte) (*Config, error) {\n\tconf := NewConfig()\n\terr := yaml.Unmarshal(yamlInput, conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = conf.loadTransformSettings(conf)\n\treturn conf, err\n}\n\nfunc TestLoadTransformSettings(t *testing.T) {\n\t// Test with valid YAML input\n\tt.Run(\"valid YAML and settings\", func(t *testing.T) {\n\t\tconf, err := prepareConfig(validYAML)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif conf.Transformations[\"FQDN->DomainRecord\"].Confidence != 50 {\n\t\t\tt.Errorf(\"Expected confidence to be set to global value\")\n\t\t}\n\t})\n\n\t// Test with conflicting 'none' transformation\n\tt.Run(\"conflicting transformations - none after\", func(t *testing.T) {\n\t\t_, err := prepareConfig(conflictingNoneYAML)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error due to conflicting 'none' transformation, got nil\")\n\t\t}\n\t})\n\n\t// Test with conflicting 'none' transformation\n\tt.Run(\"conflicting transformations - none before\", func(t *testing.T) {\n\t\t_, err := prepareConfig(conflictingNoneYAML2)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error due to conflicting 'none' transformation, got nil\")\n\t\t}\n\t})\n\n\t// Test with invalid key format in YAML\n\tt.Run(\"invalid key format\", func(t *testing.T) {\n\t\t_, err := prepareConfig(invalidKeyYAML)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error due to invalid key format, got nil\")\n\t\t}\n\t})\n\n\t// Test with non-OAM compliant 'to' transformation\n\tt.Run(\"non-OAM compliant 'to' transformation\", func(t *testing.T) {\n\t\t_, err := prepareConfig(nonOAMtoYAML)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error due to non-OAM compliant 'to' transformation\")\n\t\t}\n\t})\n\n\t// Test with non-OAM compliant 'from' transformation\n\tt.Run(\"non-OAM compliant 'from' transformation\", func(t *testing.T) {\n\t\t_, err := prepareConfig(nonOAMfromYAML)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error due to non-OAM compliant 'from' transformation, got nil\")\n\t\t}\n\t})\n}\n\nfunc TestSplit(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tkey string\n\t\texpected *Transformation\n\t\texpectErr bool\n\t}{\n\t\t{\n\t\t\tname: \"Valid key1\",\n\t\t\tkey: \"FQDN->IPAddress\",\n\t\t\texpected: &Transformation{From: \"fqdn\", To: \"ipaddress\"},\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid key2\",\n\t\t\tkey: \"FQDN->IPAddress\",\n\t\t\texpected: &Transformation{From: \"fqdn\", To: \"ipaddress\"},\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid key delimiter\",\n\t\t\tkey: \"FQDN-IPAddress\",\n\t\t\texpected: nil,\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Empty key\",\n\t\t\tkey: \"\",\n\t\t\texpected: nil,\n\t\t\texpectErr: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttf := &Transformation{}\n\t\t\tif tt.name == \"Valid key1\" {\n\t\t\t\ttf.From = \"FQDN\"\n\t\t\t\ttf.To = \"IPAddress\"\n\t\t\t}\n\t\t\terr := tf.Split(tt.key)\n\t\t\tif tt.expectErr {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"Expected error, got nil\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t\t}\n\t\t\t\tif tf.From != tt.expected.From || tf.To != tt.expected.To {\n\t\t\t\t\tt.Errorf(\"Expected From: %s, To: %s, got From: %s, To: %s\", tt.expected.From, tt.expected.To, tf.From, tf.To)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsMatch(t *testing.T) {\n\tm := &Matches{\n\t\tto: map[string]struct {\n\t\t\tttl int\n\t\t\tconfidence int\n\t\t}{\n\t\t\t\"ipaddress\": {},\n\t\t\t\"domainrecord\": {},\n\t\t\t\"rirorg\": {},\n\t\t},\n\t}\n\tm2 := &Matches{}\n\n\ttests := []struct {\n\t\tname string\n\t\tto string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname: \"Existing match\",\n\t\t\tto: \"ipaddress\",\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Non-existing match\",\n\t\t\tto: \"tls\",\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Empty match\",\n\t\t\tto: \"\",\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Nil match\",\n\t\t\tto: \"\",\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tvar result bool\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.name == \"Nil match\" {\n\t\t\t\tresult = m2.IsMatch(tt.to)\n\t\t\t} else {\n\t\t\t\tresult = m.IsMatch(tt.to)\n\t\t\t}\n\t\t\tif result != tt.expected {\n\t\t\t\tt.Errorf(\"Expected %v, but got %v\", tt.expected, result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc TestCheckTransformations(t *testing.T) {\n\tconf := NewConfig()\n\tconf.Transformations = map[string]*Transformation{\n\t\t\"FQDN->IPAddress\": {\n\t\t\tFrom: \"fqdn\",\n\t\t\tTo: \"ipaddress\",\n\t\t\tPriority: 1,\n\t\t\tConfidence: 80,\n\t\t},\n\t\t\"FQDN->DomainRecord\": {\n\t\t\tFrom: \"fqdn\",\n\t\t\tTo: \"domainrecord\",\n\t\t\tPriority: 2,\n\t\t},\n\t\t\"FQDN->ALL\": {\n\t\t\tFrom: \"fqdn\",\n\t\t\tTo: \"all\",\n\t\t\tExclude: []string{\"tls\", \"fqdn\", \"rirorg\"},\n\t\t},\n\t\t\"DomainRecord->ALL\": {\n\t\t\tFrom: \"domainrecord\",\n\t\t\tTo: \"all\",\n\t\t\tExclude: []string{\"fqdn\"},\n\t\t},\n\t}\n\tconf2 := NewConfig()\n\tconf2.Transformations = map[string]*Transformation{\n\t\t\"FQDN->IPAddress\": {\n\t\t\tFrom: \"fqdn\",\n\t\t\tTo: \"ipaddress\",\n\t\t},\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfrom string\n\t\ttos []string\n\t\texpectErr bool\n\t\terrMessage string\n\t\texpected *Matches\n\t}{\n\t\t{\n\t\t\tname: \"Valid transformation\",\n\t\t\tfrom: \"fqdn\",\n\t\t\ttos: []string{\"ipaddress\"},\n\t\t\texpectErr: false,\n\t\t\texpected: &Matches{\n\t\t\t\tto: map[string]struct {\n\t\t\t\t\tttl int\n\t\t\t\t\tconfidence int\n\t\t\t\t}{\n\t\t\t\t\t\"ipaddress\": {\n\t\t\t\t\t\tconfidence: 80,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"No match\",\n\t\t\tfrom: \"fqdn\",\n\t\t\ttos: []string{\"rirorg\"},\n\t\t\texpectErr: true,\n\t\t\terrMessage: \"zero transformation matches in the session config\",\n\t\t\texpected: &Matches{to: make(map[string]struct {\n\t\t\t\tttl int\n\t\t\t\tconfidence int\n\t\t\t})}},\n\t\t{\n\t\t\tname: \"Transformation to 'all'\",\n\t\t\tfrom: \"fqdn\",\n\t\t\ttos: []string{\"registrant\", \"rirorg\"},\n\t\t\texpectErr: false,\n\t\t\texpected: &Matches{\n\t\t\t\tto: map[string]struct {\n\t\t\t\t\tttl int\n\t\t\t\t\tconfidence int\n\t\t\t\t}{\n\t\t\t\t\t\"registrant\": {},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Transformation with excluded targets\",\n\t\t\tfrom: \"fqdn\",\n\t\t\ttos: []string{\"fqdn\", \"tls\"},\n\t\t\texpectErr: true,\n\t\t\terrMessage: \"zero transformation matches in the session config\",\n\t\t\texpected: &Matches{to: make(map[string]struct {\n\t\t\t\tttl int\n\t\t\t\tconfidence int\n\t\t\t})}},\n\t\t{\n\t\t\tname: \"No \\\"from\\\" matches with config\",\n\t\t\tfrom: \"ip\",\n\t\t\ttos: []string{\"tls\", \"rirorg\"},\n\t\t\texpectErr: true,\n\t\t\terrMessage: \"zero transformation matches in the session config\",\n\t\t\texpected: &Matches{to: make(map[string]struct {\n\t\t\t\tttl int\n\t\t\t\tconfidence int\n\t\t\t})}},\n\t\t{\n\t\t\tname: \"No \\\"to\\\" matches with config\",\n\t\t\tfrom: \"domainrecord\",\n\t\t\ttos: []string{\"fqdn\"},\n\t\t\texpectErr: true,\n\t\t\terrMessage: \"zero transformation matches in the session config\",\n\t\t\texpected: &Matches{to: make(map[string]struct {\n\t\t\t\tttl int\n\t\t\t\tconfidence int\n\t\t\t})}},\n\t\t{\n\t\t\tname: \"Nil \\\"to\\\" matches with config\",\n\t\t\tfrom: \"fqdn\",\n\t\t\ttos: []string{\"rirorg\"},\n\t\t\texpectErr: true,\n\t\t\terrMessage: \"zero transformation matches in the session config\",\n\t\t\texpected: &Matches{to: make(map[string]struct {\n\t\t\t\tttl int\n\t\t\t\tconfidence int\n\t\t\t})}},\n\t}\n\n\tvar err error\n\tvar matches *Matches\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.name != \"Nil \\\"to\\\" matches with config\" {\n\t\t\t\tmatches, err = conf.CheckTransformations(tt.from, tt.tos...)\n\t\t\t} else {\n\t\t\t\tmatches, err = conf2.CheckTransformations(tt.from, tt.tos...)\n\t\t\t}\n\t\t\tif tt.expectErr {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"Expected error message '%s', got '%s'\", tt.errMessage, err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected error: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif matches != nil && tt.expected != nil && !reflect.DeepEqual(matches.to, tt.expected.to) {\n\t\t\t\tt.Errorf(\"Expected matches: %v, but got: %v\", tt.expected, matches)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMatches(t *testing.T) {\n\tconf := NewConfig()\n\t_ = yaml.Unmarshal(validttlYAML, conf)\n\t_ = yaml.Unmarshal(validDataSrcYAML, conf.DataSrcConfigs)\n\t_ = conf.loadTransformSettings(conf)\n\tconf.DataSrcConfigs.ttlCheck()\n\n\tt.Run(\"Matching transformation\", func(t *testing.T) {\n\t\tm, err := conf.CheckTransformations(\"FQDN\", \"IPAddress\", \"Netblock\", \"AlienVault\", \"BinaryEdge\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif m.Len() != 4 {\n\t\t\tt.Fatalf(\"Expected 4 mathces, got %d\", m.Len())\n\t\t}\n\t\tif m.TTL(\"IPAddress\") != 770 {\n\t\t\tt.Errorf(\"Expected TTL of 770, got %d\", m.TTL(\"IPAddress\"))\n\t\t}\n\t\tif m.TTL(\"AlienVault\") != 4320 {\n\t\t\tt.Errorf(\"Expected TTL of 4320, got %d\", m.TTL(\"BinaryEdge\"))\n\t\t}\n\t\tif m.TTL(\"BinaryEdge\") != 1300 {\n\t\t\tt.Errorf(\"Expected TTL of 1300, got %d\", m.TTL(\"BinaryEdge\"))\n\t\t}\n\t\tif m.TTL(\"Netblock\") != 69 {\n\t\t\tt.Errorf(\"Expected TTL of 69, got %d\", m.TTL(\"Netblock\"))\n\t\t}\n\n\t\tm, err = conf.CheckTransformations(\"IPAddress\", \"IPAddress\", \"Netblock\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\t\tif m.TTL(\"Netblock\") != 69 {\n\t\t\tt.Errorf(\"Expected TTL of 69, got %d\", m.TTL(\"Netblock\"))\n\t\t}\n\t})\n\n\tt.Run(\"No matching transformation\", func(t *testing.T) {\n\t\tm, err := conf.CheckTransformations(\"IPAddress\", \"RIRORG\")\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error, got nil\")\n\t\t}\n\t\tif m != nil {\n\t\t\tt.Fatalf(\"Expected 0 matches, got %d\", m.Len())\n\t\t}\n\t})\n\n\tt.Run(\"Matching transformation - no default TTL\", func(t *testing.T) {\n\n\t\tconf = NewConfig()\n\t\tif err := yaml.Unmarshal(validttlNoDefaultYAML, conf); err != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\t\t_ = yaml.Unmarshal(validDataSrcYAML, conf.DataSrcConfigs)\n\t\tconf.DataSrcConfigs.ttlCheck()\n\t\t_ = conf.loadTransformSettings(conf)\n\n\t\tm, err := conf.CheckTransformations(\"FQDN\", \"IPAddress\", \"Netblock\", \"AlienVault\", \"BinaryEdge\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t}\n\n\t\tif m.Len() != 4 {\n\t\t\tt.Fatalf(\"Expected 4 mathces, got %d\", m.Len())\n\t\t}\n\n\t\tif m.TTL(\"Netblock\") != 1440 {\n\t\t\tt.Errorf(\"Expected TTL of 1440, got %d\", m.TTL(\"Netblock\"))\n\t\t}\n\t})\n\n\tt.Run(\"Invalid default TTL\", func(t *testing.T) {\n\t\tnonvalid := [][]byte{nonvalidttlYAML, nonvalidttlYAML2, nonvalidttlYAML3}\n\t\tfor _, y := range nonvalid {\n\t\t\tconf = NewConfig()\n\t\t\tif err := yaml.Unmarshal(y, conf); err != nil {\n\t\t\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t\t\t}\n\t\t\terr := conf.loadTransformSettings(conf)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(\"Expected error, got nil when using \" + string(y))\n\t\t\t}\n\t\t}\n\t})\n\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/wordlist.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tmaskLetters = \"abcdefghijklmnopqrstuvwxyz\"\n\tmaskDigits = \"0123456789\"\n\tmaskSpecial = \"-\"\n)\n\n// ExpandMask will return a slice of words that a \"hashcat-style\" mask matches.\nfunc ExpandMask(word string) ([]string, error) {\n\tvar expanded []string\n\tvar chars string\n\n\tif strings.Count(word, \"?\") > 3 {\n\t\treturn expanded, fmt.Errorf(\"exceeded maximum mask size (3): %s\", word)\n\t}\n\n\tparts := strings.SplitN(word, \"?\", 2)\n\tif len(parts) > 1 {\n\t\tif len(parts[1]) > 0 {\n\t\t\tswitch parts[1][0] {\n\t\t\tcase 'a':\n\t\t\t\tchars = maskLetters + maskDigits + maskSpecial\n\t\t\tcase 'd':\n\t\t\t\tchars = maskDigits\n\t\t\tcase 'u':\n\t\t\t\tfallthrough\n\t\t\tcase 'l':\n\t\t\t\tchars = maskLetters\n\t\t\tcase 's':\n\t\t\t\tchars = maskSpecial\n\t\t\tdefault:\n\t\t\t\treturn expanded, fmt.Errorf(\"improper mask used: %s\", word)\n\t\t\t}\n\t\t\tfor _, ch := range chars {\n\t\t\t\tnewWord := parts[0] + string(ch) + parts[1][1:]\n\t\t\t\tnextRound, err := ExpandMask(newWord)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn expanded, err\n\t\t\t\t}\n\t\t\t\texpanded = append(expanded, nextRound...)\n\t\t\t}\n\t\t}\n\t} else {\n\t\texpanded = append(expanded, word)\n\t}\n\treturn expanded, nil\n}\n\n// ExpandMaskWordlist performs ExpandMask on a slice of words.\nfunc ExpandMaskWordlist(wordlist []string) ([]string, error) {\n\tvar newWordlist []string\n\n\tfor _, word := range wordlist {\n\t\tif words, err := ExpandMask(word); err == nil {\n\t\t\tnewWordlist = append(newWordlist, words...)\n\t\t}\n\t}\n\n\treturn newWordlist, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: config/wordlist_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage config\n\nimport (\n\t\"testing\"\n)\n\nfunc TestExpandMask(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tevent string\n\t\texpected int\n\t}{\n\n\t\t{\"Test 1: All\", \"test?a\", 37},\n\t\t{\"Test 2: Letter (?l)\", \"test?l\", 26},\n\t\t{\"Test 3: Letter (?u)\", \"test?u\", 26},\n\t\t{\"Test 4: Digit\", \"test?d\", 10},\n\t\t{\"Test 5: Special\", \"test?s\", 1},\n\t\t{\"Test 6: Multiple All\", \"test?a?a\", 1369},\n\t\t{\"Test 7: Multiple Letters (?l)\", \"test?l?l\", 676},\n\t\t{\"Test 8: Multiple Letters (?u)\", \"test?u?u\", 676},\n\t\t{\"Test 9: Multiple Digits\", \"test?d?d\", 100},\n\t\t{\"Test 10: Multiple Special\", \"test?s?s\", 1},\n\t\t{\"Test 11: Mixed Mask\", \"test?a?l?d\", 9620},\n\t\t{\"Test 12: Mask too long\", \"test?a?a?a?a?a\", 0},\n\t\t{\"Test 13: No Mask\", \"test\", 1},\n\t\t{\"Test 14: Bad Mask\", \"?#\", 0},\n\t\t{\"Test 15: Worse Mask\", \"?a?^\", 0},\n\t}\n\n\tfor _, tt := range tests {\n\t\ts, _ := ExpandMask(tt.event)\n\t\tif len(s) != tt.expected {\n\t\t\tt.Errorf(\"Error Event %s: was expecting %d, got %d\", tt.name, tt.expected, len(s))\n\t\t}\n\t}\n}\n\nfunc TestExpandMaskWordlist(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tevent []string\n\t\texpected int\n\t}{\n\n\t\t{\"Test 1: Wordlist\", []string{\"?a\", \"?d\", \"?u\", \"?l\", \"?s\", \"none\", \"none2\", \"?#\", \"?a?%\"}, 102},\n\t}\n\tfor _, tt := range tests {\n\t\ts, _ := ExpandMaskWordlist(tt.event)\n\n\t\tif len(s) != tt.expected {\n\t\t\tt.Errorf(\"Error Event %s: was expecting %d, got %d\", tt.name, tt.expected, len(s))\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/engine.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage engine\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/api/graphql/server\"\n\t\"github.com/owasp-amass/amass/v5/engine/dispatcher\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins\"\n\t\"github.com/owasp-amass/amass/v5/engine/registry\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\ntype Engine struct {\n\tLog *slog.Logger\n\tDispatcher et.Dispatcher\n\tRegistry et.Registry\n\tManager et.SessionManager\n\tServer *server.Server\n}\n\nfunc NewEngine(l *slog.Logger) (*Engine, error) {\n\tif l == nil {\n\t\tl = slog.New(slog.NewTextHandler(os.Stdout, nil))\n\t}\n\n\tmgr := sessions.NewManager(l)\n\tif mgr == nil {\n\t\treturn nil, errors.New(\"failed to create the session manager\")\n\t}\n\treg := registry.NewRegistry(l)\n\n\tdis := dispatcher.NewDispatcher(l, reg, mgr)\n\tif dis == nil {\n\t\tmgr.Shutdown()\n\t\treturn nil, errors.New(\"failed to create the event scheduler\")\n\t}\n\n\tif err := plugins.LoadAndStartPlugins(reg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := reg.BuildPipelines(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := server.NewServer(l, dis, mgr)\n\tif srv == nil {\n\t\tdis.Shutdown()\n\t\tmgr.Shutdown()\n\t\treturn nil, errors.New(\"failed to create the API server\")\n\t}\n\n\tch := make(chan error, 1)\n\tgo func(errch chan error) { errch <- srv.Start() }(ch)\n\n\tt := time.NewTimer(3 * time.Second)\n\tdefer t.Stop()\n\n\tselect {\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\t_ = srv.Shutdown()\n\t\t\tdis.Shutdown()\n\t\t\tmgr.Shutdown()\n\t\t\treturn nil, err\n\t\t}\n\tcase <-t.C:\n\t\t// If the server does not return an error within 3 seconds, we assume it started successfully\n\t}\n\n\treturn &Engine{\n\t\tLog: l,\n\t\tDispatcher: dis,\n\t\tRegistry: reg,\n\t\tManager: mgr,\n\t\tServer: srv,\n\t}, nil\n}\n\nfunc (e *Engine) Shutdown() {\n\t_ = e.Server.Shutdown()\n\te.Dispatcher.Shutdown()\n\te.Manager.Shutdown()\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/client/client.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage client\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/gorilla/websocket\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\ntype Handler func(message string)\n\ntype Client struct {\n\turl string\n\thttpClient http.Client\n\twsClient *websocket.Conn\n}\n\nfunc NewClient(url string) *Client {\n\treturn &Client{url: url, httpClient: http.Client{}}\n}\n\nfunc (c *Client) Query(query string) (string, error) {\n\tquoted := strings.Trim(strconv.Quote((string(query))), `\"`)\n\tb := []byte(fmt.Sprintf(`{\"query\":\"%s\"}`, quoted))\n\n\treq, err := http.NewRequest(http.MethodPost, c.url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tres, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t} else if res.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"response indicated status: %s\", res.Status)\n\t}\n\tdefer func() { _ = res.Body.Close() }()\n\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n// Create a session by sending the config elements as graphql named fields\n// TODO: Not Implemented. The transfromations use \"->\" in the config YAML,\n// but that is not a valid field name in GraphQL\nfunc (c *Client) CreateSession(config *config.Config) (uuid.UUID, error) {\n\tvar token uuid.UUID\n\tconfigJson, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tquoted := strings.Trim(strconv.Quote((string(configJson))), `\"`)\n\tquery := fmt.Sprintf(`mutation { createSessionFromJson(input: {config: \"%s\"}) {sessionToken} }`, quoted)\n\n\tres, err := c.Query(query)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tvar resp struct {\n\t\tErrors []struct {\n\t\t\tMessage string `json:\"message\"`\n\t\t} `json:\"errors\"`\n\t\tData struct {\n\t\t\tCreateSessionFromJson struct {\n\t\t\t\tSessionToken string\n\t\t\t} `json:\"createSessionFromJson\"`\n\t\t} `json:\"data\"`\n\t}\n\tif err := json.Unmarshal([]byte(res), &resp); err != nil {\n\t\treturn token, err\n\t}\n\tif len(resp.Errors) > 0 && resp.Errors[0].Message != \"\" {\n\t\treturn token, errors.New(resp.Errors[0].Message)\n\t}\n\n\treturn uuid.Parse(resp.Data.CreateSessionFromJson.SessionToken)\n}\n\nfunc (c *Client) CreateAsset(asset et.Asset, token uuid.UUID) error {\n\tasset.Session = token\n\tassetJson, err := json.Marshal(asset)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar data interface{}\n\tif err := json.Unmarshal(assetJson, &data); err != nil {\n\t\treturn err\n\t}\n\tq := gqlEncoder(data)\n\n\tqueryStr := fmt.Sprintf(`mutation { createAsset(input: %s) {id} }`, string(q))\n\tif _, err := c.Query(queryStr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Client) TerminateSession(token uuid.UUID) {\n\t_, _ = c.Query(fmt.Sprintf(`mutation { terminateSession(sessionToken: \"%s\") }`, token.String()))\n}\n\nfunc (c *Client) SessionStats(token uuid.UUID) (*et.SessionStats, error) {\n\tqueryStr := fmt.Sprintf(`query { sessionStats(sessionToken: \"%s\"){\n\t\tWorkItemsCompleted \n\t\tWorkItemsTotal} }`, token.String())\n\n\tres, err := c.Query(queryStr)\n\tif err != nil {\n\t\treturn &et.SessionStats{}, err\n\t}\n\n\tvar resp struct {\n\t\tErrors []struct {\n\t\t\tMessage string `json:\"message\"`\n\t\t} `json:\"errors\"`\n\t\tData struct {\n\t\t\tSessionStats et.SessionStats `json:\"sessionStats\"`\n\t\t} `json:\"data\"`\n\t}\n\tif err := json.Unmarshal([]byte(res), &resp); err != nil {\n\t\treturn &et.SessionStats{}, err\n\t}\n\tif len(resp.Errors) > 0 && resp.Errors[0].Message != \"\" {\n\t\treturn &et.SessionStats{}, errors.New(resp.Errors[0].Message)\n\t}\n\treturn &resp.Data.SessionStats, nil\n}\n\n// Creates subscription to receove a stream of log messages from the sever\nfunc (c *Client) Subscribe(token uuid.UUID) (<-chan string, error) {\n\tparsedURL, _ := url.Parse(c.url)\n\tparsedURL.Scheme = \"ws\"\n\tid := uuid.New().String()\n\n\tconn, _, err := websocket.DefaultDialer.Dial(parsedURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.wsClient = conn\n\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\t// Subprotocol Init\n\tmessage := fmt.Sprintf(`{\"type\": \"connection_init\",\"id\": \"%s\",\"payload\": {}}`, id)\n\terr = conn.WriteMessage(websocket.TextMessage, []byte(message))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Start the subscription\n\tid = uuid.New().String()\n\tmessage = fmt.Sprintf(`{\"type\": \"start\", \"id\":\"%s\", \"payload\":{\"query\":\"subscription { logMessages(sessionToken: \\\"%s\\\")}\"} }`, id, token.String())\n\terr = conn.WriteMessage(websocket.TextMessage, []byte(message))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch := make(chan string)\n\t// Receive go routine\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-interrupt:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\t_, message, err := c.wsClient.ReadMessage()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tch <- string(message)\n\t\t\t}\n\t\t}\n\t}()\n\treturn ch, nil\n}\n\n// Converts unmarshalled JSON into graphql field syntax\n// This is a simple function for testing\nfunc gqlEncoder(data interface{}) string {\n\tvar q string\n\n\tswitch data := data.(type) {\n\tcase map[string]interface{}:\n\t\tq += \"{\"\n\t\tfor key, val := range data {\n\t\t\tq += fmt.Sprintf(\"%s: %v,\", key, gqlEncoder(val))\n\t\t}\n\t\tq = strings.TrimRight(q, \", \")\n\t\tq += \"}\"\n\tcase []interface{}:\n\t\tq += \"[\"\n\t\tfor _, val := range data {\n\t\t\tq += fmt.Sprintf(\"%v, \", gqlEncoder(val))\n\t\t}\n\t\tq = strings.TrimRight(q, \", \")\n\t\tq += \"]\"\n\tcase string:\n\t\tq += fmt.Sprintf(\"\\\"%s\\\"\", data)\n\tdefault:\n\t\tq += fmt.Sprintf(\"%v\", data)\n\t}\n\treturn q\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/client/client_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2024. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage client\n\n/*\nfunc TestCreateSession(t *testing.T) {\n\tl := slog.New(slog.NewTextHandler(io.Discard, nil))\n\n\te, err := engine.NewEngine(l)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new engine: %v\", err)\n\t}\n\tdefer e.Shutdown()\n\n\tc := config.NewConfig()\n\tif err := config.AcquireConfig(\"\", \"config.yml\", c); err != nil {\n\t\tt.Errorf(\"AcquireConfig failed: %v\", err)\n\t}\n\n\tclient := NewClient(\"http://localhost:4000/graphql\")\n\tif _, err := client.CreateSession(c); err != nil {\n\t\tt.Errorf(\"CreateSession failed: %v\", err)\n\t}\n}\n\nfunc TestCreateAsset(t *testing.T) {\n\tl := slog.New(slog.NewTextHandler(io.Discard, nil))\n\n\te, err := engine.NewEngine(l)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new engine: %v\", err)\n\t}\n\tdefer e.Shutdown()\n\n\tc := config.NewConfig()\n\tif err := config.AcquireConfig(\"\", \"config.yml\", c); err != nil {\n\t\tt.Errorf(\"AcquireConfig failed: %v\", err)\n\t}\n\n\tclient := NewClient(\"http://localhost:4000/graphql\")\n\ttoken, _ := client.CreateSession(c)\n\n\taddr, _ := netip.ParseAddr(\"192.168.0.1\")\n\tasset := oamnet.IPAddress{Address: addr, Type: \"IPv4\"}\n\tdata := types.AssetData{\n\t\tOAMAsset: asset,\n\t\tOAMType: asset.AssetType(),\n\t}\n\n\ta := types.Asset{Session: token, Name: \"Asset#1\", Data: data}\n\tif err := client.CreateAsset(a, token); err != nil {\n\t\tt.Errorf(\"CreateAsset failed: %v\", err)\n\t}\n}\n\nfunc TestSubscribe(t *testing.T) {\n\tl := slog.New(slog.NewTextHandler(io.Discard, nil))\n\n\te, err := engine.NewEngine(l)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new engine: %v\", err)\n\t}\n\tdefer e.Shutdown()\n\n\tc := config.NewConfig()\n\tif err := config.AcquireConfig(\"\", \"config.yml\", c); err != nil {\n\t\tt.Errorf(\"AcquireConfig failed: %v\", err)\n\t}\n\n\tclient := NewClient(\"http://localhost:4000/graphql\")\n\ttoken, _ := client.CreateSession(c)\n\n\tch, err := client.Subscribe(token)\n\tif err != nil {\n\t\tt.Errorf(\"Subscribe failed: %v\", err)\n\t}\n\ttime.Sleep(time.Second)\n\n\tselect {\n\tcase <-ch:\n\tdefault:\n\t\tt.Error(\"Failed to receive a message from the channel\")\n\t}\n}\n*/\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/client/curl_test.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n#!/bin/bash\n\n\n#curl -X POST -H \"Content-Type: application/json\" -d '{\n# \"query\": \"mutation { createSession(input: {config: \\\"x\\\"}) { token }}\"\n#}' http://localhost:8080/graphql\n\n\n#curl -X POST -H \"Content-Type: application/json\" -d '{ \"query\": \"mutation { createEvent(input: {session_id: \\\"x\\\", event_name: \\\"asset\\\", data: \\\"y\\\", type: \\\"FQDN\\\"}) { id }}\"}' http://localhost:8080/graphql\n\ncurl -X POST -H \"Content-Type: application/json\" -d '{ \"query\": \" { ) { id }}\"}' http://localhost:8080/graphql\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/generated.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.\n\npackage server\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"embed\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/99designs/gqlgen/graphql\"\n\t\"github.com/99designs/gqlgen/graphql/introspection\"\n\t\"github.com/owasp-amass/amass/v5/engine/api/graphql/server/model\"\n\tgqlparser \"github.com/vektah/gqlparser/v2\"\n\t\"github.com/vektah/gqlparser/v2/ast\"\n)\n\n// region ************************** generated!.gotpl **************************\n\n// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface.\nfunc NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tschema: cfg.Schema,\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}\n\ntype Config struct {\n\tSchema *ast.Schema\n\tResolvers ResolverRoot\n\tDirectives DirectiveRoot\n\tComplexity ComplexityRoot\n}\n\ntype ResolverRoot interface {\n\tMutation() MutationResolver\n\tQuery() QueryResolver\n\tSubscription() SubscriptionResolver\n}\n\ntype DirectiveRoot struct {\n}\n\ntype ComplexityRoot struct {\n\tAsset struct {\n\t\tID func(childComplexity int) int\n\t}\n\n\tMutation struct {\n\t\tCreateAsset func(childComplexity int, input model.CreateAssetInput) int\n\t\tCreateSession func(childComplexity int, input model.CreateSessionInput) int\n\t\tCreateSessionFromJSON func(childComplexity int, input model.CreateSessionJSONInput) int\n\t\tTerminateSession func(childComplexity int, sessionToken string) int\n\t}\n\n\tQuery struct {\n\t\tSessionStats func(childComplexity int, sessionToken string) int\n\t}\n\n\tSession struct {\n\t\tSessionToken func(childComplexity int) int\n\t}\n\n\tSessionStats struct {\n\t\tWorkItemsCompleted func(childComplexity int) int\n\t\tWorkItemsTotal func(childComplexity int) int\n\t}\n\n\tSubscription struct {\n\t\tLogMessages func(childComplexity int, sessionToken string) int\n\t}\n}\n\ntype MutationResolver interface {\n\tCreateSession(ctx context.Context, input model.CreateSessionInput) (*model.Session, error)\n\tCreateSessionFromJSON(ctx context.Context, input model.CreateSessionJSONInput) (*model.Session, error)\n\tCreateAsset(ctx context.Context, input model.CreateAssetInput) (*model.Asset, error)\n\tTerminateSession(ctx context.Context, sessionToken string) (*bool, error)\n}\ntype QueryResolver interface {\n\tSessionStats(ctx context.Context, sessionToken string) (*model.SessionStats, error)\n}\ntype SubscriptionResolver interface {\n\tLogMessages(ctx context.Context, sessionToken string) (<-chan *string, error)\n}\n\ntype executableSchema struct {\n\tschema *ast.Schema\n\tresolvers ResolverRoot\n\tdirectives DirectiveRoot\n\tcomplexity ComplexityRoot\n}\n\nfunc (e *executableSchema) Schema() *ast.Schema {\n\tif e.schema != nil {\n\t\treturn e.schema\n\t}\n\treturn parsedSchema\n}\n\nfunc (e *executableSchema) Complexity(ctx context.Context, typeName, field string, childComplexity int, rawArgs map[string]any) (int, bool) {\n\tec := executionContext{nil, e, 0, 0, nil}\n\t_ = ec\n\tswitch typeName + \".\" + field {\n\n\tcase \"Asset.id\":\n\t\tif e.complexity.Asset.ID == nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn e.complexity.Asset.ID(childComplexity), true\n\n\tcase \"Mutation.createAsset\":\n\t\tif e.complexity.Mutation.CreateAsset == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Mutation_createAsset_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Mutation.CreateAsset(childComplexity, args[\"input\"].(model.CreateAssetInput)), true\n\n\tcase \"Mutation.createSession\":\n\t\tif e.complexity.Mutation.CreateSession == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Mutation_createSession_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Mutation.CreateSession(childComplexity, args[\"input\"].(model.CreateSessionInput)), true\n\n\tcase \"Mutation.createSessionFromJson\":\n\t\tif e.complexity.Mutation.CreateSessionFromJSON == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Mutation_createSessionFromJson_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Mutation.CreateSessionFromJSON(childComplexity, args[\"input\"].(model.CreateSessionJSONInput)), true\n\n\tcase \"Mutation.terminateSession\":\n\t\tif e.complexity.Mutation.TerminateSession == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Mutation_terminateSession_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Mutation.TerminateSession(childComplexity, args[\"sessionToken\"].(string)), true\n\n\tcase \"Query.sessionStats\":\n\t\tif e.complexity.Query.SessionStats == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Query_sessionStats_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Query.SessionStats(childComplexity, args[\"sessionToken\"].(string)), true\n\n\tcase \"Session.sessionToken\":\n\t\tif e.complexity.Session.SessionToken == nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn e.complexity.Session.SessionToken(childComplexity), true\n\n\tcase \"SessionStats.WorkItemsCompleted\":\n\t\tif e.complexity.SessionStats.WorkItemsCompleted == nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn e.complexity.SessionStats.WorkItemsCompleted(childComplexity), true\n\n\tcase \"SessionStats.WorkItemsTotal\":\n\t\tif e.complexity.SessionStats.WorkItemsTotal == nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn e.complexity.SessionStats.WorkItemsTotal(childComplexity), true\n\n\tcase \"Subscription.logMessages\":\n\t\tif e.complexity.Subscription.LogMessages == nil {\n\t\t\tbreak\n\t\t}\n\n\t\targs, err := ec.field_Subscription_logMessages_args(context.TODO(), rawArgs)\n\t\tif err != nil {\n\t\t\treturn 0, false\n\t\t}\n\n\t\treturn e.complexity.Subscription.LogMessages(childComplexity, args[\"sessionToken\"].(string)), true\n\n\t}\n\treturn 0, false\n}\n\nfunc (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler {\n\trc := graphql.GetOperationContext(ctx)\n\tec := executionContext{rc, e, 0, 0, make(chan graphql.DeferredResult)}\n\tinputUnmarshalMap := graphql.BuildUnmarshalerMap(\n\t\tec.unmarshalInputConfig,\n\t\tec.unmarshalInputCreateAssetInput,\n\t\tec.unmarshalInputCreateSessionInput,\n\t\tec.unmarshalInputCreateSessionJsonInput,\n\t)\n\tfirst := true\n\n\tswitch rc.Operation.Operation {\n\tcase ast.Query:\n\t\treturn func(ctx context.Context) *graphql.Response {\n\t\t\tvar response graphql.Response\n\t\t\tvar data graphql.Marshaler\n\t\t\tif first {\n\t\t\t\tfirst = false\n\t\t\t\tctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap)\n\t\t\t\tdata = ec._Query(ctx, rc.Operation.SelectionSet)\n\t\t\t} else {\n\t\t\t\tif atomic.LoadInt32(&ec.pendingDeferred) > 0 {\n\t\t\t\t\tresult := <-ec.deferredResults\n\t\t\t\t\tatomic.AddInt32(&ec.pendingDeferred, -1)\n\t\t\t\t\tdata = result.Result\n\t\t\t\t\tresponse.Path = result.Path\n\t\t\t\t\tresponse.Label = result.Label\n\t\t\t\t\tresponse.Errors = result.Errors\n\t\t\t\t} else {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tdata.MarshalGQL(&buf)\n\t\t\tresponse.Data = buf.Bytes()\n\t\t\tif atomic.LoadInt32(&ec.deferred) > 0 {\n\t\t\t\thasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0\n\t\t\t\tresponse.HasNext = &hasNext\n\t\t\t}\n\n\t\t\treturn &response\n\t\t}\n\tcase ast.Mutation:\n\t\treturn func(ctx context.Context) *graphql.Response {\n\t\t\tif !first {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfirst = false\n\t\t\tctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap)\n\t\t\tdata := ec._Mutation(ctx, rc.Operation.SelectionSet)\n\t\t\tvar buf bytes.Buffer\n\t\t\tdata.MarshalGQL(&buf)\n\n\t\t\treturn &graphql.Response{\n\t\t\t\tData: buf.Bytes(),\n\t\t\t}\n\t\t}\n\tcase ast.Subscription:\n\t\tnext := ec._Subscription(ctx, rc.Operation.SelectionSet)\n\n\t\tvar buf bytes.Buffer\n\t\treturn func(ctx context.Context) *graphql.Response {\n\t\t\tbuf.Reset()\n\t\t\tdata := next(ctx)\n\n\t\t\tif data == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tdata.MarshalGQL(&buf)\n\n\t\t\treturn &graphql.Response{\n\t\t\t\tData: buf.Bytes(),\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn graphql.OneShot(graphql.ErrorResponse(ctx, \"unsupported GraphQL operation\"))\n\t}\n}\n\ntype executionContext struct {\n\t*graphql.OperationContext\n\t*executableSchema\n\tdeferred int32\n\tpendingDeferred int32\n\tdeferredResults chan graphql.DeferredResult\n}\n\nfunc (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) {\n\tatomic.AddInt32(&ec.pendingDeferred, 1)\n\tgo func() {\n\t\tctx := graphql.WithFreshResponseContext(dg.Context)\n\t\tdg.FieldSet.Dispatch(ctx)\n\t\tds := graphql.DeferredResult{\n\t\t\tPath: dg.Path,\n\t\t\tLabel: dg.Label,\n\t\t\tResult: dg.FieldSet,\n\t\t\tErrors: graphql.GetErrors(ctx),\n\t\t}\n\t\t// null fields should bubble up\n\t\tif dg.FieldSet.Invalids > 0 {\n\t\t\tds.Result = graphql.Null\n\t\t}\n\t\tec.deferredResults <- ds\n\t}()\n}\n\nfunc (ec *executionContext) introspectSchema() (*introspection.Schema, error) {\n\tif ec.DisableIntrospection {\n\t\treturn nil, errors.New(\"introspection disabled\")\n\t}\n\treturn introspection.WrapSchema(ec.Schema()), nil\n}\n\nfunc (ec *executionContext) introspectType(name string) (*introspection.Type, error) {\n\tif ec.DisableIntrospection {\n\t\treturn nil, errors.New(\"introspection disabled\")\n\t}\n\treturn introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil\n}\n\n//go:embed \"schema.graphqls\"\nvar sourcesFS embed.FS\n\nfunc sourceData(filename string) string {\n\tdata, err := sourcesFS.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"codegen problem: %s not available\", filename))\n\t}\n\treturn string(data)\n}\n\nvar sources = []*ast.Source{\n\t{Name: \"schema.graphqls\", Input: sourceData(\"schema.graphqls\"), BuiltIn: false},\n}\nvar parsedSchema = gqlparser.MustLoadSchema(sources...)\n\n// endregion ************************** generated!.gotpl **************************\n\n// region ***************************** args.gotpl *****************************\n\nfunc (ec *executionContext) field_Mutation_createAsset_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.CreateAssetInput\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNCreateAssetInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateAssetInput(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Mutation_createSessionFromJson_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.CreateSessionJSONInput\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNCreateSessionJsonInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateSessionJSONInput(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Mutation_createSession_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.CreateSessionInput\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNCreateSessionInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateSessionInput(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Mutation_terminateSession_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 string\n\tif tmp, ok := rawArgs[\"sessionToken\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"sessionToken\"))\n\t\targ0, err = ec.unmarshalNString2string(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"sessionToken\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 string\n\tif tmp, ok := rawArgs[\"name\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"name\"))\n\t\targ0, err = ec.unmarshalNString2string(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"name\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Query_sessionStats_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 string\n\tif tmp, ok := rawArgs[\"sessionToken\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"sessionToken\"))\n\t\targ0, err = ec.unmarshalNString2string(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"sessionToken\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field_Subscription_logMessages_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 string\n\tif tmp, ok := rawArgs[\"sessionToken\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"sessionToken\"))\n\t\targ0, err = ec.unmarshalNString2string(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"sessionToken\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 bool\n\tif tmp, ok := rawArgs[\"includeDeprecated\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"includeDeprecated\"))\n\t\targ0, err = ec.unmarshalOBoolean2bool(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"includeDeprecated\"] = arg0\n\treturn args, nil\n}\n\nfunc (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 bool\n\tif tmp, ok := rawArgs[\"includeDeprecated\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"includeDeprecated\"))\n\t\targ0, err = ec.unmarshalOBoolean2bool(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"includeDeprecated\"] = arg0\n\treturn args, nil\n}\n\n// endregion ***************************** args.gotpl *****************************\n\n// region ************************** directives.gotpl **************************\n\n// endregion ************************** directives.gotpl **************************\n\n// region **************************** field.gotpl *****************************\n\nfunc (ec *executionContext) _Asset_id(ctx context.Context, field graphql.CollectedField, obj *model.Asset) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Asset_id(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Asset_id(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Asset\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type ID does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Mutation_createSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Mutation_createSession(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Mutation().CreateSession(rctx, fc.Args[\"input\"].(model.CreateSessionInput))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*model.Session)\n\tfc.Result = res\n\treturn ec.marshalOSession2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690Session(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Mutation_createSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Mutation\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"sessionToken\":\n\t\t\t\treturn ec.fieldContext_Session_sessionToken(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type Session\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Mutation_createSession_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Mutation_createSessionFromJson(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Mutation_createSessionFromJson(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Mutation().CreateSessionFromJSON(rctx, fc.Args[\"input\"].(model.CreateSessionJSONInput))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*model.Session)\n\tfc.Result = res\n\treturn ec.marshalOSession2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690Session(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Mutation_createSessionFromJson(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Mutation\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"sessionToken\":\n\t\t\t\treturn ec.fieldContext_Session_sessionToken(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type Session\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Mutation_createSessionFromJson_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Mutation_createAsset(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Mutation_createAsset(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Mutation().CreateAsset(rctx, fc.Args[\"input\"].(model.CreateAssetInput))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*model.Asset)\n\tfc.Result = res\n\treturn ec.marshalOAsset2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690Asset(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Mutation_createAsset(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Mutation\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"id\":\n\t\t\t\treturn ec.fieldContext_Asset_id(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type Asset\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Mutation_createAsset_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Mutation_terminateSession(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Mutation_terminateSession(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Mutation().TerminateSession(rctx, fc.Args[\"sessionToken\"].(string))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*bool)\n\tfc.Result = res\n\treturn ec.marshalOBoolean2\u1696bool(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Mutation_terminateSession(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Mutation\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Boolean does not have child fields\")\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Mutation_terminateSession_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Query_sessionStats(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Query_sessionStats(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Query().SessionStats(rctx, fc.Args[\"sessionToken\"].(string))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*model.SessionStats)\n\tfc.Result = res\n\treturn ec.marshalOSessionStats2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690SessionStats(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Query_sessionStats(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Query\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"WorkItemsCompleted\":\n\t\t\t\treturn ec.fieldContext_SessionStats_WorkItemsCompleted(ctx, field)\n\t\t\tcase \"WorkItemsTotal\":\n\t\t\t\treturn ec.fieldContext_SessionStats_WorkItemsTotal(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type SessionStats\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Query_sessionStats_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Query___type(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.introspectType(fc.Args[\"name\"].(string))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Query\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Query___schema(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.introspectSchema()\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Schema)\n\tfc.Result = res\n\treturn ec.marshalO__Schema2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Schema(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Query___schema(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Query\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Schema_description(ctx, field)\n\t\t\tcase \"types\":\n\t\t\t\treturn ec.fieldContext___Schema_types(ctx, field)\n\t\t\tcase \"queryType\":\n\t\t\t\treturn ec.fieldContext___Schema_queryType(ctx, field)\n\t\t\tcase \"mutationType\":\n\t\t\t\treturn ec.fieldContext___Schema_mutationType(ctx, field)\n\t\t\tcase \"subscriptionType\":\n\t\t\t\treturn ec.fieldContext___Schema_subscriptionType(ctx, field)\n\t\t\tcase \"directives\":\n\t\t\t\treturn ec.fieldContext___Schema_directives(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Schema\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Session_sessionToken(ctx context.Context, field graphql.CollectedField, obj *model.Session) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Session_sessionToken(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.SessionToken, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_Session_sessionToken(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Session\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type ID does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _SessionStats_WorkItemsCompleted(ctx context.Context, field graphql.CollectedField, obj *model.SessionStats) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_SessionStats_WorkItemsCompleted(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.WorkItemsCompleted, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*int)\n\tfc.Result = res\n\treturn ec.marshalOInt2\u1696int(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_SessionStats_WorkItemsCompleted(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"SessionStats\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Int does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _SessionStats_WorkItemsTotal(ctx context.Context, field graphql.CollectedField, obj *model.SessionStats) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_SessionStats_WorkItemsTotal(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.WorkItemsTotal, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*int)\n\tfc.Result = res\n\treturn ec.marshalOInt2\u1696int(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext_SessionStats_WorkItemsTotal(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"SessionStats\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Int does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) _Subscription_logMessages(ctx context.Context, field graphql.CollectedField) (ret func(ctx context.Context) graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Subscription_logMessages(ctx, field)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = nil\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Subscription().LogMessages(rctx, fc.Args[\"sessionToken\"].(string))\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn nil\n\t}\n\tif resTmp == nil {\n\t\treturn nil\n\t}\n\treturn func(ctx context.Context) graphql.Marshaler {\n\t\tselect {\n\t\tcase res, ok := <-resTmp.(<-chan *string):\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn graphql.WriterFunc(func(w io.Writer) {\n\t\t\t\tw.Write([]byte{'{'})\n\t\t\t\tgraphql.MarshalString(field.Alias).MarshalGQL(w)\n\t\t\t\tw.Write([]byte{':'})\n\t\t\t\tec.marshalOString2\u1696string(ctx, field.Selections, res).MarshalGQL(w)\n\t\t\t\tw.Write([]byte{'}'})\n\t\t\t})\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc (ec *executionContext) fieldContext_Subscription_logMessages(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"Subscription\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: true,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field_Subscription_logMessages_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Directive_name(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Name, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNString2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Directive_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Directive\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Directive_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Directive_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Directive\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Directive_locations(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Locations, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]string)\n\tfc.Result = res\n\treturn ec.marshalN__DirectiveLocation2\u1695string\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Directive_locations(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Directive\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type __DirectiveLocation does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Directive_args(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Args, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.InputValue)\n\tfc.Result = res\n\treturn ec.marshalN__InputValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Directive_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Directive\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___InputValue_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___InputValue_description(ctx, field)\n\t\t\tcase \"type\":\n\t\t\t\treturn ec.fieldContext___InputValue_type(ctx, field)\n\t\t\tcase \"defaultValue\":\n\t\t\t\treturn ec.fieldContext___InputValue_defaultValue(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __InputValue\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Directive_isRepeatable(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.IsRepeatable, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(bool)\n\tfc.Result = res\n\treturn ec.marshalNBoolean2bool(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Directive\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Boolean does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___EnumValue_name(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Name, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNString2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___EnumValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__EnumValue\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___EnumValue_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___EnumValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__EnumValue\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___EnumValue_isDeprecated(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.IsDeprecated(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(bool)\n\tfc.Result = res\n\treturn ec.marshalNBoolean2bool(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__EnumValue\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Boolean does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___EnumValue_deprecationReason(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.DeprecationReason(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__EnumValue\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_name(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Name, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNString2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_args(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Args, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.InputValue)\n\tfc.Result = res\n\treturn ec.marshalN__InputValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_args(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___InputValue_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___InputValue_description(ctx, field)\n\t\t\tcase \"type\":\n\t\t\t\treturn ec.fieldContext___InputValue_type(ctx, field)\n\t\t\tcase \"defaultValue\":\n\t\t\t\treturn ec.fieldContext___InputValue_defaultValue(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __InputValue\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_type(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Type, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalN__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_isDeprecated(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.IsDeprecated(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(bool)\n\tfc.Result = res\n\treturn ec.marshalNBoolean2bool(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_isDeprecated(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type Boolean does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Field_deprecationReason(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.DeprecationReason(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Field_deprecationReason(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Field\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___InputValue_name(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Name, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNString2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___InputValue_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__InputValue\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___InputValue_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___InputValue_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__InputValue\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___InputValue_type(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Type, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalN__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___InputValue_type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__InputValue\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___InputValue_defaultValue(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.DefaultValue, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__InputValue\",\n\t\tField: field,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_types(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Types(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalN__Type2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_types(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_queryType(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.QueryType(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalN__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_queryType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_mutationType(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.MutationType(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_mutationType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_subscriptionType(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.SubscriptionType(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Schema_directives(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Directives(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.Directive)\n\tfc.Result = res\n\treturn ec.marshalN__Directive2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Directive\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Schema_directives(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Schema\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Directive_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Directive_description(ctx, field)\n\t\t\tcase \"locations\":\n\t\t\t\treturn ec.fieldContext___Directive_locations(ctx, field)\n\t\t\tcase \"args\":\n\t\t\t\treturn ec.fieldContext___Directive_args(ctx, field)\n\t\t\tcase \"isRepeatable\":\n\t\t\t\treturn ec.fieldContext___Directive_isRepeatable(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Directive\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_kind(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Kind(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalN__TypeKind2string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_kind(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type __TypeKind does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_name(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Name(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_name(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_description(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Description(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_description(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_fields(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Fields(fc.Args[\"includeDeprecated\"].(bool)), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.Field)\n\tfc.Result = res\n\treturn ec.marshalO__Field2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Field\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_fields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Field_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Field_description(ctx, field)\n\t\t\tcase \"args\":\n\t\t\t\treturn ec.fieldContext___Field_args(ctx, field)\n\t\t\tcase \"type\":\n\t\t\t\treturn ec.fieldContext___Field_type(ctx, field)\n\t\t\tcase \"isDeprecated\":\n\t\t\t\treturn ec.fieldContext___Field_isDeprecated(ctx, field)\n\t\t\tcase \"deprecationReason\":\n\t\t\t\treturn ec.fieldContext___Field_deprecationReason(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Field\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field___Type_fields_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_interfaces(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.Interfaces(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_interfaces(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_possibleTypes(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.PossibleTypes(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_possibleTypes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_enumValues(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.EnumValues(fc.Args[\"includeDeprecated\"].(bool)), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.EnumValue)\n\tfc.Result = res\n\treturn ec.marshalO__EnumValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690EnumValue\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___EnumValue_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___EnumValue_description(ctx, field)\n\t\t\tcase \"isDeprecated\":\n\t\t\t\treturn ec.fieldContext___EnumValue_isDeprecated(ctx, field)\n\t\t\tcase \"deprecationReason\":\n\t\t\t\treturn ec.fieldContext___EnumValue_deprecationReason(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __EnumValue\", field.Name)\n\t\t},\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = ec.Recover(ctx, r)\n\t\t\tec.Error(ctx, err)\n\t\t}\n\t}()\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tif fc.Args, err = ec.field___Type_enumValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn fc, err\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_inputFields(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.InputFields(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.([]introspection.InputValue)\n\tfc.Result = res\n\treturn ec.marshalO__InputValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue\u1684(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_inputFields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___InputValue_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___InputValue_description(ctx, field)\n\t\t\tcase \"type\":\n\t\t\t\treturn ec.fieldContext___InputValue_type(ctx, field)\n\t\t\tcase \"defaultValue\":\n\t\t\t\treturn ec.fieldContext___InputValue_defaultValue(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __InputValue\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_ofType(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.OfType(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*introspection.Type)\n\tfc.Result = res\n\treturn ec.marshalO__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_ofType(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\tswitch field.Name {\n\t\t\tcase \"kind\":\n\t\t\t\treturn ec.fieldContext___Type_kind(ctx, field)\n\t\t\tcase \"name\":\n\t\t\t\treturn ec.fieldContext___Type_name(ctx, field)\n\t\t\tcase \"description\":\n\t\t\t\treturn ec.fieldContext___Type_description(ctx, field)\n\t\t\tcase \"fields\":\n\t\t\t\treturn ec.fieldContext___Type_fields(ctx, field)\n\t\t\tcase \"interfaces\":\n\t\t\t\treturn ec.fieldContext___Type_interfaces(ctx, field)\n\t\t\tcase \"possibleTypes\":\n\t\t\t\treturn ec.fieldContext___Type_possibleTypes(ctx, field)\n\t\t\tcase \"enumValues\":\n\t\t\t\treturn ec.fieldContext___Type_enumValues(ctx, field)\n\t\t\tcase \"inputFields\":\n\t\t\t\treturn ec.fieldContext___Type_inputFields(ctx, field)\n\t\t\tcase \"ofType\":\n\t\t\t\treturn ec.fieldContext___Type_ofType(ctx, field)\n\t\t\tcase \"specifiedByURL\":\n\t\t\t\treturn ec.fieldContext___Type_specifiedByURL(ctx, field)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"no field named %q was found under type __Type\", field.Name)\n\t\t},\n\t}\n\treturn fc, nil\n}\n\nfunc (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext___Type_specifiedByURL(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.SpecifiedByURL(), nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(*string)\n\tfc.Result = res\n\treturn ec.marshalOString2\u1696string(ctx, field.Selections, res)\n}\n\nfunc (ec *executionContext) fieldContext___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {\n\tfc = &graphql.FieldContext{\n\t\tObject: \"__Type\",\n\t\tField: field,\n\t\tIsMethod: true,\n\t\tIsResolver: false,\n\t\tChild: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {\n\t\t\treturn nil, errors.New(\"field of type String does not have child fields\")\n\t\t},\n\t}\n\treturn fc, nil\n}\n\n// endregion **************************** field.gotpl *****************************\n\n// region **************************** input.gotpl *****************************\n\nfunc (ec *executionContext) unmarshalInputConfig(ctx context.Context, obj interface{}) (model.Config, error) {\n\tvar it model.Config\n\tasMap := map[string]interface{}{}\n\tfor k, v := range obj.(map[string]interface{}) {\n\t\tasMap[k] = v\n\t}\n\n\tfieldsInOrder := [...]string{\"scope\", \"ports\", \"blacklist\", \"domains\", \"resolvers\", \"ips\", \"cirds\", \"transformations\", \"database\", \"bruteForce\", \"alterations\"}\n\tfor _, k := range fieldsInOrder {\n\t\tv, ok := asMap[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch k {\n\t\tcase \"scope\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"scope\"))\n\t\t\tdata, err := ec.unmarshalOAny2\u1695interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Scope = data\n\t\tcase \"ports\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"ports\"))\n\t\t\tdata, err := ec.unmarshalOInt2\u1695\u1696int(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Ports = data\n\t\tcase \"blacklist\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"blacklist\"))\n\t\t\tdata, err := ec.unmarshalOString2\u1695\u1696string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Blacklist = data\n\t\tcase \"domains\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"domains\"))\n\t\t\tdata, err := ec.unmarshalOString2\u1695\u1696string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Domains = data\n\t\tcase \"resolvers\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"resolvers\"))\n\t\t\tdata, err := ec.unmarshalOString2\u1695\u1696string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Resolvers = data\n\t\tcase \"ips\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"ips\"))\n\t\t\tdata, err := ec.unmarshalOString2\u1695\u1696string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Ips = data\n\t\tcase \"cirds\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"cirds\"))\n\t\t\tdata, err := ec.unmarshalOAny2\u1695interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Cirds = data\n\t\tcase \"transformations\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"transformations\"))\n\t\t\tdata, err := ec.unmarshalOAny2\u1695interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Transformations = data\n\t\tcase \"database\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"database\"))\n\t\t\tdata, err := ec.unmarshalOAny2\u1695interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Database = data\n\t\tcase \"bruteForce\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"bruteForce\"))\n\t\t\tdata, err := ec.unmarshalOBoolean2\u1696bool(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.BruteForce = data\n\t\tcase \"alterations\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"alterations\"))\n\t\t\tdata, err := ec.unmarshalOBoolean2\u1696bool(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Alterations = data\n\t\t}\n\t}\n\n\treturn it, nil\n}\n\nfunc (ec *executionContext) unmarshalInputCreateAssetInput(ctx context.Context, obj interface{}) (model.CreateAssetInput, error) {\n\tvar it model.CreateAssetInput\n\tasMap := map[string]interface{}{}\n\tfor k, v := range obj.(map[string]interface{}) {\n\t\tasMap[k] = v\n\t}\n\n\tfieldsInOrder := [...]string{\"sessionToken\", \"assetName\", \"data\"}\n\tfor _, k := range fieldsInOrder {\n\t\tv, ok := asMap[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch k {\n\t\tcase \"sessionToken\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"sessionToken\"))\n\t\t\tdata, err := ec.unmarshalNID2string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.SessionToken = data\n\t\tcase \"assetName\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"assetName\"))\n\t\t\tdata, err := ec.unmarshalOString2\u1696string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.AssetName = data\n\t\tcase \"data\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"data\"))\n\t\t\tdata, err := ec.unmarshalOAny2interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Data = data\n\t\t}\n\t}\n\n\treturn it, nil\n}\n\nfunc (ec *executionContext) unmarshalInputCreateSessionInput(ctx context.Context, obj interface{}) (model.CreateSessionInput, error) {\n\tvar it model.CreateSessionInput\n\tasMap := map[string]interface{}{}\n\tfor k, v := range obj.(map[string]interface{}) {\n\t\tasMap[k] = v\n\t}\n\n\tfieldsInOrder := [...]string{\"config\"}\n\tfor _, k := range fieldsInOrder {\n\t\tv, ok := asMap[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch k {\n\t\tcase \"config\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"config\"))\n\t\t\tdata, err := ec.unmarshalNAny2interface(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Config = data\n\t\t}\n\t}\n\n\treturn it, nil\n}\n\nfunc (ec *executionContext) unmarshalInputCreateSessionJsonInput(ctx context.Context, obj interface{}) (model.CreateSessionJSONInput, error) {\n\tvar it model.CreateSessionJSONInput\n\tasMap := map[string]interface{}{}\n\tfor k, v := range obj.(map[string]interface{}) {\n\t\tasMap[k] = v\n\t}\n\n\tfieldsInOrder := [...]string{\"config\"}\n\tfor _, k := range fieldsInOrder {\n\t\tv, ok := asMap[k]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch k {\n\t\tcase \"config\":\n\t\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"config\"))\n\t\t\tdata, err := ec.unmarshalNString2string(ctx, v)\n\t\t\tif err != nil {\n\t\t\t\treturn it, err\n\t\t\t}\n\t\t\tit.Config = data\n\t\t}\n\t}\n\n\treturn it, nil\n}\n\n// endregion **************************** input.gotpl *****************************\n\n// region ************************** interface.gotpl ***************************\n\n// endregion ************************** interface.gotpl ***************************\n\n// region **************************** object.gotpl ****************************\n\nvar assetImplementors = []string{\"Asset\"}\n\nfunc (ec *executionContext) _Asset(ctx context.Context, sel ast.SelectionSet, obj *model.Asset) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, assetImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"Asset\")\n\t\tcase \"id\":\n\t\t\tout.Values[i] = ec._Asset_id(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar mutationImplementors = []string{\"Mutation\"}\n\nfunc (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, mutationImplementors)\n\tctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{\n\t\tObject: \"Mutation\",\n\t})\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tinnerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{\n\t\t\tObject: field.Name,\n\t\t\tField: field,\n\t\t})\n\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"Mutation\")\n\t\tcase \"createSession\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Mutation_createSession(ctx, field)\n\t\t\t})\n\t\tcase \"createSessionFromJson\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Mutation_createSessionFromJson(ctx, field)\n\t\t\t})\n\t\tcase \"createAsset\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Mutation_createAsset(ctx, field)\n\t\t\t})\n\t\tcase \"terminateSession\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Mutation_terminateSession(ctx, field)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar queryImplementors = []string{\"Query\"}\n\nfunc (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors)\n\tctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{\n\t\tObject: \"Query\",\n\t})\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tinnerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{\n\t\t\tObject: field.Name,\n\t\t\tField: field,\n\t\t})\n\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"Query\")\n\t\tcase \"sessionStats\":\n\t\t\tfield := field\n\n\t\t\tinnerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tres = ec._Query_sessionStats(ctx, field)\n\t\t\t\treturn res\n\t\t\t}\n\n\t\t\trrm := func(ctx context.Context) graphql.Marshaler {\n\t\t\t\treturn ec.OperationContext.RootResolverMiddleware(ctx,\n\t\t\t\t\tfunc(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })\n\t\t\t}\n\n\t\t\tout.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })\n\t\tcase \"__type\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Query___type(ctx, field)\n\t\t\t})\n\t\tcase \"__schema\":\n\t\t\tout.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {\n\t\t\t\treturn ec._Query___schema(ctx, field)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar sessionImplementors = []string{\"Session\"}\n\nfunc (ec *executionContext) _Session(ctx context.Context, sel ast.SelectionSet, obj *model.Session) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, sessionImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"Session\")\n\t\tcase \"sessionToken\":\n\t\t\tout.Values[i] = ec._Session_sessionToken(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar sessionStatsImplementors = []string{\"SessionStats\"}\n\nfunc (ec *executionContext) _SessionStats(ctx context.Context, sel ast.SelectionSet, obj *model.SessionStats) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, sessionStatsImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"SessionStats\")\n\t\tcase \"WorkItemsCompleted\":\n\t\t\tout.Values[i] = ec._SessionStats_WorkItemsCompleted(ctx, field, obj)\n\t\tcase \"WorkItemsTotal\":\n\t\t\tout.Values[i] = ec._SessionStats_WorkItemsTotal(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar subscriptionImplementors = []string{\"Subscription\"}\n\nfunc (ec *executionContext) _Subscription(ctx context.Context, sel ast.SelectionSet) func(ctx context.Context) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, subscriptionImplementors)\n\tctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{\n\t\tObject: \"Subscription\",\n\t})\n\tif len(fields) != 1 {\n\t\tec.Errorf(ctx, \"must subscribe to exactly one stream\")\n\t\treturn nil\n\t}\n\n\tswitch fields[0].Name {\n\tcase \"logMessages\":\n\t\treturn ec._Subscription_logMessages(ctx, fields[0])\n\tdefault:\n\t\tpanic(\"unknown field \" + strconv.Quote(fields[0].Name))\n\t}\n}\n\nvar __DirectiveImplementors = []string{\"__Directive\"}\n\nfunc (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__Directive\")\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec.___Directive_name(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___Directive_description(ctx, field, obj)\n\t\tcase \"locations\":\n\t\t\tout.Values[i] = ec.___Directive_locations(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"args\":\n\t\t\tout.Values[i] = ec.___Directive_args(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"isRepeatable\":\n\t\t\tout.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar __EnumValueImplementors = []string{\"__EnumValue\"}\n\nfunc (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__EnumValue\")\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec.___EnumValue_name(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___EnumValue_description(ctx, field, obj)\n\t\tcase \"isDeprecated\":\n\t\t\tout.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"deprecationReason\":\n\t\t\tout.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar __FieldImplementors = []string{\"__Field\"}\n\nfunc (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__Field\")\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec.___Field_name(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___Field_description(ctx, field, obj)\n\t\tcase \"args\":\n\t\t\tout.Values[i] = ec.___Field_args(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"type\":\n\t\t\tout.Values[i] = ec.___Field_type(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"isDeprecated\":\n\t\t\tout.Values[i] = ec.___Field_isDeprecated(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"deprecationReason\":\n\t\t\tout.Values[i] = ec.___Field_deprecationReason(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar __InputValueImplementors = []string{\"__InputValue\"}\n\nfunc (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__InputValue\")\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec.___InputValue_name(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___InputValue_description(ctx, field, obj)\n\t\tcase \"type\":\n\t\t\tout.Values[i] = ec.___InputValue_type(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"defaultValue\":\n\t\t\tout.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar __SchemaImplementors = []string{\"__Schema\"}\n\nfunc (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__Schema\")\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___Schema_description(ctx, field, obj)\n\t\tcase \"types\":\n\t\t\tout.Values[i] = ec.___Schema_types(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"queryType\":\n\t\t\tout.Values[i] = ec.___Schema_queryType(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"mutationType\":\n\t\t\tout.Values[i] = ec.___Schema_mutationType(ctx, field, obj)\n\t\tcase \"subscriptionType\":\n\t\t\tout.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj)\n\t\tcase \"directives\":\n\t\t\tout.Values[i] = ec.___Schema_directives(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\nvar __TypeImplementors = []string{\"__Type\"}\n\nfunc (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors)\n\n\tout := graphql.NewFieldSet(fields)\n\tdeferred := make(map[string]*graphql.FieldSet)\n\tfor i, field := range fields {\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"__Type\")\n\t\tcase \"kind\":\n\t\t\tout.Values[i] = ec.___Type_kind(ctx, field, obj)\n\t\t\tif out.Values[i] == graphql.Null {\n\t\t\t\tout.Invalids++\n\t\t\t}\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec.___Type_name(ctx, field, obj)\n\t\tcase \"description\":\n\t\t\tout.Values[i] = ec.___Type_description(ctx, field, obj)\n\t\tcase \"fields\":\n\t\t\tout.Values[i] = ec.___Type_fields(ctx, field, obj)\n\t\tcase \"interfaces\":\n\t\t\tout.Values[i] = ec.___Type_interfaces(ctx, field, obj)\n\t\tcase \"possibleTypes\":\n\t\t\tout.Values[i] = ec.___Type_possibleTypes(ctx, field, obj)\n\t\tcase \"enumValues\":\n\t\t\tout.Values[i] = ec.___Type_enumValues(ctx, field, obj)\n\t\tcase \"inputFields\":\n\t\t\tout.Values[i] = ec.___Type_inputFields(ctx, field, obj)\n\t\tcase \"ofType\":\n\t\t\tout.Values[i] = ec.___Type_ofType(ctx, field, obj)\n\t\tcase \"specifiedByURL\":\n\t\t\tout.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\tout.Dispatch(ctx)\n\tif out.Invalids > 0 {\n\t\treturn graphql.Null\n\t}\n\n\tatomic.AddInt32(&ec.deferred, int32(len(deferred)))\n\n\tfor label, dfs := range deferred {\n\t\tec.processDeferredGroup(graphql.DeferredGroup{\n\t\t\tLabel: label,\n\t\t\tPath: graphql.GetPath(ctx),\n\t\t\tFieldSet: dfs,\n\t\t\tContext: ctx,\n\t\t})\n\t}\n\n\treturn out\n}\n\n// endregion **************************** object.gotpl ****************************\n\n// region ***************************** type.gotpl *****************************\n\nfunc (ec *executionContext) unmarshalNAny2interface(ctx context.Context, v interface{}) (interface{}, error) {\n\tres, err := graphql.UnmarshalAny(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalNAny2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler {\n\tif v == nil {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := graphql.MarshalAny(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) {\n\tres, err := graphql.UnmarshalBoolean(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler {\n\tres := graphql.MarshalBoolean(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalNCreateAssetInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateAssetInput(ctx context.Context, v interface{}) (model.CreateAssetInput, error) {\n\tres, err := ec.unmarshalInputCreateAssetInput(ctx, v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) unmarshalNCreateSessionInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateSessionInput(ctx context.Context, v interface{}) (model.CreateSessionInput, error) {\n\tres, err := ec.unmarshalInputCreateSessionInput(ctx, v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) unmarshalNCreateSessionJsonInput2github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690CreateSessionJSONInput(ctx context.Context, v interface{}) (model.CreateSessionJSONInput, error) {\n\tres, err := ec.unmarshalInputCreateSessionJsonInput(ctx, v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) unmarshalNID2string(ctx context.Context, v interface{}) (string, error) {\n\tres, err := graphql.UnmarshalID(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler {\n\tres := graphql.MarshalID(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) {\n\tres, err := graphql.UnmarshalString(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler {\n\tres := graphql.MarshalString(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) marshalN__Directive2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Directive(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler {\n\treturn ec.___Directive(ctx, sel, &v)\n}\n\nfunc (ec *executionContext) marshalN__Directive2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Directive\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.Directive) graphql.Marshaler {\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__Directive2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Directive(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v interface{}) (string, error) {\n\tres, err := graphql.UnmarshalString(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler {\n\tres := graphql.MarshalString(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalN__DirectiveLocation2\u1695string\u1684(ctx context.Context, v interface{}) ([]string, error) {\n\tvar vSlice []interface{}\n\tif v != nil {\n\t\tvSlice = graphql.CoerceList(v)\n\t}\n\tvar err error\n\tres := make([]string, len(vSlice))\n\tfor i := range vSlice {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))\n\t\tres[i], err = ec.unmarshalN__DirectiveLocation2string(ctx, vSlice[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (ec *executionContext) marshalN__DirectiveLocation2\u1695string\u1684(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler {\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__DirectiveLocation2string(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalN__EnumValue2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690EnumValue(ctx context.Context, sel ast.SelectionSet, v introspection.EnumValue) graphql.Marshaler {\n\treturn ec.___EnumValue(ctx, sel, &v)\n}\n\nfunc (ec *executionContext) marshalN__Field2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Field(ctx context.Context, sel ast.SelectionSet, v introspection.Field) graphql.Marshaler {\n\treturn ec.___Field(ctx, sel, &v)\n}\n\nfunc (ec *executionContext) marshalN__InputValue2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue(ctx context.Context, sel ast.SelectionSet, v introspection.InputValue) graphql.Marshaler {\n\treturn ec.___InputValue(ctx, sel, &v)\n}\n\nfunc (ec *executionContext) marshalN__InputValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler {\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__InputValue2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalN__Type2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx context.Context, sel ast.SelectionSet, v introspection.Type) graphql.Marshaler {\n\treturn ec.___Type(ctx, sel, &v)\n}\n\nfunc (ec *executionContext) marshalN__Type2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler {\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__Type2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalN__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler {\n\tif v == nil {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\treturn ec.___Type(ctx, sel, v)\n}\n\nfunc (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v interface{}) (string, error) {\n\tres, err := graphql.UnmarshalString(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler {\n\tres := graphql.MarshalString(v)\n\tif res == graphql.Null {\n\t\tif !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {\n\t\t\tec.Errorf(ctx, \"the requested element is null which the schema does not allow\")\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalOAny2interface(ctx context.Context, v interface{}) (interface{}, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tres, err := graphql.UnmarshalAny(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalOAny2interface(ctx context.Context, sel ast.SelectionSet, v interface{}) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tres := graphql.MarshalAny(v)\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalOAny2\u1695interface(ctx context.Context, v interface{}) ([]interface{}, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tvar vSlice []interface{}\n\tif v != nil {\n\t\tvSlice = graphql.CoerceList(v)\n\t}\n\tvar err error\n\tres := make([]interface{}, len(vSlice))\n\tfor i := range vSlice {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))\n\t\tres[i], err = ec.unmarshalOAny2interface(ctx, vSlice[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (ec *executionContext) marshalOAny2\u1695interface(ctx context.Context, sel ast.SelectionSet, v []interface{}) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tfor i := range v {\n\t\tret[i] = ec.marshalOAny2interface(ctx, sel, v[i])\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalOAsset2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690Asset(ctx context.Context, sel ast.SelectionSet, v *model.Asset) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\treturn ec._Asset(ctx, sel, v)\n}\n\nfunc (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v interface{}) (bool, error) {\n\tres, err := graphql.UnmarshalBoolean(v)\n\treturn res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler {\n\tres := graphql.MarshalBoolean(v)\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalOBoolean2\u1696bool(ctx context.Context, v interface{}) (*bool, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tres, err := graphql.UnmarshalBoolean(v)\n\treturn &res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalOBoolean2\u1696bool(ctx context.Context, sel ast.SelectionSet, v *bool) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tres := graphql.MarshalBoolean(*v)\n\treturn res\n}\n\nfunc (ec *executionContext) unmarshalOInt2\u1695\u1696int(ctx context.Context, v interface{}) ([]*int, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tvar vSlice []interface{}\n\tif v != nil {\n\t\tvSlice = graphql.CoerceList(v)\n\t}\n\tvar err error\n\tres := make([]*int, len(vSlice))\n\tfor i := range vSlice {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))\n\t\tres[i], err = ec.unmarshalOInt2\u1696int(ctx, vSlice[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (ec *executionContext) marshalOInt2\u1695\u1696int(ctx context.Context, sel ast.SelectionSet, v []*int) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tfor i := range v {\n\t\tret[i] = ec.marshalOInt2\u1696int(ctx, sel, v[i])\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) unmarshalOInt2\u1696int(ctx context.Context, v interface{}) (*int, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tres, err := graphql.UnmarshalInt(v)\n\treturn &res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalOInt2\u1696int(ctx context.Context, sel ast.SelectionSet, v *int) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tres := graphql.MarshalInt(*v)\n\treturn res\n}\n\nfunc (ec *executionContext) marshalOSession2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690Session(ctx context.Context, sel ast.SelectionSet, v *model.Session) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\treturn ec._Session(ctx, sel, v)\n}\n\nfunc (ec *executionContext) marshalOSessionStats2\u1696github\u1697com\u168bowasp\u1691amass\u168bengine\u168bapi\u168bgraphql\u168bserver\u168bmodel\u1690SessionStats(ctx context.Context, sel ast.SelectionSet, v *model.SessionStats) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\treturn ec._SessionStats(ctx, sel, v)\n}\n\nfunc (ec *executionContext) unmarshalOString2\u1695\u1696string(ctx context.Context, v interface{}) ([]*string, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tvar vSlice []interface{}\n\tif v != nil {\n\t\tvSlice = graphql.CoerceList(v)\n\t}\n\tvar err error\n\tres := make([]*string, len(vSlice))\n\tfor i := range vSlice {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))\n\t\tres[i], err = ec.unmarshalOString2\u1696string(ctx, vSlice[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (ec *executionContext) marshalOString2\u1695\u1696string(ctx context.Context, sel ast.SelectionSet, v []*string) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tfor i := range v {\n\t\tret[i] = ec.marshalOString2\u1696string(ctx, sel, v[i])\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) unmarshalOString2\u1696string(ctx context.Context, v interface{}) (*string, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tres, err := graphql.UnmarshalString(v)\n\treturn &res, graphql.ErrorOnPath(ctx, err)\n}\n\nfunc (ec *executionContext) marshalOString2\u1696string(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tres := graphql.MarshalString(*v)\n\treturn res\n}\n\nfunc (ec *executionContext) marshalO__EnumValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690EnumValue\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__EnumValue2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690EnumValue(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalO__Field2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Field\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.Field) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__Field2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Field(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalO__InputValue2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__InputValue2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690InputValue(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalO__Schema2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Schema(ctx context.Context, sel ast.SelectionSet, v *introspection.Schema) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\treturn ec.___Schema(ctx, sel, v)\n}\n\nfunc (ec *executionContext) marshalO__Type2\u1695github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type\u1684(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\tret := make(graphql.Array, len(v))\n\tvar wg sync.WaitGroup\n\tisLen1 := len(v) == 1\n\tif !isLen1 {\n\t\twg.Add(len(v))\n\t}\n\tfor i := range v {\n\t\ti := i\n\t\tfc := &graphql.FieldContext{\n\t\t\tIndex: &i,\n\t\t\tResult: &v[i],\n\t\t}\n\t\tctx := graphql.WithFieldContext(ctx, fc)\n\t\tf := func(i int) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\t\t\tret = nil\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif !isLen1 {\n\t\t\t\tdefer wg.Done()\n\t\t\t}\n\t\t\tret[i] = ec.marshalN__Type2github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx, sel, v[i])\n\t\t}\n\t\tif isLen1 {\n\t\t\tf(i)\n\t\t} else {\n\t\t\tgo f(i)\n\t\t}\n\n\t}\n\twg.Wait()\n\n\tfor _, e := range ret {\n\t\tif e == graphql.Null {\n\t\t\treturn graphql.Null\n\t\t}\n\t}\n\n\treturn ret\n}\n\nfunc (ec *executionContext) marshalO__Type2\u1696github\u1697com\u168b99designs\u168bgqlgen\u168bgraphql\u168bintrospection\u1690Type(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler {\n\tif v == nil {\n\t\treturn graphql.Null\n\t}\n\treturn ec.___Type(ctx, sel, v)\n}\n\n// endregion ***************************** type.gotpl *****************************\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/regenerate.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n#!/bin/sh\n\ngo run github.com/99designs/gqlgen generate\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/resolver.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\npackage server\n\n// This file will not be regenerated automatically.\n//\n// It serves as dependency injection for your app, add any dependencies you require here.\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\ntype Resolver struct {\n\tLog *slog.Logger\n\tManager et.SessionManager\n\tDispatcher et.Dispatcher\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/schema.resolvers.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage server\n\n// This file will be automatically regenerated based on the schema, any resolver implementations\n// will be copied through when generating and any unknown code will be moved to the end.\n// Code generated by github.com/99designs/gqlgen version v0.17.41\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/api/graphql/server/model\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/account\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/file\"\n\t\"github.com/owasp-amass/open-asset-model/financial\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n\t\"github.com/owasp-amass/open-asset-model/people\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n)\n\n// CreateSession is the resolver for the createSession field.\nfunc (r *mutationResolver) CreateSession(ctx context.Context, input model.CreateSessionInput) (*model.Session, error) {\n\ttestSession := &model.Session{\n\t\tSessionToken: \"00000000-0000-0000-0000-0000000000033\", //?\n\t}\n\treturn testSession, nil\n}\n\n// CreateSessionFromJSON is the resolver for the createSessionFromJson field.\nfunc (r *mutationResolver) CreateSessionFromJSON(ctx context.Context, input model.CreateSessionJSONInput) (*model.Session, error) {\n\tvar config config.Config\n\n\tif err := json.Unmarshal([]byte(input.Config), &config); err != nil {\n\t\treturn nil, err\n\t}\n\t// Populate FROM/TO in transformations\n\tfor k, t := range config.Transformations {\n\t\t_ = t.Split(k)\n\t}\n\n\ts, err := r.Manager.NewSession(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model.Session{SessionToken: s.ID().String()}, nil\n}\n\n// CreateAsset is the resolver for the createAsset field.\nfunc (r *mutationResolver) CreateAsset(ctx context.Context, input model.CreateAssetInput) (*model.Asset, error) {\n\t// Check if the session token is valid\n\ttoken, err := uuid.Parse(input.SessionToken)\n\tif err != nil {\n\t\treturn nil, errors.New(\"invalid session token\")\n\t}\n\t// Check if the session exists\n\t// and if the session is not already terminated\n\tsession := r.Manager.GetSession(token)\n\tif session == nil {\n\t\treturn nil, errors.New(\"invalid session token\")\n\t}\n\n\tdata, ok := input.Data.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, errors.New(\"failed to cast the asset data\")\n\t}\n\tatype := data[\"type\"].(string)\n\n\tj, err := json.Marshal(input.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Unmarshal json into AssetData struct\n\tassetData := &et.AssetData{\n\t\tOAMAsset: createSeedAsset(atype),\n\t}\n\tif err := json.Unmarshal(j, assetData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdba, err := session.Cache().CreateAsset(assetData.OAMAsset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create and schedule new event\n\tevent := &et.Event{\n\t\tName: *input.AssetName,\n\t\tEntity: dba,\n\t\tDispatcher: r.Dispatcher,\n\t\tSession: session,\n\t}\n\n\tif err := r.Dispatcher.DispatchEvent(event); err != nil {\n\t\treturn nil, errors.New(\"failed to create asset\")\n\t}\n\n\treturn &model.Asset{ID: token.String()}, nil\n}\n\n// TerminateSession is the resolver for the terminateSession field.\nfunc (r *mutationResolver) TerminateSession(ctx context.Context, sessionToken string) (*bool, error) {\n\tvar result bool\n\t// Check if the session token is valid\n\ttoken, err := uuid.Parse(sessionToken)\n\tif err != nil {\n\t\treturn &result, errors.New(\"invalid session token\")\n\t}\n\t// Check if the session exists\n\t// and if the session is not already terminated\n\tif r.Manager.GetSession(token) == nil {\n\t\treturn &result, errors.New(\"invalid session token\")\n\t}\n\n\tresult = true\n\tgo r.Manager.CancelSession(token)\n\treturn &result, nil\n}\n\n// SessionStats is the resolver for the sessionStats field.\nfunc (r *queryResolver) SessionStats(ctx context.Context, sessionToken string) (*model.SessionStats, error) {\n\t// Check if the session token is valid\n\ttoken, err := uuid.Parse(sessionToken)\n\tif err != nil {\n\t\treturn nil, errors.New(\"invalid session token\")\n\t}\n\t// Check if the session exists\n\t// and if the session is not already terminated\n\tsession := r.Manager.GetSession(token)\n\tif session == nil {\n\t\treturn nil, errors.New(\"invalid session token\")\n\t}\n\n\tstats := session.Stats()\n\tstats.Lock()\n\tcompleted := stats.WorkItemsCompleted\n\ttotal := stats.WorkItemsTotal\n\tstats.Unlock()\n\n\treturn &model.SessionStats{\n\t\tWorkItemsCompleted: &completed,\n\t\tWorkItemsTotal: &total,\n\t}, nil\n}\n\n// LogMessages is the resolver for the logMessages field.\nfunc (r *subscriptionResolver) LogMessages(ctx context.Context, sessionToken string) (<-chan *string, error) {\n\ttoken, _ := uuid.Parse(sessionToken)\n\tsession := r.Manager.GetSession(token)\n\n\tif session != nil {\n\t\tsession.PubSub().Publish(\"Channel created\")\n\t\tch := session.PubSub().Subscribe()\n\t\treturn ch, nil\n\t}\n\treturn nil, nil\n}\n\n// Mutation returns MutationResolver implementation.\nfunc (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }\n\n// Query returns QueryResolver implementation.\nfunc (r *Resolver) Query() QueryResolver { return &queryResolver{r} }\n\n// Subscription returns SubscriptionResolver implementation.\nfunc (r *Resolver) Subscription() SubscriptionResolver { return &subscriptionResolver{r} }\n\ntype mutationResolver struct{ *Resolver }\ntype queryResolver struct{ *Resolver }\ntype subscriptionResolver struct{ *Resolver }\n\nfunc createSeedAsset(atype string) oam.Asset {\n\tswitch atype {\n\tcase string(oam.Account):\n\t\treturn &account.Account{}\n\tcase string(oam.AutnumRecord):\n\t\treturn &oamreg.AutnumRecord{}\n\tcase string(oam.AutonomousSystem):\n\t\treturn &network.AutonomousSystem{}\n\tcase string(oam.ContactRecord):\n\t\treturn &contact.ContactRecord{}\n\tcase string(oam.DomainRecord):\n\t\treturn &oamreg.DomainRecord{}\n\tcase string(oam.File):\n\t\treturn &file.File{}\n\tcase string(oam.FQDN):\n\t\treturn &oamdns.FQDN{}\n\tcase string(oam.FundsTransfer):\n\t\treturn &financial.FundsTransfer{}\n\tcase string(oam.Identifier):\n\t\treturn &general.Identifier{}\n\tcase string(oam.IPAddress):\n\t\treturn &network.IPAddress{}\n\tcase string(oam.IPNetRecord):\n\t\treturn &oamreg.IPNetRecord{}\n\tcase string(oam.Location):\n\t\treturn &contact.Location{}\n\tcase string(oam.Netblock):\n\t\treturn &network.Netblock{}\n\tcase string(oam.Organization):\n\t\treturn &org.Organization{}\n\tcase string(oam.Phone):\n\t\treturn &contact.Phone{}\n\tcase string(oam.Person):\n\t\treturn &people.Person{}\n\tcase string(oam.Product):\n\t\treturn &platform.Product{}\n\tcase string(oam.ProductRelease):\n\t\treturn &platform.ProductRelease{}\n\tcase string(oam.Service):\n\t\treturn &platform.Service{}\n\tcase string(oam.TLSCertificate):\n\t\treturn &oamcert.TLSCertificate{}\n\tcase string(oam.URL):\n\t\treturn &url.URL{}\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/server.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage server\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/99designs/gqlgen/graphql/handler\"\n\t\"github.com/99designs/gqlgen/graphql/handler/extension\"\n\t\"github.com/99designs/gqlgen/graphql/handler/lru\"\n\t\"github.com/99designs/gqlgen/graphql/handler/transport\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/vektah/gqlparser/v2/ast\"\n)\n\nconst keyServerAddr key = \"serverAddr\"\n\ntype key string\n\ntype Server struct {\n\tctx context.Context\n\tcancel context.CancelFunc\n\tch chan struct{}\n\tsrv *http.Server\n}\n\nfunc NewServer(logger *slog.Logger, d et.Dispatcher, mgr et.SessionManager) *Server {\n\tsrv := handler.New(NewExecutableSchema(Config{\n\t\tResolvers: &Resolver{\n\t\t\tLog: logger,\n\t\t\tManager: mgr,\n\t\t\tDispatcher: d,\n\t\t},\n\t}))\n\t// Needed for subscription\n\t// Connecting websocket clients need to support the proper subprotocols \\\n\t// e.g. graphql-ws, graphql-transport-ws, subscriptions-transport-ws, etc\n\tsrv.AddTransport(transport.Websocket{\n\t\tKeepAlivePingInterval: 10 * time.Second,\n\t})\n\n\tsrv.AddTransport(transport.Options{})\n\tsrv.AddTransport(transport.GET{})\n\tsrv.AddTransport(transport.POST{})\n\tsrv.AddTransport(transport.MultipartForm{})\n\n\tsrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))\n\n\tsrv.Use(extension.Introspection{})\n\tsrv.Use(extension.AutomaticPersistedQuery{\n\t\tCache: lru.New[string](100),\n\t})\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/graphql\", srv)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tch: make(chan struct{}),\n\t\tsrv: &http.Server{\n\t\t\tAddr: \":4000\",\n\t\t\tHandler: mux,\n\t\t\tBaseContext: func(l net.Listener) context.Context {\n\t\t\t\tctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())\n\t\t\t\treturn ctx\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (s *Server) Start() error {\n\terr := s.srv.ListenAndServe()\n\n\ts.cancel()\n\tclose(s.ch)\n\treturn err\n}\n\nfunc (s *Server) Shutdown() error {\n\terr := s.srv.Shutdown(s.ctx)\n\n\t<-s.ch\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/api/graphql/server/model/models_gen.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.\n\npackage model\n\ntype Asset struct {\n\tID string `json:\"id\"`\n}\n\ntype Config struct {\n\tScope []interface{} `json:\"scope,omitempty\"`\n\tPorts []*int `json:\"ports,omitempty\"`\n\tBlacklist []*string `json:\"blacklist,omitempty\"`\n\tDomains []*string `json:\"domains,omitempty\"`\n\tResolvers []*string `json:\"resolvers,omitempty\"`\n\tIps []*string `json:\"ips,omitempty\"`\n\tCirds []interface{} `json:\"cirds,omitempty\"`\n\tTransformations []interface{} `json:\"transformations,omitempty\"`\n\tDatabase []interface{} `json:\"database,omitempty\"`\n\tBruteForce *bool `json:\"bruteForce,omitempty\"`\n\tAlterations *bool `json:\"alterations,omitempty\"`\n}\n\ntype CreateAssetInput struct {\n\tSessionToken string `json:\"sessionToken\"`\n\tAssetName *string `json:\"assetName,omitempty\"`\n\tData interface{} `json:\"data,omitempty\"`\n}\n\ntype CreateSessionInput struct {\n\tConfig interface{} `json:\"config\"`\n}\n\ntype CreateSessionJSONInput struct {\n\tConfig string `json:\"config\"`\n}\n\ntype Session struct {\n\tSessionToken string `json:\"sessionToken\"`\n}\n\ntype SessionStats struct {\n\tWorkItemsCompleted *int `json:\"WorkItemsCompleted,omitempty\"`\n\tWorkItemsTotal *int `json:\"WorkItemsTotal,omitempty\"`\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/dispatcher/dispatcher.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dispatcher\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\nconst (\n\tMinPipelineQueueSize = 100\n\tMaxPipelineQueueSize = 500\n)\n\ntype dis struct {\n\tlogger *slog.Logger\n\treg et.Registry\n\tmgr et.SessionManager\n\tdone chan struct{}\n\tdchan chan *et.Event\n\tcchan chan *et.EventDataElement\n}\n\nfunc NewDispatcher(l *slog.Logger, r et.Registry, mgr et.SessionManager) et.Dispatcher {\n\tif l == nil {\n\t\tl = slog.New(slog.NewTextHandler(os.Stdout, nil))\n\t}\n\n\td := &dis{\n\t\tlogger: l,\n\t\treg: r,\n\t\tmgr: mgr,\n\t\tdone: make(chan struct{}),\n\t\tdchan: make(chan *et.Event, MinPipelineQueueSize),\n\t\tcchan: make(chan *et.EventDataElement, MinPipelineQueueSize),\n\t}\n\n\tgo d.maintainPipelines()\n\treturn d\n}\n\nfunc (d *dis) Shutdown() {\n\tselect {\n\tcase <-d.done:\n\t\treturn\n\tdefault:\n\t}\n\tclose(d.done)\n}\n\nfunc (d *dis) DispatchEvent(e *et.Event) error {\n\tif e == nil {\n\t\treturn errors.New(\"the event is nil\")\n\t} else if e.Session == nil {\n\t\treturn errors.New(\"the event has no associated session\")\n\t} else if e.Session.Done() {\n\t\treturn errors.New(\"the associated session has been terminated\")\n\t} else if e.Entity == nil || e.Entity.Asset == nil {\n\t\treturn errors.New(\"the event has no associated entity or asset\")\n\t}\n\n\td.dchan <- e\n\treturn nil\n}\n\nfunc (d *dis) maintainPipelines() {\n\tctick := time.NewTimer(time.Second)\n\tdefer ctick.Stop()\n\tmtick := time.NewTimer(10 * time.Second)\n\tdefer mtick.Stop()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-d.done:\n\t\t\tbreak loop\n\t\tcase <-mtick.C:\n\t\t\tcheckOnTheHeap()\n\t\t\tmtick.Reset(10 * time.Second)\n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctick.C:\n\t\t\td.fillPipelineQueues()\n\t\t\tctick.Reset(time.Second)\n\t\tcase e := <-d.dchan:\n\t\t\tif err := d.safeDispatch(e); err != nil {\n\t\t\t\td.logger.Error(fmt.Sprintf(\"Failed to dispatch event: %s\", err.Error()))\n\t\t\t}\n\t\tcase e := <-d.cchan:\n\t\t\td.completedCallback(e)\n\t\t}\n\t}\n}\n\nfunc checkOnTheHeap() {\n\tvar mstats runtime.MemStats\n\truntime.ReadMemStats(&mstats)\n\n\th := mstats.HeapAlloc\n\tn := mstats.NextGC\n\tif h <= n {\n\t\treturn\n\t}\n\n\tif diff := mstats.HeapAlloc - mstats.NextGC; bToMb(diff) > 500 {\n\t\truntime.GC()\n\t}\n}\n\nfunc bToMb(b uint64) uint64 {\n\treturn b / 1024 / 1024\n}\n\nfunc (d *dis) fillPipelineQueues() {\n\tsessions := d.mgr.GetSessions()\n\tif len(sessions) == 0 {\n\t\treturn\n\t}\n\n\tvar ptypes []oam.AssetType\n\tfor _, atype := range oam.AssetList {\n\t\tif ap, err := d.reg.GetPipeline(atype); err == nil {\n\t\t\tif ap.Queue.Len() < MinPipelineQueueSize {\n\t\t\t\tptypes = append(ptypes, atype)\n\t\t\t}\n\t\t}\n\t}\n\n\tnumRequested := MaxPipelineQueueSize / len(sessions)\n\tfor _, s := range sessions {\n\t\tif s == nil || s.Done() {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, atype := range ptypes {\n\t\t\tif entities, err := s.Queue().Next(atype, numRequested); err == nil && len(entities) > 0 {\n\t\t\t\tfor _, entity := range entities {\n\t\t\t\t\te := &et.Event{\n\t\t\t\t\t\tName: fmt.Sprintf(\"%s - %s\", string(atype), entity.Asset.Key()),\n\t\t\t\t\t\tEntity: entity,\n\t\t\t\t\t\tSession: s,\n\t\t\t\t\t}\n\t\t\t\t\tif err := d.appendToPipeline(e); err != nil {\n\t\t\t\t\t\td.logger.Error(fmt.Sprintf(\"Failed to append to a data pipeline: %s\", err.Error()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (d *dis) completedCallback(data interface{}) {\n\tede, ok := data.(*et.EventDataElement)\n\tif !ok {\n\t\treturn\n\t}\n\n\tif err := ede.Error; err != nil {\n\t\tede.Event.Session.Log().WithGroup(\"event\").With(\"name\", ede.Event.Name).Error(err.Error())\n\t}\n\t// increment the number of events processed in the session\n\tif stats := ede.Event.Session.Stats(); stats != nil {\n\t\tstats.Lock()\n\t\tstats.WorkItemsCompleted++\n\t\tstats.Unlock()\n\t}\n}\n\nfunc (d *dis) safeDispatch(e *et.Event) error {\n\t// there is no need to dispatch the event if there's no associated asset pipeline\n\tif ap, err := d.reg.GetPipeline(e.Entity.Asset.AssetType()); err != nil || ap == nil {\n\t\treturn err\n\t}\n\n\t// do not schedule the same asset more than once\n\tif e.Session.Queue().Has(e.Entity) {\n\t\treturn nil\n\t}\n\n\terr := e.Session.Queue().Append(e.Entity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// increment the number of events processed in the session\n\tif stats := e.Session.Stats(); stats != nil {\n\t\tstats.Lock()\n\t\tstats.WorkItemsTotal++\n\t\tstats.Unlock()\n\t}\n\n\tif e.Meta != nil {\n\t\tif err := d.appendToPipeline(e); err != nil {\n\t\t\td.logger.Error(fmt.Sprintf(\"Failed to append to a data pipeline: %s\", err.Error()))\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d *dis) appendToPipeline(e *et.Event) error {\n\tif e == nil || e.Session == nil || e.Entity == nil || e.Entity.Asset == nil {\n\t\treturn errors.New(\"the event is nil\")\n\t}\n\n\tap, err := d.reg.GetPipeline(e.Entity.Asset.AssetType())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.Dispatcher = d\n\tif data := et.NewEventDataElement(e); data != nil {\n\t\t_ = e.Session.Queue().Processed(e.Entity)\n\t\tdata.Queue = d.cchan\n\t\tap.Queue.Append(data)\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/ip_netblock.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage plugins\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\ntype ipNetblock struct {\n\tname string\n\tlog *slog.Logger\n\tsource *et.Source\n}\n\nfunc NewIPNetblock() et.Plugin {\n\treturn &ipNetblock{\n\t\tname: \"IP-Netblock\",\n\t\tsource: &et.Source{\n\t\t\tName: \"IP-Netblock\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (d *ipNetblock) Name() string {\n\treturn d.name\n}\n\nfunc (d *ipNetblock) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tname := d.name + \"-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: name,\n\t\tPriority: 4,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.Netblock)},\n\t\tEventType: oam.IPAddress,\n\t\tCallback: d.lookup,\n\t}); err != nil {\n\t\td.log.Error(fmt.Sprintf(\"Failed to register a handler: %v\", err), \"handler\", name)\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *ipNetblock) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *ipNetblock) lookup(e *et.Event) error {\n\tip, ok := e.Entity.Asset.(*oamnet.IPAddress)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the IPAddress asset\")\n\t}\n\n\tif reserved, cidr := amassnet.IsReservedAddress(ip.Address.String()); reserved {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tnetblock := &oamnet.Netblock{\n\t\t\tType: \"IPv4\",\n\t\t\tCIDR: prefix,\n\t\t}\n\t\tif prefix.Addr().Is6() {\n\t\t\tnetblock.Type = \"IPv6\"\n\t\t}\n\n\t\td.reservedAS(e, netblock)\n\t\treturn nil\n\t}\n\n\tvar entry *sessions.CIDRangerEntry\n\tfor i := 0; i < 120; i++ {\n\t\tentry = support.IPNetblock(e.Session, ip.Address.String())\n\t\tif entry != nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\tif entry == nil {\n\t\treturn nil\n\t}\n\n\tnb, as := d.store(e, entry)\n\tif nb == nil || as == nil {\n\t\treturn nil\n\t}\n\n\td.process(e, e.Entity, nb, as)\n\treturn nil\n}\n\nfunc (d *ipNetblock) store(e *et.Event, entry *sessions.CIDRangerEntry) (*dbt.Entity, *dbt.Entity) {\n\tnetblock := &oamnet.Netblock{\n\t\tType: \"IPv4\",\n\t\tCIDR: netip.MustParsePrefix(entry.Net.String()),\n\t}\n\tif netblock.CIDR.Addr().Is6() {\n\t\tnetblock.Type = \"IPv6\"\n\t}\n\n\tnb, err := e.Session.Cache().CreateAsset(netblock)\n\tif err != nil || nb == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(nb, &general.SourceProperty{\n\t\tSource: entry.Src.Name,\n\t\tConfidence: entry.Src.Confidence,\n\t})\n\n\tedge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"contains\"},\n\t\tFromEntity: nb,\n\t\tToEntity: e.Entity,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: entry.Src.Name,\n\t\tConfidence: entry.Src.Confidence,\n\t})\n\n\tas, err := e.Session.Cache().CreateAsset(&oamnet.AutonomousSystem{Number: entry.ASN})\n\tif err != nil || as == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(as, &general.SourceProperty{\n\t\tSource: entry.Src.Name,\n\t\tConfidence: entry.Src.Confidence,\n\t})\n\n\tedge, err = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"announces\"},\n\t\tFromEntity: as,\n\t\tToEntity: nb,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: entry.Src.Name,\n\t\tConfidence: entry.Src.Confidence,\n\t})\n\n\treturn nb, as\n}\n\nfunc (d *ipNetblock) process(e *et.Event, ip, nb, as *dbt.Entity) {\n\tipstr := ip.Asset.Key()\n\tnbname := nb.Asset.Key()\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: nb.Asset.Key(),\n\t\tEntity: nb,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", nbname, \"relation\", \"contains\",\n\t\t\"to\", ipstr, slog.Group(\"plugin\", \"name\", d.name, \"handler\", d.name+\"-Handler\"))\n\n\tasname := \"AS\" + as.Asset.Key()\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: asname,\n\t\tEntity: as,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", asname, \"relation\", \"announces\",\n\t\t\"to\", nbname, slog.Group(\"plugin\", \"name\", d.name, \"handler\", d.name+\"-Handler\"))\n}\n\nfunc (d *ipNetblock) reservedAS(e *et.Event, netblock *oamnet.Netblock) {\n\tnb, err := e.Session.Cache().CreateAsset(netblock)\n\tif err != nil || nb == nil {\n\t\treturn\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(nb, &general.SourceProperty{\n\t\tSource: d.source.Name,\n\t\tConfidence: d.source.Confidence,\n\t})\n\n\tasn, err := e.Session.Cache().CreateAsset(&oamnet.AutonomousSystem{Number: 0})\n\tif err != nil || asn == nil {\n\t\treturn\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(nb, &general.SourceProperty{\n\t\tSource: d.source.Name,\n\t\tConfidence: d.source.Confidence,\n\t})\n\n\tautnum, err := e.Session.Cache().CreateAsset(&oamreg.AutnumRecord{\n\t\tNumber: 0,\n\t\tHandle: \"AS0\",\n\t\tName: \"Reserved Network Address Blocks\",\n\t})\n\tif err != nil || autnum == nil {\n\t\treturn\n\t}\n\n\tedge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"registration\"},\n\t\tFromEntity: asn,\n\t\tToEntity: autnum,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: d.source.Name,\n\t\tConfidence: d.source.Confidence,\n\t})\n\n\tedge, err = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"announces\"},\n\t\tFromEntity: asn,\n\t\tToEntity: nb,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: d.source.Name,\n\t\tConfidence: d.source.Confidence,\n\t})\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/jarm.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage plugins\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n)\n\ntype jarmPlugin struct {\n\tname string\n\tlog *slog.Logger\n\tsource *et.Source\n}\n\nfunc NewJARMFingerprints() et.Plugin {\n\treturn &jarmPlugin{\n\t\tname: \"JARM-Fingerprint\",\n\t\tsource: &et.Source{\n\t\t\tName: \"JARM-Fingerprint\",\n\t\t\tConfidence: 90,\n\t\t},\n\t}\n}\n\nfunc (j *jarmPlugin) Name() string {\n\treturn j.name\n}\n\nfunc (j *jarmPlugin) Start(r et.Registry) error {\n\tj.log = r.Log().WithGroup(\"plugin\").With(\"name\", j.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: j,\n\t\tName: j.name + \"-Handler\",\n\t\tMaxInstances: 25,\n\t\tTransforms: []string{string(oam.Service)},\n\t\tEventType: oam.Service,\n\t\tCallback: j.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tj.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (j *jarmPlugin) Stop() {\n\tj.log.Info(\"Plugin stopped\")\n}\n\nfunc (j *jarmPlugin) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*platform.Service)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Service asset\")\n\t}\n\n\tif !j.hasCertificate(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.Service), string(oam.Service), j.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := j.source\n\tif !support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tj.query(e)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\treturn nil\n}\n\nfunc (j *jarmPlugin) hasCertificate(e *et.Event) bool {\n\tif edges, err := e.Session.Cache().OutgoingEdges(e.Entity, e.Session.Cache().StartTime(), \"certificate\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif a.Asset.AssetType() == oam.TLSCertificate {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\ntype fingerprint struct {\n\tasset *dbt.Entity\n\tport *dbt.Edge\n\thash string\n}\n\nfunc (j *jarmPlugin) query(e *et.Event) {\n\tvar targets []*fingerprint\n\n\tif edges, err := e.Session.Cache().IncomingEdges(e.Entity, e.Session.Cache().StartTime(), \"port\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tportrel, ok := edge.Relation.(*general.PortRelation)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tswitch a.Asset.(type) {\n\t\t\t\tcase *oamdns.FQDN:\n\t\t\t\t\tif portrel.Protocol == \"https\" {\n\t\t\t\t\t\tt := &fingerprint{\n\t\t\t\t\t\t\tasset: e.Entity,\n\t\t\t\t\t\t\tport: edge,\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttargets = append([]*fingerprint{t}, targets...)\n\t\t\t\t\t}\n\t\t\t\tcase *network.IPAddress:\n\t\t\t\t\tif portrel.Protocol == \"https\" {\n\t\t\t\t\t\ttargets = append(targets, &fingerprint{\n\t\t\t\t\t\t\tasset: e.Entity,\n\t\t\t\t\t\t\tport: edge,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar results []*fingerprint\n\tfor _, target := range targets {\n\t\tportrel := target.port.Relation.(*general.PortRelation)\n\t\tif fp, err := support.JARMFingerprint(target.asset.Asset, portrel); err == nil && fp != \"\" {\n\t\t\tresults = append(results, &fingerprint{\n\t\t\t\tasset: target.asset,\n\t\t\t\tport: target.port,\n\t\t\t\thash: fp,\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(results) > 0 {\n\t\tj.store(e, results)\n\t}\n}\n\nfunc (j *jarmPlugin) store(e *et.Event, fps []*fingerprint) {\n\tfor _, fp := range fps {\n\t\t_, _ = e.Session.Cache().CreateEdgeProperty(fp.port, &general.SimpleProperty{\n\t\t\tPropertyName: \"JARM\",\n\t\t\tPropertyValue: fp.hash,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/known_fqdn.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage plugins\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/db\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n)\n\ntype knownFQDN struct {\n\tname string\n\tlog *slog.Logger\n}\n\nfunc NewKnownFQDN() et.Plugin {\n\treturn &knownFQDN{\n\t\tname: \"Known-FQDN\",\n\t}\n}\n\nfunc (d *knownFQDN) Name() string {\n\treturn d.name\n}\n\nfunc (d *knownFQDN) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.name + \"-Handler\",\n\t\tPriority: 7,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *knownFQDN) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *knownFQDN) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif a, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf == 0 || a == nil {\n\t\treturn nil\n\t} else if f, ok := a.(*oamdns.FQDN); !ok || f == nil || !strings.EqualFold(fqdn.Name, f.Name) {\n\t\treturn nil\n\t}\n\n\tsupport.AddSLDInScope(e)\n\td.process(e, d.lookup(e, e.Entity))\n\treturn nil\n}\n\nfunc (d *knownFQDN) lookup(e *et.Event, dom *dbt.Entity) []*dbt.Entity {\n\tnames, _ := db.FindByFQDNScope(e.Session.Cache(), dom, time.Time{})\n\treturn names\n}\n\nfunc (d *knownFQDN) process(e *et.Event, names []*dbt.Entity) {\n\tfor _, n := range names {\n\t\tif fqdn, ok := n.Asset.(*oamdns.FQDN); ok {\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: fqdn.Name,\n\t\t\t\tEntity: n,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/load.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage plugins\n\nimport (\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/api\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/api/aviato\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/api/gleif\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/api/rdap\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/archive\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/brute\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/enrich\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/horizontals\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/scrape\"\n\tdnssd \"github.com/owasp-amass/amass/v5/engine/plugins/service_discovery/dns\"\n\thp \"github.com/owasp-amass/amass/v5/engine/plugins/service_discovery/http_probes\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/whois\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/whois/bgptools\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\nvar pluginNewFuncs = []func() et.Plugin{\n\tapi.NewBinaryEdge,\n\tapi.NewChaos,\n\tapi.NewCrtsh,\n\tapi.NewDNSRepo,\n\tapi.NewGrepApp,\n\tapi.NewHackerTarget,\n\t//api.NewHunterIO,\n\tapi.NewLeakIX,\n\tapi.NewPassiveTotal,\n\tapi.NewProspeo,\n\tapi.NewSecurityTrails,\n\t//api.NewURLScan,\n\tapi.NewVirusTotal,\n\tapi.NewZetalytics,\n\tarchive.NewWayback,\n\taviato.NewAviato,\n\tbgptools.NewBGPTools,\n\tbrute.NewFQDNAlterations,\n\tdns.NewDNS,\n\tdnssd.NewDNSPlugin,\n\tenrich.NewBannerURLs,\n\tenrich.NewContacts,\n\tenrich.NewEmails,\n\tenrich.NewTLSCerts,\n\tenrich.NewURLs,\n\tgleif.NewGLEIF,\n\thorizontals.NewHorizontals,\n\thp.NewHTTPProbing,\n\trdap.NewRDAP,\n\tscrape.NewBing,\n\tscrape.NewDNSHistory,\n\tscrape.NewDuckDuckGo,\n\tscrape.NewIPVerse,\n\tscrape.NewRapidDNS,\n\tscrape.NewSiteDossier,\n\twhois.NewWHOIS,\n\tNewIPNetblock,\n\tNewJARMFingerprints,\n\tNewKnownFQDN,\n\tNewVerifiedEmail,\n}\n\nfunc LoadAndStartPlugins(r et.Registry) error {\n\tvar started []et.Plugin\n\n\tfor _, f := range pluginNewFuncs {\n\t\tif p := f(); p != nil {\n\t\t\tif err := p.Start(r); err != nil {\n\t\t\t\tstopPlugins(started)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc stopPlugins(started []et.Plugin) {\n\tfor _, p := range started {\n\t\tp.Stop()\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/verified_email.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage plugins\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\ntype verifiedEmail struct {\n\tname string\n\tlog *slog.Logger\n}\n\nfunc NewVerifiedEmail() et.Plugin {\n\treturn &verifiedEmail{\n\t\tname: \"Verified-Email\",\n\t}\n}\n\nfunc (v *verifiedEmail) Name() string {\n\treturn v.name\n}\n\nfunc (v *verifiedEmail) Start(r et.Registry) error {\n\tv.log = r.Log().WithGroup(\"plugin\").With(\"name\", v.name)\n\n\tname := v.name + \"-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: v,\n\t\tName: name,\n\t\tTransforms: []string{string(oam.Identifier)},\n\t\tPriority: 9,\n\t\tEventType: oam.Identifier,\n\t\tCallback: v.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tv.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (v *verifiedEmail) Stop() {\n\tv.log.Info(\"Plugin stopped\")\n}\n\nfunc (v *verifiedEmail) check(e *et.Event) error {\n\temail, ok := e.Entity.Asset.(*general.Identifier)\n\tif !ok || email.Type != general.EmailAddress {\n\t\treturn nil\n\t}\n\n\tvar storeEmail bool\n\tif meta, ok := e.Meta.(*et.EmailMeta); ok && meta.VerifyAttempted {\n\t\tif meta.Verified {\n\t\t\tstoreEmail = true\n\t\t}\n\t} else {\n\t\tstoreEmail = true\n\t}\n\n\tif storeEmail {\n\t\t_, _ = e.Session.Cache().CreateAsset(email)\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/binaryedge.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype binaryEdge struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewBinaryEdge() et.Plugin {\n\tlimit := rate.Every(10 * time.Second)\n\n\treturn &binaryEdge{\n\t\tname: \"BinaryEdge\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"BinaryEdge\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (be *binaryEdge) Name() string {\n\treturn be.name\n}\n\nfunc (be *binaryEdge) Start(r et.Registry) error {\n\tbe.log = r.Log().WithGroup(\"plugin\").With(\"name\", be.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: be,\n\t\tName: be.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: be.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tbe.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (be *binaryEdge) Stop() {\n\tbe.log.Info(\"Plugin stopped\")\n}\n\nfunc (be *binaryEdge) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(be.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), be.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, be.source, since) {\n\t\tnames = append(names, be.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, be.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, be.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tbe.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (be *binaryEdge) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), be.source, since)\n}\n\nfunc (be *binaryEdge) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\tpagenum := 1\nloop:\n\tfor _, key := range keys {\n\t\tfor pagenum <= 500 {\n\t\t\t_ = be.rlimit.Wait(context.TODO())\n\t\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\t\tHeader: http.Header{\"X-KEY\": []string{key}},\n\t\t\t\tURL: \"https://api.binaryedge.io/v2/query/domains/subdomain/\" + name + \"?page=\" + strconv.Itoa(pagenum),\n\t\t\t})\n\t\t\tif err != nil || resp.Body == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tvar j struct {\n\t\t\t\tResults struct {\n\t\t\t\t\tPage int `json:\"page\"`\n\t\t\t\t\tPageSize int `json:\"pagesize\"`\n\t\t\t\t\tTotal int `json:\"total\"`\n\t\t\t\t\tEvents []string `json:\"events\"`\n\t\t\t\t} `json:\"results\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(\"{\\\"results\\\":\"+resp.Body+\"}\"), &j); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, n := range j.Results.Events {\n\t\t\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t\t\t// if the subdomain is not in scope, skip it\n\t\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\t\tsubs.Insert(nstr)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif j.Results.Page > 0 && j.Results.Page <= 500 && j.Results.PageSize > 0 &&\n\t\t\t\tj.Results.Total > 0 && j.Results.Page <= (j.Results.Total/j.Results.PageSize) {\n\t\t\t\tpagenum++\n\t\t\t} else {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}\n\n\treturn be.store(e, subs.Slice())\n}\n\nfunc (be *binaryEdge) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, be.source, be.name, be.name+\"-Handler\")\n}\n\nfunc (be *binaryEdge) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, be.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/chaos.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype chaos struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewChaos() et.Plugin {\n\tlimit := rate.Every(10 * time.Second)\n\n\treturn &chaos{\n\t\tname: \"Chaos\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Chaos\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (c *chaos) Name() string {\n\treturn c.name\n}\n\nfunc (c *chaos) Start(r et.Registry) error {\n\tc.log = r.Log().WithGroup(\"plugin\").With(\"name\", c.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: c,\n\t\tName: c.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: c.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tc.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (c *chaos) Stop() {\n\tc.log.Info(\"Plugin stopped\")\n}\n\nfunc (c *chaos) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(c.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), c.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, c.source, since) {\n\t\tnames = append(names, c.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, c.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, c.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tc.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (c *chaos) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), c.source, since)\n}\n\nfunc (c *chaos) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tvar names []string\n\n\tfor _, key := range keys {\n\t\t_ = c.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\tURL: \"https://dns.projectdiscovery.io/dns/\" + name + \"/subdomains\",\n\t\t\tHeader: http.Header{\"Authorization\": []string{key}},\n\t\t})\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result struct {\n\t\t\tSubdomains []string `json:\"subdomains\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, sub := range result.Subdomains {\n\t\t\tn := dns.RemoveAsteriskLabel(sub + \".\" + name)\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: n}, 0); conf > 0 {\n\t\t\t\tnames = append(names, strings.ToLower(strings.TrimSpace(n)))\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\treturn c.store(e, names)\n}\n\nfunc (c *chaos) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, c.source, c.name, c.name+\"-Handler\")\n}\n\nfunc (c *chaos) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, c.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/crtsh.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype crtsh struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewCrtsh() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &crtsh{\n\t\tname: \"crt.sh\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"HackerTarget\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (c *crtsh) Name() string {\n\treturn c.name\n}\n\nfunc (c *crtsh) Start(r et.Registry) error {\n\tc.log = r.Log().WithGroup(\"plugin\").With(\"name\", c.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: c,\n\t\tName: c.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: c.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tc.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (c *crtsh) Stop() {\n\tc.log.Info(\"Plugin stopped\")\n}\n\nfunc (c *crtsh) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), c.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, c.source, since) {\n\t\tnames = append(names, c.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, c.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, c.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tc.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (c *crtsh) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), c.source, since)\n}\n\nfunc (c *crtsh) query(e *et.Event, name string) []*dbt.Entity {\n\t_ = c.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tURL: \"https://crt.sh/?CN=\" + name + \"&output=json&exclude=expired\",\n\t})\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar result struct {\n\t\tCerts []struct {\n\t\t\tNames string `json:\"name_value\"`\n\t\t} `json:\"certs\"`\n\t}\n\tif err := json.Unmarshal([]byte(\"{\\\"certs\\\":\"+resp.Body+\"}\"), &result); err != nil {\n\t\treturn nil\n\t}\n\n\tvar names []string\n\tfor _, cert := range result.Certs {\n\t\tfor _, n := range strings.Split(cert.Names, \"\\n\") {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(dns.RemoveAsteriskLabel(n)))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tnames = append(names, nstr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn c.store(e, names)\n}\n\nfunc (c *crtsh) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, c.source, c.name, c.name+\"-Handler\")\n}\n\nfunc (c *crtsh) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, c.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/dnsrepo.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype dnsrepo struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewDNSRepo() et.Plugin {\n\tlimit := rate.Every(10 * time.Second)\n\n\treturn &dnsrepo{\n\t\tname: \"DNSRepo\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"DNSRepo\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (d *dnsrepo) Name() string {\n\treturn d.name\n}\n\nfunc (d *dnsrepo) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *dnsrepo) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *dnsrepo) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tds := e.Session.Config().GetDataSourceConfig(d.name)\n\tif ds != nil {\n\t\tfor _, cred := range ds.Creds {\n\t\t\tkeys = append(keys, cred.Apikey)\n\t\t}\n\t}\n\t// add an empty API key\n\tkeys = append(keys, \"\")\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), d.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\tnames = append(names, d.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, d.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, d.source)\n\t}\n\n\tif len(names) > 0 {\n\t\td.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (d *dnsrepo) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), d.source, since)\n}\n\nfunc (d *dnsrepo) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tvar names []string\n\n\tfor _, key := range keys {\n\t\tvar req *http.Request\n\n\t\tif key == \"\" {\n\t\t\treq = &http.Request{URL: \"https://dnsrepo.noc.org/?domain=\" + name}\n\t\t} else {\n\t\t\treq = &http.Request{\n\t\t\t\tURL: \"https://dnsrepo.noc.org/api/?apikey=\" + key + \"&search=\" + name + \"&limit=5000\",\n\t\t\t}\n\t\t}\n\n\t\t_ = d.rlimit.Wait(context.TODO())\n\t\tif resp, err := http.RequestWebPage(context.TODO(), req); err == nil {\n\t\t\tif key == \"\" {\n\t\t\t\tnames = append(names, d.parseHTML(e, resp.Body)...)\n\t\t\t} else {\n\t\t\t\tnames = append(names, d.parseJSON(e, resp.Body)...)\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\te.Session.Log().Error(fmt.Sprintf(\"Failed to use the API endpoint: %v\", err),\n\t\t\t\tslog.Group(\"plugin\", \"name\", d.name, \"handler\", d.name+\"-Handler\"))\n\t\t}\n\t}\n\n\treturn d.store(e, names)\n}\n\nfunc (d *dnsrepo) parseHTML(e *et.Event, body string) []string {\n\tvar names []string\n\n\tfor _, sub := range support.ScrapeSubdomainNames(body) {\n\t\tif sub != \"\" {\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tname := http.CleanName(sub)\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: name}, 0); conf > 0 {\n\t\t\t\tnames = append(names, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn names\n}\n\nfunc (d *dnsrepo) parseJSON(e *et.Event, body string) []string {\n\tset := stringset.New()\n\tdefer set.Close()\n\n\tvar resp struct {\n\t\tResults []struct {\n\t\t\tDomain string `json:\"domain\"`\n\t\t\tAlias string `json:\"cname\"`\n\t\t\tIPv4 []string `json:\"ipv4\"`\n\t\t\tIPv6 []string `json:\"ipv6\"`\n\t\t} `json:\"results\"`\n\t}\n\n\tif err := json.Unmarshal([]byte(\"{\\\"results\\\":\"+body+\"}\"), &resp); err != nil {\n\t\treturn set.Slice()\n\t}\n\n\tfor _, r := range resp.Results {\n\t\tfor _, sub := range []string{r.Domain, r.Alias} {\n\t\t\tif slen := len(sub); slen > 0 {\n\t\t\t\tname := sub\n\t\t\t\t// remove an ending dot from the name\n\t\t\t\tif sub[slen-1] == '.' {\n\t\t\t\t\tname = sub[:slen-1]\n\t\t\t\t}\n\t\t\t\t// if the subdomain is not in scope, skip it\n\t\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: name}, 0); conf > 0 {\n\t\t\t\t\tset.Insert(name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn set.Slice()\n}\n\nfunc (d *dnsrepo) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, d.source, d.name, d.name+\"-Handler\")\n}\n\nfunc (d *dnsrepo) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, d.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/grepapp.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype grepApp struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewGrepApp() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &grepApp{\n\t\tname: \"Grep.App\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Grep.App\",\n\t\t\tConfidence: 50,\n\t\t},\n\t}\n}\n\nfunc (g *grepApp) Name() string {\n\treturn g.name\n}\n\nfunc (g *grepApp) Start(r et.Registry) error {\n\tg.log = r.Log().WithGroup(\"plugin\").With(\"name\", g.name)\n\n\tname := g.name + \"-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: g,\n\t\tName: name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.Identifier)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: g.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tg.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (g *grepApp) Stop() {\n\tg.log.Info(\"Plugin stopped\")\n}\n\nfunc (g *grepApp) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.Identifier), g.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, g.source, since) {\n\t\tnames = append(names, g.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, g.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, g.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tg.process(e, names)\n\t}\n\treturn nil\n}\nfunc (g *grepApp) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.Identifier), g.source, since)\n}\n\nfunc (g *grepApp) query(e *et.Event, name string) []*dbt.Entity {\n\tnewdlt := strings.ReplaceAll(name, \".\", `\\.`)\n\tescapedQuery := url.QueryEscape(\"([a-zA-Z0-9._-]+)@\" + newdlt)\n\tre := regexp.MustCompile(`([a-zA-Z0-9._-]+)@` + newdlt)\n\n\temails := stringset.New()\n\tdefer emails.Close()\n\n\tcont := true\n\tfor page := 1; cont; page++ {\n\t\t_ = g.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\tURL: fmt.Sprintf(\"https://grep.app/api/search?page=%s&q=%s®exp=true\", strconv.Itoa(page), escapedQuery),\n\t\t})\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tvar response struct {\n\t\t\tFacets struct {\n\t\t\t\tHits []struct {\n\t\t\t\t\tContent struct {\n\t\t\t\t\t\tSnippet string `json:\"snippet\"`\n\t\t\t\t\t} `json:\"content\"`\n\t\t\t\t} `json:\"hits\"`\n\t\t\t\tTotal int `json:\"total\"`\n\t\t\t} `json:\"facets\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(resp.Body), &response); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcont = false\n\t\tif len(response.Facets.Hits) > 0 {\n\t\t\tcont = true\n\t\t\t// loop through the hits and append the snippets to the results\n\t\t\tfor _, hit := range response.Facets.Hits {\n\t\t\t\temails.InsertMany(re.FindAllString(hit.Content.Snippet, -1)...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn g.store(e, emails.Slice())\n}\n\nfunc (g *grepApp) store(e *et.Event, emails []string) []*dbt.Entity {\n\treturn support.StoreEmailsWithSource(e.Session, emails, g.source, g.name, g.name+\"-Handler\")\n}\n\nfunc (g *grepApp) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessEmailsWithSource(e, assets, g.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/hackertarget.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/csv\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype hackerTarget struct {\n\tname string\n\turl string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewHackerTarget() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &hackerTarget{\n\t\tname: \"HackerTarget\",\n\t\turl: \"https://api.hackertarget.com/hostsearch/?q=\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"HackerTarget\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (ht *hackerTarget) Name() string {\n\treturn ht.name\n}\n\nfunc (ht *hackerTarget) Start(r et.Registry) error {\n\tht.log = r.Log().WithGroup(\"plugin\").With(\"name\", ht.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: ht,\n\t\tName: ht.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: ht.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tht.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (ht *hackerTarget) Stop() {\n\tht.log.Info(\"Plugin stopped\")\n}\n\nfunc (ht *hackerTarget) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), ht.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, ht.source, since) {\n\t\tnames = append(names, ht.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, ht.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, ht.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tht.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (ht *hackerTarget) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), ht.source, since)\n}\n\nfunc (ht *hackerTarget) query(e *et.Event, name string) []*dbt.Entity {\n\t_ = ht.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: ht.url + name})\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar names []string\n\tif records, err := csv.NewReader(strings.NewReader(resp.Body)).ReadAll(); err == nil {\n\t\tfor _, record := range records {\n\t\t\tif len(record) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tn := strings.ToLower(strings.TrimSpace(record[0]))\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: n}, 0); conf > 0 {\n\t\t\t\tnames = append(names, n)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ht.store(e, names)\n}\n\nfunc (ht *hackerTarget) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, ht.source, ht.name, ht.name+\"-Handler\")\n}\n\nfunc (ht *hackerTarget) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, ht.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/hunterio.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2024. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\n/*\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\t\"github.com/owasp-amass/open-asset-model/domain\"\n\t\"github.com/owasp-amass/open-asset-model/source\"\n\t\"go.uber.org/ratelimit\"\n)\n\ntype hunterIO struct {\n\tname string\n\tcounturl string\n\tqueryurl string\n\temailVerifierurl string\n\taccounttype string\n\tlog *slog.Logger\n\trlimit ratelimit.Limiter\n\tsource *et.Source\n}\n\nfunc NewHunterIO() et.Plugin {\n\treturn &hunterIO{\n\t\tname: \"Hunter.io\",\n\t\tcounturl: \"https://api.hunter.io/v2/email-count?domain=\",\n\t\tqueryurl: \"https://api.hunter.io/v2/domain-search?domain=\",\n\t\temailVerifierurl: \"https://api.hunter.io/v2/email-verifier?email=\",\n\t\trlimit: ratelimit.New(15, ratelimit.WithoutSlack),\n\t\tsource: &et.Source{\n\t\t\tName: \"Hunter.io\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (h *hunterIO) Name() string {\n\treturn h.name\n}\n\nfunc (h *hunterIO) Start(r et.Registry) error {\n\th.log = r.Log().WithGroup(\"plugin\").With(\"name\", h.name)\n\n\tname := h.name + \"-Email-Generation-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: h,\n\t\tName: name,\n\t\tTransforms: []string{\"emailaddress\"},\n\t\tEventType: oam.FQDN,\n\t\tCallback: h.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tname = h.name + \"-Email-Verification-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: h,\n\t\tName: name,\n\t\tTransforms: []string{\"emailaddress\"},\n\t\tEventType: oam.EmailAddress,\n\t\tCallback: h.verify,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\th.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (h *hunterIO) Stop() {\n\th.log.Info(\"Plugin stopped\")\n}\n\nfunc (h *hunterIO) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*domain.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tdomlt := strings.ToLower(strings.TrimSpace(fqdn.Name))\n\tif e.Session.Config().WhichDomain(domlt) != domlt {\n\t\treturn nil\n\t}\n\n\n\th.rlimit.Take()\n\tif count, err := h.count(domlt); err != nil {\n\t\te.Session.Log().Error(fmt.Sprintf(\"Failed to use the API count endpoint: %v\", err),\n\t\t\tslog.Group(\"plugin\", \"name\", h.name, \"handler\", h.name+\"-Email-Generation-Handler\"))\n\t\treturn nil\n\t} else {\n\t\tapi, err := h.account_type(e)\n\t\tif err != nil || api == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tresults, err := h.query(domlt, count, api)\n\t\tif err != nil {\n\t\t\te.Session.Log().Error(fmt.Sprintf(\"Failed to query: %v\", err),\n\t\t\t\tslog.Group(\"plugin\", \"name\", h.name, \"handler\", h.name+\"-Email-Generation-Handler\"))\n\t\t\treturn nil\n\t\t}\n\t\tsupport.ProcessEmailsWithSource(e, results, h.source)\n\t}\n\treturn nil\n}\n\nfunc (h *hunterIO) verify(e *et.Event) error {\n\temail, ok := e.Entity.Asset.(*contact.EmailAddress)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the EmailAddress asset\")\n\t}\n\n\th.rlimit.Take()\n\tapi, err := support.GetAPI(h.name, e)\n\tif err != nil || api == \"\" {\n\t\treturn nil\n\t}\n\n\ttype responseJSON struct {\n\t\tData struct {\n\t\t\tStatus string `json:\"status\"`\n\t\t\tResult string `json:\"result\"`\n\t\t} `json:\"data\"`\n\t}\n\n\tvar result responseJSON\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: h.emailVerifierurl + email.Address + \"&api_key=\" + api})\n\tif err != nil {\n\t\te.Session.Log().Error(fmt.Sprintf(\"Failed to make Verify request: %v\", err),\n\t\t\tslog.Group(\"plugin\", \"name\", h.name, \"handler\", h.name+\"-Email-Verification-Handler\"))\n\t\treturn nil\n\t}\n\n\tif err := json.NewDecoder(strings.NewReader(resp.Body)).Decode(&result); err != nil {\n\t\te.Session.Log().Error(fmt.Sprintf(\"Failed to decode JSON: %v\", err),\n\t\t\tslog.Group(\"plugin\", \"name\", h.name, \"handler\", h.name+\"-Email-Verification-Handler\"))\n\t\treturn nil\n\t}\n\n\teventMeta, ok := e.Meta.(*et.EmailMeta)\n\tif !ok {\n\t\tif e.Meta != nil {\n\t\t\treturn fmt.Errorf(\"unexpected Meta type: %T\", e.Meta)\n\t\t}\n\t\treturn nil\n\t}\n\teventMeta.VerifyAttempted = true\n\n\tif result.Data.Status != \"unknown\" && result.Data.Status != \"invalid\" &&\n\t\tresult.Data.Status != \"disposable\" && result.Data.Status != \"accept_all\" {\n\t\teventMeta.Verified = true\n\t}\n\treturn nil\n}\n\nfunc (h *hunterIO) account_type(e *et.Event) (string, error) {\n\tapi, err := support.GetAPI(h.name, e)\n\tif err != nil || api == \"\" {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: \"https://api.hunter.io/v2/account?api_key=\" + api})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// make a struct to hold the response since it returns as json\n\ttype responseJSON struct {\n\t\tData struct {\n\t\t\tPlan string `json:\"plan_name\"`\n\t\t} `json:\"data\"`\n\t}\n\n\tvar response responseJSON\n\t// decode the json then return the total only\n\tif err := json.NewDecoder(strings.NewReader(resp.Body)).Decode(&response); err != nil {\n\t\treturn \"\", err\n\t}\n\th.accounttype = response.Data.Plan\n\treturn api, nil\n}\n\nfunc (h *hunterIO) count(domain string) (int, error) {\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: h.counturl + domain})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// make a struct to hold the response since it returns as json\n\ttype responseJSON struct {\n\t\tData struct {\n\t\t\tTotal int `json:\"total\"`\n\t\t} `json:\"data\"`\n\t}\n\n\tvar response responseJSON\n\t// decode the json then return the total only\n\tif err := json.NewDecoder(strings.NewReader(resp.Body)).Decode(&response); err != nil {\n\t\treturn 0, err\n\t}\n\treturn response.Data.Total, nil\n\n}\n\nfunc (h *hunterIO) query(domain string, count int, api string) ([]string, error) {\n\tvar result []string\n\t// make a struct to hold the response since it returns as json\n\ttype responseJSON struct {\n\t\tData struct {\n\t\t\tEmail []struct {\n\t\t\t\tValue string `json:\"value\"`\n\t\t\t} `json:\"emails\"`\n\t\t} `json:\"data\"`\n\t}\n\n\tvar response responseJSON\n\t// if the count is less than or equal to 10, we can get all the emails in one request\n\t// TODO: add another condition for free API keys, since they could only get the first ten anyways.\n\tif count <= 10 || h.accounttype == \"Free\" {\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: h.queryurl + domain + \"&api_key=\" + api})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := json.NewDecoder(strings.NewReader(resp.Body)).Decode(&response); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, data := range response.Data.Email {\n\t\t\tresult = append(result, data.Value)\n\t\t}\n\n\t} else {\n\t\tfor offset := 0; offset < count; offset += 100 {\n\t\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: h.queryurl + domain + \"&api_key=\" + api + \"&limit=100&offset=\" + strconv.Itoa(offset)})\n\t\t\tif err != nil && resp.StatusCode != 400 {\n\t\t\t\treturn nil, err\n\t\t\t} else if resp.StatusCode == 400 { // since the API returns 400 when the limit is exceeded or if any error occurs, we break the loop\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err := json.NewDecoder(strings.NewReader(resp.Body)).Decode(&response); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, data := range response.Data.Email {\n\t\t\t\tresult = append(result, data.Value)\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn result, nil\n}\n*/\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/leakix.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype leakix struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewLeakIX() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &leakix{\n\t\tname: \"LeakIX\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"LeakIX\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (ix *leakix) Name() string {\n\treturn ix.name\n}\n\nfunc (ix *leakix) Start(r et.Registry) error {\n\tix.log = r.Log().WithGroup(\"plugin\").With(\"name\", ix.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: ix,\n\t\tName: ix.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: ix.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tix.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (ix *leakix) Stop() {\n\tix.log.Info(\"Plugin stopped\")\n}\n\nfunc (ix *leakix) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(ix.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), ix.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, ix.source, since) {\n\t\tnames = append(names, ix.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, ix.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, ix.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tix.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (ix *leakix) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), ix.source, since)\n}\n\nfunc (ix *leakix) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tvar names []string\n\n\tfor _, key := range keys {\n\t\t_ = ix.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\tURL: \"https://leakix.net/api/subdomains/\" + name,\n\t\t\tHeader: http.Header{\"Accept\": []string{\"application/json\"}, \"api-key\": []string{key}},\n\t\t})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result struct {\n\t\t\tSubdomains []struct {\n\t\t\t\tFQDN string `json:\"subdomain\"`\n\t\t\t} `json:\"subdomains\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(\"{\\\"subdomains\\\":\"+resp.Body+\"}\"), &result); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, s := range result.Subdomains {\n\t\t\tname := strings.ToLower(strings.TrimSpace(dns.RemoveAsteriskLabel(s.FQDN)))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: name}, 0); conf > 0 {\n\t\t\t\tnames = append(names, name)\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\treturn ix.store(e, names)\n}\n\nfunc (ix *leakix) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, ix.source, ix.name, ix.name+\"-Handler\")\n}\n\nfunc (ix *leakix) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, ix.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/passivetotal.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype passiveTotal struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewPassiveTotal() et.Plugin {\n\tlimit := rate.Every(10 * time.Second)\n\n\treturn &passiveTotal{\n\t\tname: \"PassiveTotal\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"PassiveTotal\",\n\t\t\tConfidence: 30,\n\t\t},\n\t}\n}\n\nfunc (pt *passiveTotal) Name() string {\n\treturn pt.name\n}\n\nfunc (pt *passiveTotal) Start(r et.Registry) error {\n\tpt.log = r.Log().WithGroup(\"plugin\").With(\"name\", pt.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: pt,\n\t\tName: pt.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: pt.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tpt.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (pt *passiveTotal) Stop() {\n\tpt.log.Info(\"Plugin stopped\")\n}\n\nfunc (pt *passiveTotal) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(pt.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), pt.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, pt.source, since) {\n\t\tnames = append(names, pt.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, pt.query(e, fqdn.Name, ds)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, pt.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tpt.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (pt *passiveTotal) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), pt.source, since)\n}\n\nfunc (pt *passiveTotal) query(e *et.Event, name string, ds *config.DataSource) []*dbt.Entity {\n\tnames := support.NewFQDNFilter()\n\tdefer names.Close()\n\n\tvar lastid string\nloop:\n\tfor _, cr := range ds.Creds {\n\t\tfor lastid != \"\" {\n\t\t\tif cr == nil || cr.Username == \"\" || cr.Apikey == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\turl := \"https://api.riskiq.net/pt/v2/enrichment/subdomains?query=\" + name\n\t\t\tif lastid != \"\" {\n\t\t\t\turl += \"&lastId=\" + lastid\n\t\t\t}\n\n\t\t\t_ = pt.rlimit.Wait(context.TODO())\n\t\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\t\tURL: url,\n\t\t\t\tAuth: &http.BasicAuth{\n\t\t\t\t\tUsername: cr.Username,\n\t\t\t\t\tPassword: cr.Apikey,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil || resp.Body == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar result struct {\n\t\t\t\tSuccess bool `json:\"success\"`\n\t\t\t\tSubdomains []string `json:\"subdomains\"`\n\t\t\t\tLastID string `json:\"lastId\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil || !result.Success {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, sub := range result.Subdomains {\n\t\t\t\tn := dns.RemoveAsteriskLabel(http.CleanName(sub + \".\" + name))\n\t\t\t\t// if the subdomain is not in scope, skip it\n\t\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: n}, 0); conf > 0 {\n\t\t\t\t\tnames.Insert(n)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlastid = result.LastID\n\t\t\tif lastid == \"\" {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}\n\n\tnames.Prune(1000)\n\treturn pt.store(e, names.Slice())\n}\n\nfunc (pt *passiveTotal) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, pt.source, pt.name, pt.name+\"-Handler\")\n}\n\nfunc (pt *passiveTotal) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, pt.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/prospeo.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype Prospeo struct {\n\tname string\n\taccturl string\n\tcounturl string\n\tqueryurl string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewProspeo() et.Plugin {\n\tlimit := rate.Every(15 * time.Second)\n\n\treturn &Prospeo{\n\t\tname: \"Prospeo\",\n\t\taccturl: \"https://api.prospeo.io/account-information\",\n\t\tcounturl: \"https://api.prospeo.io/email-count\",\n\t\tqueryurl: \"https://api.prospeo.io/domain-search\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Prospeo\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (p *Prospeo) Name() string {\n\treturn p.name\n}\n\nfunc (p *Prospeo) Start(r et.Registry) error {\n\tp.log = r.Log().WithGroup(\"plugin\").With(\"name\", p.name)\n\n\tname := p.name + \"-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: p,\n\t\tName: name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.Identifier)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: p.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tp.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (p *Prospeo) Stop() {\n\tp.log.Info(\"Plugin stopped\")\n}\n\nfunc (p *Prospeo) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.Identifier), p.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, p.source, since) {\n\t\tnames = append(names, p.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, p.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, p.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tp.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (p *Prospeo) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\tvar emails []*dbt.Entity\n\n\tfor _, e := range support.SourceToAssetsWithinTTL(e.Session, name, string(oam.Identifier), p.source, since) {\n\t\tif email, ok := e.Asset.(*general.Identifier); ok && email != nil && email.Type == general.EmailAddress {\n\t\t\temails = append(emails, e)\n\t\t}\n\t}\n\n\treturn emails\n}\n\nfunc (p *Prospeo) query(e *et.Event, name string) []*dbt.Entity {\n\tkey, err := support.GetAPI(p.name, e)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\trcreds, err := p.accountType(key)\n\tif err != nil || key == \"\" {\n\t\treturn nil\n\t}\n\n\tcount, err := p.count(name, key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tlimit := rcreds * 50\n\tif limit > count {\n\t\tlimit = count\n\t}\n\n\t_ = p.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tMethod: \"POST\",\n\t\tBody: `{\"company\": \"` + name + `\", \"limit\": ` + strconv.Itoa(limit) + `}`,\n\t\tURL: p.queryurl,\n\t\tHeader: http.Header{\"Content-Type\": []string{\"application/json\"}, \"X-KEY\": []string{key}},\n\t})\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar r struct {\n\t\tResponse struct {\n\t\t\tEmails []struct {\n\t\t\t\tEmail string `json:\"email\"`\n\t\t\t} `json:\"email_list\"`\n\t\t} `json:\"response\"`\n\t}\n\tif err := json.Unmarshal([]byte(resp.Body), &r); err != nil {\n\t\treturn nil\n\t}\n\n\tvar emails []string\n\tfor _, e := range r.Response.Emails {\n\t\temails = append(emails, e.Email)\n\t}\n\treturn p.store(e, emails)\n}\n\nfunc (p *Prospeo) store(e *et.Event, emails []string) []*dbt.Entity {\n\treturn support.StoreEmailsWithSource(e.Session, emails, p.source, p.name, p.name+\"-Handler\")\n}\n\nfunc (p *Prospeo) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessEmailsWithSource(e, assets, p.source)\n}\n\nfunc (p *Prospeo) accountType(key string) (int, error) {\n\t_ = p.rlimit.Wait(context.TODO())\n\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tMethod: \"POST\",\n\t\tURL: p.accturl,\n\t\tHeader: http.Header{\"Content-Type\": []string{\"application/json\"}, \"X-KEY\": []string{key}},\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar r struct {\n\t\tResponse struct {\n\t\t\tRemainingCredits int `json:\"remaining_credits\"`\n\t\t} `json:\"response\"`\n\t}\n\tif err := json.Unmarshal([]byte(resp.Body), &r); err != nil {\n\t\treturn 0, err\n\t}\n\treturn r.Response.RemainingCredits, nil\n}\n\nfunc (p *Prospeo) count(domain string, key string) (int, error) {\n\t_ = p.rlimit.Wait(context.TODO())\n\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tMethod: \"POST\",\n\t\tBody: `{\"domain\": \"` + domain + `\"}`,\n\t\tURL: p.counturl,\n\t\tHeader: http.Header{\"Content-Type\": []string{\"application/json\"}, \"X-KEY\": []string{key}},\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar r struct {\n\t\tResponse struct {\n\t\t\tCount int `json:\"count\"`\n\t\t} `json:\"response\"`\n\t}\n\tif err := json.Unmarshal([]byte(resp.Body), &r); err != nil {\n\t\treturn 0, err\n\t}\n\treturn r.Response.Count, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/securitytrails.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype securityTrails struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewSecurityTrails() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &securityTrails{\n\t\tname: \"SecurityTrails\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"SecurityTrails\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (st *securityTrails) Name() string {\n\treturn st.name\n}\n\nfunc (st *securityTrails) Start(r et.Registry) error {\n\tst.log = r.Log().WithGroup(\"plugin\").With(\"name\", st.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: st,\n\t\tName: st.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: st.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tst.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (st *securityTrails) Stop() {\n\tst.log.Info(\"Plugin stopped\")\n}\n\nfunc (st *securityTrails) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(st.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), st.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, st.source, since) {\n\t\tnames = append(names, st.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, st.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, st.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tst.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (st *securityTrails) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), st.source, since)\n}\n\nfunc (st *securityTrails) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tvar names []string\n\n\tfor _, key := range keys {\n\t\t_ = st.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\tURL: \"https://api.securitytrails.com/v1/domain/\" + name + \"/subdomains\",\n\t\t\tHeader: http.Header{\"APIKEY\": []string{key}},\n\t\t})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result struct {\n\t\t\tSubdomains []string `json:\"subdomains\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, sub := range result.Subdomains {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(dns.RemoveAsteriskLabel(sub + \".\" + name)))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tnames = append(names, nstr)\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\treturn st.store(e, names)\n}\n\nfunc (st *securityTrails) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, st.source, st.name, st.name+\"-Handler\")\n}\n\nfunc (st *securityTrails) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, st.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/virustotal.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype virusTotal struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewVirusTotal() et.Plugin {\n\tlimit := rate.Every(5 * time.Second)\n\n\treturn &virusTotal{\n\t\tname: \"VirusTotal\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"VirusTotal\",\n\t\t\tConfidence: 60,\n\t\t},\n\t}\n}\n\nfunc (vt *virusTotal) Name() string {\n\treturn vt.name\n}\n\nfunc (vt *virusTotal) Start(r et.Registry) error {\n\tvt.log = r.Log().WithGroup(\"plugin\").With(\"name\", vt.name)\n\n\tname := vt.name + \"-Handler\"\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: vt,\n\t\tName: name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: vt.check,\n\t}); err != nil {\n\t\tr.Log().Error(fmt.Sprintf(\"Failed to register a handler: %v\", err),\n\t\t\tslog.Group(\"plugin\", \"name\", vt.name, \"handler\", name))\n\t\treturn err\n\t}\n\n\tvt.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (vt *virusTotal) Stop() {\n\tvt.log.Info(\"Plugin stopped\")\n}\n\nfunc (vt *virusTotal) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(vt.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), vt.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, vt.source, since) {\n\t\tnames = append(names, vt.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, vt.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, vt.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tvt.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (vt *virusTotal) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), vt.source, since)\n}\n\nfunc (vt *virusTotal) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tvar names []string\n\n\tfor _, key := range keys {\n\t\t_ = vt.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\t\tURL: \"https://www.virustotal.com/vtapi/v2/domain/report?domain=\" + name + \"&apikey=\" + key,\n\t\t})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result struct {\n\t\t\tSubdomains []string `json:\"subdomains\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, sub := range result.Subdomains {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(dns.RemoveAsteriskLabel(sub)))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tnames = append(names, nstr)\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\treturn vt.store(e, names)\n}\n\nfunc (vt *virusTotal) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, vt.source, vt.name, vt.name+\"-Handler\")\n}\n\nfunc (vt *virusTotal) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, vt.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/zetalytics.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage api\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype zetalytics struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewZetalytics() et.Plugin {\n\tlimit := rate.Every(5 * time.Second)\n\n\treturn &zetalytics{\n\t\tname: \"ZETAlytics\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"ZETAlytics\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (z *zetalytics) Name() string {\n\treturn z.name\n}\n\nfunc (z *zetalytics) Start(r et.Registry) error {\n\tz.log = r.Log().WithGroup(\"plugin\").With(\"name\", z.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: z,\n\t\tName: z.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: z.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tz.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (z *zetalytics) Stop() {\n\tz.log.Info(\"Plugin stopped\")\n}\n\nfunc (z *zetalytics) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(z.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), z.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, z.source, since) {\n\t\tnames = append(names, z.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, z.query(e, fqdn.Name, keys)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, z.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tz.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (z *zetalytics) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), z.source, since)\n}\n\nfunc (z *zetalytics) query(e *et.Event, name string, keys []string) []*dbt.Entity {\n\tnames := support.NewFQDNFilter()\n\tdefer names.Close()\n\n\tfor _, key := range keys {\n\t\tstart := time.Now().Add((time.Hour * 24) * -90).Unix() // The epoch 90 days ago\n\t\turl := \"https://zonecruncher.com/api/v1/subdomains?q=\" + name +\n\t\t\t\"&token=\" + key + \"&tsfield=last_seen&start=\" + strconv.FormatInt(start, 10)\n\n\t\t_ = z.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: url})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result struct {\n\t\t\tTotal int `json:\"total\"`\n\t\t\tSubdomains []struct {\n\t\t\t\tFQDN string `json:\"qname\"`\n\t\t\t\t//FirstSeen string `json:\"first_seen\"`\n\t\t\t\t//LastSeen string `json:\"last_seen\"`\n\t\t\t} `json:\"results\"`\n\t\t\tMsg string `json:\"msg\"`\n\t\t}\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil || result.Total == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, s := range result.Subdomains {\n\t\t\tname := strings.ToLower(strings.TrimSpace(dns.RemoveAsteriskLabel(http.CleanName(s.FQDN))))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: name}, 0); conf > 0 {\n\t\t\t\tnames.Insert(name)\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\tnames.Prune(1000)\n\treturn z.store(e, names.Slice())\n}\n\nfunc (z *zetalytics) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, z.source, z.name, z.name+\"-Handler\")\n}\n\nfunc (z *zetalytics) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, z.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/company_enrich.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (ce *companyEnrich) check(e *et.Event) error {\n\toamid, ok := e.Entity.Asset.(*general.Identifier)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Identifier asset\")\n\t} else if oamid.Type != AviatoCompanyID {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(ce.plugin.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Identifier), string(oam.Organization), ce.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar orgent *dbt.Entity\n\tsrc := &et.Source{\n\t\tName: ce.name,\n\t\tConfidence: ce.plugin.source.Confidence,\n\t}\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\torgent = ce.lookup(e, e.Entity, since)\n\t} else if o, data := ce.query(e, e.Entity, keys); data != nil {\n\t\torgent = o\n\t\tce.store(e, o, data)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif orgent != nil {\n\t\tce.process(e, e.Entity, orgent)\n\t}\n\treturn nil\n}\n\nfunc (ce *companyEnrich) lookup(e *et.Event, ident *dbt.Entity, since time.Time) *dbt.Entity {\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ce.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*org.Organization); ok {\n\t\t\t\t\treturn a\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ce *companyEnrich) query(e *et.Event, ident *dbt.Entity, apikey []string) (*dbt.Entity, *companyEnrichResult) {\n\toamid := e.Entity.Asset.(*general.Identifier)\n\n\torgent := ce.lookup(e, ident, time.Time{})\n\tif orgent == nil {\n\t\tmsg := fmt.Sprintf(\"failed to find the Organization asset for %s\", oamid.UniqueID)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\treturn nil, nil\n\t}\n\n\tvar enrich *companyEnrichResult\n\tfor _, key := range apikey {\n\t\theaders := http.Header{\"Content-Type\": []string{\"application/json\"}}\n\t\theaders[\"Authorization\"] = []string{\"Bearer \" + key}\n\n\t\t_ = ce.plugin.rlimit.Wait(context.TODO())\n\t\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\t\tdefer cancel()\n\n\t\tu := fmt.Sprintf(\"https://data.api.aviato.co/company/enrich?id=%s\", url.QueryEscape(oamid.ID))\n\t\tresp, err := http.RequestWebPage(ctx, &http.Request{URL: u, Header: headers})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company enrich result for %s: %s\", oamid.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\tcontinue\n\t\t} else if resp.StatusCode != 200 {\n\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company enrich result for %s: %s\", oamid.ID, resp.Status)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\tcontinue\n\t\t} else if resp.Body == \"\" {\n\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company enrich result for %s: empty body\", oamid.ID)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\tcontinue\n\t\t} else if strings.Contains(resp.Body, \"error\") {\n\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company enrich result for %s: %s\", oamid.ID, resp.Body)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar result companyEnrichResult\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err == nil {\n\t\t\tenrich = &result\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"failed to unmarshal the company enrich result for %s: %s\", oamid.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t}\n\t\tbreak\n\t}\n\n\tif enrich == nil {\n\t\treturn nil, nil\n\t}\n\treturn orgent, enrich\n}\n\nfunc (ce *companyEnrich) store(e *et.Event, orgent *dbt.Entity, data *companyEnrichResult) {\n\to := orgent.Asset.(*org.Organization)\n\n\to.Active = false\n\tif strings.EqualFold(data.Status, \"active\") {\n\t\to.Active = true\n\t}\n\to.NonProfit = data.IsNonProfit\n\to.Headcount = data.Headcount\n\n\t// attempt to set the legal name\n\tif o.LegalName == \"\" && data.LegalName != \"\" {\n\t\to.LegalName = data.LegalName\n\n\t\toamid := &general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.LegalName, o.LegalName),\n\t\t\tID: o.LegalName,\n\t\t\tType: general.LegalName,\n\t\t}\n\n\t\tident, err := e.Session.Cache().CreateAsset(oamid)\n\t\tif err != nil || ident == nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Identifier asset for %s: %s\", o.LegalName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\treturn\n\t\t}\n\n\t\t_, err = e.Session.Cache().CreateEntityProperty(ident, &general.SourceProperty{\n\t\t\tSource: ce.name,\n\t\t\tConfidence: ce.plugin.source.Confidence,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the SourceProperty for %s: %s\", o.LegalName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\t_ = e.Session.Cache().DeleteEntity(ident.ID)\n\t\t\treturn\n\t\t}\n\n\t\terr = ce.plugin.createRelation(e.Session, orgent, general.SimpleRelation{Name: \"id\"}, ident, ce.plugin.source.Confidence)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the relation for %s: %s\", o.LegalName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\t\t_ = e.Session.Cache().DeleteEntity(ident.ID)\n\t\t\treturn\n\t\t}\n\t}\n\t// update entity\n\t_, err := e.Session.Cache().CreateEntity(orgent)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to update the Organization asset for %s: %s\", o.Name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n\t\treturn\n\t}\n}\n\nfunc (ce *companyEnrich) process(e *et.Event, ident, orgent *dbt.Entity) {\n\to := orgent.Asset.(*org.Organization)\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: fmt.Sprintf(\"%s:%s\", o.Name, o.ID),\n\t\tEntity: orgent,\n\t\tSession: e.Session,\n\t})\n\n\tid := ident.Asset.(*general.Identifier)\n\te.Session.Log().Info(\"relationship discovered\", \"from\", id.UniqueID, \"relation\", \"id\",\n\t\t\"to\", o.Name, slog.Group(\"plugin\", \"name\", ce.plugin.name, \"handler\", ce.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/company_rounds.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/account\"\n\t\"github.com/owasp-amass/open-asset-model/financial\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n\t\"github.com/owasp-amass/open-asset-model/people\"\n)\n\nfunc (cr *companyRounds) check(e *et.Event) error {\n\toamid, ok := e.Entity.Asset.(*general.Identifier)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Identifier asset\")\n\t} else if oamid.Type != AviatoCompanyID {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(cr.plugin.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Identifier), string(oam.Organization), cr.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar fundents []*dbt.Entity\n\tsrc := &et.Source{\n\t\tName: cr.name,\n\t\tConfidence: cr.plugin.source.Confidence,\n\t}\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tfundents = cr.lookup(e, e.Entity, since)\n\t} else {\n\t\tfundents = cr.query(e, e.Entity, keys)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif len(fundents) > 0 {\n\t\tcr.process(e, fundents)\n\t}\n\treturn nil\n}\n\nfunc (cr *companyRounds) lookup(e *et.Event, ident *dbt.Entity, since time.Time) []*dbt.Entity {\n\tvar orgent *dbt.Entity\n\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, cr.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\torgent = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar fundents []*dbt.Entity\n\tif orgent == nil {\n\t\treturn fundents\n\t}\n\n\tvar accountents []*dbt.Entity\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, since, \"account\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, cr.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif acc, ok := a.Asset.(*account.Account); ok && acc.Type == account.Checking && acc.Number == \"default\" {\n\t\t\t\t\taccountents = append(accountents, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, ent := range accountents {\n\t\tif edges, err := e.Session.Cache().IncomingEdges(ent, since, \"recipient\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, cr.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*financial.FundsTransfer); ok {\n\t\t\t\t\t\tfundents = append(fundents, a)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fundents\n}\n\nfunc (cr *companyRounds) query(e *et.Event, ident *dbt.Entity, apikey []string) []*dbt.Entity {\n\toamid := e.Entity.Asset.(*general.Identifier)\n\n\torgent := cr.getAssociatedOrg(e, ident)\n\tif orgent == nil {\n\t\tmsg := fmt.Sprintf(\"failed to find the Organization asset for %s\", oamid.UniqueID)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\treturn []*dbt.Entity{}\n\t}\n\n\tpage := 0\n\ttotal := 1\n\tperPage := 100\n\tvar fundents []*dbt.Entity\nloop:\n\tfor _, key := range apikey {\n\t\tfor ; page < total; page++ {\n\t\t\theaders := http.Header{\"Content-Type\": []string{\"application/json\"}}\n\t\t\theaders[\"Authorization\"] = []string{\"Bearer \" + key}\n\n\t\t\t_ = cr.plugin.rlimit.Wait(context.TODO())\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tu := fmt.Sprintf(\"https://data.api.aviato.co/company/%s/funding-rounds?perPage=%d&page=%d\", url.QueryEscape(oamid.ID), perPage, page)\n\t\t\tresp, err := http.RequestWebPage(ctx, &http.Request{URL: u, Header: headers})\n\t\t\tif err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the funding rounds for %s: %s\", oamid.ID, err)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\t\tcontinue\n\t\t\t} else if resp.StatusCode != 200 {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the funding rounds for %s: %s\", oamid.ID, resp.Status)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\t\tcontinue\n\t\t\t} else if resp.Body == \"\" {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the funding rounds for %s: empty body\", oamid.ID)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\t\tcontinue\n\t\t\t} else if strings.Contains(resp.Body, \"error\") {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the funding rounds for %s: %s\", oamid.ID, resp.Body)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar result companyRoundsResult\n\t\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to unmarshal the funding rounds for %s: %s\", oamid.ID, err)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\t\tbreak loop\n\t\t\t} else if len(result.FundingRounds) == 0 {\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t\tif len(result.FundingRounds) > 0 {\n\t\t\t\tif ents := cr.store(e, ident, orgent, &result); len(ents) > 0 {\n\t\t\t\t\tfundents = append(fundents, ents...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttotal = result.Pages\n\t\t}\n\n\t\tif page >= total {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn fundents\n}\n\nfunc (cr *companyRounds) getAssociatedOrg(e *et.Event, ident *dbt.Entity) *dbt.Entity {\n\tvar orgent *dbt.Entity\n\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\torgent = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn orgent\n}\n\nfunc (cr *companyRounds) store(e *et.Event, ident, orgent *dbt.Entity, funds *companyRoundsResult) []*dbt.Entity {\n\tvar fundents []*dbt.Entity\n\n\tif orgent == nil {\n\t\treturn fundents\n\t}\n\to := orgent.Asset.(*oamorg.Organization)\n\n\tfor _, round := range funds.FundingRounds {\n\t\torgacc := cr.orgCheckingAccount(e, orgent)\n\t\tif orgacc == nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the checking account for %s\", o.Name)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tseedacc := cr.createSeedAccount(e, &round)\n\t\tif seedacc == nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the seed account for %s\", o.Name)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tf := &financial.FundsTransfer{\n\t\t\tID: fmt.Sprintf(\"%s:%s\", round.Name, round.Stage),\n\t\t\tAmount: float64(round.MoneyRaised),\n\t\t\tCurrency: \"USD\",\n\t\t\tExchangeDate: round.AnnouncedOn,\n\t\t}\n\n\t\tfundent, err := e.Session.Cache().CreateAsset(f)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the FundsTransfer asset for %s: %s\", f.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = e.Session.Cache().CreateEntityProperty(fundent, &general.SourceProperty{\n\t\t\tSource: cr.plugin.source.Name,\n\t\t\tConfidence: cr.plugin.source.Confidence,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the FundsTransfer asset source property for %s: %s\", f.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := cr.plugin.createRelation(e.Session, fundent,\n\t\t\tgeneral.SimpleRelation{Name: \"recipient\"}, orgacc, cr.plugin.source.Confidence); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the recipient relation for %s: %s\", f.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := cr.plugin.createRelation(e.Session, fundent,\n\t\t\tgeneral.SimpleRelation{Name: \"sender\"}, seedacc, cr.plugin.source.Confidence); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the sender relation for %s: %s\", f.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tfundents = append(fundents, fundent)\n\t}\n\n\treturn fundents\n}\n\nfunc (cr *companyRounds) orgCheckingAccount(e *et.Event, orgent *dbt.Entity) *dbt.Entity {\n\tvar accountent *dbt.Entity\n\to := orgent.Asset.(*oamorg.Organization)\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, time.Time{}, \"account\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif acc, ok := a.Asset.(*account.Account); ok && acc.Type == account.Checking && acc.Number == \"default\" {\n\t\t\t\t\taccountent = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif accountent == nil {\n\t\tent, err := e.Session.Cache().CreateAsset(&account.Account{\n\t\t\tID: uuid.New().String(),\n\t\t\tType: account.Checking,\n\t\t\tNumber: \"default\",\n\t\t\tBalance: 0,\n\t\t\tActive: o.Active,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Account asset for %s: %s\", o.Name, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\treturn nil\n\t\t}\n\n\t\taccountent = ent\n\t}\n\n\t_, err := e.Session.Cache().CreateEntityProperty(accountent, &general.SourceProperty{\n\t\tSource: cr.plugin.source.Name,\n\t\tConfidence: cr.plugin.source.Confidence,\n\t})\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the Account asset source property for %s: %s\", o.Name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\treturn nil\n\t}\n\n\tif err := cr.plugin.createRelation(e.Session, orgent,\n\t\tgeneral.SimpleRelation{Name: \"account\"}, accountent, cr.plugin.source.Confidence); err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the account relation for %s: %s\", o.Name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t}\n\n\treturn accountent\n}\n\nfunc (cr *companyRounds) createSeedAccount(e *et.Event, round *companyFundingRound) *dbt.Entity {\n\tname := fmt.Sprintf(\"%s:%s\", round.Name, round.Stage)\n\taccountent, err := e.Session.Cache().CreateAsset(&account.Account{\n\t\tID: name,\n\t\tType: account.Checking,\n\t\tNumber: \"default\",\n\t\tBalance: float64(round.MoneyRaised),\n\t\tActive: false,\n\t})\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the Account asset for %s: %s\", name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\treturn nil\n\t}\n\n\t_, err = e.Session.Cache().CreateEntityProperty(accountent, &general.SourceProperty{\n\t\tSource: cr.plugin.source.Name,\n\t\tConfidence: cr.plugin.source.Confidence,\n\t})\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the Account asset source property for %s: %s\", name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\treturn nil\n\t}\n\n\tinvestors := cr.createOrgInvestors(e, round)\n\tif ents := cr.createPersonInvestors(e, round); len(ents) > 0 {\n\t\tinvestors = append(investors, ents...)\n\t}\n\n\tfor _, investor := range investors {\n\t\tif err := cr.plugin.createRelation(e.Session, investor,\n\t\t\tgeneral.SimpleRelation{Name: \"account\"}, accountent, cr.plugin.source.Confidence); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the account relation for %s: %s\", investor.ID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t}\n\t}\n\n\treturn accountent\n}\n\nfunc (cr *companyRounds) createOrgInvestors(e *et.Event, round *companyFundingRound) []*dbt.Entity {\n\tvar investors []*dbt.Entity\n\n\tif len(round.CompanyInvestors) == 0 {\n\t\treturn investors\n\t}\n\n\tfor _, investor := range round.CompanyInvestors {\n\t\toamid := &general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", AviatoCompanyID, investor.CompanyID),\n\t\t\tID: investor.CompanyID,\n\t\t\tType: AviatoCompanyID,\n\t\t}\n\n\t\tident, err := e.Session.Cache().CreateAsset(oamid)\n\t\tif err != nil || ident == nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the identifier asset for %s: %s\", oamid.UniqueID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar orgent *dbt.Entity\n\t\t// check if the Person asset already exists\n\t\tif edges, err := e.Session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, time.Time{}, cr.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\t\torgent = a\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif orgent != nil {\n\t\t\tinvestors = append(investors, orgent)\n\t\t\tcontinue\n\t\t}\n\n\t\t// create the Organization asset\n\t\to := &oamorg.Organization{Name: investor.Name}\n\t\torgent, err = org.CreateOrgAsset(e.Session, nil, nil, o, cr.plugin.source)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Organization asset for %s: %s\", o.Name, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = e.Session.Cache().CreateEntityProperty(orgent, &general.SourceProperty{\n\t\t\tSource: cr.plugin.source.Name,\n\t\t\tConfidence: cr.plugin.source.Confidence,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Organization asset source property for %s: %s\", o.Name, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := cr.plugin.createRelation(e.Session, orgent,\n\t\t\tgeneral.SimpleRelation{Name: \"id\"}, ident, cr.plugin.source.Confidence); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the id relation for %s: %s\", oamid.UniqueID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: oamid.UniqueID,\n\t\t\tEntity: ident,\n\t\t\tSession: e.Session,\n\t\t})\n\t\tinvestors = append(investors, orgent)\n\t}\n\n\treturn investors\n}\n\nfunc (cr *companyRounds) createPersonInvestors(e *et.Event, round *companyFundingRound) []*dbt.Entity {\n\tvar investors []*dbt.Entity\n\n\tif len(round.PersonInvestors) == 0 {\n\t\treturn investors\n\t}\n\n\tfor _, investor := range round.PersonInvestors {\n\t\toamid := &general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", AviatoPersonID, investor.PersonID),\n\t\t\tID: investor.PersonID,\n\t\t\tType: AviatoPersonID,\n\t\t}\n\n\t\tident, err := e.Session.Cache().CreateAsset(oamid)\n\t\tif err != nil || ident == nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the identifier asset for %s: %s\", oamid.UniqueID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar personent *dbt.Entity\n\t\t// check if the Person asset already exists\n\t\tif edges, err := e.Session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, time.Time{}, cr.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*people.Person); ok {\n\t\t\t\t\t\tpersonent = a\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif personent != nil {\n\t\t\tinvestors = append(investors, personent)\n\t\t\tcontinue\n\t\t}\n\n\t\t// create the Person asset\n\t\tp := support.FullNameToPerson(investor.FullName)\n\t\tif p == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpersonent, err = e.Session.Cache().CreateAsset(p)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Person asset for %s: %s\", p.FullName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = e.Session.Cache().CreateEntityProperty(personent, &general.SourceProperty{\n\t\t\tSource: cr.plugin.source.Name,\n\t\t\tConfidence: cr.plugin.source.Confidence,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Person asset source property for %s: %s\", p.FullName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := cr.plugin.createRelation(e.Session, personent,\n\t\t\tgeneral.SimpleRelation{Name: \"id\"}, ident, cr.plugin.source.Confidence); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the id relation for %s: %s\", oamid.UniqueID, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cr.plugin.name, \"handler\", cr.name))\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: oamid.UniqueID,\n\t\t\tEntity: ident,\n\t\t\tSession: e.Session,\n\t\t})\n\t\tinvestors = append(investors, personent)\n\t}\n\n\treturn investors\n}\n\nfunc (cr *companyRounds) process(e *et.Event, fundents []*dbt.Entity) {\n\tfor _, fund := range fundents {\n\t\tf := fund.Asset.(*financial.FundsTransfer)\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fmt.Sprintf(\"%f:%s\", f.Amount, f.ID),\n\t\t\tEntity: fund,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/company_search.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (cs *companySearch) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamorg.Organization)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Organization asset\")\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(cs.plugin.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Organization), string(oam.Identifier), cs.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar id *dbt.Entity\n\tsrc := &et.Source{\n\t\tName: cs.name,\n\t\tConfidence: cs.plugin.source.Confidence,\n\t}\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tid = cs.lookup(e, e.Entity, since)\n\t} else {\n\t\tid = cs.query(e, e.Entity, keys)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif id != nil {\n\t\tcs.process(e, e.Entity, id)\n\t}\n\treturn nil\n}\n\nfunc (cs *companySearch) lookup(e *et.Event, orgent *dbt.Entity, since time.Time) *dbt.Entity {\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge,\n\t\t\t\tsince, cs.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif id, ok := a.Asset.(*general.Identifier); ok && id != nil && id.Type == AviatoCompanyID {\n\t\t\t\t\treturn a\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (cs *companySearch) query(e *et.Event, orgent *dbt.Entity, apikey []string) *dbt.Entity {\n\to := orgent.Asset.(*oamorg.Organization)\n\tbrand := org.ExtractBrandName(o.Name)\n\n\tvar body string\n\tsuccess := false\n\tfor _, key := range apikey {\n\t\theaders := http.Header{\"Content-Type\": []string{\"application/json\"}}\n\t\theaders[\"Authorization\"] = []string{\"Bearer \" + key}\n\n\t\t_ = cs.plugin.rlimit.Wait(context.TODO())\n\t\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\t\tdefer cancel()\n\n\t\tfilters := []map[string]*dslEvalObj{\n\t\t\t{\n\t\t\t\t\"name\": &dslEvalObj{\n\t\t\t\t\tOperation: \"eq\",\n\t\t\t\t\tValue: brand,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\treqDSL := &dsl{\n\t\t\tOffset: 0,\n\t\t\tLimit: 10,\n\t\t\tFilters: filters,\n\t\t}\n\n\t\tdslJSON, err := json.Marshal(reqDSL)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif resp, err := http.RequestWebPage(ctx, &http.Request{\n\t\t\tURL: \"https://data.api.aviato.co/company/search\",\n\t\t\tMethod: \"POST\",\n\t\t\tHeader: headers,\n\t\t\tBody: `{\"dsl\": ` + string(dslJSON) + `}`,\n\t\t}); err == nil {\n\t\t\tif resp.StatusCode == 200 {\n\t\t\t\tsuccess = true\n\t\t\t\tbody = resp.Body\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company search result for %s: %s\", o.Name, resp.Status)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\t\t}\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"failed to obtain the company search result for %s: %s\", o.Name, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\t}\n\t}\n\n\tif !success {\n\t\treturn nil\n\t}\n\n\tvar result companySearchResult\n\tif err := json.Unmarshal([]byte(body), &result); err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to unmarshal the company search result for %s: %s\", o.Name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\treturn nil\n\t} else if len(result.Items) == 0 {\n\t\treturn nil\n\t}\n\n\treturn cs.store(e, orgent, result.Items[0].ID)\n}\n\nfunc (cs *companySearch) store(e *et.Event, orgent *dbt.Entity, companyID string) *dbt.Entity {\n\toamid := &general.Identifier{\n\t\tUniqueID: fmt.Sprintf(\"%s:%s\", AviatoCompanyID, companyID),\n\t\tID: companyID,\n\t\tType: AviatoCompanyID,\n\t}\n\n\tident, err := e.Session.Cache().CreateAsset(oamid)\n\tif err != nil || ident == nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the identifier asset for %s: %s\", companyID, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\treturn nil\n\t}\n\n\t_, err = e.Session.Cache().CreateEntityProperty(ident, &general.SourceProperty{\n\t\tSource: cs.name,\n\t\tConfidence: cs.plugin.source.Confidence,\n\t})\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the identifier source property for %s: %s\", companyID, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\treturn nil\n\t}\n\n\tif err := cs.plugin.createRelation(e.Session, orgent,\n\t\tgeneral.SimpleRelation{Name: \"id\"}, ident, cs.plugin.source.Confidence); err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the identifier relation for %s: %s\", companyID, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n\t\t_ = e.Session.Cache().DeleteEntity(ident.ID)\n\t\treturn nil\n\t}\n\treturn ident\n}\n\nfunc (cs *companySearch) process(e *et.Event, orgent, ident *dbt.Entity) {\n\tid := ident.Asset.(*general.Identifier)\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: id.UniqueID,\n\t\tEntity: ident,\n\t\tSession: e.Session,\n\t})\n\n\to := orgent.Asset.(*oamorg.Organization)\n\te.Session.Log().Info(\"relationship discovered\", \"from\", o.Name, \"relation\", \"id\",\n\t\t\"to\", id.UniqueID, slog.Group(\"plugin\", \"name\", cs.plugin.name, \"handler\", cs.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/employees.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n\t\"github.com/owasp-amass/open-asset-model/people\"\n)\n\nfunc (ae *employees) check(e *et.Event) error {\n\toamid, ok := e.Entity.Asset.(*general.Identifier)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Identifier asset\")\n\t} else if oamid.Type != AviatoCompanyID {\n\t\treturn nil\n\t}\n\n\tds := e.Session.Config().GetDataSourceConfig(ae.plugin.name)\n\tif ds == nil || len(ds.Creds) == 0 {\n\t\treturn nil\n\t}\n\n\tvar keys []string\n\tfor _, cr := range ds.Creds {\n\t\tif cr != nil && cr.Apikey != \"\" {\n\t\t\tkeys = append(keys, cr.Apikey)\n\t\t}\n\t}\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Identifier), string(oam.Person), ae.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar orgent *dbt.Entity\n\tvar employents []*dbt.Entity\n\tsrc := &et.Source{\n\t\tName: ae.name,\n\t\tConfidence: ae.plugin.source.Confidence,\n\t}\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\torgent, employents = ae.lookup(e, e.Entity, since)\n\t} else {\n\t\torgent, employents = ae.query(e, e.Entity, keys)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif orgent != nil && len(employents) > 0 {\n\t\tae.process(e, orgent, employents)\n\t}\n\treturn nil\n}\n\nfunc (ae *employees) lookup(e *et.Event, ident *dbt.Entity, since time.Time) (*dbt.Entity, []*dbt.Entity) {\n\tvar orgent *dbt.Entity\n\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ae.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*org.Organization); ok {\n\t\t\t\t\torgent = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar employents []*dbt.Entity\n\tif orgent == nil {\n\t\treturn nil, employents\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, since, \"member\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ae.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*people.Person); ok {\n\t\t\t\t\temployents = append(employents, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn orgent, employents\n}\n\nfunc (ae *employees) query(e *et.Event, ident *dbt.Entity, apikey []string) (*dbt.Entity, []*dbt.Entity) {\n\toamid := e.Entity.Asset.(*general.Identifier)\n\n\torgent := ae.getAssociatedOrg(e, ident)\n\tif orgent == nil {\n\t\tmsg := fmt.Sprintf(\"failed to find the Organization asset for %s\", oamid.UniqueID)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\treturn nil, []*dbt.Entity{}\n\t}\n\n\tpage := 0\n\ttotal := 1\n\tperPage := 1000\n\tvar employents []*dbt.Entity\nloop:\n\tfor _, key := range apikey {\n\t\tfor ; page < total; page++ {\n\t\t\theaders := http.Header{\"Content-Type\": []string{\"application/json\"}}\n\t\t\theaders[\"Authorization\"] = []string{\"Bearer \" + key}\n\n\t\t\t_ = ae.plugin.rlimit.Wait(context.TODO())\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tu := fmt.Sprintf(\"https://data.api.aviato.co/company/%s/employees?perPage=%d&page=%d\", url.QueryEscape(oamid.ID), perPage, page)\n\t\t\tresp, err := http.RequestWebPage(ctx, &http.Request{URL: u, Header: headers})\n\t\t\tif err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the employees for %s: %s\", oamid.ID, err)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\t\tcontinue\n\t\t\t} else if resp.StatusCode != 200 {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the employees for %s: %s\", oamid.ID, resp.Status)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\t\tcontinue\n\t\t\t} else if resp.Body == \"\" {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the employees for %s: empty body\", oamid.ID)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\t\tcontinue\n\t\t\t} else if strings.Contains(resp.Body, \"error\") {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to obtain the employees for %s: %s\", oamid.ID, resp.Body)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar result employeesResult\n\t\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"failed to unmarshal the employees for %s: %s\", oamid.ID, err)\n\t\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\t\tbreak loop\n\t\t\t} else if len(result.Employees) == 0 {\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t\tif len(result.Employees) > 0 {\n\t\t\t\tif ents := ae.store(e, ident, orgent, result.Employees); len(ents) > 0 {\n\t\t\t\t\temployents = append(employents, ents...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttotal = result.Pages\n\t\t}\n\n\t\tif page >= total {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(employents) == 0 {\n\t\treturn nil, []*dbt.Entity{}\n\t}\n\treturn orgent, employents\n}\n\nfunc (ae *employees) getAssociatedOrg(e *et.Event, ident *dbt.Entity) *dbt.Entity {\n\tvar orgent *dbt.Entity\n\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*org.Organization); ok {\n\t\t\t\t\torgent = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn orgent\n}\n\nfunc (ae *employees) store(e *et.Event, ident, orgent *dbt.Entity, employlist []employeeResult) []*dbt.Entity {\n\tvar employents []*dbt.Entity\n\n\tfor _, emp := range employlist {\n\t\tp := support.FullNameToPerson(emp.Person.FullName)\n\t\tif p == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpersonent, err := e.Session.Cache().CreateAsset(p)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Person asset for %s: %s\", p.FullName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = e.Session.Cache().CreateEntityProperty(personent, &general.SourceProperty{\n\t\t\tSource: ae.name,\n\t\t\tConfidence: ae.plugin.source.Confidence,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the Person asset source property for %s: %s\", p.FullName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := ae.plugin.createRelation(e.Session, orgent,\n\t\t\tgeneral.SimpleRelation{Name: \"member\"}, personent, ae.plugin.source.Confidence); err == nil {\n\t\t\temployents = append(employents, personent)\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"failed to create the member relation for %s: %s\", p.FullName, err)\n\t\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t\t}\n\t}\n\n\treturn employents\n}\n\nfunc (ae *employees) process(e *et.Event, orgent *dbt.Entity, employents []*dbt.Entity) {\n\tfor _, employee := range employents {\n\t\tp := employee.Asset.(*people.Person)\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fmt.Sprintf(\"%s:%s\", p.FullName, p.ID),\n\t\t\tEntity: employee,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\to := orgent.Asset.(*org.Organization)\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", o.Name, \"relation\", \"member\",\n\t\t\t\"to\", p.FullName, slog.Group(\"plugin\", \"name\", ae.plugin.name, \"handler\", ae.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"golang.org/x/time/rate\"\n)\n\nfunc NewAviato() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &aviato{\n\t\tname: \"Aviato\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Aviato\",\n\t\t\tConfidence: 90,\n\t\t},\n\t}\n}\n\nfunc (a *aviato) Name() string {\n\treturn a.name\n}\n\nfunc (a *aviato) Start(r et.Registry) error {\n\ta.log = r.Log().WithGroup(\"plugin\").With(\"name\", a.name)\n\n\ta.companyEnrich = &companyEnrich{\n\t\tname: a.name + \"-Company-Enrich-Handler\",\n\t\tplugin: a,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: a,\n\t\tName: a.companyEnrich.name,\n\t\tPriority: 7,\n\t\tTransforms: []string{string(oam.Organization)},\n\t\tEventType: oam.Identifier,\n\t\tCallback: a.companyEnrich.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\ta.companyRounds = &companyRounds{\n\t\tname: a.name + \"-Company-Rounds-Handler\",\n\t\tplugin: a,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: a,\n\t\tName: a.companyRounds.name,\n\t\tPriority: 7,\n\t\tTransforms: []string{\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Account),\n\t\t\tstring(oam.FundsTransfer),\n\t\t},\n\t\tEventType: oam.Identifier,\n\t\tCallback: a.companyRounds.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\ta.employees = &employees{\n\t\tname: a.name + \"-Employees-Handler\",\n\t\tplugin: a,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: a,\n\t\tName: a.employees.name,\n\t\tPriority: 6,\n\t\tTransforms: []string{string(oam.Person)},\n\t\tEventType: oam.Identifier,\n\t\tCallback: a.employees.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\ta.companySearch = &companySearch{\n\t\tname: a.name + \"-Company-Search-Handler\",\n\t\tplugin: a,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: a,\n\t\tName: a.companySearch.name,\n\t\tPriority: 6,\n\t\tTransforms: []string{string(oam.Identifier)},\n\t\tEventType: oam.Organization,\n\t\tCallback: a.companySearch.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\ta.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (a *aviato) Stop() {\n\ta.log.Info(\"Plugin stopped\")\n}\n\nfunc (a *aviato) createRelation(session et.Session, obj *dbt.Entity, rel oam.Relation, subject *dbt.Entity, conf int) error {\n\tedge, err := session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: obj,\n\t\tToEntity: subject,\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if edge == nil {\n\t\treturn errors.New(\"failed to create the edge\")\n\t}\n\n\t_, err = session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: a.source.Name,\n\t\tConfidence: conf,\n\t})\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/aviato/types.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage aviato\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"golang.org/x/time/rate\"\n)\n\nconst (\n\tAviatoPersonID = \"aviato_person_id\"\n\tAviatoCompanyID = \"aviato_company_id\"\n)\n\ntype aviato struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tcompanyEnrich *companyEnrich\n\tcompanyRounds *companyRounds\n\temployees *employees\n\tcompanySearch *companySearch\n\tsource *et.Source\n}\n\ntype dsl struct {\n\tOffset int `json:\"offset\"`\n\tLimit int `json:\"limit\"`\n\tFilters []map[string]*dslEvalObj `json:\"filters\"`\n}\n\ntype dslEvalObj struct {\n\tOperation string `json:\"operation\"`\n\tValue string `json:\"value\"`\n}\n\ntype companySearchResult struct {\n\tCount struct {\n\t\tValue string `json:\"value\"`\n\t\tIsEstimate bool `json:\"isEstimate\"`\n\t} `json:\"count\"`\n\tItems []struct {\n\t\tID string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t\tCountry string `json:\"country\"`\n\t\tRegion string `json:\"region\"`\n\t\tLocality string `json:\"locality\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t\tIndustryList []string `json:\"industryList\"`\n\t} `json:\"items\"`\n}\n\ntype companyEnrich struct {\n\tname string\n\tplugin *aviato\n}\n\ntype companyRounds struct {\n\tname string\n\tplugin *aviato\n}\n\ntype companyRoundsResult struct {\n\tFundingRounds []companyFundingRound `json:\"fundingRounds\"`\n\tPages int `json:\"pages\"`\n\tTotalResults int `json:\"totalResults\"`\n}\n\ntype companyFundingRound struct {\n\tID int `json:\"id\"`\n\tAnnouncedOn string `json:\"announcedOn\"`\n\tMoneyRaised int `json:\"moneyRaised\"`\n\tName string `json:\"name\"`\n\tStage string `json:\"stage\"`\n\tLeadPersonInvestors []struct {\n\t\tPersonID string `json:\"id\"`\n\t\tFullName string `json:\"fullName\"`\n\t\tEntityType string `json:\"entityType\"`\n\t\tLocation string `json:\"location\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t} `json:\"leadPersonInvestorList\"`\n\tPersonInvestors []struct {\n\t\tPersonID string `json:\"id\"`\n\t\tFullName string `json:\"fullName\"`\n\t\tEntityType string `json:\"entityType\"`\n\t\tLocation string `json:\"location\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t} `json:\"personInvestorList\"`\n\tLeadCompanyInvestors []struct {\n\t\tCompanyID string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t\tCountry string `json:\"country\"`\n\t\tRegion string `json:\"region\"`\n\t\tLocality string `json:\"locality\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t\tIndustryList []string `json:\"industryList\"`\n\t} `json:\"leadCompanyInvestorList\"`\n\tCompanyInvestors []struct {\n\t\tCompanyID string `json:\"id\"`\n\t\tName string `json:\"name\"`\n\t\tCountry string `json:\"country\"`\n\t\tRegion string `json:\"region\"`\n\t\tLocality string `json:\"locality\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t\tIndustryList []string `json:\"industryList\"`\n\t} `json:\"companyInvestorList\"`\n\tCompanyID string `json:\"companyID\"`\n}\n\ntype companySearch struct {\n\tname string\n\tplugin *aviato\n}\n\ntype employees struct {\n\tname string\n\tplugin *aviato\n}\n\ntype employeesResult struct {\n\tEmployees []employeeResult `json:\"employees\"`\n\tPages int `json:\"pages\"`\n\tTotalResults int `json:\"totalResults\"`\n}\n\ntype employeeResult struct {\n\tStartDate string `json:\"startDate\"`\n\tEndDate string `json:\"endDate\"`\n\tEntityType string `json:\"entityType\"`\n\tPositionList []struct {\n\t\tStartDate string `json:\"startDate\"`\n\t\tEndDate string `json:\"endDate\"`\n\t\tTitle string `json:\"title\"`\n\t\tDescription string `json:\"description\"`\n\t} `json:\"positionList\"`\n\tPersonID string `json:\"personID\"`\n\tCompanyID string `json:\"companyID\"`\n\tCompanyName string `json:\"companyName\"`\n\tPerson struct {\n\t\tID string `json:\"id\"`\n\t\tFullName string `json:\"fullName\"`\n\t\tEntityType string `json:\"entityType\"`\n\t\tLocation string `json:\"location\"`\n\t\tURLs URLResult `json:\"URLs\"`\n\t} `json:\"person\"`\n}\n\ntype companyEnrichResult struct {\n\tID string `json:\"id\"`\n\tName string `json:\"name\"`\n\tLegalName string `json:\"legalName\"`\n\tAlternateNames []string `json:\"alternateNames\"`\n\tCageCode string `json:\"cageCode\"`\n\tCIKNumber string `json:\"CIKNumber\"`\n\tDunsNumber string `json:\"dunsNumber\"`\n\tLinkedinID string `json:\"linkedinID\"`\n\tNAICSCode string `json:\"NAICSCode\"`\n\tStockSymbol string `json:\"stockSymbol\"`\n\tStatus string `json:\"status\"`\n\tTagline string `json:\"tagline\"`\n\tFounded string `json:\"founded\"`\n\tOwnershipStatus string `json:\"ownershipStatus\"`\n\tHeadcount int `json:\"headcount\"`\n\tDescription string `json:\"description\"`\n\tIsAcquired bool `json:\"isAcquired\"`\n\tIsExited bool `json:\"isExited\"`\n\tIsGovernment bool `json:\"isGovernment\"`\n\tIsNonProfit bool `json:\"isNonProfit\"`\n\tIsShutDown bool `json:\"isShutDown\"`\n\tLocality string `json:\"locality\"`\n\tRegion string `json:\"region\"`\n\tCountry string `json:\"country\"`\n\tLocationDetails struct {\n\t\tContinent LocationDetails `json:\"continent\"`\n\t\tCountry LocationDetails `json:\"country\"`\n\t\tCounty LocationDetails `json:\"county\"`\n\t\tLocalAdmin LocationDetails `json:\"localadmin\"`\n\t\tLocality LocationDetails `json:\"locality\"`\n\t\tBorough LocationDetails `json:\"borough\"`\n\t\tMacroregion LocationDetails `json:\"macroregion\"`\n\t\tRegion LocationDetails `json:\"region\"`\n\t\tMacrohood LocationDetails `json:\"macrohood\"`\n\t\tNeighbourhood LocationDetails `json:\"neighbourhood\"`\n\t} `json:\"locationDetails\"`\n\tLocationIDList []int `json:\"locationIDList\"`\n\tIndustryList []string `json:\"industryList\"`\n\tBusinessModelList []string `json:\"businessModelList\"`\n\tProductList []struct {\n\t\tProductName string `json:\"productName\"`\n\t\tTagline string `json:\"tagline\"`\n\t\t//CreatedAt string `json:\"createdAt\"` documentation is not clear\n\t\tImageID string `json:\"imageID\"`\n\t\tProductURL string `json:\"productURL\"`\n\t\tProductHuntURL string `json:\"producthuntURL\"`\n\t} `json:\"productList\"`\n\tCustomerTypes []string `json:\"customerTypes\"`\n\tJobFamilyList []string `json:\"jobFamilyList\"`\n\tJobListingList []struct {\n\t\tCategory string `json:\"category\"`\n\t\tSubCategory string `json:\"subCategory\"`\n\t\tTitle string `json:\"title\"`\n\t\tIsFullTime bool `json:\"isFullTime\"`\n\t\tIsRemote bool `json:\"isRemote\"`\n\t\t//Locations []string `json:\"locations\"` documentation is not clear\n\t\tDescription string `json:\"mdDescription\"`\n\t\tSlug string `json:\"slug\"`\n\t\tURL string `json:\"url\"`\n\t} `json:\"jobListingList\"`\n\tScreenshotList []string `json:\"screenshotList\"`\n\tTargetMarketList []string `json:\"targetMarketList\"`\n\tTechStackList []struct {\n\t\tProductName string `json:\"productName\"`\n\t\tProductCategories []string `json:\"productCategories\"`\n\t} `json:\"techStackList\"`\n\tURLs URLResult `json:\"URLs\"`\n\tLinkedinFollowers int `json:\"linkedinFollowers\"`\n\tWebTrafficSources struct {\n\t\tMail float64 `json:\"mail\"`\n\t\tDirect float64 `json:\"direct\"`\n\t\tSearch float64 `json:\"search\"`\n\t\tSocial float64 `json:\"social\"`\n\t\tReferrals float64 `json:\"referrals\"`\n\t\tPaidReferrals float64 `json:\"paidReferrals\"`\n\t} `json:\"webTrafficSources\"`\n\tAcquiredBy struct {\n\t\tID int `json:\"id\"`\n\t\tAnnouncedOn string `json:\"announcedOn\"`\n\t\tAcquirerName string `json:\"acquirerName\"`\n\t\tAcquireeName string `json:\"acquireeName\"`\n\t\tPrice float64 `json:\"price\"`\n\t} `json:\"acquiredBy\"`\n\tEmbeddedNews []struct {\n\t\t//Date string `json:\"date\"` documentation is not clear\n\t\tTitle string `json:\"title\"`\n\t\tAuthor string `json:\"author\"`\n\t\tSource string `json:\"source\"`\n\t\tURL string `json:\"linkUrl\"`\n\t\tImageURL string `json:\"imageUrl\"`\n\t} `json:\"embeddedNews\"`\n\tPatentCount int `json:\"patentCount\"`\n\tOwnedPatents []struct {\n\t\tInventionTitle string `json:\"inventionTitle\"`\n\t\tDatePublished string `json:\"datePublished\"`\n\t\tDocumentID string `json:\"documentId\"`\n\t\tDocumentURL string `json:\"documentUrl\"`\n\t\tLatestFilingDate string `json:\"latestFilingDate\"`\n\t} `json:\"ownedPatents\"`\n\tGovernmentAwards []struct {\n\t\tAwardID string `json:\"awardId\"`\n\t\tAwardType string `json:\"awardType\"`\n\t\tAwardAmount float64 `json:\"awardAmount\"`\n\t\tStartDate string `json:\"startDate\"`\n\t\tEndDate string `json:\"endDate\"`\n\t\tActionDate string `json:\"actionDate\"`\n\t\tDateSigned string `json:\"dateSigned\"`\n\t\tTopTierAgency string `json:\"awardingTopTierAgency\"`\n\t\tSubTierAgency string `json:\"awardingSubTierAgency\"`\n\t\tDescription string `json:\"productOrServiceDescription\"`\n\t\tCFDAProgram string `json:\"cfdaProgram\"`\n\t} `json:\"governmentAwards\"`\n\tFinancingStatus string `json:\"financingStatus\"`\n\tTotalFunding float64 `json:\"totalFunding\"`\n\tInvestorCount int `json:\"investorCount\"`\n\tFundingRoundCount int `json:\"fundingRoundCount\"`\n\tLastRoundValuation float64 `json:\"lastRoundValuation\"`\n\tLatestDealDate string `json:\"latestDealDate\"`\n\tLatestDealType string `json:\"latestDealType\"`\n\tLatestDealAmount int `json:\"latestDealAmount\"`\n\tStockExchange string `json:\"stockExchange\"`\n\tIPODate string `json:\"ipoDate\"`\n\tSharePrice float64 `json:\"sharePrice\"`\n\tOutstandingShares float64 `json:\"outstandingShares\"`\n\tMarketCap float64 `json:\"marketCap\"`\n}\n\ntype URLResult struct {\n\tGolden string `json:\"golden\"`\n\tContact string `json:\"contact\"`\n\tTwitter string `json:\"twitter\"`\n\tWebsite string `json:\"website\"`\n\tFacebook string `json:\"facebook\"`\n\tLinkedin string `json:\"linkedin\"`\n\tPitchbook string `json:\"pitchbook\"`\n\tAngelList string `json:\"angelList\"`\n\tSignalNFX string `json:\"signalNFX\"`\n\tCrunchbase string `json:\"crunchbase\"`\n}\n\ntype LocationDetails struct {\n\tID int `json:\"id\"`\n\tName string `json:\"name\"`\n\tPlaceType string `json:\"placeType\"`\n\tGeometry struct {\n\t\tAreaSquareDegrees float64 `json:\"area_square_degrees\"`\n\t\tBoundingBox string `json:\"bbox\"`\n\t\tLatitude float64 `json:\"lat\"`\n\t\tLongitude float64 `json:\"lon\"`\n\t} `json:\"geometry\"`\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/fuzzy.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"math\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (fc *fuzzyCompletions) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamorg.Organization)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Organization asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Organization), string(oam.Identifier), fc.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar id *dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, fc.plugin.source, since) {\n\t\tid = fc.lookup(e, e.Entity, since)\n\t} else {\n\t\tid = fc.query(e, e.Entity)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, fc.plugin.source)\n\t}\n\n\tif id != nil {\n\t\tfc.process(e, e.Entity, id)\n\t}\n\treturn nil\n}\n\nfunc (fc *fuzzyCompletions) lookup(e *et.Event, orgent *dbt.Entity, since time.Time) *dbt.Entity {\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge,\n\t\t\t\tsince, fc.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif id, ok := a.Asset.(*general.Identifier); ok && id != nil && id.Type == general.LEICode {\n\t\t\t\t\treturn a\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fc *fuzzyCompletions) query(e *et.Event, orgent *dbt.Entity) *dbt.Entity {\n\tvar conf int\n\tvar rec *org.LEIRecord\n\n\tif leient := fc.plugin.orgEntityToLEI(e, orgent); leient != nil {\n\t\tlei := leient.Asset.(*general.Identifier)\n\n\t\tif r, err := org.GLEIFGetLEIRecord(lei.ID); err == nil {\n\t\t\trec = r\n\t\t\tconf = 100\n\t\t}\n\t}\n\n\tif rec == nil {\n\t\to := orgent.Asset.(*oamorg.Organization)\n\t\tbrand := org.ExtractBrandName(o.Name)\n\n\t\tresult, err := org.GLEIFSearchFuzzyCompletions(brand)\n\t\tif err != nil {\n\t\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", fc.plugin.name, \"handler\", fc.name))\n\t\t\treturn nil\n\t\t}\n\n\t\tm := make(map[string]string)\n\t\tfor _, d := range result.Data {\n\t\t\tif d.Type == \"fuzzycompletions\" && d.Relationships.LEIRecords.Data.Type == \"lei-records\" {\n\t\t\t\tm[d.Attributes.Value] = d.Relationships.LEIRecords.Data.ID\n\t\t\t}\n\t\t}\n\t\trec = filterFuzzyCompletions(e, orgent, brand, m)\n\t}\n\n\tif rec == nil {\n\t\te.Session.Log().Info(\"no LEI record found for organization\",\n\t\t\t\"org\", orgent.ID, slog.Group(\"plugin\", \"name\", fc.plugin.name, \"handler\", fc.name))\n\t\treturn nil\n\t}\n\treturn fc.store(e, orgent, rec, conf)\n}\n\nfunc filterFuzzyCompletions(e *et.Event, orgent *dbt.Entity, brand string, m map[string]string) *org.LEIRecord {\n\tvar rec *org.LEIRecord\n\to := orgent.Asset.(*oamorg.Organization)\n\n\tvar names []string\n\tfor k := range m {\n\t\tnames = append(names, k)\n\t}\n\tif len(names) == 0 {\n\t\treturn nil\n\t}\n\n\tif exact, partial, found := org.NameMatch(e.Session, orgent, names); found {\n\t\tvar conf int\n\n\t\tfor _, match := range exact {\n\t\t\tscore := 30\n\n\t\t\tif len(exact) == 1 {\n\t\t\t\tscore += 30\n\t\t\t}\n\n\t\t\tlei := m[match]\n\t\t\tif r, err := org.GLEIFGetLEIRecord(lei); err == nil {\n\t\t\t\tif org.LocMatch(e, orgent, r) {\n\t\t\t\t\tscore += 40\n\t\t\t\t}\n\t\t\t\tif score > conf {\n\t\t\t\t\trec = r\n\t\t\t\t\tconf = score\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswg := metrics.NewSmithWatermanGotoh()\n\t\tswg.CaseSensitive = false\n\t\tswg.GapPenalty = -0.1\n\t\tswg.Substitution = metrics.MatchMismatch{\n\t\t\tMatch: 1,\n\t\t\tMismatch: -0.5,\n\t\t}\n\n\t\tfor _, match := range partial {\n\t\t\tif !strings.Contains(strings.ToLower(match), strings.ToLower(brand)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsim := strutil.Similarity(o.Name, match, swg)\n\t\t\tscore := int(math.Round(sim * 30))\n\n\t\t\tif len(partial) == 1 {\n\t\t\t\tscore += 30\n\t\t\t}\n\n\t\t\tlei := m[match]\n\t\t\tif r, err := org.GLEIFGetLEIRecord(lei); err == nil {\n\t\t\t\tif org.LocMatch(e, orgent, r) {\n\t\t\t\t\tscore += 40\n\t\t\t\t}\n\t\t\t\tif score > conf {\n\t\t\t\t\trec = r\n\t\t\t\t\tconf = score\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rec\n}\n\nfunc (fc *fuzzyCompletions) store(e *et.Event, orgent *dbt.Entity, rec *org.LEIRecord, conf int) *dbt.Entity {\n\tfc.plugin.updateOrgFromLEIRecord(e, orgent, rec, conf)\n\n\tident, err := fc.plugin.createLEIFromRecord(e, orgent, rec, conf)\n\tif err != nil {\n\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", fc.plugin.name, \"handler\", fc.name))\n\t\treturn nil\n\t}\n\n\treturn ident\n}\n\nfunc (fc *fuzzyCompletions) process(e *et.Event, orgent, ident *dbt.Entity) {\n\tid := ident.Asset.(*general.Identifier)\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: id.UniqueID,\n\t\tEntity: ident,\n\t\tSession: e.Session,\n\t})\n\n\to := orgent.Asset.(*oamorg.Organization)\n\te.Session.Log().Info(\"relationship discovered\", \"from\", o.Name, \"relation\", \"id\",\n\t\t\"to\", id.UniqueID, slog.Group(\"plugin\", \"name\", fc.plugin.name, \"handler\", fc.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/lei_record.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\nfunc (g *gleif) createLEIIdentifier(session et.Session, orgent *dbt.Entity, lei *general.Identifier, conf int) (*dbt.Entity, error) {\n\tid, err := session.Cache().CreateAsset(lei)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if id == nil {\n\t\treturn nil, errors.New(\"failed to create the Identifier asset\")\n\t}\n\n\t_, _ = session.Cache().CreateEntityProperty(id, &general.SourceProperty{\n\t\tSource: g.source.Name,\n\t\tConfidence: conf,\n\t})\n\n\tif orgent != nil {\n\t\tif err := g.createRelation(session, orgent, general.SimpleRelation{Name: \"id\"}, id, conf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn id, nil\n}\n\nfunc (g *gleif) createLEIFromRecord(e *et.Event, orgent *dbt.Entity, lei *org.LEIRecord, conf int) (*dbt.Entity, error) {\n\treturn g.createLEIIdentifier(e.Session, orgent, &general.Identifier{\n\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.LEICode, lei.ID),\n\t\tID: lei.ID,\n\t\tType: general.LEICode,\n\t\tStatus: lei.Attributes.Registration.Status,\n\t\tCreationDate: lei.Attributes.Registration.InitialRegistrationDate,\n\t\tUpdatedDate: lei.Attributes.Registration.LastUpdateDate,\n\t\tExpirationDate: lei.Attributes.Registration.NextRenewalDate,\n\t}, conf)\n}\n\nfunc (g *gleif) buildAddrFromLEIAddress(addr *org.LEIAddress) string {\n\tstreet := strings.Join(addr.AddressLines, \" \")\n\n\tprovince := addr.Region\n\tif parts := strings.Split(province, \"-\"); len(parts) > 1 {\n\t\tprovince = parts[1]\n\t}\n\n\treturn fmt.Sprintf(\"%s %s %s %s %s\", street, addr.City, province, addr.PostalCode, addr.Country)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/org_lei.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (g *gleif) orgEntityToLEI(e *et.Event, orgent *dbt.Entity) *dbt.Entity {\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent, time.Time{}, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif id, ok := a.Asset.(*general.Identifier); ok && id.Type == general.LEICode {\n\t\t\t\t\treturn a\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (g *gleif) leiToOrgEntity(e *et.Event, ident *dbt.Entity) *dbt.Entity {\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\treturn a\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (g *gleif) updateOrgFromLEIRecord(e *et.Event, orgent *dbt.Entity, lei *org.LEIRecord, conf int) {\n\to := orgent.Asset.(*oamorg.Organization)\n\n\t// check if the org entity already has a LEI identifier\n\tif leient := g.orgEntityToLEI(e, orgent); leient != nil {\n\t\t// check if the LEI identifier is the same as the one we are processing\n\t\tif id, ok := leient.Asset.(*general.Identifier); ok && id.ID != lei.ID {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif _, err := g.createLEIFromRecord(e, orgent, lei, conf); err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to create the LEI Identifier from the record: %s\", err.Error())\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", g.name, \"handler\", g.name))\n\t}\n\n\to.LegalName = strings.ToLower(lei.Attributes.Entity.LegalName.Name)\n\tif o.LegalName != \"\" {\n\t\t_ = g.addIdentifiersToOrg(e, orgent, general.LegalName, []string{o.LegalName}, conf)\n\t}\n\n\tvar otherNames []string\n\tfor _, other := range lei.Attributes.Entity.OtherNames {\n\t\totherNames = append(otherNames, strings.ToLower(other.Name))\n\t}\n\tfor _, other := range lei.Attributes.Entity.TransliteratedOtherNames {\n\t\totherNames = append(otherNames, strings.ToLower(other.Name))\n\t}\n\t_ = g.addIdentifiersToOrg(e, orgent, general.OrganizationName, otherNames, conf)\n\n\to.FoundingDate = lei.Attributes.Entity.CreationDate\n\to.Jurisdiction = lei.Attributes.Entity.Jurisdiction\n\to.RegistrationID = lei.Attributes.Entity.RegisteredAs\n\tif lei.Attributes.Entity.Status == \"ACTIVE\" {\n\t\to.Active = true\n\t} else {\n\t\to.Active = false\n\t}\n\n\taddr := g.buildAddrFromLEIAddress(&lei.Attributes.Entity.LegalAddress)\n\t_ = g.addAddress(e, orgent, general.SimpleRelation{Name: \"legal_address\"}, addr, conf)\n\n\taddr = g.buildAddrFromLEIAddress(&lei.Attributes.Entity.HeadquartersAddress)\n\t_ = g.addAddress(e, orgent, general.SimpleRelation{Name: \"hq_address\"}, addr, conf)\n\n\tfor _, a := range lei.Attributes.Entity.OtherAddresses {\n\t\taddr = g.buildAddrFromLEIAddress(&a)\n\t\t_ = g.addAddress(e, orgent, general.SimpleRelation{Name: \"location\"}, addr, conf)\n\t}\n\n\t_ = g.addIdentifiersToOrg(e, orgent, general.BankIDCode, lei.Attributes.BIC, conf)\n\t_ = g.addIdentifiersToOrg(e, orgent, general.MarketIDCode, lei.Attributes.MIC, conf)\n\t_ = g.addIdentifiersToOrg(e, orgent, general.OpenCorpID, []string{lei.Attributes.OCID}, conf)\n\t_ = g.addIdentifiersToOrg(e, orgent, general.SPGlobalCompanyID, lei.Attributes.SPGlobal, conf)\n\n\t// update the Organization\n\tif _, err := e.Session.Cache().CreateEntity(orgent); err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to update the Organization asset for %s: %s\", o.Name, err)\n\t\te.Session.Log().Error(msg, slog.Group(\"plugin\", \"name\", g.name, \"handler\", g.name))\n\t}\n}\n\nfunc (g *gleif) addAddress(e *et.Event, orgent *dbt.Entity, rel oam.Relation, addr string, conf int) error {\n\tloc := support.StreetAddressToLocation(addr)\n\tif loc == nil {\n\t\treturn errors.New(\"failed to create location\")\n\t}\n\n\ta, err := e.Session.Cache().CreateAsset(loc)\n\tif err != nil || a == nil {\n\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", g.name, \"handler\", g.name))\n\t\treturn err\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(a, &general.SourceProperty{\n\t\tSource: g.source.Name,\n\t\tConfidence: conf,\n\t})\n\n\tif err := g.createRelation(e.Session, orgent, rel, a, conf); err != nil {\n\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", g.name, \"handler\", g.name))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (g *gleif) addIdentifiersToOrg(e *et.Event, orgent *dbt.Entity, idtype string, ids []string, conf int) error {\n\tfor _, id := range ids {\n\t\tif id == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\toamid := &general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", idtype, id),\n\t\t\tID: id,\n\t\t\tType: idtype,\n\t\t}\n\n\t\tident, err := e.Session.Cache().CreateAsset(oamid)\n\t\tif err != nil || ident == nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(ident, &general.SourceProperty{\n\t\t\tSource: g.source.Name,\n\t\t\tConfidence: conf,\n\t\t})\n\n\t\tif err := g.createRelation(e.Session, orgent, general.SimpleRelation{Name: \"id\"}, ident, conf); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"errors\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\nfunc NewGLEIF() et.Plugin {\n\treturn &gleif{\n\t\tname: \"GLEIF\",\n\t\tsource: &et.Source{\n\t\t\tName: \"GLEIF\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (g *gleif) Name() string {\n\treturn g.name\n}\n\nfunc (g *gleif) Start(r et.Registry) error {\n\tg.log = r.Log().WithGroup(\"plugin\").With(\"name\", g.name)\n\n\tg.fuzzy = &fuzzyCompletions{\n\t\tname: g.name + \"-Fuzzy-Handler\",\n\t\tplugin: g,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: g,\n\t\tName: g.fuzzy.name,\n\t\tPriority: 6,\n\t\tTransforms: []string{string(oam.Identifier)},\n\t\tEventType: oam.Organization,\n\t\tCallback: g.fuzzy.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tg.related = &relatedOrgs{\n\t\tname: g.name + \"-LEI-Handler\",\n\t\tplugin: g,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: g,\n\t\tName: g.related.name,\n\t\tPriority: 5,\n\t\tTransforms: []string{string(oam.Organization)},\n\t\tEventType: oam.Identifier,\n\t\tCallback: g.related.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tg.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (g *gleif) Stop() {\n\tg.log.Info(\"Plugin stopped\")\n}\n\nfunc (g *gleif) createRelation(session et.Session, obj *dbt.Entity, rel oam.Relation, subject *dbt.Entity, conf int) error {\n\tedge, err := session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: obj,\n\t\tToEntity: subject,\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if edge == nil {\n\t\treturn errors.New(\"failed to create the edge\")\n\t}\n\n\t_, err = session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: g.source.Name,\n\t\tConfidence: conf,\n\t})\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/related.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (ro *relatedOrgs) check(e *et.Event) error {\n\tident, ok := e.Entity.Asset.(*general.Identifier)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Identifier asset\")\n\t} else if ident.Type != general.LEICode {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Identifier), string(oam.Identifier), ro.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar orgs []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, ro.plugin.source, since) {\n\t\torgs = append(orgs, ro.lookup(e, e.Entity, since)...)\n\t} else {\n\t\torgs = append(orgs, ro.query(e, e.Entity)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, ro.plugin.source)\n\t}\n\n\tif len(orgs) > 0 {\n\t\tro.process(e, orgs)\n\t}\n\treturn nil\n}\n\nfunc (ro *relatedOrgs) lookup(e *et.Event, ident *dbt.Entity, since time.Time) []*dbt.Entity {\n\tvar o *dbt.Entity\n\n\tif edges, err := e.Session.Cache().IncomingEdges(ident, since, \"id\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ro.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\to = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar p *dbt.Entity\n\tif edges, err := e.Session.Cache().IncomingEdges(o, since, \"subsidiary\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ro.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\tp = a\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar children []*dbt.Entity\n\tif edges, err := e.Session.Cache().OutgoingEdges(o, since, \"subsidiary\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, ro.plugin.source.Name); err != nil || len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\tchildren = append(children, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn append([]*dbt.Entity{o, p}, children...)\n}\n\nfunc (ro *relatedOrgs) query(e *et.Event, ident *dbt.Entity) []*dbt.Entity {\n\tid := ident.Asset.(*general.Identifier)\n\n\tparent, _ := org.GLEIFGetDirectParentRecord(id.ID)\n\tchildren, _ := org.GLEIFGetDirectChildrenRecords(id.ID)\n\treturn ro.store(e, ident, parent, children)\n}\n\nfunc (ro *relatedOrgs) store(e *et.Event, ident *dbt.Entity, parent *org.LEIRecord, children []*org.LEIRecord) []*dbt.Entity {\n\tvar orgs []*dbt.Entity\n\n\torgent := ro.plugin.leiToOrgEntity(e, ident)\n\tif orgent == nil {\n\t\treturn orgs\n\t}\n\n\tif parent != nil {\n\t\tparentorg := &oamorg.Organization{Name: parent.Attributes.Entity.LegalName.Name}\n\n\t\tparentent, err := org.CreateOrgAsset(e.Session, orgent, nil, parentorg, ro.plugin.source)\n\t\tif err == nil {\n\t\t\torgs = append(orgs, parentent)\n\t\t\tro.plugin.updateOrgFromLEIRecord(e, parentent, parent, ro.plugin.source.Confidence)\n\t\t\tsupport.MarkAssetMonitored(e.Session, parentent, ro.plugin.source)\n\t\t\t_ = ro.plugin.createRelation(e.Session, parentent,\n\t\t\t\t&general.SimpleRelation{Name: \"subsidiary\"}, orgent, ro.plugin.source.Confidence)\n\t\t}\n\t}\n\n\tfor _, child := range children {\n\t\tchildorg := &oamorg.Organization{Name: child.Attributes.Entity.LegalName.Name}\n\n\t\tchildent, err := org.CreateOrgAsset(e.Session, orgent,\n\t\t\t&general.SimpleRelation{Name: \"subsidiary\"}, childorg, ro.plugin.source)\n\t\tif err == nil {\n\t\t\torgs = append(orgs, childent)\n\t\t\tro.plugin.updateOrgFromLEIRecord(e, childent, child, ro.plugin.source.Confidence)\n\t\t\tsupport.MarkAssetMonitored(e.Session, childent, ro.plugin.source)\n\t\t}\n\t}\n\n\treturn orgs\n}\n\nfunc (ro *relatedOrgs) process(e *et.Event, assets []*dbt.Entity) {\n\tfor _, orgent := range assets {\n\t\to := orgent.Asset.(*oamorg.Organization)\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fmt.Sprintf(\"%s:%s\", o.Name, o.ID),\n\t\t\tEntity: orgent,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/gleif/types.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage gleif\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\ntype gleif struct {\n\tname string\n\tlog *slog.Logger\n\tfuzzy *fuzzyCompletions\n\trelated *relatedOrgs\n\tsource *et.Source\n}\n\ntype fuzzyCompletions struct {\n\tname string\n\tplugin *gleif\n}\n\ntype relatedOrgs struct {\n\tname string\n\tplugin *gleif\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/rdap/autnum.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage rdap\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/openrdap/rdap\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n)\n\ntype autnum struct {\n\tname string\n\tplugin *rdapPlugin\n\ttransforms []string\n}\n\nfunc (r *autnum) Name() string {\n\treturn r.name\n}\n\nfunc (r *autnum) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamreg.AutnumRecord)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the AutnumRecord asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.AutnumRecord), append(r.transforms, r.plugin.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tvar findings []*support.Finding\n\tif record, ok := e.Meta.(*rdap.Autnum); ok && record != nil {\n\t\tr.store(e, record, e.Entity, matches)\n\t} else {\n\t\tfindings = append(findings, r.lookup(e, e.Entity, matches)...)\n\t}\n\n\tif len(findings) > 0 {\n\t\tr.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (r *autnum) lookup(e *et.Event, asset *dbt.Entity, m *config.Matches) []*support.Finding {\n\tvar rtypes []string\n\tvar findings []*support.Finding\n\tsinces := make(map[string]time.Time)\n\n\tfor _, atype := range r.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.AutnumRecord), atype, r.plugin.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tswitch atype {\n\t\tcase string(oam.URL):\n\t\t\trtypes = append(rtypes, \"rdap_url\")\n\t\tcase string(oam.FQDN):\n\t\t\trtypes = append(rtypes, \"whois_server\")\n\t\tcase string(oam.ContactRecord):\n\t\t\trtypes = append(rtypes, \"registrant\", \"admin_contact\", \"abuse_contact\", \"technical_contact\")\n\t\t}\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(asset, time.Time{}, rtypes...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotype := string(a.Asset.AssetType())\n\n\t\t\tsince, ok := sinces[totype]\n\t\t\tif !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !r.oneOfSources(e, edge, r.plugin.source, since) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar name string\n\t\t\tswitch v := a.Asset.(type) {\n\t\t\tcase *oamdns.FQDN:\n\t\t\t\tname = v.Name\n\t\t\tcase *contact.ContactRecord:\n\t\t\t\tname = \"ContactRecord: \" + v.DiscoveredAt\n\t\t\tcase *url.URL:\n\t\t\t\tname = v.Raw\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tautrec := asset.Asset.(*oamreg.AutnumRecord)\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"AutnumRecord: \" + autrec.Handle,\n\t\t\t\tTo: a,\n\t\t\t\tToName: name,\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (r *autnum) oneOfSources(e *et.Event, edge *dbt.Edge, src *et.Source, since time.Time) bool {\n\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, src.Name); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (r *autnum) store(e *et.Event, resp *rdap.Autnum, entity *dbt.Entity, m *config.Matches) {\n\tvar findings []*support.Finding\n\tautrec := entity.Asset.(*oamreg.AutnumRecord)\n\n\tif u := r.plugin.getJSONLink(resp.Links); u != nil && m.IsMatch(string(oam.URL)) {\n\t\tif a, err := e.Session.Cache().CreateAsset(u); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: entity,\n\t\t\t\tFromName: \"AutnumRecord: \" + autrec.Handle,\n\t\t\t\tTo: a,\n\t\t\t\tToName: u.Raw,\n\t\t\t\tRel: &general.SimpleRelation{Name: \"rdap_url\"},\n\t\t\t})\n\t\t}\n\t}\n\tif name := autrec.WhoisServer; name != \"\" && m.IsMatch(string(oam.FQDN)) {\n\t\tfqdn := &oamdns.FQDN{Name: name}\n\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf > 0 {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(fqdn); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: entity,\n\t\t\t\t\tFromName: \"AutnumRecord: \" + autrec.Handle,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: name,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"whois_server\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// process the relations built above\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n\n\tif m.IsMatch(string(oam.ContactRecord)) {\n\t\tfor _, v := range resp.Entities {\n\t\t\tr.plugin.storeEntity(e, 1, &v, entity, r.plugin.source, m)\n\t\t}\n\t}\n}\n\nfunc (r *autnum) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/rdap/autsys.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage rdap\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/openrdap/rdap\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\ntype autsys struct {\n\tname string\n\tplugin *rdapPlugin\n}\n\nfunc (r *autsys) Name() string {\n\treturn r.name\n}\n\nfunc (r *autsys) check(e *et.Event) error {\n\tas, ok := e.Entity.Asset.(*network.AutonomousSystem)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the AutonomousSystem asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.AutonomousSystem), string(oam.AutnumRecord), r.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar asset *dbt.Entity\n\tvar record *rdap.Autnum\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, r.plugin.source, since) {\n\t\tasset = r.lookup(e, strconv.Itoa(as.Number), since)\n\t} else {\n\t\tasset, record = r.query(e, e.Entity)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, r.plugin.source)\n\t}\n\n\tif asset != nil {\n\t\tr.process(e, record, asset)\n\t}\n\treturn nil\n}\n\nfunc (r *autsys) lookup(e *et.Event, num string, since time.Time) *dbt.Entity {\n\tif assets := support.SourceToAssetsWithinTTL(e.Session, num, string(oam.AutnumRecord), r.plugin.source, since); len(assets) > 0 {\n\t\treturn assets[0]\n\t}\n\treturn nil\n}\n\nfunc (r *autsys) query(e *et.Event, asset *dbt.Entity) (*dbt.Entity, *rdap.Autnum) {\n\tas := asset.Asset.(*network.AutonomousSystem)\n\treq := rdap.NewAutnumRequest(uint32(as.Number))\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\treq = req.WithContext(ctx)\n\n\t_ = r.plugin.rlimit.Wait(context.TODO())\n\tresp, err := r.plugin.client.Do(req)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\trecord, ok := resp.Object.(*rdap.Autnum)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn r.store(e, record, asset), record\n}\n\nfunc (r *autsys) store(e *et.Event, resp *rdap.Autnum, asset *dbt.Entity) *dbt.Entity {\n\tas := asset.Asset.(*network.AutonomousSystem)\n\tautrec := &oamreg.AutnumRecord{\n\t\tNumber: as.Number,\n\t\tHandle: resp.Handle,\n\t\tName: resp.Name,\n\t\tWhoisServer: resp.Port43,\n\t\tStatus: resp.Status,\n\t}\n\n\tvar reg, last bool\n\tfor _, event := range resp.Events {\n\t\tswitch event.Action {\n\t\tcase \"registration\":\n\t\t\tif t, err := time.Parse(time.RFC3339, event.Date); err == nil {\n\t\t\t\tautrec.CreatedDate = support.TimeToJSONString(&t)\n\t\t\t\treg = true\n\t\t\t}\n\t\tcase \"last changed\":\n\t\t\tif t, err := time.Parse(time.RFC3339, event.Date); err == nil {\n\t\t\t\tautrec.UpdatedDate = support.TimeToJSONString(&t)\n\t\t\t\tlast = true\n\t\t\t}\n\t\t}\n\t}\n\tif !reg || !last {\n\t\treturn nil\n\t}\n\n\tautasset, err := e.Session.Cache().CreateAsset(autrec)\n\tif err == nil && autasset != nil {\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: &general.SimpleRelation{Name: \"registration\"},\n\t\t\tFromEntity: asset,\n\t\t\tToEntity: autasset,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: r.plugin.source.Name,\n\t\t\t\tConfidence: r.plugin.source.Confidence,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn autasset\n}\n\nfunc (r *autsys) process(e *et.Event, record *rdap.Autnum, asset *dbt.Entity) {\n\tautnum := asset.Asset.(*oamreg.AutnumRecord)\n\n\tname := \"AutnumRecord: \" + autnum.Name\n\t_ = e.Dispatcher.DispatchEvent((&et.Event{\n\t\tName: name,\n\t\tMeta: record,\n\t\tEntity: asset,\n\t\tSession: e.Session,\n\t}))\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", autnum.Handle, \"relation\",\n\t\t\"registration\", \"to\", name, slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/rdap/ipnet.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage rdap\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/openrdap/rdap\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n)\n\ntype ipnet struct {\n\tname string\n\tplugin *rdapPlugin\n\ttransforms []string\n}\n\nfunc (r *ipnet) Name() string {\n\treturn r.name\n}\n\nfunc (r *ipnet) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamreg.IPNetRecord)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the IPNetRecord asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.IPNetRecord), append(r.transforms, r.plugin.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tvar findings []*support.Finding\n\tif record, ok := e.Meta.(*rdap.IPNetwork); ok && record != nil {\n\t\tr.store(e, record, e.Entity, matches)\n\t} else {\n\t\tfindings = append(findings, r.lookup(e, e.Entity, matches)...)\n\t}\n\n\tif len(findings) > 0 {\n\t\tr.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (r *ipnet) lookup(e *et.Event, asset *dbt.Entity, m *config.Matches) []*support.Finding {\n\tvar rtypes []string\n\tvar findings []*support.Finding\n\tsinces := make(map[string]time.Time)\n\n\tfor _, atype := range r.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.IPNetRecord), atype, r.plugin.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tswitch atype {\n\t\tcase string(oam.URL):\n\t\t\trtypes = append(rtypes, \"rdap_url\")\n\t\tcase string(oam.FQDN):\n\t\t\trtypes = append(rtypes, \"whois_server\")\n\t\tcase string(oam.ContactRecord):\n\t\t\trtypes = append(rtypes, \"registrant\", \"admin_contact\", \"abuse_contact\", \"technical_contact\")\n\t\t}\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(asset, time.Time{}, rtypes...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotype := string(a.Asset.AssetType())\n\n\t\t\tsince, ok := sinces[totype]\n\t\t\tif !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !r.oneOfSources(e, edge, r.plugin.source, since) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar name string\n\t\t\tswitch v := a.Asset.(type) {\n\t\t\tcase *oamdns.FQDN:\n\t\t\t\tname = v.Name\n\t\t\tcase *contact.ContactRecord:\n\t\t\t\tname = \"ContactRecord: \" + v.DiscoveredAt\n\t\t\tcase *url.URL:\n\t\t\t\tname = v.Raw\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tiprec := asset.Asset.(*oamreg.IPNetRecord)\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"IPNetRecord: \" + iprec.Handle,\n\t\t\t\tTo: a,\n\t\t\t\tToName: name,\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (r *ipnet) oneOfSources(e *et.Event, edge *dbt.Edge, src *et.Source, since time.Time) bool {\n\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, src.Name); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (r *ipnet) store(e *et.Event, resp *rdap.IPNetwork, entity *dbt.Entity, m *config.Matches) {\n\tvar findings []*support.Finding\n\tiprec := entity.Asset.(*oamreg.IPNetRecord)\n\n\tif u := r.plugin.getJSONLink(resp.Links); u != nil && m.IsMatch(string(oam.URL)) {\n\t\tif a, err := e.Session.Cache().CreateAsset(u); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: entity,\n\t\t\t\tFromName: \"IPNetRecord: \" + iprec.Handle,\n\t\t\t\tTo: a,\n\t\t\t\tToName: u.Raw,\n\t\t\t\tRel: &general.SimpleRelation{Name: \"rdap_url\"},\n\t\t\t})\n\t\t}\n\t}\n\tif name := iprec.WhoisServer; name != \"\" && m.IsMatch(string(oam.FQDN)) {\n\t\tfqdn := &oamdns.FQDN{Name: name}\n\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf > 0 {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(fqdn); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: entity,\n\t\t\t\t\tFromName: \"IPNetRecord: \" + iprec.Handle,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: name,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"whois_server\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// process the relations built above\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n\n\tif m.IsMatch(string(oam.ContactRecord)) {\n\t\tfor _, v := range resp.Entities {\n\t\t\tr.plugin.storeEntity(e, 1, &v, entity, r.plugin.source, m)\n\t\t}\n\t}\n}\n\nfunc (r *ipnet) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/rdap/netblock.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage rdap\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/netip\"\n\t\"time\"\n\n\t\"github.com/openrdap/rdap\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\ntype netblock struct {\n\tname string\n\tplugin *rdapPlugin\n}\n\nfunc (nb *netblock) Name() string {\n\treturn nb.name\n}\n\nfunc (nb *netblock) check(e *et.Event) error {\n\tn, ok := e.Entity.Asset.(*network.Netblock)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Netblock asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(),\n\t\tstring(oam.Netblock), string(oam.IPNetRecord), nb.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar asset *dbt.Entity\n\tvar record *rdap.IPNetwork\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, nb.plugin.source, since) {\n\t\tasset = nb.lookup(e, n.CIDR.String(), since)\n\t} else {\n\t\tasset, record = nb.query(e, e.Entity)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, nb.plugin.source)\n\t}\n\n\tif asset != nil {\n\t\tnb.process(e, record, asset)\n\t}\n\treturn nil\n}\n\nfunc (nb *netblock) lookup(e *et.Event, cidr string, since time.Time) *dbt.Entity {\n\tif assets := support.SourceToAssetsWithinTTL(e.Session, cidr, string(oam.IPNetRecord), nb.plugin.source, since); len(assets) > 0 {\n\t\treturn assets[0]\n\t}\n\treturn nil\n}\n\nfunc (nb *netblock) query(e *et.Event, asset *dbt.Entity) (*dbt.Entity, *rdap.IPNetwork) {\n\tn := asset.Asset.(*network.Netblock)\n\n\t_, ipnet, err := net.ParseCIDR(n.CIDR.String())\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\treq := rdap.NewIPNetRequest(ipnet)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\treq = req.WithContext(ctx)\n\n\t_ = nb.plugin.rlimit.Wait(context.TODO())\n\tresp, err := nb.plugin.client.Do(req)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\trecord, ok := resp.Object.(*rdap.IPNetwork)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn nb.store(e, record, asset), record\n}\n\nfunc (nb *netblock) store(e *et.Event, resp *rdap.IPNetwork, asset *dbt.Entity) *dbt.Entity {\n\tn := asset.Asset.(*network.Netblock)\n\tipnetrec := &oamreg.IPNetRecord{\n\t\tCIDR: n.CIDR,\n\t\tHandle: resp.Handle,\n\t\tStartAddress: netip.MustParseAddr(resp.StartAddress),\n\t\tEndAddress: netip.MustParseAddr(resp.EndAddress),\n\t\tType: n.Type,\n\t\tName: resp.Name,\n\t\tMethod: resp.Type,\n\t\tCountry: resp.Country,\n\t\tParentHandle: resp.ParentHandle,\n\t\tWhoisServer: resp.Port43,\n\t\tStatus: resp.Status,\n\t}\n\n\tvar reg, last bool\n\tfor _, event := range resp.Events {\n\t\tswitch event.Action {\n\t\tcase \"registration\":\n\t\t\tif t, err := time.Parse(time.RFC3339, event.Date); err == nil {\n\t\t\t\tipnetrec.CreatedDate = support.TimeToJSONString(&t)\n\t\t\t\treg = true\n\t\t\t}\n\t\tcase \"last changed\":\n\t\t\tif t, err := time.Parse(time.RFC3339, event.Date); err == nil {\n\t\t\t\tipnetrec.UpdatedDate = support.TimeToJSONString(&t)\n\t\t\t\tlast = true\n\t\t\t}\n\t\t}\n\t}\n\tif !reg || !last {\n\t\treturn nil\n\t}\n\n\trecord, err := e.Session.Cache().CreateAsset(ipnetrec)\n\tif err == nil && record != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(record, &general.SourceProperty{\n\t\t\tSource: nb.plugin.source.Name,\n\t\t\tConfidence: nb.plugin.source.Confidence,\n\t\t})\n\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: &general.SimpleRelation{Name: \"registration\"},\n\t\t\tFromEntity: asset,\n\t\t\tToEntity: record,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: nb.plugin.source.Name,\n\t\t\t\tConfidence: nb.plugin.source.Confidence,\n\t\t\t})\n\t\t}\n\t}\n\treturn record\n}\n\nfunc (nb *netblock) process(e *et.Event, record *rdap.IPNetwork, asset *dbt.Entity) {\n\tipnet := asset.Asset.(*oamreg.IPNetRecord)\n\n\tname := \"IPNetRecord: \" + ipnet.Handle\n\t_ = e.Dispatcher.DispatchEvent((&et.Event{\n\t\tName: name,\n\t\tMeta: record,\n\t\tEntity: asset,\n\t\tSession: e.Session,\n\t}))\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", ipnet.CIDR.String(), \"relation\",\n\t\t\"registration\", \"to\", name, slog.Group(\"plugin\", \"name\", nb.plugin.name, \"handler\", nb.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/api/rdap/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage rdap\n\nimport (\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/openrdap/rdap\"\n\t\"github.com/openrdap/rdap/bootstrap\"\n\t\"github.com/openrdap/rdap/bootstrap/cache\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype rdapPlugin struct {\n\tname string\n\tlog *slog.Logger\n\tclient *rdap.Client\n\trlimit *rate.Limiter\n\tautsys *autsys\n\tautnum *autnum\n\tnetblock *netblock\n\tipnet *ipnet\n\tsource *et.Source\n}\n\nfunc NewRDAP() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &rdapPlugin{\n\t\tname: \"RDAP\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"RDAP\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (rd *rdapPlugin) Name() string {\n\treturn rd.name\n}\n\nfunc (rd *rdapPlugin) Start(r et.Registry) error {\n\trd.log = r.Log().WithGroup(\"plugin\").With(\"name\", rd.name)\n\n\toutdir := config.OutputDirectory()\n\tif outdir == \"\" {\n\t\treturn errors.New(\"failed to obtain the Amass output directory\")\n\t}\n\n\tc := cache.NewDiskCache()\n\tif c == nil {\n\t\treturn errors.New(\"failed to create the RDAP disk cache\")\n\t}\n\tc.Dir = filepath.Join(outdir, \".openrdap\")\n\n\tbs := &bootstrap.Client{Cache: c}\n\ttlsConfig := &tls.Config{InsecureSkipVerify: true}\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSClientConfig: tlsConfig,\n\t}\n\tbs.HTTP = &http.Client{\n\t\tTransport: transport,\n\t}\n\thttpClient := &http.Client{\n\t\tTransport: transport,\n\t}\n\trd.client = &rdap.Client{\n\t\tHTTP: httpClient,\n\t\tBootstrap: bs,\n\t}\n\n\trd.autsys = &autsys{\n\t\tname: rd.name + \"-Autsys-Handler\",\n\t\tplugin: rd,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: rd,\n\t\tName: rd.autsys.name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.AutnumRecord)},\n\t\tEventType: oam.AutonomousSystem,\n\t\tCallback: rd.autsys.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\trd.autnum = &autnum{\n\t\tname: rd.name + \"-Autnum-Handler\",\n\t\tplugin: rd,\n\t\ttransforms: []string{\n\t\t\tstring(oam.FQDN),\n\t\t\tstring(oam.URL),\n\t\t\tstring(oam.ContactRecord),\n\t\t\tstring(oam.Person),\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Location),\n\t\t\tstring(oam.Identifier),\n\t\t\tstring(oam.Phone),\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: rd,\n\t\tName: rd.autnum.name,\n\t\tPriority: 1,\n\t\tTransforms: rd.autnum.transforms,\n\t\tEventType: oam.AutnumRecord,\n\t\tCallback: rd.autnum.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\trd.netblock = &netblock{\n\t\tname: rd.name + \"-Netblock-Handler\",\n\t\tplugin: rd,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: rd,\n\t\tName: rd.netblock.name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.IPNetRecord)},\n\t\tEventType: oam.Netblock,\n\t\tCallback: rd.netblock.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\trd.ipnet = &ipnet{\n\t\tname: rd.name + \"-IPNetwork-Handler\",\n\t\tplugin: rd,\n\t\ttransforms: []string{\n\t\t\tstring(oam.FQDN),\n\t\t\tstring(oam.URL),\n\t\t\tstring(oam.ContactRecord),\n\t\t\tstring(oam.Person),\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Location),\n\t\t\tstring(oam.Identifier),\n\t\t\tstring(oam.Phone),\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: rd,\n\t\tName: rd.ipnet.name,\n\t\tPriority: 1,\n\t\tTransforms: rd.ipnet.transforms,\n\t\tEventType: oam.IPNetRecord,\n\t\tCallback: rd.ipnet.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\trd.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (rd *rdapPlugin) Stop() {\n\trd.log.Info(\"Plugin stopped\")\n}\n\nfunc (rd *rdapPlugin) storeEntity(e *et.Event, level int, entity *rdap.Entity, asset *dbt.Entity, src *et.Source, m *config.Matches) {\n\troles := stringset.New(entity.Roles...)\n\tdefer roles.Close()\n\n\tu := rd.getJSONLink(entity.Links)\n\tif u == nil {\n\t\treturn\n\t}\n\n\tvar rel string\n\tif roles.Has(\"registrant\") && level == 1 {\n\t\trel = \"registrant\"\n\t} else if roles.Has(\"administrative\") {\n\t\trel = \"admin_contact\"\n\t} else if roles.Has(\"abuse\") {\n\t\trel = \"abuse_contact\"\n\t} else if roles.Has(\"technical\") {\n\t\trel = \"technical_contact\"\n\t} else {\n\t\treturn\n\t}\n\n\tcr, err := e.Session.Cache().CreateAsset(&contact.ContactRecord{DiscoveredAt: u.Raw})\n\tif err != nil || cr == nil {\n\t\treturn\n\t}\n\n\tvar name string\n\tswitch v := asset.Asset.(type) {\n\tcase *oamreg.AutnumRecord:\n\t\tname = \"AutnumRecord: \" + v.Handle\n\tcase *oamreg.IPNetRecord:\n\t\tname = \"IPNetRecord: \" + v.Handle\n\t}\n\n\tif m.IsMatch(string(oam.URL)) {\n\t\ta, err := e.Session.Cache().CreateAsset(u)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"url\"}, src)\n\t}\n\n\tv := entity.VCard\n\tprop := v.GetFirst(\"kind\")\n\tif prop == nil {\n\t\treturn\n\t}\n\n\tif adr := v.GetFirst(\"adr\"); adr != nil && m.IsMatch(string(oam.Location)) {\n\t\tif label, ok := adr.Parameters[\"label\"]; ok {\n\t\t\ts := strings.Join(label, \" \")\n\n\t\t\taddr := strings.Join(strings.Split(s, \"\\n\"), \" \")\n\t\t\tif loc := support.StreetAddressToLocation(addr); loc != nil {\n\t\t\t\tif a, err := e.Session.Cache().CreateAsset(loc); err == nil && a != nil {\n\t\t\t\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"location\"}, src)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif email := strings.ToLower(v.Email()); m.IsMatch(string(oam.Identifier)) && email != \"\" {\n\t\tif a, err := e.Session.Cache().CreateAsset(&general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.EmailAddress, email),\n\t\t\tID: email,\n\t\t\tType: general.EmailAddress,\n\t\t}); err == nil && a != nil {\n\t\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"id\"}, src)\n\t\t}\n\t}\n\tif m.IsMatch(string(oam.Phone)) {\n\t\tif phone := support.PhoneToOAMPhone(v.Tel(), \"\", v.Country()); phone != nil {\n\t\t\tphone.Type = contact.PhoneTypeRegular\n\t\t\tif a, err := e.Session.Cache().CreateAsset(phone); err == nil && a != nil {\n\t\t\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"phone\"}, src)\n\t\t\t}\n\t\t}\n\t\tif fax := support.PhoneToOAMPhone(v.Fax(), \"\", v.Country()); fax != nil {\n\t\t\tfax.Type = contact.PhoneTypeFax\n\t\t\tif a, err := e.Session.Cache().CreateAsset(fax); err == nil && a != nil {\n\t\t\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"phone\"}, src)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar findings []*support.Finding\n\tfindings = append(findings, &support.Finding{\n\t\tFrom: asset,\n\t\tFromName: name,\n\t\tTo: cr,\n\t\tToName: \"ContactRecord: \" + u.Raw,\n\t\tRel: &general.SimpleRelation{Name: rel},\n\t})\n\t// process the relation immediately\n\tsupport.ProcessAssetsWithSource(e, findings, rd.source, rd.name, rd.name+\"-storeEntity\")\n\n\tname = v.Name()\n\t// the organization must come last due to a potential chicken-and-egg problem\n\tif kind := strings.Join(prop.Values(), \" \"); m.IsMatch(string(oam.Person)) && name != \"\" && kind == \"individual\" {\n\t\tif p := support.FullNameToPerson(name); p != nil {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(p); err == nil && a != nil {\n\t\t\t\t_ = rd.createContactEdge(e.Session, cr, a, &general.SimpleRelation{Name: \"person\"}, src)\n\t\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\t\tName: fmt.Sprintf(\"%s:%s\", p.FullName, p.ID),\n\t\t\t\t\tEntity: a,\n\t\t\t\t\tSession: e.Session,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t} else if m.IsMatch(string(oam.Organization)) && kind == \"org\" {\n\t\torgent, err := org.CreateOrgAsset(e.Session, cr,\n\t\t\t&general.SimpleRelation{Name: \"organization\"}, &oamorg.Organization{Name: name}, src)\n\n\t\tif err == nil && orgent != nil {\n\t\t\to := orgent.Asset.(*oamorg.Organization)\n\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: fmt.Sprintf(\"%s:%s\", o.Name, o.ID),\n\t\t\t\tEntity: orgent,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\t\t}\n\t}\n\n\tlevel++\n\tfor _, ent := range entity.Entities {\n\t\trd.storeEntity(e, level, &ent, asset, rd.source, m)\n\t}\n}\n\nfunc (rd *rdapPlugin) getJSONLink(links []rdap.Link) *url.URL {\n\tvar url *url.URL\n\tfor _, link := range links {\n\t\tif link.Type == \"application/rdap+json\" {\n\t\t\turl = support.RawURLToOAM(link.Href)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn url\n}\n\nfunc (rd *rdapPlugin) createContactEdge(sess et.Session, cr, a *dbt.Entity, rel oam.Relation, src *et.Source) error {\n\tedge, err := sess.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: cr,\n\t\tToEntity: a,\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if edge == nil {\n\t\treturn errors.New(\"failed to create the edge\")\n\t}\n\n\t_, err = sess.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: src.Name,\n\t\tConfidence: src.Confidence,\n\t})\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/archive/wayback.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage archive\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype wayback struct {\n\tname string\n\tURL string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewWayback() et.Plugin {\n\tlimit := rate.Every(5 * time.Second)\n\n\treturn &wayback{\n\t\tname: \"Wayback\",\n\t\tURL: \"https://web.archive.org/cdx/search/cdx?matchType=domain&fl=original&output=json&collapse=urlkey&url=\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Wayback\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (w *wayback) Name() string {\n\treturn w.name\n}\n\nfunc (w *wayback) Start(r et.Registry) error {\n\tw.log = r.Log().WithGroup(\"plugin\").With(\"name\", w.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: w,\n\t\tName: w.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: w.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tw.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (w *wayback) Stop() {\n\tw.log.Info(\"Plugin stopped\")\n}\n\nfunc (w *wayback) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), w.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, w.source, since) {\n\t\tnames = append(names, w.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, w.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, w.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tw.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (w *wayback) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), w.source, since)\n}\n\nfunc (w *wayback) query(e *et.Event, name string) []*dbt.Entity {\n\t_ = w.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: w.URL + name})\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\tvar urls [][]string\n\tif err := json.Unmarshal([]byte(resp.Body), &urls); err != nil {\n\t\treturn nil\n\t}\n\n\tfor _, url := range urls {\n\t\tif len(url) != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tu := url[0]\n\n\t\tif n := dns.AnySubdomainRegex().FindString(u); n != \"\" {\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: n}, 0); conf > 0 {\n\t\t\t\tsubs.Insert(n)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn w.store(e, subs.Slice())\n}\n\nfunc (w *wayback) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, w.source, w.name, w.name+\"-Handler\")\n}\n\nfunc (w *wayback) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, w.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/brute/alterations.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage brute\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n)\n\ntype alts struct {\n\tname string\n\tlog *slog.Logger\n\tchars string\n\tsource *et.Source\n}\n\nfunc NewFQDNAlterations() et.Plugin {\n\treturn &alts{\n\t\tname: \"FQDN-Alterations\",\n\t\tchars: \"abcdefghijklmnopqrstuvwxyz0123456789-\",\n\t\tsource: &et.Source{\n\t\t\tName: \"FQDN-Alterations\",\n\t\t\tConfidence: 0,\n\t\t},\n\t}\n}\n\nfunc (d *alts) Name() string {\n\treturn d.name\n}\n\nfunc (d *alts) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.name + \"-Handler\",\n\t\tPriority: 8,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{\"fqdn\"},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *alts) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *alts) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tcfg := e.Session.Config()\n\tif cfg != nil && (!cfg.BruteForcing || !cfg.Alterations) {\n\t\treturn nil\n\t}\n\n\tif e.Meta == nil {\n\t\treturn nil\n\t}\n\n\tvar dom string\n\tname := strings.ToLower(strings.TrimSpace(fqdn.Name))\n\tif a, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf == 0 || a == nil {\n\t\treturn nil\n\t} else if dfqdn, ok := a.(*oamdns.FQDN); !ok || dfqdn == nil {\n\t\treturn nil\n\t} else {\n\t\tdom = dfqdn.Name\n\t}\n\n\tsince, err := support.TTLStartTime(cfg, \"FQDN\", \"FQDN\", d.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\treturn nil\n\t}\n\n\tguesses := stringset.New()\n\tdefer guesses.Close()\n\n\tif cfg.FlipWords && len(cfg.AltWordlist) > 0 {\n\t\tguesses.InsertMany(flipWords(name, cfg.AltWordlist)...)\n\t}\n\tif cfg.FlipNumbers {\n\t\tguesses.InsertMany(flipNumbers(name)...)\n\t}\n\tif cfg.AddNumbers {\n\t\tguesses.InsertMany(appendNumbers(name)...)\n\t}\n\tif cfg.AddWords && len(cfg.AltWordlist) > 0 {\n\t\tguesses.InsertMany(addPrefixWords(name, cfg.AltWordlist)...)\n\t\tguesses.InsertMany(addSuffixWords(name, cfg.AltWordlist)...)\n\t}\n\tif distance := cfg.EditDistance; distance > 0 {\n\t\tguesses.InsertMany(fuzzyLabelSearches(name, distance, d.chars)...)\n\t}\n\tguesses.Remove(dom)\n\tguesses.Remove(name)\n\n\tvar assets []*dbt.Entity\n\t//subre := dns.SubdomainRegex(dom)\n\tfor _, guess := range guesses.Slice() {\n\t\t//if match := subre.FindString(guess); guess != match {\n\t\t//\tcontinue\n\t\t//}\n\t\tif a := d.store(e, guess); a != nil {\n\t\t\tassets = append(assets, a...)\n\t\t}\n\t}\n\n\tif len(assets) > 0 {\n\t\td.process(e, assets, d.source)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, d.source)\n\t}\n\treturn nil\n}\n\nfunc (d *alts) store(e *et.Event, name string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, []string{name}, d.source, d.name, d.name+\"-Handler\")\n}\n\nfunc (d *alts) process(e *et.Event, fqdns []*dbt.Entity, src *et.Source) {\n\tsupport.ProcessFQDNsWithSource(e, fqdns, d.source)\n}\n\n// flipWords flips prefixes and suffixes found within the provided name.\nfunc flipWords(name string, words []string) []string {\n\tnames := strings.SplitN(name, \".\", 2)\n\tsubdomain := names[0]\n\tdomain := names[1]\n\n\tparts := strings.Split(subdomain, \"-\")\n\tif len(parts) < 2 {\n\t\treturn []string{}\n\t}\n\n\tvar guesses []string\n\tfor _, k := range words {\n\t\tguesses = append(guesses, k+\"-\"+strings.Join(parts[1:], \"-\")+\".\"+domain)\n\t}\n\tfor _, k := range words {\n\t\tguesses = append(guesses, strings.Join(parts[:len(parts)-1], \"-\")+\"-\"+k+\".\"+domain)\n\t}\n\treturn guesses\n}\n\n// flipNumbers flips numbers in a subdomain name.\nfunc flipNumbers(name string) []string {\n\tn := name\n\tparts := strings.SplitN(n, \".\", 2)\n\t// Find the first character that is a number\n\tfirst := strings.IndexFunc(parts[0], unicode.IsNumber)\n\tif first < 0 {\n\t\treturn []string{}\n\t}\n\n\tvar guesses []string\n\t// Flip the first number and attempt a second number\n\tfor i := 0; i < 10; i++ {\n\t\tsf := n[:first] + strconv.Itoa(i) + n[first+1:]\n\t\tguesses = append(guesses, secondNumberFlip(sf, first+1)...)\n\t}\n\t// Take the first number out\n\tguesses = append(guesses, secondNumberFlip(n[:first]+n[first+1:], -1)...)\n\treturn guesses\n}\n\nfunc secondNumberFlip(name string, minIndex int) []string {\n\tparts := strings.SplitN(name, \".\", 2)\n\t// Find the second character that is a number\n\tlast := strings.LastIndexFunc(parts[0], unicode.IsNumber)\n\tif last < 0 || last < minIndex {\n\t\treturn []string{name}\n\t}\n\n\tvar guesses []string\n\t// Flip those numbers and send out the mutations\n\tfor i := 0; i < 10; i++ {\n\t\tguesses = append(guesses, name[:last]+strconv.Itoa(i)+name[last+1:])\n\t}\n\t// Take the second number out\n\tguesses = append(guesses, name[:last]+name[last+1:])\n\treturn guesses\n}\n\n// appendNumbers appends a number to a subdomain name.\nfunc appendNumbers(name string) []string {\n\tparts := strings.SplitN(name, \".\", 2)\n\n\tparts[0] = strings.Trim(parts[0], \"-\")\n\tif parts[0] == \"\" {\n\t\treturn []string{}\n\t}\n\n\tvar guesses []string\n\tfor i := 0; i < 10; i++ {\n\t\tguesses = append(guesses, addSuffix(parts, strconv.Itoa(i))...)\n\t}\n\treturn guesses\n}\n\n// addSuffixWords appends a suffix to a subdomain name.\nfunc addSuffixWords(name string, words []string) []string {\n\tparts := strings.SplitN(name, \".\", 2)\n\n\tparts[0] = strings.Trim(parts[0], \"-\")\n\tif parts[0] == \"\" {\n\t\treturn []string{}\n\t}\n\n\tvar guesses []string\n\tfor _, word := range words {\n\t\tguesses = append(guesses, addSuffix(parts, word)...)\n\t}\n\treturn guesses\n}\n\n// addPrefixWords appends a subdomain name to a prefix.\nfunc addPrefixWords(name string, words []string) []string {\n\tname = strings.Trim(name, \"-\")\n\tif name == \"\" {\n\t\treturn []string{}\n\t}\n\n\tvar guesses []string\n\tfor _, word := range words {\n\t\tguesses = append(guesses, addPrefix(name, word)...)\n\t}\n\treturn guesses\n}\n\nfunc addSuffix(parts []string, suffix string) []string {\n\treturn []string{\n\t\tparts[0] + suffix + \".\" + parts[1],\n\t\tparts[0] + \"-\" + suffix + \".\" + parts[1],\n\t}\n}\n\nfunc addPrefix(name, prefix string) []string {\n\treturn []string{\n\t\tprefix + name,\n\t\tprefix + \"-\" + name,\n\t}\n}\n\n// fuzzyLabelSearches returns new names generated by making slight\n// mutations to the provided name.\nfunc fuzzyLabelSearches(name string, distance int, chars string) []string {\n\tparts := strings.SplitN(name, \".\", 2)\n\n\tvar results []string\n\tif len(parts) < 2 {\n\t\treturn results\n\t}\n\n\tresults = append(results, parts[0])\n\tfor i := 0; i < distance; i++ {\n\t\tvar conv []string\n\n\t\tconv = append(conv, additions(results, chars)...)\n\t\tconv = append(conv, deletions(results)...)\n\t\tconv = append(conv, substitutions(results, chars)...)\n\t\tresults = append(results, conv...)\n\t}\n\n\tvar guesses []string\n\tfor _, alt := range results {\n\t\tif label := strings.Trim(alt, \"-\"); label != \"\" {\n\t\t\tguesses = append(guesses, label+\".\"+parts[1])\n\t\t}\n\t}\n\treturn guesses\n}\n\nfunc additions(set []string, chars string) []string {\n\tldh := []rune(chars)\n\tldhLen := len(ldh)\n\n\tvar guesses []string\n\tfor _, str := range set {\n\t\trstr := []rune(str)\n\t\trlen := len(rstr)\n\n\t\tfor i := 0; i <= rlen; i++ {\n\t\t\tfor j := 0; j < ldhLen; j++ {\n\t\t\t\ttemp := append(rstr, ldh[0])\n\n\t\t\t\tcopy(temp[i+1:], temp[i:])\n\t\t\t\ttemp[i] = ldh[j]\n\t\t\t\tguesses = append(guesses, string(temp))\n\t\t\t}\n\t\t}\n\t}\n\treturn guesses\n}\n\nfunc deletions(set []string) []string {\n\tvar guesses []string\n\n\tfor _, str := range set {\n\t\trstr := []rune(str)\n\t\trlen := len(rstr)\n\n\t\tfor i := 0; i < rlen; i++ {\n\t\t\tif del := string(append(rstr[:i], rstr[i+1:]...)); del != \"\" {\n\t\t\t\tguesses = append(guesses, del)\n\t\t\t}\n\t\t}\n\t}\n\treturn guesses\n}\n\nfunc substitutions(set []string, chars string) []string {\n\tldh := []rune(chars)\n\tldhLen := len(ldh)\n\n\tvar guesses []string\n\tfor _, str := range set {\n\t\trstr := []rune(str)\n\t\trlen := len(rstr)\n\n\t\tfor i := 0; i < rlen; i++ {\n\t\t\ttemp := rstr\n\n\t\t\tfor j := 0; j < ldhLen; j++ {\n\t\t\t\ttemp[i] = ldh[j]\n\t\t\t\tguesses = append(guesses, string(temp))\n\t\t\t}\n\t\t}\n\t}\n\treturn guesses\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/apex.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\ntype dnsApex struct {\n\tname string\n\tplugin *dnsPlugin\n}\n\nfunc (d *dnsApex) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif e.Meta == nil {\n\t\treturn nil\n\t} else if m, ok := e.Meta.(*support.FQDNMeta); !ok || len(m.RecordTypes) == 0 {\n\t\treturn nil\n\t}\n\n\t// determine which domain apex is the parent of this name\n\tvar name string\n\tbest := len(fqdn.Name)\n\tfor _, n := range d.plugin.getApexList() {\n\t\tif idx := strings.Index(fqdn.Name, n); idx != -1 && idx != 0 && idx < best {\n\t\t\tbest = idx\n\t\t\tname = n\n\t\t}\n\t}\n\tif name == \"\" {\n\t\treturn nil\n\t}\n\n\tif apex := d.plugin.getApex(name); apex != nil && apex.Asset.Key() != fqdn.Name {\n\t\td.store(e, fqdn.Name, e.Entity, apex)\n\t}\n\treturn nil\n}\n\nfunc (d *dnsApex) store(e *et.Event, name string, fqdn, apex *dbt.Entity) {\n\tif _, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"node\"},\n\t\tFromEntity: apex,\n\t\tToEntity: fqdn,\n\t}); err == nil {\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", apex.Asset.Key(), \"relation\",\n\t\t\t\"node\", \"to\", name, slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/cname.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/resolve/utils\"\n)\n\ntype dnsCNAME struct {\n\tname string\n\tplugin *dnsPlugin\n\tsource *et.Source\n}\n\ntype relAlias struct {\n\talias *dbt.Entity\n\ttarget *dbt.Entity\n}\n\nfunc (d *dnsCNAME) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"FQDN\", \"FQDN\", d.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar alias []*relAlias\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\talias = append(alias, d.lookup(e, e.Entity, since)...)\n\t} else {\n\t\talias = append(alias, d.query(e, e.Entity)...)\n\t}\n\n\tif len(alias) > 0 {\n\t\td.process(e, alias)\n\t\tsupport.AddDNSRecordType(e, int(dns.TypeCNAME))\n\t}\n\treturn nil\n}\n\nfunc (d *dnsCNAME) lookup(e *et.Event, fqdn *dbt.Entity, since time.Time) []*relAlias {\n\tvar alias []*relAlias\n\n\tn, ok := fqdn.Asset.(*oamdns.FQDN)\n\tif !ok || n == nil {\n\t\treturn alias\n\t}\n\n\tif assets := d.plugin.lookupWithinTTL(e.Session, n.Name, oam.FQDN, since, oam.BasicDNSRelation, 5); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\talias = append(alias, &relAlias{alias: fqdn, target: a})\n\t\t}\n\t}\n\treturn alias\n}\n\nfunc (d *dnsCNAME) query(e *et.Event, name *dbt.Entity) []*relAlias {\n\tvar alias []*relAlias\n\n\tfqdn := name.Asset.(*oamdns.FQDN)\n\tif rr, err := support.PerformQuery(fqdn.Name, dns.TypeCNAME); err == nil {\n\t\tif records := d.store(e, name, rr); len(records) > 0 {\n\t\t\talias = append(alias, records...)\n\t\t\tsupport.MarkAssetMonitored(e.Session, name, d.source)\n\t\t}\n\t}\n\n\treturn alias\n}\n\nfunc (d *dnsCNAME) store(e *et.Event, fqdn *dbt.Entity, rr []dns.RR) []*relAlias {\n\tvar alias []*relAlias\n\n\tfor _, record := range rr {\n\t\tif record.Header().Rrtype != dns.TypeCNAME {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := strings.ToLower(strings.TrimSpace((record.(*dns.CNAME)).Target))\n\t\tname := utils.RemoveLastDot(data)\n\t\tif cname, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name}); err == nil && cname != nil {\n\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\tRelation: &oamdns.BasicDNSRelation{\n\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tFromEntity: fqdn,\n\t\t\t\tToEntity: cname,\n\t\t\t}); err == nil && edge != nil {\n\t\t\t\talias = append(alias, &relAlias{alias: fqdn, target: cname})\n\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\tSource: d.source.Name,\n\t\t\t\t\tConfidence: d.source.Confidence,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn alias\n}\n\nfunc (d *dnsCNAME) process(e *et.Event, alias []*relAlias) {\n\tfor _, a := range alias {\n\t\ttarget := a.target.Asset.(*oamdns.FQDN)\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: target.Name,\n\t\t\tEntity: a.target,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", d.plugin.source.Name, \"relation\",\n\t\t\t\"cname_record\", \"to\", target.Name, slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/ip.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/netip\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\ntype dnsIP struct {\n\tname string\n\tqueries []uint16\n\tplugin *dnsPlugin\n\tsource *et.Source\n}\n\ntype relIP struct {\n\trtype string\n\tip *dbt.Entity\n}\n\nfunc (d *dnsIP) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif support.HasDNSRecordType(e, int(dns.TypeCNAME)) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"FQDN\", \"IPAddress\", d.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar ips []*relIP\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\tips = append(ips, d.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tips = append(ips, d.query(e, e.Entity)...)\n\t}\n\n\tif len(ips) > 0 {\n\t\td.process(e, fqdn.Name, ips)\n\n\t\tfor _, v := range ips {\n\t\t\tip, ok := v.ip.Asset.(*oamnet.IPAddress)\n\t\t\tif !ok || ip == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar size int\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(ip, 0); conf > 0 {\n\t\t\t\tsize = d.plugin.secondSweepSize\n\t\t\t\tif e.Session.Config().Active {\n\t\t\t\t\tsize = d.plugin.maxSweepSize\n\t\t\t\t}\n\t\t\t} else if _, conf2 := e.Session.Scope().IsAssetInScope(fqdn, 0); conf2 > 0 {\n\t\t\t\tsize = d.plugin.firstSweepSize\n\t\t\t}\n\t\t\tif size > 0 {\n\t\t\t\tsupport.IPAddressSweep(e, ip, d.source, size, sweepCallback)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d *dnsIP) lookup(e *et.Event, fqdn string, since time.Time) []*relIP {\n\tvar ips []*relIP\n\n\tif assets := d.plugin.lookupWithinTTL(e.Session, fqdn, oam.IPAddress, since, oam.BasicDNSRelation, 1); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\tips = append(ips, &relIP{rtype: \"dns_record\", ip: a})\n\t\t}\n\t}\n\tif assets := d.plugin.lookupWithinTTL(e.Session, fqdn, oam.IPAddress, since, oam.BasicDNSRelation, 28); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\tips = append(ips, &relIP{rtype: \"dns_record\", ip: a})\n\t\t}\n\t}\n\n\treturn ips\n}\n\nfunc (d *dnsIP) query(e *et.Event, name *dbt.Entity) []*relIP {\n\tvar ips []*relIP\n\n\tfqdn := name.Asset.(*oamdns.FQDN)\n\tfor _, qtype := range d.queries {\n\t\tif rr, err := support.PerformQuery(fqdn.Name, qtype); err == nil {\n\t\t\tif records := d.store(e, name, rr); len(records) > 0 {\n\t\t\t\tips = append(ips, records...)\n\t\t\t\tsupport.MarkAssetMonitored(e.Session, name, d.source)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ips\n}\n\nfunc (d *dnsIP) store(e *et.Event, fqdn *dbt.Entity, rr []dns.RR) []*relIP {\n\tvar ips []*relIP\n\n\tfor _, record := range rr {\n\t\tif record.Header().Rrtype == dns.TypeA {\n\t\t\taddr := (record.(*dns.A)).A.String()\n\n\t\t\tif ip, err := e.Session.Cache().CreateAsset(&oamnet.IPAddress{Address: netip.MustParseAddr(string(addr)), Type: \"IPv4\"}); err == nil && ip != nil {\n\t\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &oamdns.BasicDNSRelation{\n\t\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tFromEntity: fqdn,\n\t\t\t\t\tToEntity: ip,\n\t\t\t\t}); err == nil && edge != nil {\n\t\t\t\t\tips = append(ips, &relIP{rtype: \"dns_record\", ip: ip})\n\t\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\t\tSource: d.source.Name,\n\t\t\t\t\t\tConfidence: d.source.Confidence,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t\t\t}\n\t\t} else if record.Header().Rrtype == dns.TypeAAAA {\n\t\t\taddr := (record.(*dns.AAAA)).AAAA.String()\n\n\t\t\tif ip, err := e.Session.Cache().CreateAsset(&oamnet.IPAddress{Address: netip.MustParseAddr(addr), Type: \"IPv6\"}); err == nil {\n\t\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &oamdns.BasicDNSRelation{\n\t\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tFromEntity: fqdn,\n\t\t\t\t\tToEntity: ip,\n\t\t\t\t}); err == nil && edge != nil {\n\t\t\t\t\tips = append(ips, &relIP{rtype: \"dns_record\", ip: ip})\n\t\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\t\tSource: d.source.Name,\n\t\t\t\t\t\tConfidence: d.source.Confidence,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ips\n}\n\nfunc (d *dnsIP) process(e *et.Event, name string, addrs []*relIP) {\n\tfor _, a := range addrs {\n\t\tip := a.ip.Asset.(*oamnet.IPAddress)\n\n\t\tswitch ip.Type {\n\t\tcase \"IPv4\":\n\t\t\tsupport.AddDNSRecordType(e, int(dns.TypeA))\n\t\tcase \"IPv6\":\n\t\t\tsupport.AddDNSRecordType(e, int(dns.TypeAAAA))\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: ip.Address.String(),\n\t\t\tEntity: a.ip,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", name, \"relation\", a.rtype,\n\t\t\t\"to\", ip.Address.String(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\ntype dnsPlugin struct {\n\tname string\n\ttxt *dnsTXT\n\tlog *slog.Logger\n\tapex *dnsApex\n\tcname *dnsCNAME\n\tip *dnsIP\n\treverse *dnsReverse\n\tsubs *dnsSubs\n\tfirstSweepSize int\n\tsecondSweepSize int\n\tmaxSweepSize int\n\tsource *et.Source\n\tapexLock sync.Mutex\n\tapexList map[string]*dbt.Entity\n}\n\nfunc NewDNS() et.Plugin {\n\treturn &dnsPlugin{\n\t\tname: \"DNS\",\n\t\tfirstSweepSize: 25,\n\t\tsecondSweepSize: 100,\n\t\tmaxSweepSize: 250,\n\t\tsource: &et.Source{\n\t\t\tName: \"DNS\",\n\t\t\tConfidence: 100,\n\t\t},\n\t\tapexList: make(map[string]*dbt.Entity),\n\t}\n}\n\nfunc (d *dnsPlugin) Name() string {\n\treturn d.name\n}\n\nfunc (d *dnsPlugin) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\td.apex = &dnsApex{name: d.name + \"-Apex\", plugin: d}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.apex.name,\n\t\tPriority: 5,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.apex.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tcname := d.name + \"-CNAME\"\n\td.cname = &dnsCNAME{\n\t\tname: cname,\n\t\tplugin: d,\n\t\tsource: &et.Source{\n\t\t\tName: cname,\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.cname.name,\n\t\tPriority: 2,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.cname.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tipname := d.name + \"-IP\"\n\td.ip = &dnsIP{\n\t\tname: ipname,\n\t\tqueries: []uint16{dns.TypeA, dns.TypeAAAA},\n\t\tplugin: d,\n\t\tsource: &et.Source{\n\t\t\tName: ipname,\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.ip.name,\n\t\tPriority: 3,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.IPAddress)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.ip.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.reverse = NewReverse(d)\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.reverse.name,\n\t\tPriority: 8,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.IPAddress,\n\t\tCallback: d.reverse.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.subs = NewSubs(d)\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.subs.name,\n\t\tPriority: 4,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.subs.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\tgo d.subs.releaseSessions()\n\n\ttxtname := d.name + \"-TXT\"\n\td.txt = &dnsTXT{\n\t\tname: d.name + \"-TXT\",\n\t\tplugin: d,\n\t\tsource: &et.Source{\n\t\t\tName: txtname,\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.txt.name,\n\t\tPriority: 1,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.txt.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *dnsPlugin) Stop() {\n\tclose(d.subs.done)\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *dnsPlugin) lookupWithinTTL(session et.Session, name string, atype oam.AssetType, since time.Time, reltype oam.RelationType, rrtypes ...int) []*dbt.Entity {\n\tvar results []*dbt.Entity\n\n\tif len(rrtypes) == 0 || !since.IsZero() {\n\t\treturn results\n\t}\n\n\tents, err := session.Cache().FindEntitiesByContent(&oamdns.FQDN{Name: name}, time.Time{})\n\tif err != nil || len(ents) != 1 {\n\t\treturn results\n\t}\n\tentity := ents[0]\n\n\tif edges, err := session.Cache().OutgoingEdges(entity, since, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif tags, err := session.Cache().GetEdgeTags(edge, since, d.source.Name); err == nil && len(tags) > 0 {\n\t\t\t\tvar found bool\n\n\t\t\t\tfor _, tag := range tags {\n\t\t\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar rrtype int\n\t\t\tswitch v := edge.Relation.(type) {\n\t\t\tcase *oamdns.BasicDNSRelation:\n\t\t\t\tif v.RelationType() == reltype {\n\t\t\t\t\trrtype = v.Header.RRType\n\t\t\t\t}\n\t\t\tcase *oamdns.PrefDNSRelation:\n\t\t\t\tif v.RelationType() == reltype {\n\t\t\t\t\trrtype = v.Header.RRType\n\t\t\t\t}\n\t\t\tcase *oamdns.SRVDNSRelation:\n\t\t\t\tif v.RelationType() == reltype {\n\t\t\t\t\trrtype = v.Header.RRType\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, t := range rrtypes {\n\t\t\t\tif rrtype == t {\n\t\t\t\t\tif to, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && to != nil && to.Asset.AssetType() == atype {\n\t\t\t\t\t\tresults = append(results, to)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results\n}\n\nfunc sweepCallback(e *et.Event, ip *oamnet.IPAddress, src *et.Source) {\n\tentity, err := e.Session.Cache().CreateAsset(ip)\n\tif err == nil && entity != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(entity, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\t}\n\n\tif entity != nil {\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: ip.Address.String(),\n\t\t\tEntity: entity,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\nfunc (d *dnsPlugin) addApex(name string, entity *dbt.Entity) {\n\td.apexLock.Lock()\n\tdefer d.apexLock.Unlock()\n\n\tif _, found := d.apexList[name]; !found {\n\t\td.apexList[name] = entity\n\t}\n}\n\nfunc (d *dnsPlugin) getApex(name string) *dbt.Entity {\n\td.apexLock.Lock()\n\tdefer d.apexLock.Unlock()\n\n\tif entity, found := d.apexList[name]; found {\n\t\treturn entity\n\t}\n\treturn nil\n}\n\nfunc (d *dnsPlugin) getApexList() []string {\n\td.apexLock.Lock()\n\tdefer d.apexLock.Unlock()\n\n\tvar results []string\n\tfor name := range d.apexList {\n\t\tresults = append(results, name)\n\t}\n\treturn results\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/reverse.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/resolve/utils\"\n)\n\ntype dnsReverse struct {\n\tname string\n\tplugin *dnsPlugin\n}\n\ntype relRev struct {\n\tipFQDN *dbt.Entity\n\ttarget *dbt.Entity\n}\n\nfunc NewReverse(p *dnsPlugin) *dnsReverse {\n\treturn &dnsReverse{\n\t\tname: p.name + \"-Reverse\",\n\t\tplugin: p,\n\t}\n}\n\nfunc (d *dnsReverse) check(e *et.Event) error {\n\tip, ok := e.Entity.Asset.(*oamnet.IPAddress)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the IPAddress asset\")\n\t}\n\n\taddrstr := ip.Address.String()\n\tif reserved, _ := amassnet.IsReservedAddress(addrstr); reserved {\n\t\treturn nil\n\t}\n\n\treverse, err := dns.ReverseAddr(ip.Address.String())\n\tif err != nil {\n\t\treturn nil\n\t}\n\treverse = utils.RemoveLastDot(reverse)\n\n\tsrc := d.plugin.source\n\tptr := d.createPTRAlias(e, reverse, e.Entity)\n\tif ptr == nil {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"IPAddress\", \"FQDN\", d.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rev []*relRev\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\trev = append(rev, d.lookup(e, ptr, since)...)\n\t} else {\n\t\trev = append(rev, d.query(e, addrstr, ptr)...)\n\t\tsupport.MarkAssetMonitored(e.Session, ptr, src)\n\t}\n\n\tif len(rev) > 0 {\n\t\td.process(e, rev)\n\t\tsupport.AddDNSRecordType(e, int(dns.TypePTR))\n\n\t\tvar size int\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(ip, 0); conf > 0 {\n\t\t\tsize = d.plugin.secondSweepSize\n\t\t\tif e.Session.Config().Active {\n\t\t\t\tsize = d.plugin.maxSweepSize\n\t\t\t}\n\t\t}\n\t\tif size > 0 {\n\t\t\tsupport.IPAddressSweep(e, ip, src, size, sweepCallback)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d *dnsReverse) lookup(e *et.Event, fqdn *dbt.Entity, since time.Time) []*relRev {\n\tvar rev []*relRev\n\n\tn, ok := fqdn.Asset.(*oamdns.FQDN)\n\tif !ok || n == nil {\n\t\treturn rev\n\t}\n\n\tif assets := d.plugin.lookupWithinTTL(e.Session, n.Name, oam.FQDN, since, oam.BasicDNSRelation, 12); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\trev = append(rev, &relRev{ipFQDN: fqdn, target: a})\n\t\t}\n\t}\n\n\treturn rev\n}\n\nfunc (d *dnsReverse) query(e *et.Event, ipstr string, ptr *dbt.Entity) []*relRev {\n\tvar rev []*relRev\n\n\tif rr, err := support.PerformQuery(ipstr, dns.TypePTR); err == nil {\n\t\tif records := d.store(e, ptr, rr); len(records) > 0 {\n\t\t\trev = append(rev, records...)\n\t\t}\n\t}\n\treturn rev\n}\n\nfunc (d *dnsReverse) store(e *et.Event, ptr *dbt.Entity, rr []dns.RR) []*relRev {\n\tvar rev []*relRev\n\t// additional validation of the PTR record\n\tfor _, record := range rr {\n\t\tif record.Header().Rrtype != dns.TypePTR {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := strings.ToLower(strings.TrimSpace((record.(*dns.PTR)).Ptr))\n\t\tname := support.ScrapeSubdomainNames(data)\n\t\tif len(name) != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif t, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name[0]}); err == nil && t != nil {\n\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\tRelation: &oamdns.BasicDNSRelation{\n\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tFromEntity: ptr,\n\t\t\t\tToEntity: t,\n\t\t\t}); err == nil && edge != nil {\n\t\t\t\trev = append(rev, &relRev{ipFQDN: ptr, target: t})\n\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\tSource: d.plugin.source.Name,\n\t\t\t\t\tConfidence: d.plugin.source.Confidence,\n\t\t\t\t})\n\t\t\t}\n\t\t} else {\n\t\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t\t}\n\t}\n\n\treturn rev\n}\n\nfunc (d *dnsReverse) createPTRAlias(e *et.Event, name string, ip *dbt.Entity) *dbt.Entity {\n\tptr, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name})\n\tif err != nil || ptr == nil {\n\t\treturn nil\n\t}\n\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"ptr_record\"},\n\t\tFromEntity: ip,\n\t\tToEntity: ptr,\n\t}); err == nil && edge != nil {\n\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\tSource: d.plugin.source.Name,\n\t\t\tConfidence: d.plugin.source.Confidence,\n\t\t})\n\t}\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: ptr.Asset.Key(),\n\t\tEntity: ptr,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", ip.Asset.Key(), \"relation\", \"ptr_record\",\n\t\t\"to\", ptr.Asset.Key(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\n\treturn ptr\n}\n\nfunc (d *dnsReverse) process(e *et.Event, rev []*relRev) {\n\tfor _, r := range rev {\n\t\tip := r.ipFQDN.Asset.(*oamdns.FQDN)\n\t\ttarget := r.target.Asset.(*oamdns.FQDN)\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: target.Name,\n\t\t\tEntity: r.target,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", ip.Name, \"relation\", \"ptr_record\",\n\t\t\t\"to\", target.Name, slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/subs.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/resolve/utils\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype subsQtypes struct {\n\tQtype uint16\n\tRtype string\n}\n\ntype subsSession struct {\n\tsession et.Session\n\tstrset *stringset.Set\n}\n\ntype dnsSubs struct {\n\tsync.Mutex\n\tname string\n\ttypes []subsQtypes\n\tdone chan struct{}\n\tsessNames map[string]*subsSession\n\tplugin *dnsPlugin\n}\n\ntype relSubs struct {\n\trtype string\n\talias *dbt.Entity\n\ttarget *dbt.Entity\n}\n\nfunc NewSubs(p *dnsPlugin) *dnsSubs {\n\treturn &dnsSubs{\n\t\tname: p.name + \"-Subdomains\",\n\t\ttypes: []subsQtypes{\n\t\t\t{Qtype: dns.TypeNS, Rtype: \"ns_record\"},\n\t\t\t{Qtype: dns.TypeMX, Rtype: \"mx_record\"},\n\t\t\t//{Qtype: dns.TypeSOA, Rtype: \"soa_record\"},\n\t\t\t//{Qtype: dns.TypeSPF, Rtype: \"spf_record\"},\n\t\t},\n\t\tdone: make(chan struct{}),\n\t\tsessNames: make(map[string]*subsSession),\n\t\tplugin: p,\n\t}\n}\n\nfunc (d *dnsSubs) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasDNSRecordType(e, int(dns.TypeA)) && !support.HasDNSRecordType(e, int(dns.TypeAAAA)) {\n\t\treturn nil\n\t}\n\n\tdom := d.registered(e, fqdn.Name)\n\tif dom == \"\" {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"FQDN\", \"FQDN\", d.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif names := d.traverse(e, dom, e.Entity, since); len(names) > 0 {\n\t\td.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (d *dnsSubs) registered(e *et.Event, name string) string {\n\tif a, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: name}, 0); conf > 0 && a != nil {\n\t\tif fqdn, ok := a.(*oamdns.FQDN); ok {\n\t\t\treturn fqdn.Name\n\t\t}\n\t}\n\n\tfqdns, err := e.Session.Cache().FindEntitiesByContent(&oamdns.FQDN{Name: name}, time.Time{})\n\tif err != nil || len(fqdns) != 1 {\n\t\treturn \"\"\n\t}\n\tfqdn := fqdns[0]\n\n\tvar rels []*dbt.Edge\n\t// allow name servers and mail servers to be investigated like in-scope assets\n\tif edges, err := e.Session.Cache().IncomingEdges(fqdn, time.Time{}, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif r, ok := edge.Relation.(*oamdns.PrefDNSRelation); ok {\n\t\t\t\tif r.Header.RRType == int(dns.TypeNS) || r.Header.RRType == int(dns.TypeMX) {\n\t\t\t\t\trels = append(rels, edge)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar inscope bool\n\tfor _, r := range rels {\n\t\tfrom, err := e.Session.Cache().FindEntityById(r.FromEntity.ID)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif f, ok := from.Asset.(*oamdns.FQDN); ok && from != nil {\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(f, 0); conf > 0 {\n\t\t\t\tinscope = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif inscope {\n\t\tif dom, err := publicsuffix.EffectiveTLDPlusOne(name); err == nil {\n\t\t\treturn dom\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (d *dnsSubs) traverse(e *et.Event, dom string, fqdn *dbt.Entity, since time.Time) []*relSubs {\n\tvar alias []*relSubs\n\n\tdlabels := strings.Split(dom, \".\")\n\tdlen := len(dlabels)\n\tif dlen < 2 {\n\t\treturn alias\n\t}\n\n\tsub := fqdn.Asset.Key()\n\tfor labels := strings.Split(sub, \".\"); dlen <= len(labels); labels = labels[1:] {\n\t\tsub = strings.TrimSpace(strings.Join(labels, \".\"))\n\n\t\t// no need to check subdomains already evaluated\n\t\tif d.fqdnAvailable(e, sub) {\n\t\t\tresults := d.lookup(e, sub, since)\n\t\t\tif len(results) == 0 {\n\t\t\t\tresults = d.query(e, sub)\n\t\t\t}\n\t\t\talias = append(alias, results...)\n\t\t}\n\t}\n\n\treturn alias\n}\n\nfunc (d *dnsSubs) lookup(e *et.Event, subdomain string, since time.Time) []*relSubs {\n\tvar alias []*relSubs\n\n\tfqdns, err := e.Session.Cache().FindEntitiesByContent(&oamdns.FQDN{Name: subdomain}, time.Time{})\n\tif err != nil || len(fqdns) != 1 {\n\t\treturn alias\n\t}\n\tfqdn := fqdns[0]\n\n\tn := fqdn.Asset.Key()\n\t// Check for NS records within the since period\n\tif assets := d.plugin.lookupWithinTTL(e.Session, n, oam.FQDN, since, oam.PrefDNSRelation, 2); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\talias = append(alias, &relSubs{rtype: \"dns_record\", alias: fqdn, target: a})\n\t\t}\n\t}\n\t// Check for MX records within the since period\n\tif assets := d.plugin.lookupWithinTTL(e.Session, n, oam.FQDN, since, oam.PrefDNSRelation, 15); len(assets) > 0 {\n\t\tfor _, a := range assets {\n\t\t\talias = append(alias, &relSubs{rtype: \"dns_record\", alias: fqdn, target: a})\n\t\t}\n\t}\n\treturn alias\n}\n\nfunc (d *dnsSubs) query(e *et.Event, subdomain string) []*relSubs {\n\tapex := true\n\tvar alias []*relSubs\n\n\tfor i, t := range d.types {\n\t\tif rr, err := support.PerformQuery(subdomain, t.Qtype); err == nil && len(rr) > 0 {\n\t\t\tif records := d.store(e, subdomain, rr); len(records) > 0 {\n\t\t\t\talias = append(alias, records...)\n\t\t\t}\n\t\t} else if i == 0 {\n\t\t\t// do not continue if we failed to obtain the NS record\n\t\t\tapex = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !apex {\n\t\treturn alias\n\t}\n\n\trch := make(chan []*relSubs, len(srvNames))\n\tdefer close(rch)\n\n\tfor _, name := range srvNames {\n\t\tgo func(label, sub string, ch chan []*relSubs) {\n\t\t\tn := name + \".\" + subdomain\n\n\t\t\tvar results []*relSubs\n\t\t\tif rr, err := support.PerformQuery(n, dns.TypeSRV); err == nil && len(rr) > 0 {\n\t\t\t\tif records := d.store(e, n, rr); len(records) > 0 {\n\t\t\t\t\tresults = append(results, records...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tch <- results\n\t\t}(name, subdomain, rch)\n\t}\n\n\tfor i := 0; i < len(srvNames); i++ {\n\t\tanswers := <-rch\n\t\talias = append(alias, answers...)\n\t}\n\n\treturn alias\n}\n\nfunc (d *dnsSubs) store(e *et.Event, name string, rr []dns.RR) []*relSubs {\n\tvar alias []*relSubs\n\n\tfqdn, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name})\n\tif err != nil || fqdn == nil {\n\t\treturn alias\n\t}\n\n\tfor _, record := range rr {\n\t\tvar a *dbt.Entity\n\t\tvar edge *dbt.Edge\n\n\t\tif record.Header().Rrtype == dns.TypeNS {\n\t\t\tdata := utils.RemoveLastDot((record.(*dns.NS)).Ns)\n\n\t\t\ta, err = e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: data})\n\t\t\tif err == nil && a != nil {\n\t\t\t\tedge, err = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &oamdns.BasicDNSRelation{\n\t\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tFromEntity: fqdn,\n\t\t\t\t\tToEntity: a,\n\t\t\t\t})\n\t\t\t}\n\t\t} else if record.Header().Rrtype == dns.TypeMX {\n\t\t\tdata := utils.RemoveLastDot((record.(*dns.MX)).Mx)\n\n\t\t\ta, err = e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: data})\n\t\t\tif err == nil && a != nil {\n\t\t\t\tedge, err = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &oamdns.PrefDNSRelation{\n\t\t\t\t\t\tName: \"dns_record\",\n\t\t\t\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\t\t\t\tRRType: int(record.Header().Rrtype),\n\t\t\t\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tPreference: int((record.(*dns.MX)).Preference),\n\t\t\t\t\t},\n\t\t\t\t\tFromEntity: fqdn,\n\t\t\t\t\tToEntity: a,\n\t\t\t\t})\n\t\t\t}\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err == nil && edge != nil {\n\t\t\talias = append(alias, &relSubs{rtype: \"dns_record\", alias: fqdn, target: a})\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: d.plugin.source.Name,\n\t\t\t\tConfidence: d.plugin.source.Confidence,\n\t\t\t})\n\t\t} else {\n\t\t\te.Session.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t\t}\n\t}\n\n\tif len(alias) > 0 {\n\t\td.plugin.addApex(name, fqdn)\n\t}\n\treturn alias\n}\n\nfunc (d *dnsSubs) process(e *et.Event, results []*relSubs) {\n\tfor _, finding := range results {\n\t\tfname, ok := finding.alias.Asset.(*oamdns.FQDN)\n\t\tif !ok || fname == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fname.Name,\n\t\t\tEntity: finding.alias,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\ttname, ok := finding.target.Asset.(*oamdns.FQDN)\n\t\tif !ok || tname == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: tname.Name,\n\t\t\tEntity: finding.target,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\te.Session.Log().Info(\"relationship discovered\", \"from\", fname.Name, \"relation\",\n\t\t\tfinding.rtype, \"to\", tname.Name, slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\nfunc (d *dnsSubs) fqdnAvailable(e *et.Event, fqdn string) bool {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tid := e.Session.ID().String()\n\tif _, found := d.sessNames[id]; !found {\n\t\td.sessNames[id] = &subsSession{\n\t\t\tsession: e.Session,\n\t\t\tstrset: stringset.New(),\n\t\t}\n\t}\n\n\tvar avail bool\n\tif !d.sessNames[id].strset.Has(fqdn) {\n\t\tavail = true\n\t\td.sessNames[id].strset.Insert(fqdn)\n\t}\n\treturn avail\n}\n\nfunc (d *dnsSubs) releaseSessions() {\n\tt := time.NewTicker(time.Minute)\n\tdefer t.Stop()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-d.done:\n\t\t\tbreak loop\n\t\tcase <-t.C:\n\t\t\td.Lock()\n\t\t\tvar ids []string\n\t\t\tfor id, s := range d.sessNames {\n\t\t\t\tif s.session.Done() {\n\t\t\t\t\tids = append(ids, id)\n\t\t\t\t\ts.strset.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, id := range ids {\n\t\t\t\tdelete(d.sessNames, id)\n\t\t\t}\n\t\t\td.Unlock()\n\t\t}\n\t}\n\n\td.Lock()\n\tfor _, sess := range d.sessNames {\n\t\tsess.strset.Close()\n\t}\n\td.Unlock()\n}\n\nvar srvNames = []string{\n\t\"_afs3-kaserver._tcp\",\n\t\"_afs3-kaserver._tcp\",\n\t\"_afs3-kaserver._udp\",\n\t\"_afs3-prserver._tcp\",\n\t\"_afs3-prserver._udp\",\n\t\"_afs3-vlserver._tcp\",\n\t\"_afs3-vlserver._udp\",\n\t\"_amt._udp\",\n\t\"_autodiscover._tcp\",\n\t\"_autotunnel._udp\",\n\t\"_avatars-sec._tcp\",\n\t\"_avatars._tcp\",\n\t\"_bittorrent-tracker._tcp\",\n\t\"_caldav._tcp\",\n\t\"_caldavs._tcp\",\n\t\"_carddav._tcp\",\n\t\"_carddavs._tcp\",\n\t\"_ceph-mon._tcp\",\n\t\"_ceph._tcp\",\n\t\"_certificates._tcp\",\n\t\"_chat._udp\",\n\t\"_citrixreceiver._tcp\",\n\t\"_collab-edge._tls\",\n\t\"_crls._tcp\",\n\t\"_daap._tcp\",\n\t\"_diameters._tcp\",\n\t\"_diameter._tcp\",\n\t\"_diameter._tls\",\n\t\"_dns-llq._tcp\",\n\t\"_dns-llq-tls._tcp\",\n\t\"_dns-llq-tls._udp\",\n\t\"_dns-llq._udp\",\n\t\"_dns-push-tls._tcp\",\n\t\"_dns-sd._udp\",\n\t\"_dns._udp\",\n\t\"_dns-update._tcp\",\n\t\"_dns-update-tls._tcp\",\n\t\"_dns-update._udp\",\n\t\"_dots-call-home._tcp\",\n\t\"_dots-call-home._udp\",\n\t\"_dots-data._tcp\",\n\t\"_dots-signal._tcp\",\n\t\"_dots-signal._udp\",\n\t\"_dvbservdsc._tcp\",\n\t\"_dvbservdsc._udp\",\n\t\"_ftp._tcp\",\n\t\"_gc._tcp\",\n\t\"_hip-nat-t._udp\",\n\t\"_http._tcp\",\n\t\"_hybrid-pop._tcp\",\n\t\"_hybrid-pop._udp\",\n\t\"_imap3._tcp\",\n\t\"_imap3._udp\",\n\t\"_imaps._tcp\",\n\t\"_imaps._udp\",\n\t\"_imap._tcp\",\n\t\"_imap._udp\",\n\t\"_imps-server._tcp\",\n\t\"_ipp._tcp\",\n\t\"_jabber._tcp\",\n\t\"_jmap._tcp\",\n\t\"_kca._udp\",\n\t\"_kerberos-adm._tcp\",\n\t\"_kerberos-adm._udp\",\n\t\"_kerberos-master._tcp\",\n\t\"_kerberos-master._udp\",\n\t\"_kerberos._tcp\",\n\t\"_kerberos-tls._tcp\",\n\t\"_kerberos._udp\",\n\t\"_kerneros-iv._udp\",\n\t\"_kftp-data._tcp\",\n\t\"_kftp-data._udp\",\n\t\"_kftp._tcp\",\n\t\"_kftp._udp\",\n\t\"_kpasswd._tcp\",\n\t\"_kpasswd._udp\",\n\t\"_ktelnet._tcp\",\n\t\"_ktelnet._udp\",\n\t\"_ldap-admin._tcp\",\n\t\"_ldap-admin._udp\",\n\t\"_ldaps._tcp\",\n\t\"_ldaps._udp\",\n\t\"_ldap._tcp\",\n\t\"_ldap._udp\",\n\t\"_matrix._tcp\",\n\t\"_matrix-vnet._tcp\",\n\t\"_MIHIS._tcp\",\n\t\"_MIHIS._udp\",\n\t\"_minecraft._tcp\",\n\t\"_msft-gc-ssl._tcp\",\n\t\"_msft-gc-ssl._udp\",\n\t\"_msrps._tcp\",\n\t\"_mtqp._tcp\",\n\t\"_nfs-domainroot._tcp\",\n\t\"_nicname._tcp\",\n\t\"_nicname._udp\",\n\t\"_ntp._udp\",\n\t\"_pop2._tcp\",\n\t\"_pop2._udp\",\n\t\"_pop3s._tcp\",\n\t\"_pop3s._udp\",\n\t\"_pop3._tcp\",\n\t\"_pop3._udp\",\n\t\"_presence._tcp\",\n\t\"_presence._udp\",\n\t\"_puppet._tcp\",\n\t\"_radiusdtls._udp\",\n\t\"_radiustls._tcp\",\n\t\"_radiustls._udp\",\n\t\"_radsec._tcp\",\n\t\"_rwhois._tcp\",\n\t\"_rwhois._udp\",\n\t\"_sieve._tcp\",\n\t\"_sips._tcp\",\n\t\"_sips._udp\",\n\t\"_sip._tcp\",\n\t\"_sip._udp\",\n\t\"_slpda._tcp\",\n\t\"_slpda._udp\",\n\t\"_slp._tcp\",\n\t\"_slp._udp\",\n\t\"_smtp._tcp\",\n\t\"_smtp._tls\",\n\t\"_smtp._udp\",\n\t\"_soap-beep._tcp\",\n\t\"_ssh._tcp\",\n\t\"_stun-behaviors._tcp\",\n\t\"_stun-behaviors._udp\",\n\t\"_stun-behavior._tcp\",\n\t\"_stun-behavior._udp\",\n\t\"_stun-p1._tcp\",\n\t\"_stun-p1._udp\",\n\t\"_stun-p2._tcp\",\n\t\"_stun-p2._udp\",\n\t\"_stun-p3._tcp\",\n\t\"_stun-p3._udp\",\n\t\"_stun-port._tcp\",\n\t\"_stun-port._udp\",\n\t\"_stuns._tcp\",\n\t\"_stuns._udp\",\n\t\"_stun._tcp\",\n\t\"_stun._udp\",\n\t\"_submissions._tcp\",\n\t\"_submission._tcp\",\n\t\"_submission._udp\",\n\t\"_sztp._tcp\",\n\t\"_telnet._tcp\",\n\t\"_timezones._tcp\",\n\t\"_timezone._tcp\",\n\t\"_ts3._udp\",\n\t\"_tsdns._tcp\",\n\t\"_tunnel._tcp\",\n\t\"_turns._tcp\",\n\t\"_turns._udp\",\n\t\"_turn._tcp\",\n\t\"_turn._udp\",\n\t\"_whoispp._tcp\",\n\t\"_whoispp._udp\",\n\t\"_www-http._tcp\",\n\t\"_www-ldap-gw._tcp\",\n\t\"_www-ldap-gw._udp\",\n\t\"_www._tcp\",\n\t\"_xmlrpc-beep._tcp\",\n\t\"_xmpp-bosh._tcp\",\n\t\"_xmpp-client._tcp\",\n\t\"_xmpp-client._udp\",\n\t\"_xmpp-server._tcp\",\n\t\"_xmpp-server._udp\",\n\t\"_xmpp._tcp\",\n\t\"_x-puppet._tcp\",\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/dns/txt.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n)\n\ntype dnsTXT struct {\n\tname string\n\tplugin *dnsPlugin\n\tsource *et.Source\n}\n\nfunc (d *dnsTXT) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"FQDN\", \"FQDN\", d.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar txtRecords []dns.RR\n\tvar props []*oamdns.DNSRecordProperty\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\tprops = d.lookup(e, e.Entity, since)\n\t} else {\n\t\ttxtRecords = d.query(e, e.Entity)\n\t\td.store(e, e.Entity, txtRecords)\n\t}\n\n\tif len(txtRecords) > 0 {\n\t\td.process(e, e.Entity, txtRecords, props)\n\t\tsupport.AddDNSRecordType(e, int(dns.TypeTXT))\n\t}\n\treturn nil\n}\n\nfunc (d *dnsTXT) lookup(e *et.Event, fqdn *dbt.Entity, since time.Time) []*oamdns.DNSRecordProperty {\n\tvar props []*oamdns.DNSRecordProperty\n\n\tn, ok := fqdn.Asset.(*oamdns.FQDN)\n\tif !ok || n == nil {\n\t\treturn props\n\t}\n\n\tif tags, err := e.Session.Cache().GetEntityTags(fqdn, since, \"dns_record\"); err == nil {\n\t\tfor _, tag := range tags {\n\t\t\tif prop, ok := tag.Property.(*oamdns.DNSRecordProperty); ok && prop.Header.RRType == int(dns.TypeTXT) {\n\t\t\t\tprops = append(props, prop)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn props\n}\n\nfunc (d *dnsTXT) query(e *et.Event, name *dbt.Entity) []dns.RR {\n\tvar txtRecords []dns.RR\n\n\tfqdn, ok := name.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn txtRecords\n\t}\n\n\tif rr, err := support.PerformQuery(fqdn.Name, dns.TypeTXT); err == nil {\n\t\ttxtRecords = append(txtRecords, rr...)\n\t\tsupport.MarkAssetMonitored(e.Session, name, d.source)\n\t}\n\n\treturn txtRecords\n}\n\nfunc (d *dnsTXT) store(e *et.Event, fqdn *dbt.Entity, rr []dns.RR) {\n\tfor _, record := range rr {\n\t\tif record.Header().Rrtype != dns.TypeTXT {\n\t\t\tcontinue\n\t\t}\n\n\t\ttxtValue := strings.Join((record.(*dns.TXT)).Txt, \" \")\n\t\t_, err := e.Session.Cache().CreateEntityProperty(fqdn, &oamdns.DNSRecordProperty{\n\t\t\tPropertyName: \"dns_record\",\n\t\t\tHeader: oamdns.RRHeader{\n\t\t\t\tRRType: int(dns.TypeTXT),\n\t\t\t\tClass: int(record.Header().Class),\n\t\t\t\tTTL: int(record.Header().Ttl),\n\t\t\t},\n\t\t\tData: txtValue,\n\t\t})\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"failed to create entity property for %s: %s\", txtValue, err)\n\t\t\te.Session.Log().Error(msg, \"error\", err.Error(),\n\t\t\t\tslog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t\t}\n\t}\n}\n\nfunc (d *dnsTXT) process(e *et.Event, fqdn *dbt.Entity, txtRecords []dns.RR, props []*oamdns.DNSRecordProperty) {\n\tfor _, record := range txtRecords {\n\t\te.Session.Log().Info(\"TXT record discovered\", \"fqdn\", fqdn.Asset.(*oamdns.FQDN).Name,\n\t\t\t\"txt\", strings.Join((record.(*dns.TXT)).Txt, \" \"), slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n\tfor _, prop := range props {\n\t\te.Session.Log().Info(\"TXT record discovered\", \"fqdn\", fqdn.Asset.(*oamdns.FQDN).Name,\n\t\t\t\"txt\", prop.Data, slog.Group(\"plugin\", \"name\", d.plugin.name, \"handler\", d.name))\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/enrich/banner_url.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enrich\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n\toamurl \"github.com/owasp-amass/open-asset-model/url\"\n)\n\ntype bannerURLs struct {\n\tname string\n\tlog *slog.Logger\n\tsource *et.Source\n}\n\nfunc NewBannerURLs() et.Plugin {\n\treturn &bannerURLs{\n\t\tname: \"Service-Banner-URLs\",\n\t\tsource: &et.Source{\n\t\t\tName: \"Service-Banner-URLs\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (bu *bannerURLs) Name() string {\n\treturn bu.name\n}\n\nfunc (bu *bannerURLs) Start(r et.Registry) error {\n\tbu.log = r.Log().WithGroup(\"plugin\").With(\"name\", bu.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: bu,\n\t\tName: bu.name + \"-Handler\",\n\t\tTransforms: []string{string(oam.URL)},\n\t\tEventType: oam.Service,\n\t\tCallback: bu.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tbu.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (bu *bannerURLs) Stop() {\n\tbu.log.Info(\"Plugin stopped\")\n}\n\nfunc (bu *bannerURLs) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*platform.Service)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Service asset\")\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.Service), string(oam.URL), bu.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar urls []*dbt.Entity\n\t//TODO: urls = append(urls, bu.lookup(e, serv.Identifier, bu.source, since)...)\n\tif !support.AssetMonitoredWithinTTL(e.Session, e.Entity, bu.source, since) {\n\t\turls = append(urls, bu.query(e, e.Entity)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, bu.source)\n\t}\n\n\tif len(urls) > 0 {\n\t\tbu.process(e, urls)\n\t}\n\treturn nil\n}\n\nfunc (bu *bannerURLs) query(e *et.Event, asset *dbt.Entity) []*dbt.Entity {\n\tserv := asset.Asset.(*platform.Service)\n\n\tif serv.OutputLen == 0 {\n\t\treturn nil\n\t}\n\n\tvar results []*oamurl.URL\n\t// TODO: in the future, further investigation of out of scope URLs may be needed\n\tif urls := support.ExtractURLsFromString(serv.Output); len(urls) > 0 {\n\t\tfor _, u := range urls {\n\t\t\tif addr, err := netip.ParseAddr(u.Host); err == nil {\n\t\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamnet.IPAddress{Address: addr}, 0); conf > 0 {\n\t\t\t\t\tresults = append(results, u)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: u.Host}, 0); conf > 0 {\n\t\t\t\t\tresults = append(results, u)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn bu.store(e, results)\n}\n\nfunc (bu *bannerURLs) store(e *et.Event, urls []*oamurl.URL) []*dbt.Entity {\n\tvar assets []*dbt.Entity\n\n\tfor _, u := range urls {\n\t\tif a, err := e.Session.Cache().CreateAsset(u); err == nil && a != nil {\n\t\t\tassets = append(assets, a)\n\t\t\t_, _ = e.Session.Cache().CreateEntityProperty(a, &general.SourceProperty{\n\t\t\t\tSource: bu.source.Name,\n\t\t\t\tConfidence: bu.source.Confidence,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn assets\n}\n\nfunc (bu *bannerURLs) process(e *et.Event, assets []*dbt.Entity) {\n\tfor _, a := range assets {\n\t\tif u, ok := a.Asset.(*oamurl.URL); ok && e.Session.Scope().IsURLInScope(e.Session.Cache(), u) {\n\t\t\tbu.processOneURL(e, u.Raw, a)\n\t\t}\n\t}\n}\n\nfunc (bu *bannerURLs) processOneURL(e *et.Event, name string, asset *dbt.Entity) {\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: name,\n\t\tEntity: asset,\n\t\tSession: e.Session,\n\t})\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/enrich/contact.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enrich\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n)\n\ntype contactrec struct {\n\tname string\n\tlog *slog.Logger\n\ttransforms []string\n\tsource *et.Source\n}\n\nfunc NewContacts() et.Plugin {\n\treturn &contactrec{\n\t\tname: \"Contract-Record-Expansion\",\n\t\ttransforms: []string{\n\t\t\tstring(oam.URL),\n\t\t\tstring(oam.Person),\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Location),\n\t\t\tstring(oam.Identifier),\n\t\t\tstring(oam.Phone),\n\t\t},\n\t\tsource: &et.Source{\n\t\t\tName: \"Contract-Record-Expansion\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (cr *contactrec) Name() string {\n\treturn cr.name\n}\n\nfunc (cr *contactrec) Start(r et.Registry) error {\n\tcr.log = r.Log().WithGroup(\"plugin\").With(\"name\", cr.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: cr,\n\t\tName: cr.name,\n\t\tPriority: 1,\n\t\tTransforms: cr.transforms,\n\t\tEventType: oam.ContactRecord,\n\t\tCallback: cr.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tcr.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (cr *contactrec) Stop() {\n\tcr.log.Info(\"Plugin stopped\")\n}\n\nfunc (cr *contactrec) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*contact.ContactRecord)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the ContactRecord asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.ContactRecord), append(cr.transforms, cr.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tif findings := cr.lookup(e, e.Entity, matches); len(findings) > 0 {\n\t\tcr.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (cr *contactrec) lookup(e *et.Event, entity *dbt.Entity, m *config.Matches) []*support.Finding {\n\tvar rtypes []string\n\tconfs := make(map[string]int)\n\tsinces := make(map[string]time.Time)\n\tconrec := entity.Asset.(*contact.ContactRecord)\n\n\tfor _, atype := range cr.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.ContactRecord), atype, cr.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tconfs[atype] = m.Confidence(atype)\n\t\tif confs[atype] == -1 {\n\t\t\tconfs[atype] = 0\n\t\t}\n\n\t\tswitch atype {\n\t\tcase string(oam.Person):\n\t\t\trtypes = append(rtypes, \"person\")\n\t\tcase string(oam.Organization):\n\t\t\trtypes = append(rtypes, \"organization\")\n\t\tcase string(oam.Location):\n\t\t\trtypes = append(rtypes, \"location\")\n\t\tcase string(oam.Identifier):\n\t\t\trtypes = append(rtypes, \"id\")\n\t\tcase string(oam.Phone):\n\t\t\trtypes = append(rtypes, \"phone\")\n\t\tcase string(oam.URL):\n\t\t\trtypes = append(rtypes, \"url\")\n\t\t}\n\t}\n\n\tvar findings []*support.Finding\n\tif edges, err := e.Session.Cache().OutgoingEdges(entity, time.Time{}, rtypes...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttotype := string(a.Asset.AssetType())\n\t\t\tif since, ok := sinces[totype]; !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: entity,\n\t\t\t\tFromName: \"ContactRecord: \" + conrec.DiscoveredAt,\n\t\t\t\tTo: a,\n\t\t\t\tToName: a.Asset.Key(),\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\treturn findings\n}\n\nfunc (cr *contactrec) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, cr.source, cr.name, cr.name+\"-Handler\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/enrich/email.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enrich\n\nimport (\n\t\"log/slog\"\n\t\"strings\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\ntype emailexpand struct {\n\tname string\n\tlog *slog.Logger\n\tsource *et.Source\n}\n\nfunc NewEmails() et.Plugin {\n\treturn &emailexpand{\n\t\tname: \"Email-Expansion\",\n\t\tsource: &et.Source{\n\t\t\tName: \"Email-Expansion\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (ee *emailexpand) Name() string {\n\treturn ee.name\n}\n\nfunc (ee *emailexpand) Start(r et.Registry) error {\n\tee.log = r.Log().WithGroup(\"plugin\").With(\"name\", ee.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: ee,\n\t\tName: ee.name,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.Identifier,\n\t\tCallback: ee.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tee.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (ee *emailexpand) Stop() {\n\tee.log.Info(\"Plugin stopped\")\n}\n\nfunc (ee *emailexpand) check(e *et.Event) error {\n\tif id, ok := e.Entity.Asset.(*general.Identifier); !ok ||\n\t\tid == nil || id.Type != general.EmailAddress || id.ID == \"\" {\n\t\treturn nil\n\t}\n\n\tif findings := ee.store(e, e.Entity); len(findings) > 0 {\n\t\tee.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (ee *emailexpand) store(e *et.Event, asset *dbt.Entity) []*support.Finding {\n\tvar findings []*support.Finding\n\toame := asset.Asset.(*general.Identifier)\n\n\tparts := strings.Split(oame.ID, \"@\")\n\tif len(parts) != 2 {\n\t\treturn findings\n\t}\n\tdomain := parts[1]\n\n\tif cr, err := e.Session.Cache().CreateAsset(&contact.ContactRecord{DiscoveredAt: domain}); err == nil && cr != nil {\n\t\tfindings = append(findings, &support.Finding{\n\t\t\tFrom: asset,\n\t\t\tFromName: \"Identifier: \" + asset.Asset.Key(),\n\t\t\tTo: cr,\n\t\t\tToName: \"ContactRecord: \" + cr.Asset.Key(),\n\t\t\tRel: &general.SimpleRelation{Name: \"registration_agency\"},\n\t\t})\n\n\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: domain}); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: cr,\n\t\t\t\tFromName: \"ContactRecord: \" + cr.Asset.Key(),\n\t\t\t\tTo: a,\n\t\t\t\tToName: a.Asset.Key(),\n\t\t\t\tRel: &general.SimpleRelation{Name: \"fqdn\"},\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (ee *emailexpand) process(e *et.Event, findings []*support.Finding) {\n\tfor _, f := range findings {\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: f.Rel,\n\t\t\tFromEntity: f.From,\n\t\t\tToEntity: f.To,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: ee.source.Name,\n\t\t\t\tConfidence: ee.source.Confidence,\n\t\t\t})\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/enrich/tls_cert.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enrich\n\nimport (\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\ntype tlsexpand struct {\n\tname string\n\tlog *slog.Logger\n\ttransforms []string\n\tsource *et.Source\n}\n\nfunc NewTLSCerts() et.Plugin {\n\treturn &tlsexpand{\n\t\tname: \"TLCert-Expansion\",\n\t\ttransforms: []string{\n\t\t\tstring(oam.URL),\n\t\t\tstring(oam.FQDN),\n\t\t\tstring(oam.IPAddress),\n\t\t\tstring(oam.ContactRecord),\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Location),\n\t\t\tstring(oam.Identifier),\n\t\t\tstring(oam.TLSCertificate),\n\t\t},\n\t\tsource: &et.Source{\n\t\t\tName: \"TLCert-Expansion\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (te *tlsexpand) Name() string {\n\treturn te.name\n}\n\nfunc (te *tlsexpand) Start(r et.Registry) error {\n\tte.log = r.Log().WithGroup(\"plugin\").With(\"name\", te.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: te,\n\t\tName: te.name,\n\t\tTransforms: te.transforms,\n\t\tEventType: oam.TLSCertificate,\n\t\tCallback: te.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tte.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (te *tlsexpand) Stop() {\n\tte.log.Info(\"Plugin stopped\")\n}\n\nfunc (te *tlsexpand) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamcert.TLSCertificate)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the TLSCertificate asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.TLSCertificate), append(te.transforms, te.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tvar findings []*support.Finding\n\tif cert, ok := e.Meta.(*x509.Certificate); ok && cert != nil {\n\t\tte.store(e, cert, e.Entity, matches)\n\t} else {\n\t\tfindings = append(findings, te.lookup(e, e.Entity, matches)...)\n\t}\n\n\tif len(findings) > 0 {\n\t\tte.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (te *tlsexpand) lookup(e *et.Event, asset *dbt.Entity, m *config.Matches) []*support.Finding {\n\tvar rtypes []string\n\tvar findings []*support.Finding\n\tsinces := make(map[string]time.Time)\n\n\tfor _, atype := range te.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.TLSCertificate), atype, te.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tswitch atype {\n\t\tcase string(oam.URL):\n\t\t\trtypes = append(rtypes, \"san_url\", \"ocsp_server\", \"issuing_certificate_url\")\n\t\tcase string(oam.FQDN):\n\t\t\trtypes = append(rtypes, \"common_name\", \"san_dns_name\")\n\t\tcase string(oam.ContactRecord):\n\t\t\trtypes = append(rtypes, \"subject_contact\", \"issuer_contact\")\n\t\tcase string(oam.IPAddress):\n\t\t\trtypes = append(rtypes, \"san_ip_address\")\n\t\tcase string(oam.Identifier):\n\t\t\trtypes = append(rtypes, \"san_email_address\")\n\t\tcase string(oam.TLSCertificate):\n\t\t\trtypes = append(rtypes, \"issuing_certificate\")\n\t\t}\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(asset, time.Time{}, rtypes...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotype := string(a.Asset.AssetType())\n\n\t\t\tsince, ok := sinces[totype]\n\t\t\tif !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !te.oneOfSources(e, edge, te.source, since) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tt := asset.Asset.(*oamcert.TLSCertificate)\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\tTo: a,\n\t\t\t\tToName: a.Asset.Key(),\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (te *tlsexpand) oneOfSources(e *et.Event, edge *dbt.Edge, src *et.Source, since time.Time) bool {\n\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, src.Name); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (te *tlsexpand) store(e *et.Event, cert *x509.Certificate, asset *dbt.Entity, m *config.Matches) {\n\tvar findings []*support.Finding\n\tt := asset.Asset.(*oamcert.TLSCertificate)\n\n\tif m.IsMatch(string(oam.FQDN)) {\n\t\tif common := t.SubjectCommonName; common != \"\" {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: common}); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: asset,\n\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: common,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"common_name\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tfor _, n := range cert.DNSNames {\n\t\t\tfor _, name := range support.ScrapeSubdomainNames(strings.ToLower(strings.TrimSpace(n))) {\n\t\t\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name}); err == nil && a != nil {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: asset,\n\t\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\t\tTo: a,\n\t\t\t\t\t\tToName: name,\n\t\t\t\t\t\tRel: &general.SimpleRelation{Name: \"san_dns_name\"},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif m.IsMatch(string(oam.Identifier)) {\n\t\tfor _, emailstr := range cert.EmailAddresses {\n\t\t\temail := strings.ToLower(strings.TrimSpace(emailstr))\n\t\t\tif email == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif a, err := e.Session.Cache().CreateAsset(&general.Identifier{\n\t\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.EmailAddress, email),\n\t\t\t\tID: email,\n\t\t\t\tType: general.EmailAddress,\n\t\t\t}); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: asset,\n\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: email,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"san_email_address\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif m.IsMatch(string(oam.IPAddress)) {\n\t\tfor _, ip := range cert.IPAddresses {\n\t\t\toamip := &network.IPAddress{Address: netip.MustParseAddr(ip.String())}\n\n\t\t\tif oamip.Address.Is4() {\n\t\t\t\toamip.Type = \"IPv4\"\n\t\t\t} else {\n\t\t\t\toamip.Type = \"IPv6\"\n\t\t\t}\n\n\t\t\tif a, err := e.Session.Cache().CreateAsset(oamip); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: asset,\n\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: oamip.Address.String(),\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"san_ip_address\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif m.IsMatch(string(oam.URL)) {\n\t\tfor _, u := range cert.URIs {\n\t\t\tif oamurl := support.RawURLToOAM(u.String()); oamurl != nil {\n\t\t\t\tif a, err := e.Session.Cache().CreateAsset(oamurl); err == nil && a != nil {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: asset,\n\t\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\t\tTo: a,\n\t\t\t\t\t\tToName: oamurl.Raw,\n\t\t\t\t\t\tRel: &general.SimpleRelation{Name: \"san_url\"},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor _, u := range cert.IssuingCertificateURL {\n\t\t\tif oamurl := support.RawURLToOAM(u); oamurl != nil {\n\t\t\t\tif a, err := e.Session.Cache().CreateAsset(oamurl); err == nil && a != nil {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: asset,\n\t\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\t\tTo: a,\n\t\t\t\t\t\tToName: oamurl.Raw,\n\t\t\t\t\t\tRel: &general.SimpleRelation{Name: \"issuing_certificate_url\"},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor _, u := range cert.OCSPServer {\n\t\t\tif oamurl := support.RawURLToOAM(u); oamurl != nil {\n\t\t\t\tif a, err := e.Session.Cache().CreateAsset(oamurl); err == nil && a != nil {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: asset,\n\t\t\t\t\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\t\t\t\t\tTo: a,\n\t\t\t\t\t\tToName: oamurl.Raw,\n\t\t\t\t\t\tRel: &general.SimpleRelation{Name: \"ocsp_server\"},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// process the relations built so far from the certificate\n\tsupport.ProcessAssetsWithSource(e, findings, te.source, te.name, te.name+\"-Handler\")\n\n\tif m.IsMatch(string(oam.ContactRecord)) {\n\t\tbase := \"x509 Certificate: \" + cert.SerialNumber.String() + \", \"\n\t\tcontacts := []*tlsContact{\n\t\t\t{&cert.Subject, \"subject_contact\", base + \"Subject\"},\n\t\t\t{&cert.Issuer, \"issuer_contact\", base + \"Issuer\"},\n\t\t}\n\t\tfor _, c := range contacts {\n\t\t\tte.storeContact(e, c, asset, te.source, m)\n\t\t}\n\t}\n}\n\ntype tlsContact struct {\n\tcontact *pkix.Name\n\tRelationName string\n\tDiscoveredAt string\n}\n\nfunc (te *tlsexpand) storeContact(e *et.Event, c *tlsContact, asset *dbt.Entity, src *et.Source, m *config.Matches) {\n\tct := c.contact\n\n\tvar foundaddr bool\n\tif len(ct.Province) > 0 && len(ct.Country) > 0 {\n\t\tfoundaddr = true\n\t}\n\n\tvar foundorgs bool\n\tif len(ct.Organization) > 0 {\n\t\tfoundorgs = true\n\t}\n\t// only continue with the database operations if there's a contact record to create\n\tif !foundaddr && !foundorgs {\n\t\treturn\n\t}\n\n\tcr, err := e.Session.Cache().CreateAsset(&contact.ContactRecord{DiscoveredAt: c.DiscoveredAt})\n\tif err != nil || cr == nil {\n\t\treturn\n\t}\n\n\tif foundaddr && m.IsMatch(string(oam.Location)) {\n\t\tvar addr string\n\t\tfields := [][]string{\n\t\t\tct.Organization,\n\t\t\tct.StreetAddress,\n\t\t\tct.Locality,\n\t\t\tct.Province,\n\t\t\tct.PostalCode,\n\t\t\tct.Country,\n\t\t}\n\t\tfor _, field := range fields {\n\t\t\tif len(field) > 0 && field[0] != \"\" {\n\t\t\t\taddr += \" \" + field[0]\n\t\t\t}\n\t\t}\n\t\tif loc := support.StreetAddressToLocation(strings.TrimSpace(addr)); loc != nil {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(loc); err == nil && a != nil {\n\t\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &general.SimpleRelation{Name: \"location\"},\n\t\t\t\t\tFromEntity: cr,\n\t\t\t\t\tToEntity: a,\n\t\t\t\t}); err == nil && edge != nil {\n\t\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\t\tSource: src.Name,\n\t\t\t\t\t\tConfidence: src.Confidence,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\t\tName: loc.Address,\n\t\t\t\t\tEntity: a,\n\t\t\t\t\tSession: e.Session,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\tif len(ct.OrganizationalUnit) > 0 && ct.OrganizationalUnit[0] != \"\" && m.IsMatch(string(oam.URL)) {\n\t\tif u := support.ExtractURLFromString(ct.OrganizationalUnit[0]); u != nil {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(u); err == nil && a != nil {\n\t\t\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\t\t\tRelation: &general.SimpleRelation{Name: \"url\"},\n\t\t\t\t\tFromEntity: cr,\n\t\t\t\t\tToEntity: a,\n\t\t\t\t}); err == nil && edge != nil {\n\t\t\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\t\t\tSource: src.Name,\n\t\t\t\t\t\tConfidence: src.Confidence,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar findings []*support.Finding\n\tt := asset.Asset.(*oamcert.TLSCertificate)\n\tfindings = append(findings, &support.Finding{\n\t\tFrom: asset,\n\t\tFromName: \"TLSCertificate: \" + t.SerialNumber,\n\t\tTo: cr,\n\t\tToName: \"ContactRecord\" + c.DiscoveredAt,\n\t\tRel: &general.SimpleRelation{Name: c.RelationName},\n\t})\n\t// process the relation immediately\n\tsupport.ProcessAssetsWithSource(e, findings, te.source, te.name, te.name+\"-Handler\")\n\n\t// the organization must come last due to a potential chicken-and-egg problem\n\tif m.IsMatch(string(oam.Organization)) && len(ct.Organization) > 0 && ct.Organization[0] != \"\" {\n\t\torgent, err := org.CreateOrgAsset(e.Session, cr,\n\t\t\t&general.SimpleRelation{Name: \"organization\"},\n\t\t\t&oamorg.Organization{Name: ct.Organization[0]}, src)\n\n\t\tif err == nil && orgent != nil {\n\t\t\to := orgent.Asset.(*oamorg.Organization)\n\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: fmt.Sprintf(\"%s:%s\", o.Name, o.ID),\n\t\t\t\tEntity: orgent,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc (te *tlsexpand) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, te.source, te.name, te.name+\"-Handler\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/enrich/url.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enrich\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/netip\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n)\n\ntype urlexpand struct {\n\tname string\n\tlog *slog.Logger\n\ttransforms []string\n\tsource *et.Source\n}\n\nfunc NewURLs() et.Plugin {\n\treturn &urlexpand{\n\t\tname: \"URL-Expansion\",\n\t\ttransforms: []string{\n\t\t\tstring(oam.FQDN),\n\t\t\tstring(oam.IPAddress),\n\t\t\tstring(oam.Service),\n\t\t\tstring(oam.File),\n\t\t},\n\t\tsource: &et.Source{\n\t\t\tName: \"URL-Expansion\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (u *urlexpand) Name() string {\n\treturn u.name\n}\n\nfunc (u *urlexpand) Start(r et.Registry) error {\n\tu.log = r.Log().WithGroup(\"plugin\").With(\"name\", u.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: u,\n\t\tName: u.name,\n\t\tTransforms: u.transforms,\n\t\tEventType: oam.URL,\n\t\tCallback: u.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tu.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (u *urlexpand) Stop() {\n\tu.log.Info(\"Plugin stopped\")\n}\n\nfunc (u *urlexpand) check(e *et.Event) error {\n\toamu, ok := e.Entity.Asset.(*url.URL)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the URL asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(string(oam.URL), append(u.transforms, u.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tvar tstr string\n\tvar inscope bool\n\tif addr, err := netip.ParseAddr(oamu.Host); err == nil {\n\t\ttstr = string(oam.IPAddress)\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamnet.IPAddress{Address: addr}, 0); conf > 0 {\n\t\t\tinscope = true\n\t\t}\n\t} else {\n\t\ttstr = string(oam.FQDN)\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: oamu.Host}, 0); conf > 0 {\n\t\t\tinscope = true\n\t\t}\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.URL), tstr, u.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar findings []*support.Finding\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, u.source, since) {\n\t\tif inscope {\n\t\t\tfindings = append(findings, u.lookup(e, e.Entity, matches)...)\n\t\t}\n\t} else {\n\t\tfindings = append(findings, u.store(e, tstr, e.Entity, matches)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, u.source)\n\t}\n\n\tif inscope && len(findings) > 0 {\n\t\tu.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (u *urlexpand) lookup(e *et.Event, asset *dbt.Entity, m *config.Matches) []*support.Finding {\n\trtypes := stringset.New()\n\tdefer rtypes.Close()\n\n\tvar findings []*support.Finding\n\tsinces := make(map[string]time.Time)\n\tfor _, atype := range u.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.URL), atype, u.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tswitch atype {\n\t\tcase string(oam.FQDN):\n\t\t\trtypes.Insert(\"domain\")\n\t\tcase string(oam.IPAddress):\n\t\t\trtypes.Insert(\"ip_address\")\n\t\tcase string(oam.Service):\n\t\t\trtypes.Insert(\"port\")\n\t\tcase string(oam.File):\n\t\t\trtypes.Insert(\"file\")\n\t\t}\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(asset, time.Time{}, rtypes.Slice()...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttotype := string(a.Asset.AssetType())\n\t\t\tif since, ok := sinces[totype]; !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toamu := asset.Asset.(*url.URL)\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"URL: \" + oamu.Raw,\n\t\t\t\tTo: a,\n\t\t\t\tToName: a.Asset.Key(),\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (u *urlexpand) store(e *et.Event, tstr string, asset *dbt.Entity, m *config.Matches) []*support.Finding {\n\toamu := asset.Asset.(*url.URL)\n\tvar findings []*support.Finding\n\n\tif tstr == string(oam.FQDN) && m.IsMatch(string(oam.FQDN)) {\n\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: oamu.Host}); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"URL: \" + oamu.Raw,\n\t\t\t\tTo: a,\n\t\t\t\tToName: oamu.Host,\n\t\t\t\tRel: &general.SimpleRelation{Name: \"domain\"},\n\t\t\t})\n\t\t}\n\t} else if ip, err := netip.ParseAddr(oamu.Host); err == nil && m.IsMatch(string(oam.IPAddress)) {\n\t\tntype := \"IPv4\"\n\t\tif ip.Is6() {\n\t\t\tntype = \"IPv6\"\n\t\t}\n\n\t\tif a, err := e.Session.Cache().CreateAsset(&oamnet.IPAddress{\n\t\t\tAddress: ip,\n\t\t\tType: ntype,\n\t\t}); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"URL: \" + oamu.Raw,\n\t\t\t\tTo: a,\n\t\t\t\tToName: ip.String(),\n\t\t\t\tRel: &general.SimpleRelation{Name: \"ip_address\"},\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (u *urlexpand) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, u.source, u.name, u.name+\"-Handler\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/horizontals/contact.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage horizontals\n\nimport (\n\t\"errors\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/sessions/scope\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n)\n\ntype horContact struct {\n\tname string\n\tplugin *horizPlugin\n}\n\nfunc (h *horContact) Name() string {\n\treturn h.name\n}\n\nfunc (h *horContact) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*contact.ContactRecord)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the ContactRecord asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.ContactRecord), string(oam.ContactRecord), h.plugin.name)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tconf := matches.Confidence(h.plugin.name)\n\tif conf == -1 {\n\t\tconf = matches.Confidence(string(oam.ContactRecord))\n\t}\n\n\tif assocs := h.lookup(e, e.Entity, conf); len(assocs) > 0 {\n\t\tvar impacted []*dbt.Entity\n\n\t\tfor _, assoc := range assocs {\n\t\t\tif assoc.ScopeChange {\n\t\t\t\th.plugin.log.Info(assoc.Rationale)\n\t\t\t\timpacted = append(impacted, assoc.ImpactedAssets...)\n\t\t\t}\n\t\t}\n\n\t\tif len(impacted) > 0 {\n\t\t\th.plugin.process(e, impacted)\n\t\t\th.plugin.addAssociatedRelationship(e, assocs)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (h *horContact) lookup(e *et.Event, entity *dbt.Entity, conf int) []*scope.Association {\n\tlabels := []string{\"organization\", \"location\", \"id\"}\n\n\tvar results []*scope.Association\n\tif edges, err := e.Session.Cache().OutgoingEdges(entity,\n\t\te.Session.Cache().StartTime(), labels...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tentity, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// check if these asset discoveries could change the scope\n\t\t\tif assocs, err := e.Session.Scope().IsAssociated(e.Session.Cache(), &scope.Association{\n\t\t\t\tSubmission: entity,\n\t\t\t\tConfidence: conf,\n\t\t\t\tScopeChange: true,\n\t\t\t}); err == nil && len(assocs) > 0 {\n\t\t\t\tresults = append(results, assocs...)\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/horizontals/fqdn.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage horizontals\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions/scope\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype horfqdn struct {\n\tname string\n\tplugin *horizPlugin\n}\n\nfunc (h *horfqdn) Name() string {\n\treturn h.name\n}\n\nfunc (h *horfqdn) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tvar ptrs []*dbt.Edge\n\tif edges, err := e.Session.Cache().OutgoingEdges(e.Entity, e.Session.Cache().StartTime(), \"dns_record\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif rel, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && rel.Header.RRType == 12 {\n\t\t\t\tptrs = append(ptrs, edge)\n\t\t\t}\n\t\t}\n\t}\n\tif len(ptrs) == 0 {\n\t\tif !support.HasDNSRecordType(e, int(dns.TypeA)) &&\n\t\t\t!support.HasDNSRecordType(e, int(dns.TypeAAAA)) &&\n\t\t\t!support.HasDNSRecordType(e, int(dns.TypeCNAME)) {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif _, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf > 0 {\n\t\treturn nil\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(string(oam.FQDN), string(oam.FQDN), h.plugin.name)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tconf := matches.Confidence(h.plugin.name)\n\tif conf == -1 {\n\t\tconf = matches.Confidence(string(oam.FQDN))\n\t}\n\n\tif len(ptrs) > 0 {\n\t\th.checkPTR(e, ptrs, e.Entity)\n\t\treturn nil\n\t}\n\n\tif assocs := h.lookup(e, e.Entity, conf); len(assocs) > 0 {\n\t\tvar impacted []*dbt.Entity\n\n\t\tfor _, assoc := range assocs {\n\t\t\tif assoc.ScopeChange {\n\t\t\t\th.plugin.log.Info(assoc.Rationale)\n\t\t\t\timpacted = append(impacted, assoc.ImpactedAssets...)\n\t\t\t}\n\t\t}\n\n\t\tvar assets []*dbt.Entity\n\t\tfor _, im := range impacted {\n\t\t\tif a, err := e.Session.Cache().FindEntitiesByContent(im.Asset,\n\t\t\t\te.Session.Cache().StartTime()); err == nil && len(a) == 1 {\n\t\t\t\tassets = append(assets, a[0])\n\t\t\t} else if n := h.store(e, im.Asset); n != nil {\n\t\t\t\tassets = append(assets, n)\n\t\t\t}\n\t\t}\n\n\t\tif len(assets) > 0 {\n\t\t\th.plugin.process(e, assets)\n\t\t\th.plugin.addAssociatedRelationship(e, assocs)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (h *horfqdn) checkPTR(e *et.Event, edges []*dbt.Edge, fqdn *dbt.Entity) {\n\tif ins, err := e.Session.Cache().IncomingEdges(fqdn, e.Session.Cache().StartTime(), \"ptr_record\"); err == nil && len(ins) > 0 {\n\t\tfor _, r := range ins {\n\t\t\tfrom, err := e.Session.Cache().FindEntityById(r.FromEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tip, ok := from.Asset.(*oamnet.IPAddress)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar inscope bool\n\t\t\t_, conf := e.Session.Scope().IsAssetInScope(ip, 0)\n\t\t\tif conf > 0 {\n\t\t\t\tinscope = true\n\t\t\t}\n\n\t\t\tfor _, edge := range edges {\n\t\t\t\tto, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif inscope {\n\t\t\t\t\tif dom, err := publicsuffix.EffectiveTLDPlusOne(to.Asset.Key()); err == nil && dom != \"\" {\n\t\t\t\t\t\tif e.Session.Scope().AddDomain(dom) {\n\t\t\t\t\t\t\th.plugin.log.Info(fmt.Sprintf(\"[%s: %s] was added to the session scope\", \"FQDN\", dom))\n\t\t\t\t\t\t}\n\t\t\t\t\t\th.plugin.submitFQDN(e, dom)\n\t\t\t\t\t}\n\t\t\t\t} else if _, conf := e.Session.Scope().IsAssetInScope(to.Asset, 0); conf > 0 {\n\t\t\t\t\tif e.Session.Scope().Add(ip) {\n\t\t\t\t\t\tsize := 100\n\t\t\t\t\t\tif e.Session.Config().Active {\n\t\t\t\t\t\t\tsize = 250\n\t\t\t\t\t\t}\n\t\t\t\t\t\th.plugin.submitIPAddresses(e, ip, h.plugin.source)\n\t\t\t\t\t\tsupport.IPAddressSweep(e, ip, h.plugin.source, size, h.plugin.submitIPAddresses)\n\t\t\t\t\t\th.plugin.log.Info(fmt.Sprintf(\"[%s: %s] was added to the session scope\", ip.AssetType(), ip.Key()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *horfqdn) lookup(e *et.Event, asset *dbt.Entity, conf int) []*scope.Association {\n\tassocs, err := e.Session.Scope().IsAssociated(e.Session.Cache(), &scope.Association{\n\t\tSubmission: asset,\n\t\tConfidence: conf,\n\t\tScopeChange: true,\n\t})\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn assocs\n}\n\nfunc (h *horfqdn) store(e *et.Event, asset oam.Asset) *dbt.Entity {\n\ta, err := e.Session.Cache().CreateAsset(asset)\n\tif err != nil || a == nil {\n\t\treturn nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(a, &general.SourceProperty{\n\t\tSource: h.plugin.source.Name,\n\t\tConfidence: h.plugin.source.Confidence,\n\t})\n\treturn a\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/horizontals/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage horizontals\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions/scope\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/owasp-amass/resolve/utils\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype horizPlugin struct {\n\tname string\n\tlog *slog.Logger\n\thorfqdn *horfqdn\n\thorContact *horContact\n\tsource *et.Source\n}\n\nfunc NewHorizontals() et.Plugin {\n\treturn &horizPlugin{\n\t\tname: \"Horizontals\",\n\t\tsource: &et.Source{\n\t\t\tName: \"Horizontals\",\n\t\t\tConfidence: 50,\n\t\t},\n\t}\n}\n\nfunc (h *horizPlugin) Name() string {\n\treturn h.name\n}\n\nfunc (h *horizPlugin) Start(r et.Registry) error {\n\th.log = r.Log().WithGroup(\"plugin\").With(\"name\", h.name)\n\n\th.horfqdn = &horfqdn{\n\t\tname: h.name + \"-FQDN-Handler\",\n\t\tplugin: h,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: h,\n\t\tName: h.horfqdn.name,\n\t\tPriority: 6,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: h.horfqdn.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\th.horContact = &horContact{\n\t\tname: h.name + \"-ContactRecord-Handler\",\n\t\tplugin: h,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: h,\n\t\tName: h.horContact.name,\n\t\tTransforms: []string{string(oam.ContactRecord)},\n\t\tEventType: oam.ContactRecord,\n\t\tCallback: h.horContact.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\th.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (h *horizPlugin) Stop() {\n\th.log.Info(\"Plugin stopped\")\n}\n\nfunc (h *horizPlugin) addAssociatedRelationship(e *et.Event, assocs []*scope.Association) {\n\tfor _, assoc := range assocs {\n\t\tfor _, impacted := range assoc.ImpactedAssets {\n\t\t\tconf := 50\n\n\t\t\tif e.Session.Config().DefaultTransformations != nil {\n\t\t\t\tif c := e.Session.Config().DefaultTransformations.Confidence; c > 0 {\n\t\t\t\t\tconf = c\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif match, result := e.Session.Scope().IsAssetInScope(impacted.Asset, conf); result >= conf && match != nil {\n\t\t\t\tif a, err := e.Session.Cache().FindEntitiesByContent(match, e.Session.Cache().StartTime()); err == nil && len(a) == 1 {\n\t\t\t\t\tfor _, assoc2 := range e.Session.Scope().AssetsWithAssociation(e.Session.Cache(), a[0]) {\n\t\t\t\t\t\th.makeAssocRelationshipEntries(e, assoc.Match, assoc2)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// TODO: this needs to be cleaned up\nfunc (h *horizPlugin) makeAssocRelationshipEntries(e *et.Event, assoc, assoc2 *dbt.Entity) {\n\t// do not connect an asset to itself\n\tif assoc.ID == assoc2.ID {\n\t\treturn\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"associated_with\"},\n\t\tFromEntity: assoc,\n\t\tToEntity: assoc2,\n\t})\n\t_, _ = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"associated_with\"},\n\t\tFromEntity: assoc2,\n\t\tToEntity: assoc,\n\t})\n}\n\nfunc (h *horizPlugin) process(e *et.Event, assets []*dbt.Entity) {\n\tfor _, asset := range assets {\n\t\t// check for new networks added to the scope\n\t\tswitch v := asset.Asset.(type) {\n\t\tcase *oamnet.Netblock:\n\t\t\th.ipPTRTargetsInScope(e, asset)\n\t\t\th.sweepAroundIPs(e, asset)\n\t\t\t//h.sweepNetblock(e, v, src)\n\t\tcase *oamreg.IPNetRecord:\n\t\t\tif ents, err := e.Session.Cache().FindEntitiesByContent(\n\t\t\t\t&oamnet.Netblock{CIDR: v.CIDR, Type: v.Type}, e.Session.Cache().StartTime()); err == nil && len(ents) == 1 {\n\t\t\t\ta := ents[0]\n\n\t\t\t\tif _, ok := a.Asset.(*oamnet.Netblock); ok {\n\t\t\t\t\th.ipPTRTargetsInScope(e, a)\n\t\t\t\t\th.sweepAroundIPs(e, a)\n\t\t\t\t\t//h.sweepNetblock(e, nb, src)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: asset.Asset.Key(),\n\t\t\tEntity: asset,\n\t\t\tSession: e.Session,\n\t\t})\n\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(asset, &general.SourceProperty{\n\t\t\tSource: h.source.Name,\n\t\t\tConfidence: h.source.Confidence,\n\t\t})\n\t}\n}\n\nfunc (h *horizPlugin) ipPTRTargetsInScope(e *et.Event, nb *dbt.Entity) {\n\tif edges, err := e.Session.Cache().OutgoingEdges(nb, e.Session.Cache().StartTime(), \"contains\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tto, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treverse, err := dns.ReverseAddr(to.Asset.Key())\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ents, err := e.Session.Cache().FindEntitiesByContent(\n\t\t\t\t&oamdns.FQDN{Name: utils.RemoveLastDot(reverse)}, e.Session.Cache().StartTime()); err == nil && len(ents) == 1 {\n\t\t\t\ta := ents[0]\n\n\t\t\t\tif edges, err := e.Session.Cache().OutgoingEdges(a, e.Session.Cache().StartTime(), \"dns_record\"); err == nil && len(edges) > 0 {\n\t\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\t\tif rel, ok := edge.Relation.(*oamdns.BasicDNSRelation); !ok || rel.Header.RRType != 12 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tto, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif dom, err := publicsuffix.EffectiveTLDPlusOne(to.Asset.Key()); err == nil {\n\t\t\t\t\t\t\tif e.Session.Scope().AddDomain(dom) {\n\t\t\t\t\t\t\t\th.submitFQDN(e, dom)\n\t\t\t\t\t\t\t\th.log.Info(fmt.Sprintf(\"[%s: %s] was added to the session scope\", \"FQDN\", dom))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *horizPlugin) sweepAroundIPs(e *et.Event, nb *dbt.Entity) {\n\tif edges, err := e.Session.Cache().OutgoingEdges(nb, e.Session.Cache().StartTime(), \"contains\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tsize := 100\n\t\t\tif e.Session.Config().Active {\n\t\t\t\tsize = 250\n\t\t\t}\n\n\t\t\tto, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ip, ok := to.Asset.(*oamnet.IPAddress); ok {\n\t\t\t\tsupport.IPAddressSweep(e, ip, h.source, size, h.submitIPAddresses)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*\n\tfunc (h *horizPlugin) sweepNetblock(e *et.Event, nb *oamnet.Netblock, src *et.Source) {\n\t\tfor _, ip := range h.inScopeNetblockIPs(nb) {\n\t\t\th.submitIPAddresses(e, ip, src)\n\t\t}\n\t}\n\n\tfunc (h *horizPlugin) inScopeNetblockIPs(nb *oamnet.Netblock) []*oamnet.IPAddress {\n\t\t_, cidr, err := net.ParseCIDR(nb.CIDR.String())\n\t\tif err != nil {\n\t\t\treturn []*oamnet.IPAddress{}\n\t\t}\n\n\t\tvar ips []net.IP\n\t\tif nb.CIDR.Masked().Bits() > 20 {\n\t\t\tips = amassnet.AllHosts(cidr)\n\t\t} else {\n\t\t\tips = h.distAcrossNetblock(cidr, 2048)\n\t\t}\n\n\t\tvar results []*oamnet.IPAddress\n\t\tfor _, ip := range ips {\n\t\t\taddr := &oamnet.IPAddress{Address: netip.MustParseAddr(ip.String()), Type: \"IPv4\"}\n\t\t\tif addr.Address.Is6() {\n\t\t\t\taddr.Type = \"IPv6\"\n\t\t\t}\n\t\t\tresults = append(results, addr)\n\t\t}\n\t\treturn results\n\t}\n\n\tfunc (h *horizPlugin) distAcrossNetblock(cidr *net.IPNet, num int) []net.IP {\n\t\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\t_, bits := cidr.Mask.Size()\n\t\tif bits == 0 {\n\t\t\treturn []net.IP{}\n\t\t}\n\n\t\ttotal := 1 << bits\n\t\tinc := total / num\n\t\tvar results []net.IP\n\t\tfor ip := cidr.IP.Mask(cidr.Mask); cidr.Contains(ip); {\n\t\t\tsel := r.Intn(inc)\n\n\t\t\tfor i := 0; i < inc; i++ {\n\t\t\t\tif i == sel {\n\t\t\t\t\tresults = append(results, net.ParseIP(ip.String()))\n\t\t\t\t}\n\t\t\t\tamassnet.IPInc(ip)\n\t\t\t}\n\t\t}\n\t\treturn results\n\t}\n*/\nfunc (h *horizPlugin) submitIPAddresses(e *et.Event, asset *oamnet.IPAddress, src *et.Source) {\n\taddr, err := e.Session.Cache().CreateAsset(asset)\n\tif err == nil && addr != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(addr, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: addr.Asset.Key(),\n\t\t\tEntity: addr,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\nfunc (h *horizPlugin) submitFQDN(e *et.Event, dom string) {\n\tfqdn, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: dom})\n\tif err == nil && fqdn != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(fqdn, &general.SourceProperty{\n\t\t\tSource: h.source.Name,\n\t\t\tConfidence: h.source.Confidence,\n\t\t})\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fqdn.Asset.Key(),\n\t\t\tEntity: fqdn,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/bing.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype bing struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewBing() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &bing{\n\t\tname: \"Bing\",\n\t\tfmtstr: \"https://www.ask.com/web?o=0&l=dir&qo=pagination&page=%d&q=site:%s -www.%s\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"Bing\",\n\t\t\tConfidence: 60,\n\t\t},\n\t}\n}\n\nfunc (b *bing) Name() string {\n\treturn b.name\n}\n\nfunc (b *bing) Start(r et.Registry) error {\n\tb.log = r.Log().WithGroup(\"plugin\").With(\"name\", b.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: b,\n\t\tName: b.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: b.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tb.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (b *bing) Stop() {\n\tb.log.Info(\"Plugin stopped\")\n}\n\nfunc (b *bing) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, b.source, since) {\n\t\tnames = append(names, b.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, b.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, b.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tb.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (b *bing) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), b.source, since)\n}\n\nfunc (b *bing) query(e *et.Event, name string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\tfor i := 1; i < 10; i++ {\n\t\t_ = b.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(b.fmtstr, i, name, name)})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, n := range support.ScrapeSubdomainNames(resp.Body) {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tsubs.Insert(nstr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn b.store(e, subs.Slice())\n}\n\nfunc (b *bing) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, b.source, b.name, b.name+\"-Handler\")\n}\n\nfunc (b *bing) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, b.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/dnshistory.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype dnsHistory struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewDNSHistory() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &dnsHistory{\n\t\tname: \"DNSHistory\",\n\t\tfmtstr: \"https://dnshistory.org/subdomains/%d/%s\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"DNSHistory\",\n\t\t\tConfidence: 60,\n\t\t},\n\t}\n}\n\nfunc (d *dnsHistory) Name() string {\n\treturn d.name\n}\n\nfunc (d *dnsHistory) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *dnsHistory) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *dnsHistory) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), d.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\tnames = append(names, d.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, d.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, d.source)\n\t}\n\n\tif len(names) > 0 {\n\t\td.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (d *dnsHistory) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), d.source, since)\n}\n\nfunc (d *dnsHistory) query(e *et.Event, name string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\tfor i := 1; i < 20; i++ {\n\t\t_ = d.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(d.fmtstr, i, name)})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, n := range support.ScrapeSubdomainNames(resp.Body) {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tsubs.Insert(nstr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn d.store(e, subs.Slice())\n}\n\nfunc (d *dnsHistory) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, d.source, d.name, d.name+\"-Handler\")\n}\n\nfunc (d *dnsHistory) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, d.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/duckduckgo.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype duckDuckGo struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewDuckDuckGo() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &duckDuckGo{\n\t\tname: \"DuckDuckGo\",\n\t\tfmtstr: \"https://html.duckduckgo.com/html/?q=site:%s -site:www.%s\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"DuckDuckGo\",\n\t\t\tConfidence: 60,\n\t\t},\n\t}\n}\n\nfunc (d *duckDuckGo) Name() string {\n\treturn d.name\n}\n\nfunc (d *duckDuckGo) Start(r et.Registry) error {\n\td.log = r.Log().WithGroup(\"plugin\").With(\"name\", d.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: d,\n\t\tName: d.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: d.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\td.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (d *duckDuckGo) Stop() {\n\td.log.Info(\"Plugin stopped\")\n}\n\nfunc (d *duckDuckGo) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), d.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, d.source, since) {\n\t\tnames = append(names, d.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, d.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, d.source)\n\t}\n\n\tif len(names) > 0 {\n\t\td.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (d *duckDuckGo) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), d.source, since)\n}\n\nfunc (d *duckDuckGo) query(e *et.Event, name string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\t_ = d.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(d.fmtstr, name, name)})\n\tif err != nil || resp.Body == \"\" {\n\t\treturn nil\n\t}\n\n\tfor _, n := range support.ScrapeSubdomainNames(resp.Body) {\n\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t// if the subdomain is not in scope, skip it\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\tsubs.Insert(nstr)\n\t\t}\n\t}\n\n\treturn d.store(e, subs.Slice())\n}\n\nfunc (d *duckDuckGo) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, d.source, d.name, d.name+\"-Handler\")\n}\n\nfunc (d *duckDuckGo) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, d.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/ipverse.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype ipverse struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n\tasns map[int]struct{}\n}\n\nfunc NewIPVerse() et.Plugin {\n\tlimit := rate.Every(2 * time.Second)\n\n\treturn &ipverse{\n\t\tname: \"GitHub-IPVerse\",\n\t\tfmtstr: \"https://raw.githubusercontent.com/ipverse/asn-ip/master/as/%d/aggregated.json\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"GitHub-IPVerse\",\n\t\t\tConfidence: 90,\n\t\t},\n\t\tasns: make(map[int]struct{}),\n\t}\n}\n\nfunc (v *ipverse) Name() string {\n\treturn v.name\n}\n\nfunc (v *ipverse) Start(r et.Registry) error {\n\tv.log = r.Log().WithGroup(\"plugin\").With(\"name\", v.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: v,\n\t\tName: v.name + \"-Handler\",\n\t\tPriority: 1,\n\t\tTransforms: []string{string(oam.Netblock)},\n\t\tEventType: oam.AutonomousSystem,\n\t\tCallback: v.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tv.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (v *ipverse) Stop() {\n\tv.log.Info(\"Plugin stopped\")\n}\n\nfunc (v *ipverse) check(e *et.Event) error {\n\tas, ok := e.Entity.Asset.(*oamnet.AutonomousSystem)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the AutonomousSystem asset\")\n\t}\n\n\tif _, found := v.asns[as.Number]; found {\n\t\treturn nil\n\t}\n\n\trec := v.query(e.Entity)\n\tif rec == nil {\n\t\treturn nil\n\t}\n\tv.asns[as.Number] = struct{}{}\n\n\tfor _, cidr := range append(rec.CIDRs.IPv4, rec.CIDRs.IPv6...) {\n\t\t_ = support.AddNetblock(e.Session, cidr, as.Number, v.source)\n\t}\n\treturn nil\n}\n\ntype record struct {\n\tASN int `json:\"asn\"`\n\tCIDRs struct {\n\t\tIPv4 []string `json:\"ipv4\"`\n\t\tIPv6 []string `json:\"ipv6\"`\n\t} `json:\"subnets\"`\n}\n\nfunc (v *ipverse) query(asset *dbt.Entity) *record {\n\t_ = v.rlimit.Wait(context.TODO())\n\n\tas := asset.Asset.(*oamnet.AutonomousSystem)\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(v.fmtstr, as.Number)})\n\tif err != nil || resp.Body == \"\" {\n\t\treturn nil\n\t}\n\n\tvar result record\n\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\treturn nil\n\t}\n\treturn &result\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/rapiddns.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype rapidDNS struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewRapidDNS() et.Plugin {\n\tlimit := rate.Every(5 * time.Second)\n\n\treturn &rapidDNS{\n\t\tname: \"RapidDNS\",\n\t\tfmtstr: \"https://rapiddns.io/subdomain/%s?full=1\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"RapidDNS\",\n\t\t\tConfidence: 70,\n\t\t},\n\t}\n}\n\nfunc (rd *rapidDNS) Name() string {\n\treturn rd.name\n}\n\nfunc (rd *rapidDNS) Start(r et.Registry) error {\n\trd.log = r.Log().WithGroup(\"plugin\").With(\"name\", rd.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: rd,\n\t\tName: rd.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: rd.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\trd.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (rd *rapidDNS) Stop() {\n\trd.log.Info(\"Plugin stopped\")\n}\n\nfunc (rd *rapidDNS) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), rd.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, rd.source, since) {\n\t\tnames = append(names, rd.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, rd.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, rd.source)\n\t}\n\n\tif len(names) > 0 {\n\t\trd.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (rd *rapidDNS) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), rd.source, since)\n}\n\nfunc (rd *rapidDNS) query(e *et.Event, name string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\t_ = rd.rlimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(rd.fmtstr, name)})\n\tif err != nil || resp.Body == \"\" {\n\t\treturn nil\n\t}\n\n\tfor _, n := range support.ScrapeSubdomainNames(resp.Body) {\n\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t// if the subdomain is not in scope, skip it\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\tsubs.Insert(nstr)\n\t\t}\n\t}\n\n\treturn rd.store(e, subs.Slice())\n}\n\nfunc (rd *rapidDNS) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, rd.source, rd.name, rd.name+\"-Handler\")\n}\n\nfunc (rd *rapidDNS) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, rd.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/scrape/sitedossier.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrape\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype siteDossier struct {\n\tname string\n\tfmtstr string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewSiteDossier() et.Plugin {\n\tlimit := rate.Every(4 * time.Second)\n\n\treturn &siteDossier{\n\t\tname: \"SiteDossier\",\n\t\tfmtstr: \"http://www.sitedossier.com/parentdomain/%s/%d\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"SiteDossier\",\n\t\t\tConfidence: 60,\n\t\t},\n\t}\n}\n\nfunc (sd *siteDossier) Name() string {\n\treturn sd.name\n}\n\nfunc (sd *siteDossier) Start(r et.Registry) error {\n\tsd.log = r.Log().WithGroup(\"plugin\").With(\"name\", sd.name)\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: sd,\n\t\tName: sd.name + \"-Handler\",\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: sd.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tsd.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (sd *siteDossier) Stop() {\n\tsd.log.Info(\"Plugin stopped\")\n}\n\nfunc (sd *siteDossier) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !support.HasSLDInScope(e) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.FQDN), sd.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar names []*dbt.Entity\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, sd.source, since) {\n\t\tnames = append(names, sd.lookup(e, fqdn.Name, since)...)\n\t} else {\n\t\tnames = append(names, sd.query(e, fqdn.Name)...)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, sd.source)\n\t}\n\n\tif len(names) > 0 {\n\t\tsd.process(e, names)\n\t}\n\treturn nil\n}\n\nfunc (sd *siteDossier) lookup(e *et.Event, name string, since time.Time) []*dbt.Entity {\n\treturn support.SourceToAssetsWithinTTL(e.Session, name, string(oam.FQDN), sd.source, since)\n}\n\nfunc (sd *siteDossier) query(e *et.Event, name string) []*dbt.Entity {\n\tsubs := stringset.New()\n\tdefer subs.Close()\n\n\tfor i := 1; i < 20; i++ {\n\t\t_ = sd.rlimit.Wait(context.TODO())\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: fmt.Sprintf(sd.fmtstr, name, i)})\n\t\tif err != nil || resp.Body == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, n := range support.ScrapeSubdomainNames(resp.Body) {\n\t\t\tnstr := strings.ToLower(strings.TrimSpace(n))\n\t\t\t// if the subdomain is not in scope, skip it\n\t\t\tif _, conf := e.Session.Scope().IsAssetInScope(&oamdns.FQDN{Name: nstr}, 0); conf > 0 {\n\t\t\t\tsubs.Insert(nstr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sd.store(e, subs.Slice())\n}\n\nfunc (sd *siteDossier) store(e *et.Event, names []string) []*dbt.Entity {\n\treturn support.StoreFQDNsWithSource(e.Session, names, sd.source, sd.name, sd.name+\"-Handler\")\n}\n\nfunc (sd *siteDossier) process(e *et.Event, assets []*dbt.Entity) {\n\tsupport.ProcessFQDNsWithSource(e, assets, sd.source)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/service_discovery/dns/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype dnsPlugin struct {\n\tname string\n\tlog *slog.Logger\n\tsource *et.Source\n\ttxt *txtHandler\n}\n\nfunc NewDNSPlugin() et.Plugin {\n\treturn &dnsPlugin{\n\t\tname: \"DNS-SD\",\n\t\tsource: &et.Source{\n\t\t\tName: \"DNS-SD\",\n\t\t\tConfidence: 80,\n\t\t},\n\t}\n}\n\nfunc (p *dnsPlugin) Name() string {\n\treturn p.name\n}\n\nfunc (p *dnsPlugin) Start(r et.Registry) error {\n\tp.log = r.Log().WithGroup(\"plugin\").With(\"name\", p.name)\n\n\tp.txt = &txtHandler{\n\t\tname: p.name + \"-TXT-Handler\",\n\t\tsource: p.source,\n\t\tplugin: p,\n\t}\n\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: p,\n\t\tName: p.txt.name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.FQDN)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: p.txt.check,\n\t}); err != nil {\n\t\tp.log.Error(\"failed to register handler\", \"error\", err)\n\t\treturn err\n\t}\n\n\tp.log.Info(\"plugin started\")\n\treturn nil\n}\n\nfunc (p *dnsPlugin) Stop() {\n\tp.log.Info(\"plugin stopped\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/service_discovery/dns/txt.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\ntype txtHandler struct {\n\tname string\n\tsource *et.Source\n\tplugin *dnsPlugin\n}\n\nfunc (r *txtHandler) check(e *et.Event) error {\n\tsince, err := support.TTLStartTime(e.Session.Config(), \"FQDN\", \"FQDN\", r.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif orgs := r.store(e, r.lookup(e, since)); len(orgs) > 0 {\n\t\tr.process(e, orgs)\n\t}\n\treturn nil\n}\n\nfunc (r *txtHandler) lookup(e *et.Event, since time.Time) []string {\n\tvar rdata []string\n\n\tif tags, err := e.Session.Cache().GetEntityTags(e.Entity, since, \"dns_record\"); err == nil {\n\t\tfor _, tag := range tags {\n\t\t\tif prop, ok := tag.Property.(*oamdns.DNSRecordProperty); ok && prop.Header.RRType == int(dns.TypeTXT) {\n\t\t\t\trdata = append(rdata, prop.Data)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rdata\n}\n\nfunc (r *txtHandler) store(e *et.Event, records []string) []*dbt.Entity {\n\tvar orgs []*dbt.Entity\n\n\tfor _, txt := range records {\n\t\tfor prefix, name := range prefixes {\n\t\t\tif !strings.HasPrefix(txt, prefix) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\to, err := org.CreateOrgAsset(e.Session, e.Entity,\n\t\t\t\t&general.SimpleRelation{Name: \"verified_for\"},\n\t\t\t\t&oamorg.Organization{Name: name}, r.plugin.source)\n\n\t\t\tif err == nil && o != nil {\n\t\t\t\torgs = append(orgs, o)\n\t\t\t\tfqdn := e.Entity.Asset.(*oamdns.FQDN).Name\n\t\t\t\te.Session.Log().Info(fmt.Sprintf(\"%s has a site verification record for %s: %s\",\n\t\t\t\t\tfqdn, name, txt), slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn orgs\n}\n\nfunc (r *txtHandler) process(e *et.Event, entities []*dbt.Entity) {\n\tfor _, entity := range entities {\n\t\tif o, ok := entity.Asset.(*oamorg.Organization); ok && o != nil {\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: o.Name,\n\t\t\t\tEntity: entity,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\t\t}\n\t}\n}\n\nvar prefixes = map[string]string{\n\t\"adobe-idp-site-verification=\": \"Adobe Inc.\",\n\t\"adobe-sign-verification=\": \"Adobe Inc.\",\n\t\"ahrefs-site-verification_\": \"Ahrefs Pte. Ltd.\",\n\t\"airtable-verification=\": \"Formagrid, Inc.\",\n\t\"aliyun-site-verification=\": \"Alibaba Cloud US LLC\",\n\t\"amazonses=\": \"Amazon Web Services, Inc.\",\n\t\"amazonses:\": \"Amazon Web Services, Inc.\",\n\t\"anodot-domain-verification=\": \"Anodot Ltd\",\n\t\"apperio-domain-verification=\": \"PERSUIT Operations Pty Ltd\",\n\t\"apple-domain-verification=\": \"Apple Inc.\",\n\t\"asuid=\": \"Google LLC\",\n\t\"atlassian-domain-verification=\": \"Atlassian Corporation Plc\",\n\t\"brave-ledger-verification=\": \"Brave Software, Inc.\",\n\t\"bugcrowd-verification=\": \"Bugcrowd Inc.\",\n\t\"canva-site-verification=\": \"Canva LLC.\",\n\t\"ciscocidomainverification=\": \"Cisco Systems, Inc.\",\n\t\"cisco-ci-domain-verification\": \"Cisco Systems, Inc.\",\n\t\"citrix.mobile.ads.otp=\": \"Citrix Systems, Inc.\",\n\t\"citrix-verification-code=\": \"Citrix Systems, Inc.\",\n\t\"clickfunnels-domain-verification=\": \"Etison LLC\",\n\t\"cursor-domain-verification=\": \"Anysphere Inc.\",\n\t\"detectify-verification=\": \"Detectify AB\",\n\t\"docusign=\": \"DocuSign, Inc.\",\n\t\"drift-domain-verification=\": \"Drift.com, Inc.\",\n\t\"dropbox-domain-verification=\": \"Dropbox, Inc.\",\n\t\"DZC:\": \"GoDaddy.com, LLC\",\n\t\"Entrust:\": \"Entrust Corporation\",\n\t\"fastly-domain-delegation=\": \"Fastly, Inc.\",\n\t\"facebook-domain-verification=\": \"Meta Platforms, Inc.\",\n\t\"_globalsign-domain-verification=\": \"GlobalSign, Inc.\",\n\t\"globalsign-domain-verification=\": \"GlobalSign, Inc.\",\n\t\"globalsign-smime-dv=\": \"GlobalSign, Inc.\",\n\t\"godaddyverification=\": \"GoDaddy.com, LLC\",\n\t\"google-domain-verification=\": \"Google LLC\",\n\t\"google-site-verification=\": \"Google LLC\",\n\t\"have-i-been-pwned-verification=\": \"Troy Hunt / Have I Been Pwned\",\n\t\"hubspot-developer-verification=\": \"HubSpot, Inc.\",\n\t\"hubspot-site-verification=\": \"HubSpot, Inc.\",\n\t\"knowbe4-site-verification=\": \"KnowBe4, Inc.\",\n\t\"krisp-domain-verification=\": \"Krisp Technologies, Inc.\",\n\t\"lastpass-verification-code=\": \"LastPass US LP\",\n\t\"logmein-verification-code=\": \"LogMeIn, Inc.\",\n\t\"mailchimp=\": \"Intuit Inc.\",\n\t\"mailru-verification=\": \"VK Company Limited\",\n\t\"mailru-verification:\": \"VK Company Limited\",\n\t\"miro-verification=\": \"RealtimeBoard, Inc.\",\n\t\"mongodb-site-verification=\": \"MongoDB, Inc.\",\n\t\"MS=\": \"Microsoft Corporation\",\n\t\"mscid=\": \"Microsoft Corporation\",\n\t\"nethely-dvc:\": \"Nethely Kft.\",\n\t\"netlify-verification=\": \"Netlify, Inc.\",\n\t\"nifty-dns-verify:\": \"Fujitsu Limited\",\n\t\"notion-domain-verification=\": \"Notion Labs, Inc.\",\n\t\"onetrust-domain-verification=\": \"OneTrust LLC\",\n\t\"openai-domain-verification=\": \"OpenAI, Inc.\",\n\t\"pardot_\": \"Salesforce.com, Inc.\",\n\t\"pardot-domain-verification=\": \"Salesforce.com, Inc.\",\n\t\"pendo-domain-verification=\": \"Pendo.io, Inc.\",\n\t\"postman-domain-verification=\": \"Postman, Inc.\",\n\t\"Probe.ly:\": \"Probely, S.A\",\n\t\"protonmail-verification=\": \"Proton AG\",\n\t\"sendinblue-code:\": \"Sendinblue SAS\",\n\t\"Sendinblue-code:\": \"Sendinblue SAS\",\n\t\"segment-domain-verification=\": \"Twilio Inc.\",\n\t\"SFMC-\": \"ExactTarget, LLC\",\n\t\"shopify-verification-code=\": \"Shopify Inc.\",\n\t\"slack-domain-verification=\": \"Slack Technologies, LLC\",\n\t\"sophos-domain-verification=\": \"Sophos Limited\",\n\t\"square-verification=\": \"Block, Inc.\",\n\t\"status-page-domain-verification=\": \"Atlassian Corporation Plc\",\n\t\"statuspage-domain-verification=\": \"Atlassian Corporation Plc\",\n\t\"storiesonboard-verification=\": \"DevMads Ltd.\",\n\t\"stripe-verification=\": \"Stripe, Inc.\",\n\t\"teamviewer-sso-verification=\": \"TeamViewer Germany GmbH\",\n\t\"tiktok-domain-verification=\": \"TikTok Pte. Ltd.\",\n\t\"typeform-site-verification=\": \"Typeform S.L.\",\n\t\"twilio-domain-verification=\": \"Twilio Inc.\",\n\t\"upspin=\": \"Google LLC\",\n\t\"vercel-domain-verification=\": \"Vercel Inc.\",\n\t\"webexdomainverification.\": \"Cisco Systems, Inc.\",\n\t\"webexdomainverification=\": \"Cisco Systems, Inc.\",\n\t\"webflow-verification=\": \"Webflow, Inc.\",\n\t\"workplace-domain-verification=\": \"Meta Platforms, Inc.\",\n\t\"yahoo-verification-key=\": \"Yahoo! Inc.\",\n\t\"yandex-verification=\": \"YANDEX LLC\",\n\t\"zoho-verification=\": \"Zoho Corporation Pvt. Ltd.\",\n\t\"zoom-domain-verification\": \"Zoom Communications, Inc.\",\n\t\"ZOOM_verify_\": \"Zoom Communications, Inc.\",\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/service_discovery/http_probes/fqdn_endpoint.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage http_probes\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\ntype fqdnEndpoint struct {\n\tname string\n\tplugin *httpProbing\n}\n\nfunc (fe *fqdnEndpoint) Name() string {\n\treturn fe.name\n}\n\nfunc (fe *fqdnEndpoint) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tif !e.Session.Config().Active {\n\t\treturn nil\n\t}\n\tif !support.HasDNSRecordType(e, int(dns.TypeA)) &&\n\t\t!support.HasDNSRecordType(e, int(dns.TypeAAAA)) &&\n\t\t!support.HasDNSRecordType(e, int(dns.TypeCNAME)) {\n\t\treturn nil\n\t}\n\tif _, conf := e.Session.Scope().IsAssetInScope(fqdn, 0); conf == 0 {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.Service), fe.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := fe.plugin.source\n\tvar findings []*support.Finding\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tfindings = append(findings, fe.lookup(e, e.Entity, since)...)\n\t} else {\n\t\tgo func() {\n\t\t\tif findings := append(findings, fe.query(e, e.Entity)...); len(findings) > 0 {\n\t\t\t\tfe.process(e, findings)\n\t\t\t}\n\t\t}()\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif len(findings) > 0 {\n\t\tfe.process(e, findings)\n\t}\n\treturn nil\n}\n\nfunc (fe *fqdnEndpoint) lookup(e *et.Event, host *dbt.Entity, since time.Time) []*support.Finding {\n\tvar findings []*support.Finding\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(host, since, \"port\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif _, err := e.Session.Cache().GetEdgeTags(edge, since, fe.plugin.source.Name); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := edge.Relation.(*general.PortRelation); ok {\n\t\t\t\tif srv, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && srv != nil && srv.Asset.AssetType() == oam.Service {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: host,\n\t\t\t\t\t\tFromName: host.Asset.Key(),\n\t\t\t\t\t\tTo: srv,\n\t\t\t\t\t\tToName: srv.Asset.Key(),\n\t\t\t\t\t\tRel: edge.Relation,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn findings\n}\n\nfunc (fe *fqdnEndpoint) query(e *et.Event, host *dbt.Entity) []*support.Finding {\n\tvar findings []*support.Finding\n\tfqdn := host.Asset.(*oamdns.FQDN)\n\n\tfor _, port := range e.Session.Config().Scope.Ports {\n\t\taddr := fqdn.Name + \":\" + strconv.Itoa(port)\n\n\t\tproto := \"https\"\n\t\tif port == 80 || port == 8080 {\n\t\t\tproto = \"http\"\n\t\t}\n\n\t\tfindings = append(findings, fe.plugin.query(e, host, proto+\"://\"+addr, port)...)\n\t}\n\n\treturn findings\n}\n\nfunc (fe *fqdnEndpoint) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, fe.plugin.source, fe.plugin.name, fe.name)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/service_discovery/http_probes/ipaddr_endpoint.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage http_probes\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n)\n\ntype ipaddrEndpoint struct {\n\tname string\n\tplugin *httpProbing\n}\n\nfunc (r *ipaddrEndpoint) Name() string {\n\treturn r.name\n}\n\nfunc (r *ipaddrEndpoint) check(e *et.Event) error {\n\tip, ok := e.Entity.Asset.(*network.IPAddress)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the IPAddress asset\")\n\t}\n\n\tif !e.Session.Config().Active {\n\t\treturn nil\n\t}\n\n\taddrstr := ip.Address.String()\n\tif reserved, _ := amassnet.IsReservedAddress(addrstr); reserved {\n\t\treturn nil\n\t}\n\tif !e.Session.Scope().IsAddressInScope(e.Session.Cache(), ip) {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.IPAddress), string(oam.Service), r.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := r.plugin.source\n\tvar findings []*support.Finding\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tfindings = append(findings, r.lookup(e, e.Entity, since)...)\n\t} else {\n\t\tgo func() {\n\t\t\tif findings := append(findings, r.query(e, e.Entity)...); len(findings) > 0 {\n\t\t\t\tr.process(e, findings)\n\t\t\t}\n\t\t}()\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif len(findings) > 0 {\n\t\tr.process(e, findings)\n\t}\n\n\tgo support.IPAddressSweep(e, ip, src, 25, sweepCallback)\n\treturn nil\n}\n\nfunc (r *ipaddrEndpoint) lookup(e *et.Event, ip *dbt.Entity, since time.Time) []*support.Finding {\n\tvar findings []*support.Finding\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(ip, since, \"port\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif _, err := e.Session.Cache().GetEdgeTags(edge, since, r.plugin.source.Name); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := edge.Relation.(*general.PortRelation); ok {\n\t\t\t\tif srv, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && srv != nil && srv.Asset.AssetType() == oam.Service {\n\t\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\t\tFrom: ip,\n\t\t\t\t\t\tFromName: ip.Asset.Key(),\n\t\t\t\t\t\tTo: srv,\n\t\t\t\t\t\tToName: srv.Asset.Key(),\n\t\t\t\t\t\tRel: edge.Relation,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn findings\n}\n\nfunc (r *ipaddrEndpoint) query(e *et.Event, ipaddr *dbt.Entity) []*support.Finding {\n\tvar findings []*support.Finding\n\tip := ipaddr.Asset.(*network.IPAddress)\n\n\tfor _, port := range e.Session.Config().Scope.Ports {\n\t\ta := ip.Address.String()\n\t\tif ip.Type == \"IPv6\" {\n\t\t\ta = \"[\" + a + \"]\"\n\t\t}\n\t\taddr := a + \":\" + strconv.Itoa(port)\n\n\t\tproto := \"https\"\n\t\tif port == 80 || port == 8080 {\n\t\t\tproto = \"http\"\n\t\t}\n\n\t\tfindings = append(findings, r.plugin.query(e, ipaddr, proto+\"://\"+addr, port)...)\n\t}\n\n\treturn findings\n}\n\nfunc (r *ipaddrEndpoint) process(e *et.Event, findings []*support.Finding) {\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n}\n\nfunc sweepCallback(e *et.Event, ip *network.IPAddress, src *et.Source) {\n\tif entity, err := e.Session.Cache().CreateAsset(ip); err == nil && entity != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(entity, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: ip.Address.String(),\n\t\t\tEntity: entity,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/service_discovery/http_probes/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage http_probes\n\nimport (\n\t\"context\"\n\t\"crypto/x509\"\n\t\"hash/maphash\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n)\n\ntype httpProbing struct {\n\tname string\n\tlog *slog.Logger\n\tfqdnend *fqdnEndpoint\n\tipaddr *ipaddrEndpoint\n\tsource *et.Source\n\thash maphash.Hash\n\tservlock sync.Mutex\n}\n\nfunc NewHTTPProbing() et.Plugin {\n\treturn &httpProbing{\n\t\tname: \"HTTP-Probes\",\n\t\tsource: &et.Source{\n\t\t\tName: \"HTTP-Probes\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (hp *httpProbing) Name() string {\n\treturn hp.name\n}\n\nfunc (hp *httpProbing) Start(r et.Registry) error {\n\thp.hash.SetSeed(maphash.MakeSeed())\n\thp.log = r.Log().WithGroup(\"plugin\").With(\"name\", hp.name)\n\n\thp.fqdnend = &fqdnEndpoint{\n\t\tname: hp.name + \"-FQDN-Interrogation\",\n\t\tplugin: hp,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: hp,\n\t\tName: hp.fqdnend.name,\n\t\tPriority: 9,\n\t\tTransforms: []string{\n\t\t\tstring(oam.Service),\n\t\t\tstring(oam.TLSCertificate),\n\t\t},\n\t\tEventType: oam.FQDN,\n\t\tCallback: hp.fqdnend.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\thp.ipaddr = &ipaddrEndpoint{\n\t\tname: hp.name + \"-IPAddress-Interrogation\",\n\t\tplugin: hp,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: hp,\n\t\tName: hp.ipaddr.name,\n\t\tPriority: 9,\n\t\tMaxInstances: support.MaxHandlerInstances,\n\t\tTransforms: []string{\n\t\t\tstring(oam.Service),\n\t\t\tstring(oam.TLSCertificate),\n\t\t},\n\t\tEventType: oam.IPAddress,\n\t\tCallback: hp.ipaddr.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\thp.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (hp *httpProbing) Stop() {\n\thp.log.Info(\"Plugin stopped\")\n}\n\nfunc (hp *httpProbing) query(e *et.Event, entity *dbt.Entity, target string, port int) []*support.Finding {\n\tvar findings []*support.Finding\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tif resp, err := http.RequestWebPage(ctx, &http.Request{URL: target}); err == nil && resp != nil {\n\t\tfindings = append(findings, hp.store(e, resp, entity, port)...)\n\t}\n\treturn findings\n}\n\nfunc (hp *httpProbing) store(e *et.Event, resp *http.Response, entity *dbt.Entity, port int) []*support.Finding {\n\thp.servlock.Lock()\n\tdefer hp.servlock.Unlock()\n\n\taddr := entity.Asset.Key()\n\tvar firstAsset *dbt.Entity\n\tvar firstCert *x509.Certificate\n\tvar findings []*support.Finding\n\tif resp.TLS != nil && resp.TLS.HandshakeComplete && len(resp.TLS.PeerCertificates) > 0 {\n\t\tvar prev *dbt.Entity\n\t\t// traverse the certificate chain\n\t\tfor _, cert := range resp.TLS.PeerCertificates {\n\t\t\tc := support.X509ToOAMTLSCertificate(cert)\n\t\t\tif c == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ta, err := e.Session.Cache().CreateAsset(c)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif prev == nil {\n\t\t\t\tfirstAsset = a\n\t\t\t\tfirstCert = cert\n\t\t\t} else {\n\t\t\t\ttls := prev.Asset.(*oamcert.TLSCertificate)\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: prev,\n\t\t\t\t\tFromName: tls.SerialNumber,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: c.SerialNumber,\n\t\t\t\t\tToMeta: cert,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"issuing_certificate\"},\n\t\t\t\t})\n\t\t\t}\n\t\t\tprev = a\n\t\t}\n\t}\n\n\tserv := support.ServiceWithIdentifier(&hp.hash, e.Session.ID().String(), addr)\n\tif serv == nil {\n\t\treturn findings\n\t}\n\tserv.Output = resp.Body\n\tserv.OutputLen = int(resp.Length)\n\tserv.Attributes = resp.Header\n\n\tproto := \"http\"\n\tvar c *oamcert.TLSCertificate\n\tif firstAsset != nil {\n\t\tproto = \"https\"\n\t\tc = firstAsset.Asset.(*oamcert.TLSCertificate)\n\t}\n\n\tportrel := &general.PortRelation{\n\t\tName: \"port\",\n\t\tPortNumber: port,\n\t\tProtocol: proto,\n\t}\n\n\ts, err := support.CreateServiceAsset(e.Session, entity, portrel, serv, c)\n\tif err != nil {\n\t\treturn findings\n\t}\n\n\tserv = s.Asset.(*platform.Service)\n\t// for adding the source information\n\tfindings = append(findings, &support.Finding{\n\t\tFrom: entity,\n\t\tFromName: addr,\n\t\tTo: s,\n\t\tToName: \"Service: \" + serv.ID,\n\t\tRel: portrel,\n\t})\n\n\tif firstAsset != nil && firstCert != nil {\n\t\tfindings = append(findings, &support.Finding{\n\t\t\tFrom: s,\n\t\t\tFromName: \"Service: \" + serv.ID,\n\t\t\tTo: firstAsset,\n\t\t\tToName: c.SerialNumber,\n\t\t\tToMeta: firstCert,\n\t\t\tRel: &general.SimpleRelation{Name: \"certificate\"},\n\t\t})\n\t}\n\n\treturn findings\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/database.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/db\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\nfunc SourceToAssetsWithinTTL(session et.Session, name, atype string, src *et.Source, since time.Time) []*dbt.Entity {\n\tvar entities []*dbt.Entity\n\n\tswitch atype {\n\tcase string(oam.FQDN):\n\t\troots, err := session.Cache().FindEntitiesByContent(&oamdns.FQDN{Name: name}, since)\n\t\tif err != nil || len(roots) != 1 {\n\t\t\treturn nil\n\t\t}\n\t\troot := roots[0]\n\n\t\tentities, _ = db.FindByFQDNScope(session.Cache(), root, since)\n\tcase string(oam.Identifier):\n\t\tif parts := strings.Split(name, \":\"); len(parts) == 2 {\n\t\t\tid := &general.Identifier{\n\t\t\t\tUniqueID: name,\n\t\t\t\tID: parts[1],\n\t\t\t\tType: parts[0],\n\t\t\t}\n\n\t\t\tentities, _ = session.Cache().FindEntitiesByContent(id, since)\n\t\t}\n\tcase string(oam.AutnumRecord):\n\t\tnum, err := strconv.Atoi(name)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tentities, _ = session.Cache().FindEntitiesByContent(&oamreg.AutnumRecord{Number: num}, since)\n\tcase string(oam.IPNetRecord):\n\t\tprefix, err := netip.ParsePrefix(name)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tentities, _ = session.Cache().FindEntitiesByContent(&oamreg.IPNetRecord{CIDR: prefix}, since)\n\tcase string(oam.Service):\n\t\tentities, _ = session.Cache().FindEntitiesByContent(&platform.Service{ID: name}, since)\n\t}\n\n\tvar results []*dbt.Entity\n\tfor _, entity := range entities {\n\t\tif tags, err := session.Cache().GetEntityTags(entity, since, src.Name); err == nil && len(tags) > 0 {\n\t\t\tfor _, tag := range tags {\n\t\t\t\tif tag.Property.PropertyType() == oam.SourceProperty {\n\t\t\t\t\tresults = append(results, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc StoreFQDNsWithSource(session et.Session, names []string, src *et.Source, plugin, handler string) []*dbt.Entity {\n\tvar results []*dbt.Entity\n\n\tif len(names) == 0 || src == nil {\n\t\treturn results\n\t}\n\n\tfor _, name := range names {\n\t\tif a, err := session.Cache().CreateAsset(&oamdns.FQDN{Name: name}); err == nil && a != nil {\n\t\t\tresults = append(results, a)\n\t\t\t_, _ = session.Cache().CreateEntityProperty(a, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\t\t} else {\n\t\t\tsession.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", plugin, \"handler\", handler))\n\t\t}\n\t}\n\n\treturn results\n}\n\nfunc StoreEmailsWithSource(session et.Session, emails []string, src *et.Source, plugin, handler string) []*dbt.Entity {\n\tvar results []*dbt.Entity\n\n\tif len(emails) == 0 || src == nil {\n\t\treturn results\n\t}\n\n\tfor _, e := range emails {\n\t\temail := strings.ToLower(e)\n\n\t\tif a, err := session.Cache().CreateAsset(&general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.EmailAddress, email),\n\t\t\tID: email,\n\t\t\tType: general.EmailAddress,\n\t\t}); err == nil && a != nil {\n\t\t\tresults = append(results, a)\n\t\t\t_, _ = session.Cache().CreateEntityProperty(a, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\t\t} else {\n\t\t\tsession.Log().Error(err.Error(), slog.Group(\"plugin\", \"name\", plugin, \"handler\", handler))\n\t\t}\n\t}\n\n\treturn results\n}\n\nfunc MarkAssetMonitored(session et.Session, asset *dbt.Entity, src *et.Source) {\n\tif asset == nil || src == nil {\n\t\treturn\n\t}\n\n\tif tags, err := session.Cache().GetEntityTags(asset, time.Time{}, \"last_monitored\"); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif tag.Property.Value() == src.Name {\n\t\t\t\t_ = session.Cache().DeleteEntityTag(tag.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t_, _ = session.Cache().CreateEntityProperty(asset, general.SimpleProperty{\n\t\tPropertyName: \"last_monitored\",\n\t\tPropertyValue: src.Name,\n\t})\n}\n\nfunc AssetMonitoredWithinTTL(session et.Session, asset *dbt.Entity, src *et.Source, since time.Time) bool {\n\tif asset == nil || src == nil || !since.IsZero() {\n\t\treturn false\n\t}\n\n\tif tags, err := session.Cache().GetEntityTags(asset, since, \"last_monitored\"); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif tag.Property.Value() == src.Name {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc CreateServiceAsset(session et.Session, src *dbt.Entity, rel oam.Relation, serv *platform.Service, cert *oamcert.TLSCertificate) (*dbt.Entity, error) {\n\tvar srvs []*dbt.Entity\n\n\tif rport, ok := rel.(*general.PortRelation); ok && src != nil && serv != nil {\n\t\tsrcs := []*dbt.Entity{src}\n\n\t\tif _, ok := src.Asset.(*oamdns.FQDN); ok {\n\t\t\t// check for IP assresses associated with the FQDN\n\t\t\tif edges, err := session.Cache().OutgoingEdges(src, time.Time{}, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\tif to, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && to != nil {\n\t\t\t\t\t\tif _, ok := to.Asset.(*oamnet.IPAddress); ok {\n\t\t\t\t\t\t\tsrcs = append(srcs, to)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// go though the hosts that could have previously associated with the service\n\t\tfor _, s := range srcs {\n\t\t\tif edges, err := session.Cache().OutgoingEdges(s, time.Time{}, \"port\"); err == nil && len(edges) > 0 {\n\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\tif eport, ok := edge.Relation.(*general.PortRelation); ok && eport.PortNumber == rport.PortNumber && strings.EqualFold(eport.Protocol, rport.Protocol) {\n\t\t\t\t\t\tif to, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && to != nil {\n\t\t\t\t\t\t\tif srv, ok := to.Asset.(*platform.Service); ok && srv.OutputLen == serv.OutputLen {\n\t\t\t\t\t\t\t\tsrvs = append(srvs, to)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar match *dbt.Entity\n\tfor _, srv := range srvs {\n\t\tvar num int\n\n\t\ts := srv.Asset.(*platform.Service)\n\t\tfor _, key := range []string{\"Server\", \"X-Powered-By\"} {\n\t\t\tif server1, ok := serv.Attributes[key]; ok && server1[0] != \"\" {\n\t\t\t\tif server2, ok := s.Attributes[key]; ok && server1[0] == server2[0] {\n\t\t\t\t\tnum++\n\t\t\t\t} else {\n\t\t\t\t\tnum--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif cert != nil {\n\t\t\tif edges, err := session.Cache().OutgoingEdges(srv, time.Time{}, \"certificate\"); err == nil && len(edges) > 0 {\n\t\t\t\tvar found bool\n\n\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\tif t, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && t != nil {\n\t\t\t\t\t\tif c, ok := t.Asset.(*oamcert.TLSCertificate); ok && c.SerialNumber == cert.SerialNumber {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif found {\n\t\t\t\t\tnum++\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif num > 0 {\n\t\t\tmatch = srv\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar result *dbt.Entity\n\tif match != nil {\n\t\tresult = match\n\t} else {\n\t\tif a, err := session.Cache().CreateAsset(serv); err == nil && a != nil {\n\t\t\tresult = a\n\t\t} else {\n\t\t\treturn nil, errors.New(\"failed to create the OAM Service asset\")\n\t\t}\n\t}\n\n\t_, err := session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: src,\n\t\tToEntity: result,\n\t})\n\treturn result, err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/dispatch.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"log/slog\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n)\n\ntype Finding struct {\n\tFrom *dbt.Entity\n\tFromName string\n\tTo *dbt.Entity\n\tToName string\n\tToMeta interface{}\n\tRel oam.Relation\n}\n\nfunc ProcessAssetsWithSource(e *et.Event, findings []*Finding, src *et.Source, pname, hname string) {\n\tfor _, finding := range findings {\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: finding.Rel,\n\t\t\tFromEntity: finding.From,\n\t\t\tToEntity: finding.To,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: finding.ToName,\n\t\t\t\tMeta: finding.ToMeta,\n\t\t\t\tEntity: finding.To,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\n\t\t\te.Session.Log().Info(\"relationship discovered\", \"from\", finding.FromName, \"relation\",\n\t\t\t\tfinding.Rel, \"to\", finding.ToName, slog.Group(\"plugin\", \"name\", pname, \"handler\", hname))\n\t\t}\n\t}\n}\n\nfunc ProcessFQDNsWithSource(e *et.Event, entities []*dbt.Entity, src *et.Source) {\n\tfor _, entity := range entities {\n\t\tfqdn, ok := entity.Asset.(*oamdns.FQDN)\n\t\tif !ok || fqdn == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(entity, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: fqdn.Name,\n\t\t\tEntity: entity,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\nfunc ProcessEmailsWithSource(e *et.Event, entities []*dbt.Entity, src *et.Source) {\n\tfor _, entity := range entities {\n\t\temail, ok := entity.Asset.(*general.Identifier)\n\t\tif !ok || email == nil || email.Type != general.EmailAddress || email.ID == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, conf := e.Session.Scope().IsAssetInScope(email, 0); conf == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tmeta := e.Meta\n\t\tif meta == nil {\n\t\t\tmeta = &et.EmailMeta{\n\t\t\t\tVerifyAttempted: false,\n\t\t\t\tVerified: false,\n\t\t\t}\n\t\t}\n\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(entity, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\n\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\tName: email.UniqueID,\n\t\t\tMeta: meta,\n\t\t\tEntity: entity,\n\t\t\tSession: e.Session,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/filter.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype FQDNFilter map[string]interface{}\n\nfunc NewFQDNFilter() FQDNFilter {\n\treturn make(FQDNFilter)\n}\n\nfunc (r FQDNFilter) Insert(fqdn string) {\n\tparts := strings.Split(fqdn, \".\")\n\n\tvar labels []string\n\tfor i := len(parts) - 1; i >= 0; i-- {\n\t\tlabels = append(labels, parts[i])\n\t}\n\n\tcur := r\n\tllen := len(labels)\n\tfor i, label := range labels {\n\t\tif e, found := cur[label]; !found && i < llen-1 {\n\t\t\tcur[label] = make(FQDNFilter)\n\t\t\tcur = cur[label].(FQDNFilter)\n\t\t} else if found && i < llen-1 {\n\t\t\tif reflect.TypeOf(e).Kind() == reflect.Struct {\n\t\t\t\tcur[label] = make(FQDNFilter)\n\t\t\t}\n\t\t\tcur = cur[label].(FQDNFilter)\n\t\t} else if !found && i == llen-1 {\n\t\t\tcur[label] = struct{}{}\n\t\t}\n\t}\n}\n\nfunc (r FQDNFilter) Prune(limit int) {\n\tfor k, v := range r {\n\t\tswitch t := v.(type) {\n\t\tcase FQDNFilter:\n\t\t\tif len(t) >= limit {\n\t\t\t\tdelete(r, k)\n\t\t\t\tr[k] = struct{}{}\n\t\t\t} else {\n\t\t\t\tt.Prune(limit)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r FQDNFilter) Slice() []string {\n\treturn r.processMap(\"\")\n}\n\nfunc (r FQDNFilter) processMap(prefix string) []string {\n\tvar fqdns []string\n\n\tfor k, v := range r {\n\t\tname := k\n\t\tif prefix != \"\" {\n\t\t\tname += \".\" + prefix\n\t\t}\n\n\t\tswitch t := v.(type) {\n\t\tcase FQDNFilter:\n\t\t\tfqdns = append(fqdns, t.processMap(name)...)\n\t\tdefault:\n\t\t\tfqdns = append(fqdns, name)\n\t\t}\n\t}\n\n\treturn fqdns\n}\n\nfunc (r FQDNFilter) Close() {\n\tfor k := range r {\n\t\tdelete(r, k)\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/fingerprinting.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tjarm \"github.com/caffix/jarm-go\"\n\t\"github.com/owasp-amass/amass/v5/internal/net\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n)\n\nfunc JARMFingerprint(target oam.Asset, portrel *general.PortRelation) (string, error) {\n\tvar ipv6 bool\n\tvar host string\n\n\tif fqdn, ok := target.(*oamdns.FQDN); ok {\n\t\thost = fqdn.Name\n\t} else if ip, ok := target.(*network.IPAddress); ok {\n\t\tipv6 = ip.Address.Is6()\n\t\thost = ip.Address.String()\n\t} else {\n\t\treturn \"\", errors.New(\"target must be a FQDN or IPAddress\")\n\t}\n\n\taddr := host\n\tif ipv6 {\n\t\taddr = \"[\" + addr + \"]\"\n\t}\n\taddr += \":\" + strconv.Itoa(portrel.PortNumber)\n\n\tvar results []string\n\tfor _, probe := range jarm.GetProbes(host, portrel.PortNumber) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer cancel()\n\n\t\tc, err := net.DialContext(ctx, \"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer func() { _ = c.Close() }()\n\n\t\tdata := jarm.BuildProbe(probe)\n\t\t_ = c.SetWriteDeadline(time.Now().Add(5 * time.Second))\n\t\tif _, err := c.Write(data); err != nil {\n\t\t\tresults = append(results, \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\t_ = c.SetReadDeadline(time.Now().Add(5 * time.Second))\n\t\tbuf := make([]byte, 1484)\n\t\tn, err := c.Read(buf)\n\t\tif err != nil || n == 0 {\n\t\t\tresults = append(results, \"\")\n\t\t\tcontinue\n\t\t}\n\t\tdata = buf[:n]\n\n\t\tans, err := jarm.ParseServerHello(data, probe)\n\t\tif err != nil {\n\t\t\tresults = append(results, \"\")\n\t\t\tcontinue\n\t\t}\n\t\tresults = append(results, ans)\n\t}\n\n\thash := jarm.RawHashToFuzzyHash(strings.Join(results, \",\"))\n\tif hash == \"00000000000000000000000000000000000000000000000000000000000000\" {\n\t\treturn \"\", errors.New(\"probes were not successful against the target\")\n\t}\n\treturn hash, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/location.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"github.com/owasp-amass/amass/v5/internal/libpostal\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n)\n\nfunc StreetAddressToLocation(address string) *contact.Location {\n\tif address == \"\" {\n\t\treturn nil\n\t}\n\n\tloc := &contact.Location{Address: address}\n\tparts, err := libpostal.ParseAddress(loc.Address)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tfor _, part := range parts {\n\t\tswitch part.Label {\n\t\tcase \"house\":\n\t\t\tloc.Building = part.Value\n\t\tcase \"house_number\":\n\t\t\tloc.BuildingNumber = part.Value\n\t\tcase \"road\":\n\t\t\tloc.StreetName = part.Value\n\t\tcase \"unit\":\n\t\t\tloc.Unit = part.Value\n\t\tcase \"po_box\":\n\t\t\tloc.POBox = part.Value\n\t\tcase \"city\":\n\t\t\tloc.City = part.Value\n\t\tcase \"state\":\n\t\t\tloc.Province = part.Value\n\t\tcase \"postcode\":\n\t\t\tloc.PostalCode = part.Value\n\t\tcase \"country\":\n\t\t\tloc.Country = part.Value\n\t\tcase \"suburb\":\n\t\t\tfallthrough\n\t\tcase \"city_district\":\n\t\t\tif s := part.Value; s != \"\" {\n\t\t\t\tloc.Locality = s\n\t\t\t}\n\t\t}\n\t}\n\treturn loc\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/normalization.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"crypto/x509\"\n\t\"hash/maphash\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/PuerkitoBio/purell\"\n\tfnparser \"github.com/caffix/fullname_parser\"\n\t\"github.com/nyaruka/phonenumbers\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\t\"github.com/owasp-amass/open-asset-model/people\"\n\t\"github.com/owasp-amass/open-asset-model/platform\"\n\toamurl \"github.com/owasp-amass/open-asset-model/url\"\n)\n\nfunc FullNameToPerson(raw string) *people.Person {\n\tif raw == \"\" {\n\t\treturn nil\n\t}\n\n\tname := fnparser.ParseFullname(raw)\n\tif name.First == \"\" || name.Last == \"\" {\n\t\treturn nil\n\t}\n\n\tvar fullname string\n\tif name.Title != \"\" {\n\t\tfullname += name.Title + \" \"\n\t}\n\tfullname += name.First + \" \"\n\n\tif name.Middle != \"\" {\n\t\tfullname += name.Middle + \" \"\n\t}\n\tfullname += name.Last\n\n\tif name.Suffix != \"\" {\n\t\tfullname += \", \" + name.Suffix\n\t}\n\n\treturn &people.Person{\n\t\tID: fullname,\n\t\tFullName: fullname,\n\t\tFirstName: name.First,\n\t\tMiddleName: name.Middle,\n\t\tFamilyName: name.Last,\n\t}\n}\n\nfunc PhoneToOAMPhone(phone, ext, country string) *contact.Phone {\n\tif phone == \"\" {\n\t\treturn nil\n\t}\n\n\traw := phone\n\tif ext != \"\" {\n\t\traw += \" Ext. \" + ext\n\t}\n\n\tnum, err := phonenumbers.Parse(raw, country)\n\tif err != nil || !phonenumbers.IsValidNumber(num) {\n\t\treturn nil\n\t}\n\te164 := phonenumbers.Format(num, phonenumbers.E164)\n\n\traw = e164\n\text = num.GetExtension()\n\tif ext != \"\" {\n\t\traw += \" Ext. \" + ext\n\t}\n\n\treturn &contact.Phone{\n\t\tRaw: raw,\n\t\tE164: e164,\n\t\tCountryAbbrev: strings.ToUpper(country),\n\t\tCountryCode: int(num.GetCountryCode()),\n\t\tExt: ext,\n\t}\n}\n\nfunc RawURLToOAM(raw string) *oamurl.URL {\n\tif raw == \"\" {\n\t\treturn nil\n\t}\n\n\tflags := purell.FlagLowercaseScheme | purell.FlagLowercaseHost | purell.FlagUppercaseEscapes\n\tflags |= purell.FlagDecodeDWORDHost | purell.FlagDecodeHexHost | purell.FlagDecodeOctalHost\n\tflags |= purell.FlagRemoveDuplicateSlashes | purell.FlagRemoveEmptyPortSeparator | purell.FlagRemoveUnnecessaryHostDots\n\tnormalized, err := purell.NormalizeURLString(raw, flags)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tif u, err := url.Parse(normalized); err == nil && u != nil {\n\t\tou := &oamurl.URL{\n\t\t\tRaw: u.String(),\n\t\t\tScheme: u.Scheme,\n\t\t\tUsername: u.User.Username(),\n\t\t\tHost: u.Hostname(),\n\t\t\tPath: u.Path,\n\t\t\tFragment: u.Fragment,\n\t\t}\n\t\tif port := u.Port(); port != \"\" {\n\t\t\tif i, err := strconv.Atoi(port); err == nil {\n\t\t\t\tou.Port = i\n\t\t\t}\n\t\t} else {\n\t\t\tou.Port = schemeToPort(u.Scheme)\n\t\t}\n\t\tif pass, ok := u.User.Password(); ok && pass != \"\" {\n\t\t\tou.Password = pass\n\t\t}\n\t\treturn ou\n\t}\n\treturn nil\n}\n\nfunc schemeToPort(scheme string) int {\n\tvar port int\n\n\tswitch scheme {\n\tcase \"ftp-data\":\n\t\tport = 20\n\tcase \"ftp\":\n\t\tport = 21\n\tcase \"ssh\":\n\t\tport = 22\n\tcase \"telnet\":\n\t\tport = 23\n\tcase \"smtp\":\n\t\tport = 25\n\tcase \"domain\":\n\t\tport = 53\n\tcase \"tftp\":\n\t\tport = 69\n\tcase \"http\":\n\t\tport = 80\n\tcase \"sftp\":\n\t\tport = 115\n\tcase \"ntp\":\n\t\tport = 123\n\tcase \"imap\":\n\t\tport = 143\n\tcase \"snmp\":\n\t\tport = 161\n\tcase \"print-srv\":\n\t\tport = 170\n\tcase \"bgp\":\n\t\tport = 179\n\tcase \"irc\":\n\t\tport = 194\n\tcase \"imap3\":\n\t\tport = 220\n\tcase \"ldap\":\n\t\tport = 389\n\tcase \"https\":\n\t\tport = 443\n\tcase \"syslog\":\n\t\tport = 514\n\tcase \"printer\":\n\t\tport = 515\n\tcase \"ipp\":\n\t\tport = 631\n\tcase \"ldaps\":\n\t\tport = 636\n\tcase \"rsync\":\n\t\tport = 873\n\tcase \"ftps-data\":\n\t\tport = 989\n\tcase \"ftps\":\n\t\tport = 990\n\tcase \"telnets\":\n\t\tport = 992\n\tcase \"imaps\":\n\t\tport = 993\n\tcase \"pop3s\":\n\t\tport = 995\n\t}\n\n\treturn port\n}\n\nfunc TimeToJSONString(t *time.Time) string {\n\tif t == nil {\n\t\treturn \"\"\n\t}\n\treturn t.UTC().Format(\"2006-01-02T15:04:05Z07:00\")\n}\n\nfunc ServiceWithIdentifier(h *maphash.Hash, sessionid, address string) *platform.Service {\n\t_, _ = h.WriteString(sessionid + address)\n\tserv := &platform.Service{\n\t\tID: address + strconv.Itoa(int(h.Sum64())),\n\t}\n\th.Reset()\n\treturn serv\n}\n\nfunc X509ToOAMTLSCertificate(cert *x509.Certificate) *oamcert.TLSCertificate {\n\tif cert == nil {\n\t\treturn nil\n\t}\n\n\tvar common string\n\tnames := ScrapeSubdomainNames(strings.ToLower(strings.TrimSpace(cert.Subject.CommonName)))\n\tif len(names) == 0 {\n\t\treturn nil\n\t}\n\tcommon = names[0]\n\n\tc := &oamcert.TLSCertificate{\n\t\tVersion: strconv.Itoa(cert.Version),\n\t\tSerialNumber: cert.SerialNumber.String(),\n\t\tSubjectCommonName: common,\n\t\tIssuerCommonName: cert.Issuer.CommonName,\n\t\tNotBefore: TimeToJSONString(&cert.NotBefore),\n\t\tNotAfter: TimeToJSONString(&cert.NotAfter),\n\t\tSignatureAlgorithm: cert.SignatureAlgorithm.String(),\n\t\tPublicKeyAlgorithm: cert.PublicKeyAlgorithm.String(),\n\t\tIsCA: cert.IsCA,\n\t\tCRLDistributionPoints: cert.CRLDistributionPoints,\n\t\tSubjectKeyID: string(cert.SubjectKeyId),\n\t\tAuthorityKeyID: string(cert.AuthorityKeyId),\n\t}\n\n\tif cert.KeyUsage&x509.KeyUsageDigitalSignature > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageDigitalSignature)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageContentCommitment > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageContentCommitment)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageKeyEncipherment > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageKeyEncipherment)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageDataEncipherment > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageDataEncipherment)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageKeyAgreement > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageKeyAgreement)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageCertSign > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageCertSign)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageCRLSign > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageCRLSign)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageEncipherOnly > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageEncipherOnly)\n\t}\n\tif cert.KeyUsage&x509.KeyUsageDecipherOnly > 0 {\n\t\tc.KeyUsage = append(c.KeyUsage, oamcert.KeyUsageDecipherOnly)\n\t}\n\n\tfor _, usage := range cert.ExtKeyUsage {\n\t\tswitch usage {\n\t\tcase x509.ExtKeyUsageAny:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageAny)\n\t\tcase x509.ExtKeyUsageServerAuth:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageServerAuth)\n\t\tcase x509.ExtKeyUsageClientAuth:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageClientAuth)\n\t\tcase x509.ExtKeyUsageCodeSigning:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageCodeSigning)\n\t\tcase x509.ExtKeyUsageEmailProtection:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageEmailProtection)\n\t\tcase x509.ExtKeyUsageIPSECEndSystem:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageIPSECEndSystem)\n\t\tcase x509.ExtKeyUsageIPSECTunnel:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageIPSECTunnel)\n\t\tcase x509.ExtKeyUsageIPSECUser:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageIPSECUser)\n\t\tcase x509.ExtKeyUsageTimeStamping:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageTimeStamping)\n\t\tcase x509.ExtKeyUsageOCSPSigning:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageOCSPSigning)\n\t\tcase x509.ExtKeyUsageMicrosoftServerGatedCrypto:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageMicrosoftServerGatedCrypto)\n\t\tcase x509.ExtKeyUsageNetscapeServerGatedCrypto:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageNetscapeServerGatedCrypto)\n\t\tcase x509.ExtKeyUsageMicrosoftCommercialCodeSigning:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageMicrosoftCommercialCodeSigning)\n\t\tcase x509.ExtKeyUsageMicrosoftKernelCodeSigning:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, oamcert.ExtKeyUsageMicrosoftKernelCodeSigning)\n\t\tdefault:\n\t\t\tc.ExtKeyUsage = append(c.ExtKeyUsage, \"Unknown\")\n\t\t}\n\t}\n\treturn c\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/resolvers.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/resolve/conn\"\n\t\"github.com/owasp-amass/resolve/pool\"\n\t\"github.com/owasp-amass/resolve/selectors\"\n\t\"github.com/owasp-amass/resolve/servers\"\n\t\"github.com/owasp-amass/resolve/types\"\n\t\"github.com/owasp-amass/resolve/utils\"\n\t\"github.com/owasp-amass/resolve/wildcards\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype baseline struct {\n\taddress string\n\tqps int\n}\n\n// baselineResolvers is a list of trusted public DNS resolvers.\nvar baselineResolvers = []baseline{\n\t{\"8.8.8.8\", 5}, // Google Primary\n\t//\t{\"8.8.4.4\", 5}, // Google Secondary\n\t{\"95.85.95.85\", 2}, // Gcore DNS Primary\n\t{\"2.56.220.2\", 2}, // Gcore DNS Secondary\n\t{\"76.76.2.0\", 2}, // ControlD Primary\n\t{\"76.76.10.0\", 2}, // ControlD Secondary\n\t{\"9.9.9.9\", 2}, // Quad9 Primary\n\t{\"149.112.112.112\", 2}, // Quad9 Secondary\n\t{\"208.67.222.222\", 2}, // Cisco OpenDNS Home Primary\n\t{\"208.67.220.220\", 2}, // Cisco OpenDNS Home Secondary\n\t{\"1.1.1.1\", 3}, // Cloudflare Primary\n\t{\"1.0.0.1\", 3}, // Cloudflare Secondary\n\t{\"185.228.168.9\", 1}, // CleanBrowsing Primary\n\t{\"185.228.169.9\", 1}, // CleanBrowsing Secondary\n\t{\"76.76.19.19\", 1}, // Alternate DNS Primary\n\t{\"76.223.122.150\", 1}, // Alternate DNS Secondary\n\t{\"94.140.14.14\", 1}, // AdGuard DNS Primary\n\t{\"94.140.15.15\", 1}, // AdGuard DNS Secondary\n\t{\"176.103.130.130\", 1}, // AdGuard\n\t{\"176.103.130.131\", 1}, // AdGuard\n\t{\"8.26.56.26\", 1}, // Comodo Secure DNS Primary\n\t{\"8.20.247.20\", 1}, // Comodo Secure DNS Secondary\n\t{\"205.171.3.65\", 1}, // CenturyLink Level3 Primary\n\t{\"205.171.2.65\", 1}, // CenturyLink Level3 Secondary\n\t{\"64.6.64.6\", 1}, // Verisign DNS Primary\n\t{\"64.6.65.6\", 1}, // Verisign DNS Secondary\n\t{\"209.244.0.3\", 1}, // CenturyLink Level3\n\t{\"209.244.0.4\", 1}, // CenturyLink Level3\n\t{\"149.112.121.10\", 1}, // CIRA Canadian Shield Primary\n\t{\"149.112.122.10\", 1}, // CIRA Canadian Shield Secondary\n\t{\"138.197.140.189\", 1}, // OpenNIC Primary\n\t{\"162.243.19.47\", 1}, // OpenNIC Secondary\n\t{\"216.87.84.211\", 1}, // OpenNIC\n\t{\"23.90.4.6\", 1}, // OpenNIC\n\t{\"216.146.35.35\", 1}, // Oracle Dyn Primary\n\t{\"216.146.36.36\", 1}, // Oracle Dyn Secondary\n\t{\"91.239.100.100\", 1}, // UncensoredDNS Primary\n\t{\"89.233.43.71\", 1}, // UncensoredDNS Secondary\n\t{\"77.88.8.8\", 1}, // Yandex.DNS Primary\n\t{\"77.88.8.1\", 1}, // Yandex.DNS Secondary\n\t{\"74.82.42.42\", 1}, // Hurricane Electric Primary\n\t{\"94.130.180.225\", 1}, // DNS for Family Primary\n\t{\"78.47.64.161\", 1}, // DNS for Family Secondary\n\t{\"80.80.80.80\", 1}, // Freenom World Primary\n\t{\"80.80.81.81\", 1}, // Freenom World Secondary\n\t{\"84.200.69.80\", 1}, // DNS.WATCH Primary\n\t{\"84.200.70.40\", 1}, // DNS.WATCH Secondary\n\t{\"156.154.70.5\", 1}, // Neustar Primary\n\t{\"156.157.71.5\", 1}, // Neustar Secondary\n\t{\"81.218.119.11\", 1}, // GreenTeamDNS Primary\n\t{\"209.88.198.133\", 1}, // GreenTeamDNS Secondary\n\t{\"37.235.1.177\", 1}, // FreeDNS\n\t{\"38.132.106.139\", 1}, // CyberGhost\n}\n\nvar trusted *pool.Pool\nvar detector *wildcards.Detector\n\nfunc PerformQuery(name string, qtype uint16) ([]dns.RR, error) {\n\tfor num := 0; num < 10; num++ {\n\t\tmsg := utils.QueryMsg(name, qtype)\n\t\tif qtype == dns.TypePTR {\n\t\t\tmsg = utils.ReverseMsg(name)\n\t\t}\n\n\t\tif resp, err := dnsQuery(msg, trusted); err == nil && resp != nil {\n\t\t\tif wildcardDetected(resp, detector) {\n\t\t\t\treturn nil, errors.New(\"wildcard detected\")\n\t\t\t}\n\t\t\tif len(resp.Answer) > 0 {\n\t\t\t\tif rr := utils.AnswersByType(resp, qtype); len(rr) > 0 {\n\t\t\t\t\treturn rr, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.New(\"no valid answers\")\n}\n\nfunc wildcardDetected(resp *dns.Msg, r *wildcards.Detector) bool {\n\tname := strings.ToLower(utils.RemoveLastDot(resp.Question[0].Name))\n\n\tif dom, err := publicsuffix.EffectiveTLDPlusOne(name); err == nil && dom != \"\" {\n\t\treturn r.WildcardDetected(context.TODO(), resp, dom)\n\t}\n\treturn false\n}\n\nfunc dnsQuery(msg *dns.Msg, r *pool.Pool) (*dns.Msg, error) {\n\tif resp, err := r.Exchange(context.TODO(), msg); err != nil {\n\t\treturn nil, err\n\t} else if resp.Rcode == dns.RcodeNameError {\n\t\treturn nil, errors.New(\"name does not exist\")\n\t} else if resp.Rcode == dns.RcodeSuccess {\n\t\tif len(resp.Answer) == 0 {\n\t\t\treturn nil, errors.New(\"no record of this type\")\n\t\t}\n\t\treturn resp, nil\n\t}\n\treturn nil, errors.New(\"unexpected response\")\n}\n\nfunc trustedResolvers() *pool.Pool {\n\ttimeout := 2 * time.Second\n\tcpus := runtime.NumCPU()\n\t// wildcard detector\n\tserv := servers.NewNameserver(\"8.8.4.4\")\n\twconns := conn.New(cpus, selectors.NewSingle(timeout, serv))\n\tdetector = wildcards.NewDetector(serv, wconns, nil)\n\t// the server pool\n\tvar servs []types.Nameserver\n\tfor _, r := range baselineResolvers {\n\t\tservs = append(servs, servers.NewNameserver(r.address))\n\t}\n\tsel := selectors.NewRandom(timeout, servs...)\n\t//sel := selectors.NewAuthoritative(timeout, servers.NewNameserver)\n\tconns := conn.New(cpus, sel)\n\treturn pool.New(0, sel, conns, nil)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/support.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/url\"\n\txurls \"mvdan.cc/xurls/v2\"\n)\n\ntype SweepCallback func(d *et.Event, addr *oamnet.IPAddress, src *et.Source)\n\nconst MaxHandlerInstances int = 100\n\nvar done chan struct{}\nvar subre, urlre *regexp.Regexp\n\nfunc init() {\n\tdone = make(chan struct{})\n\ttrusted = trustedResolvers()\n\n\turlre = xurls.Relaxed()\n\tsubre = regexp.MustCompile(dns.AnySubdomainRegexString())\n}\n\nfunc ScrapeSubdomainNames(s string) []string {\n\tset := stringset.New()\n\tdefer set.Close()\n\n\tfor _, sub := range subre.FindAllString(s, -1) {\n\t\tif sub != \"\" {\n\t\t\tset.Insert(sub)\n\t\t}\n\t}\n\n\treturn set.Slice()\n}\n\nfunc ExtractURLFromString(s string) *url.URL {\n\tif u := urlre.FindString(s); u != \"\" {\n\t\tif !strings.HasPrefix(u, \"http\") && !strings.HasPrefix(u, \"https\") {\n\t\t\tu = \"http://\" + u\n\t\t}\n\t\treturn RawURLToOAM(u)\n\t}\n\treturn nil\n}\n\nfunc ExtractURLsFromString(s string) []*url.URL {\n\tvar results []*url.URL\n\n\tmatches := urlre.FindAllString(s, -1)\n\tif matches == nil {\n\t\treturn results\n\t}\n\n\tfor _, match := range matches {\n\t\tif match != \"\" {\n\t\t\tif !strings.HasPrefix(match, \"http\") && !strings.HasPrefix(match, \"https\") {\n\t\t\t\tmatch = \"http://\" + match\n\t\t\t}\n\t\t\tif u := RawURLToOAM(match); u != nil {\n\t\t\t\tresults = append(results, u)\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc Shutdown() {\n\tclose(done)\n}\n\nfunc TTLStartTime(c *config.Config, from, to, plugin string) (time.Time, error) {\n\tnow := time.Now()\n\n\tif matches, err := c.CheckTransformations(from, to, plugin); err == nil && matches != nil {\n\t\tif ttl := matches.TTL(plugin); ttl >= 0 {\n\t\t\treturn now.Add(time.Duration(-ttl) * time.Minute), nil\n\t\t}\n\t\tif ttl := matches.TTL(to); ttl >= 0 {\n\t\t\treturn now.Add(time.Duration(-ttl) * time.Minute), nil\n\t\t}\n\t}\n\n\treturn time.Time{}, fmt.Errorf(\"failed to obtain the TTL for transformation %s->%s\", from, to)\n}\n\nfunc GetAPI(name string, e *et.Event) (string, error) {\n\t// TODO: Add support for multiple API keys\n\tdsc := e.Session.Config().GetDataSourceConfig(name)\n\tif dsc == nil || len(dsc.Creds) == 0 {\n\t\treturn \"\", errors.New(\"no API key found\")\n\t}\n\n\tfor _, cred := range dsc.Creds {\n\t\tif cred != nil && cred.Apikey != \"\" {\n\t\t\treturn cred.Apikey, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"no API key found\")\n}\n\nfunc IPNetblock(session et.Session, addrstr string) *sessions.CIDRangerEntry {\n\tip := net.ParseIP(addrstr)\n\tif ip == nil {\n\t\treturn nil\n\t}\n\n\tentries, err := session.CIDRanger().ContainingNetworks(ip)\n\tif err != nil || len(entries) == 0 {\n\t\treturn nil\n\t}\n\n\tvar bits int\n\tvar arentry *sessions.CIDRangerEntry\n\tfor _, entry := range entries {\n\t\te, ok := entry.(*sessions.CIDRangerEntry)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tn := e.Net\n\t\tif ones, _ := n.Mask.Size(); ones > bits {\n\t\t\tbits = ones\n\t\t\tarentry = e\n\t\t}\n\t}\n\n\treturn arentry\n}\n\nfunc AddNetblock(session et.Session, cidr string, asn int, src *et.Source) error {\n\t_, ipnet, err := net.ParseCIDR(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn session.CIDRanger().Insert(&sessions.CIDRangerEntry{\n\t\tNet: ipnet,\n\t\tASN: asn,\n\t\tSrc: src,\n\t})\n}\n\nfunc IPAddressSweep(e *et.Event, addr *oamnet.IPAddress, src *et.Source, size int, callback SweepCallback) {\n\t// do not work on an IP address that was processed previously\n\t_, err := e.Session.Cache().FindEntitiesByContent(addr, e.Session.Cache().StartTime())\n\tif err == nil {\n\t\treturn\n\t}\n\n\tvar mask net.IPMask\n\taddrstr := addr.Address.String()\n\tip := net.ParseIP(addrstr)\n\tif amassnet.IsIPv4(ip) {\n\t\tmask = net.CIDRMask(18, 32)\n\t} else if amassnet.IsIPv6(ip) {\n\t\tmask = net.CIDRMask(64, 128)\n\t}\n\n\tcidr := &net.IPNet{\n\t\tIP: ip.Mask(mask),\n\t\tMask: mask,\n\t}\n\n\tfor _, ip := range amassnet.CIDRSubset(cidr, addrstr, size) {\n\t\ta := oamnet.IPAddress{\n\t\t\tType: \"IPv4\",\n\t\t\tAddress: netip.MustParseAddr(ip.String()),\n\t\t}\n\t\tif a.Address.Is6() {\n\t\t\ta.Type = \"IPv6\"\n\t\t}\n\t\tcallback(e, &a, src)\n\t}\n}\n\nfunc IsCNAME(session et.Session, name *oamdns.FQDN) (*oamdns.FQDN, bool) {\n\tfqdns, err := session.Cache().FindEntitiesByContent(name, session.Cache().StartTime())\n\tif err != nil || len(fqdns) != 1 {\n\t\treturn nil, false\n\t}\n\tfqdn := fqdns[0]\n\n\tif edges, err := session.Cache().OutgoingEdges(fqdn, session.Cache().StartTime(), \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif rec, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && rec.Header.RRType == 5 {\n\t\t\t\tif to, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil {\n\t\t\t\t\tif cname, ok := to.Asset.(*oamdns.FQDN); ok {\n\t\t\t\t\t\treturn cname, true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc NameIPAddresses(session et.Session, name *oamdns.FQDN) []*oamnet.IPAddress {\n\tfqdns, err := session.Cache().FindEntitiesByContent(name, session.Cache().StartTime())\n\tif err != nil || len(fqdns) != 1 {\n\t\treturn nil\n\t}\n\tfqdn := fqdns[0]\n\n\tvar results []*oamnet.IPAddress\n\tif edges, err := session.Cache().OutgoingEdges(fqdn, session.Cache().StartTime(), \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif rec, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && (rec.Header.RRType == 1 || rec.Header.RRType == 28) {\n\t\t\t\tif to, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil {\n\t\t\t\t\tif ip, ok := to.Asset.(*oamnet.IPAddress); ok {\n\t\t\t\t\t\tresults = append(results, ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(results) > 0 {\n\t\treturn results\n\t}\n\treturn nil\n}\n\nfunc NameResolved(session et.Session, name *oamdns.FQDN) bool {\n\tif _, found := IsCNAME(session, name); found {\n\t\treturn true\n\t}\n\tif ips := NameIPAddresses(session, name); len(ips) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype FQDNMeta struct {\n\tSLDInScope bool\n\tRecordTypes map[int]bool\n}\n\nfunc AddSLDInScope(e *et.Event) {\n\tif e == nil {\n\t\treturn\n\t} else if _, ok := e.Entity.Asset.(*oamdns.FQDN); !ok {\n\t\treturn\n\t}\n\n\tif e.Meta == nil {\n\t\te.Meta = &FQDNMeta{\n\t\t\tSLDInScope: true,\n\t\t}\n\t}\n\n\tif fm, ok := e.Meta.(*FQDNMeta); ok {\n\t\tfm.SLDInScope = true\n\t}\n}\n\nfunc HasSLDInScope(e *et.Event) bool {\n\tif e == nil {\n\t\treturn false\n\t} else if _, ok := e.Entity.Asset.(*oamdns.FQDN); !ok {\n\t\treturn false\n\t}\n\n\tif e.Meta == nil {\n\t\treturn false\n\t}\n\n\tif fm, ok := e.Meta.(*FQDNMeta); ok {\n\t\treturn fm.SLDInScope\n\t}\n\treturn false\n}\n\nfunc AddDNSRecordType(e *et.Event, rrtype int) {\n\tif e == nil {\n\t\treturn\n\t} else if _, ok := e.Entity.Asset.(*oamdns.FQDN); !ok {\n\t\treturn\n\t}\n\n\tif e.Meta == nil {\n\t\te.Meta = &FQDNMeta{\n\t\t\tRecordTypes: make(map[int]bool),\n\t\t}\n\t}\n\n\tif fm, ok := e.Meta.(*FQDNMeta); ok {\n\t\tif fm.RecordTypes == nil {\n\t\t\tfm.RecordTypes = make(map[int]bool)\n\t\t}\n\t\tfm.RecordTypes[rrtype] = true\n\t}\n}\n\nfunc HasDNSRecordType(e *et.Event, rrtype int) bool {\n\tif e == nil {\n\t\treturn false\n\t} else if _, ok := e.Entity.Asset.(*oamdns.FQDN); !ok {\n\t\treturn false\n\t}\n\n\tif e.Meta == nil {\n\t\treturn false\n\t}\n\n\tif fm, ok := e.Meta.(*FQDNMeta); ok && fm.RecordTypes != nil {\n\t\tif _, found := fm.RecordTypes[rrtype]; found {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/support_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage support\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestFQDNFilterInsert(t *testing.T) {\n\tff := NewFQDNFilter()\n\tdefer ff.Close()\n\n\tfqdn := \"www.cs.utica.edu\"\n\tff.Insert(fqdn)\n\n\tcur := ff\n\tlabels := strings.Split(fqdn, \".\")\n\tfor i := len(labels) - 1; i >= 0; i-- {\n\t\tif _, found := cur[labels[i]]; !found {\n\t\t\tt.Errorf(\"Passive DNS Filter Insert failed for label %s at index %d\", labels[i], i)\n\t\t\tbreak\n\t\t}\n\t\tif i > 0 {\n\t\t\tcur = cur[labels[i]].(FQDNFilter)\n\t\t}\n\t}\n}\n\nfunc TestFQDNFilterPrune(t *testing.T) {\n\tff := NewFQDNFilter()\n\tdefer ff.Close()\n\n\tlimit := 50\n\tfor i := 0; i < limit; i++ {\n\t\tfqdn := \"www\" + strconv.Itoa(i) + \".cs.utica.edu\"\n\t\tff.Insert(fqdn)\n\t}\n\n\tvar found bool\n\tvar name string\n\tff.Prune(limit)\n\tfor _, fqdn := range ff.Slice() {\n\t\tif fqdn == \"www1.cs.utica.edu\" {\n\t\t\tname = fqdn\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif found {\n\t\tt.Errorf(\"Passive DNS Filter Prune failed to remove the labels: %s\", name)\n\t}\n}\n\nfunc TestFQDNFilterSlice(t *testing.T) {\n\tff := NewFQDNFilter()\n\tdefer ff.Close()\n\n\tfqdn := \"www.cs.utica.edu\"\n\tff.Insert(fqdn)\n\n\tif fqdn != ff.Slice()[0] {\n\t\tt.Errorf(\"Passive DNS Filter Slice failed to produce the expected FQDN: %s\", fqdn)\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/find.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc dedupChecks(session et.Session, obj *dbt.Entity, o *oamorg.Organization) *dbt.Entity {\n\tvar names []string\n\n\tfor _, name := range []string{o.Name, o.LegalName} {\n\t\tif name != \"\" {\n\t\t\tnames = append(names, name)\n\t\t}\n\t}\n\tif len(names) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch obj.Asset.(type) {\n\tcase *contact.ContactRecord:\n\t\tif org, found := nameExistsInContactRecord(session, obj, names); found {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndSharesLocEntity(session, obj, o); err == nil {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndSharesAncestorEntity(session, obj, o); err == nil {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndHasAncestorInSession(session, o); err == nil {\n\t\t\treturn org\n\t\t}\n\tcase *oamorg.Organization:\n\t\tif org, found := nameRelatedToOrganization(session, obj, names); found {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndSharesLocEntity(session, obj, o); err == nil {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndSharesAncestorEntity(session, obj, o); err == nil {\n\t\t\treturn org\n\t\t}\n\t\tif org, err := existsAndHasAncestorInSession(session, o); err == nil {\n\t\t\treturn org\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc nameExistsInContactRecord(session et.Session, cr *dbt.Entity, names []string) (*dbt.Entity, bool) {\n\tif cr == nil {\n\t\treturn nil, false\n\t}\n\n\tif edges, err := session.Cache().OutgoingEdges(cr, time.Time{}, \"organization\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\tif _, _, found := NameMatch(session, a, names); found {\n\t\t\t\t\t\treturn a, true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc nameRelatedToOrganization(session et.Session, orgent *dbt.Entity, names []string) (*dbt.Entity, bool) {\n\tif orgent == nil {\n\t\treturn nil, false\n\t}\n\n\tif edges, err := session.Cache().IncomingEdges(orgent, time.Time{}, \"subsidiary\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\tif _, _, found := NameMatch(session, a, names); found {\n\t\t\t\t\t\treturn a, true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif edges, err := session.Cache().OutgoingEdges(orgent, time.Time{}, \"subsidiary\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\tif _, _, found := NameMatch(session, a, names); found {\n\t\t\t\t\t\treturn a, true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc existsAndSharesLocEntity(session et.Session, obj *dbt.Entity, o *oamorg.Organization) (*dbt.Entity, error) {\n\tvar locs []*dbt.Entity\n\n\tif edges, err := session.Cache().OutgoingEdges(obj, time.Time{}, \"legal_address\", \"hq_address\", \"location\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*contact.Location); ok {\n\t\t\t\t\tlocs = append(locs, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar orgents, crecords []*dbt.Entity\n\tfor _, loc := range locs {\n\t\tif edges, err := session.Cache().IncomingEdges(loc, time.Time{}, \"legal_address\", \"hq_address\", \"location\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif a, err := session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*contact.ContactRecord); ok && a.ID != obj.ID {\n\t\t\t\t\t\tcrecords = append(crecords, a)\n\t\t\t\t\t} else if _, ok := a.Asset.(*oamorg.Organization); ok && a.ID != obj.ID {\n\t\t\t\t\t\torgents = append(orgents, a)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, cr := range crecords {\n\t\tif edges, err := session.Cache().OutgoingEdges(cr, time.Time{}, \"organization\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif a, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*oamorg.Organization); ok {\n\t\t\t\t\t\torgents = append(orgents, a)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, orgent := range orgents {\n\t\tif _, _, found := NameMatch(session, orgent, []string{o.Name, o.LegalName}); found {\n\t\t\treturn orgent, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"no matching org found\")\n}\n\nfunc existsAndSharesAncestorEntity(session et.Session, obj *dbt.Entity, o *oamorg.Organization) (*dbt.Entity, error) {\n\torgents, err := orgsWithSameNames(session, []string{o.Name, o.LegalName})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tassets := []*dbt.Entity{obj}\n\tancestors := make(map[string]struct{})\n\tancestors[obj.ID] = struct{}{}\n\tfor i := 0; i < 10 && len(assets) > 0; i++ {\n\t\tremaining := assets\n\t\tassets = []*dbt.Entity{}\n\n\t\tfor _, r := range remaining {\n\t\t\tif edges, err := session.Cache().IncomingEdges(r, time.Time{}); err == nil {\n\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\tif a, err := session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\t\tif _, found := ancestors[a.ID]; !found {\n\t\t\t\t\t\t\tancestors[a.ID] = struct{}{}\n\t\t\t\t\t\t\tassets = append(assets, a)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvisited := make(map[string]struct{})\n\tfor _, orgent := range orgents {\n\t\tassets = []*dbt.Entity{orgent}\n\n\t\tfor i := 0; i < 10 && len(assets) > 0; i++ {\n\t\t\tremaining := assets\n\t\t\tassets = []*dbt.Entity{}\n\n\t\t\tfor _, r := range remaining {\n\t\t\t\tif edges, err := session.Cache().IncomingEdges(r, time.Time{}); err == nil {\n\t\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\t\tid := edge.FromEntity.ID\n\t\t\t\t\t\tif _, found := visited[id]; found {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvisited[id] = struct{}{}\n\n\t\t\t\t\t\tif a, err := session.Cache().FindEntityById(id); err == nil && a != nil {\n\t\t\t\t\t\t\tif _, found := ancestors[a.ID]; !found {\n\t\t\t\t\t\t\t\tassets = append(assets, a)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn orgent, nil\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"no matching org found\")\n}\n\nfunc existsAndHasAncestorInSession(session et.Session, o *oamorg.Organization) (*dbt.Entity, error) {\n\torgents, err := orgsWithSameNames(session, []string{o.Name, o.LegalName})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvisited := make(map[string]struct{})\n\tfor _, orgent := range orgents {\n\t\tassets := []*dbt.Entity{orgent}\n\n\t\tfor i := 0; i < 10 && len(assets) > 0; i++ {\n\t\t\tremaining := assets\n\t\t\tassets = []*dbt.Entity{}\n\n\t\t\tfor _, r := range remaining {\n\t\t\t\tif edges, err := session.Cache().IncomingEdges(r, time.Time{}); err == nil {\n\t\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\t\tid := edge.FromEntity.ID\n\t\t\t\t\t\tif _, found := visited[id]; found {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvisited[id] = struct{}{}\n\n\t\t\t\t\t\tif a, err := session.Cache().FindEntityById(id); err == nil && a != nil {\n\t\t\t\t\t\t\tif session.Queue().Has(edge.FromEntity) {\n\t\t\t\t\t\t\t\treturn orgent, nil\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tassets = append(assets, a)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"no matching org found\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/gleif.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\t\"golang.org/x/time/rate\"\n)\n\nvar gleifLimit *rate.Limiter\n\nfunc init() {\n\tlimit := rate.Every(3 * time.Second)\n\n\tgleifLimit = rate.NewLimiter(limit, 1)\n}\n\n// GLEIFSearchFuzzyCompletions performs the fuzzy completion search for the given name.\nfunc GLEIFSearchFuzzyCompletions(name string) (*FuzzyCompletionsResponse, error) {\n\tu := \"https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q=\" + url.QueryEscape(name)\n\n\t_ = gleifLimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: u})\n\tif err != nil || resp.Body == \"\" {\n\t\tmsg := fmt.Sprintf(\"Failed to obtain the LEI record for %s: %s\", name, err)\n\t\treturn nil, fmt.Errorf(\"GLEIFSearchFuzzyCompletions: %s\", msg)\n\t}\n\n\tvar result FuzzyCompletionsResponse\n\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to unmarshal the LEI record for %s: %s\", name, err)\n\t\treturn nil, fmt.Errorf(\"GLEIFSearchFuzzyCompletions: %s\", msg)\n\t} else if len(result.Data) == 0 {\n\t\treturn nil, fmt.Errorf(\"GLEIFSearchFuzzyCompletions: no results found\")\n\t}\n\n\treturn &result, nil\n}\n\n// GLEIFGetLEIRecord retrieves the LEI record for the given identifier.\nfunc GLEIFGetLEIRecord(id string) (*LEIRecord, error) {\n\tu := \"https://api.gleif.org/api/v1/lei-records/\" + id\n\n\t_ = gleifLimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: u})\n\tif err != nil || resp.StatusCode != 200 || resp.Body == \"\" {\n\t\treturn nil, err\n\t}\n\n\tvar result SingleResponse\n\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\treturn nil, err\n\t} else if result.Data.Type != \"lei-records\" || result.Data.ID != id {\n\t\treturn nil, errors.New(\"failed to find the LEI record\")\n\t}\n\treturn &result.Data, nil\n}\n\n// GLEIFGetDirectParentRecord retrieves the direct parent LEI record for the given identifier.\nfunc GLEIFGetDirectParentRecord(id string) (*LEIRecord, error) {\n\tu := \"https://api.gleif.org/api/v1/lei-records/\" + id + \"/direct-parent\"\n\n\t_ = gleifLimit.Wait(context.TODO())\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: u})\n\tif err != nil || resp.StatusCode != 200 || resp.Body == \"\" {\n\t\treturn nil, err\n\t}\n\n\tvar result SingleResponse\n\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\treturn nil, err\n\t} else if result.Data.Type != \"lei-records\" {\n\t\treturn nil, errors.New(\"failed to find the LEI record\")\n\t}\n\treturn &result.Data, nil\n}\n\n// GLEIFGetDirectChildrenRecords retrieves the direct children LEI records for the given identifier.\nfunc GLEIFGetDirectChildrenRecords(id string) ([]*LEIRecord, error) {\n\tvar children []*LEIRecord\n\n\tlast := 1\n\tlink := \"https://api.gleif.org/api/v1/lei-records/\" + id + \"/direct-children\"\n\tfor i := 1; i <= last && link != \"\"; i++ {\n\t\t_ = gleifLimit.Wait(context.TODO())\n\n\t\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{URL: link})\n\t\tif err != nil || resp.StatusCode != 200 || resp.Body == \"\" {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar result MultipleResponse\n\t\tif err := json.Unmarshal([]byte(resp.Body), &result); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, rec := range result.Data {\n\t\t\tchildren = append(children, &rec)\n\t\t}\n\n\t\tlink = result.Links.Next\n\t\tlast = result.Meta.Pagination.LastPage\n\t}\n\n\treturn children, nil\n}\n\n// LocMatch checks if the LEI record matches the location of the organization entity.\nfunc LocMatch(e *et.Event, orgent *dbt.Entity, rec *LEIRecord) bool {\n\tif rec == nil {\n\t\treturn false\n\t}\n\n\tlegal_addr := rec.Attributes.Entity.LegalAddress\n\thq_addr := rec.Attributes.Entity.HeadquartersAddress\n\tif edges, err := e.Session.Cache().OutgoingEdges(orgent,\n\t\ttime.Time{}, \"legal_address\", \"hq_address\", \"location\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif loc, ok := a.Asset.(*contact.Location); ok {\n\t\t\t\t\tfor _, p := range append([]LEIAddress{legal_addr, hq_addr}, rec.Attributes.Entity.OtherAddresses...) {\n\t\t\t\t\t\tif loc.PostalCode == p.PostalCode {\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar crs []*dbt.Entity\n\tif edges, err := e.Session.Cache().IncomingEdges(orgent, time.Time{}, \"organization\"); err == nil {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\tif _, ok := a.Asset.(*contact.ContactRecord); ok {\n\t\t\t\t\tcrs = append(crs, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, cr := range crs {\n\t\tif edges, err := e.Session.Cache().OutgoingEdges(cr, time.Time{}, \"location\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif a, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif loc, ok := a.Asset.(*contact.Location); ok {\n\t\t\t\t\t\tfor _, p := range append([]LEIAddress{legal_addr, hq_addr}, rec.Attributes.Entity.OtherAddresses...) {\n\t\t\t\t\t\t\tif loc.PostalCode == p.PostalCode {\n\t\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/gleif_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLEIRecord(t *testing.T) {\n\trecord, err := GLEIFGetLEIRecord(\"ZXTILKJKG63JELOEG630\")\n\tassert.NoError(t, err)\n\tassert.NotNil(t, record)\n\tassert.Equal(t, \"AMAZON.COM, INC.\", record.Attributes.Entity.LegalName.Name)\n}\n\nfunc TestGetDirectParentRecord(t *testing.T) {\n\trecord, err := GLEIFGetDirectParentRecord(\"25490065U2GR0UPXFY63\")\n\tassert.NoError(t, err)\n\tassert.NotNil(t, record)\n\tassert.Equal(t, \"AMAZON.COM, INC.\", record.Attributes.Entity.LegalName.Name)\n}\n\nfunc TestGetDirectChildrenRecord(t *testing.T) {\n\tchildren, err := GLEIFGetDirectChildrenRecords(\"INR2EJN1ERAN0W5ZP974\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, children)\n\tassert.GreaterOrEqual(t, len(children), 11)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/match.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n)\n\nvar acronyms []string = []string{\n\t\"Inc\",\n\t\"inc\",\n\t\"INC\",\n\t\"incorporated\",\n\t\"Incorporated\",\n\t\"INCORPORATED\",\n\t\"Co\",\n\t\"co\",\n\t\"CO\",\n\t\"LLC\",\n\t\"Llc\",\n\t\"llc\",\n\t\"LTD\",\n\t\"Ltd\",\n\t\"ltd\",\n\t\"PLC\",\n\t\"Plc\",\n\t\"plc\",\n\t\"SA\",\n\t\"sa\",\n\t`S\\.A\\.`,\n\t`s\\.a\\.`,\n\t\"AG\",\n\t\"ag\",\n\t\"GmbH\",\n\t\"gmbh\",\n\t\"AB\",\n\t\"Ab\",\n\t\"ab\",\n\t\"Oy\",\n\t\"OY\",\n\t\"oy\",\n\t\"ECI\",\n\t\"eci\",\n\t\"SARL\",\n\t`SA\\sRL`,\n\t\"sarl\",\n\t`sa\\srl`,\n\t`S\\.A\\.R\\.L`,\n\t`S\\.A\\.\\sR\\.L`,\n\t`s\\.a\\.r\\.l`,\n\t`s\\.a\\.\\sr\\.l`,\n}\n\n// ExtractBrandName extracts the brand name from a given organization name.\nfunc ExtractBrandName(name string) string {\n\tstart := `([a-zA-Z0-9]{1}[\\sa-zA-Z0-9.\\-']+)([,\\s]{1,3})`\n\texp := start + \"(\" + strings.Join(acronyms, \"|\") + `)?([.,\\s]{0,3})$`\n\tre := regexp.MustCompile(exp)\n\n\tmatches := re.FindStringSubmatch(name)\n\tif len(matches) < 5 {\n\t\treturn name\n\t}\n\treturn strings.TrimSpace(matches[1])\n}\n\n// NameMatch checks if the provided organization entity matches any of the given names.\nfunc NameMatch(session et.Session, orgent *dbt.Entity, names []string) ([]string, []string, bool) {\n\tvar found bool\n\tvar exact, partial []string\n\n\tif orgent == nil || len(names) == 0 {\n\t\treturn exact, partial, found\n\t}\n\n\to, ok := orgent.Asset.(*org.Organization)\n\tif !ok {\n\t\treturn exact, partial, found\n\t}\n\n\tvar orgNames []string\n\tif o.Name != \"\" {\n\t\torgNames = append(orgNames, o.Name)\n\t}\n\tif o.LegalName != \"\" {\n\t\torgNames = append(orgNames, o.LegalName)\n\t}\n\n\tif edges, err := session.Cache().OutgoingEdges(orgent, time.Time{}, \"id\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := session.Cache().FindEntityById(edge.ToEntity.ID); err == nil && a != nil {\n\t\t\t\tif id, ok := a.Asset.(*general.Identifier); ok &&\n\t\t\t\t\t(id.Type == general.OrganizationName || id.Type == general.LegalName) {\n\t\t\t\t\torgNames = append(orgNames, id.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswg := metrics.NewSmithWatermanGotoh()\n\tswg.CaseSensitive = false\n\tswg.GapPenalty = -0.1\n\tswg.Substitution = metrics.MatchMismatch{\n\t\tMatch: 1,\n\t\tMismatch: -0.5,\n\t}\n\n\tfor _, orgname := range orgNames {\n\t\tvar remaining []string\n\n\t\tfor _, name := range names {\n\t\t\tif strings.EqualFold(orgname, name) {\n\t\t\t\tfound = true\n\t\t\t\texact = append(exact, name)\n\t\t\t} else {\n\t\t\t\tremaining = append(remaining, name)\n\t\t\t}\n\t\t}\n\n\t\tfor _, name := range remaining {\n\t\t\tif score := strutil.Similarity(orgname, name, swg); score >= 0.85 {\n\t\t\t\tfound = true\n\t\t\t\tpartial = append(partial, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn exact, partial, found\n}\n\nfunc orgsWithSameNames(session et.Session, names []string) ([]*dbt.Entity, error) {\n\tvar idents []*dbt.Entity\n\n\tfor _, n := range names {\n\t\tif n == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tname := strings.ToLower(n)\n\n\t\t// check for known organization name identifiers\n\t\tif assets, err := session.Cache().FindEntitiesByContent(&general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.OrganizationName, name),\n\t\t\tID: name,\n\t\t\tType: general.OrganizationName,\n\t\t}, time.Time{}); err == nil {\n\t\t\tfor _, a := range assets {\n\t\t\t\tif _, ok := a.Asset.(*general.Identifier); ok {\n\t\t\t\t\tidents = append(idents, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// check for known legal name identifiers\n\t\tif assets, err := session.Cache().FindEntitiesByContent(&general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.LegalName, name),\n\t\t\tID: name,\n\t\t\tType: general.LegalName,\n\t\t}, time.Time{}); err == nil {\n\t\t\tfor _, a := range assets {\n\t\t\t\tif _, ok := a.Asset.(*general.Identifier); ok {\n\t\t\t\t\tidents = append(idents, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar orgents []*dbt.Entity\n\tfor _, ident := range idents {\n\t\tif edges, err := session.Cache().IncomingEdges(ident, time.Time{}, \"id\"); err == nil {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif a, err := session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && a != nil {\n\t\t\t\t\tif _, ok := a.Asset.(*org.Organization); ok {\n\t\t\t\t\t\torgents = append(orgents, a)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(orgents) == 0 {\n\t\treturn nil, errors.New(\"no matching organizations were found\")\n\t}\n\treturn orgents, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/org.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\t\"github.com/google/uuid\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n)\n\nvar createOrgLock sync.Mutex\n\nfunc createOrgUnlock(delay bool) {\n\tif !delay {\n\t\tcreateOrgLock.Unlock()\n\t\treturn\n\t}\n\t// If a delay is requested, wait before unlocking\n\tgo func(d bool) {\n\t\ttime.Sleep(2 * time.Second)\n\t\tcreateOrgLock.Unlock()\n\t}(delay)\n}\n\nfunc CreateOrgAsset(session et.Session, obj *dbt.Entity, rel oam.Relation, o *oamorg.Organization, src *et.Source) (*dbt.Entity, error) {\n\tcreateOrgLock.Lock()\n\tdefer createOrgUnlock(rel == nil)\n\n\tif o == nil || o.Name == \"\" {\n\t\treturn nil, errors.New(\"missing the organization name\")\n\t} else if src == nil {\n\t\treturn nil, errors.New(\"missing the source\")\n\t}\n\n\tvar orgent *dbt.Entity\n\tif obj != nil {\n\t\torgent = dedupChecks(session, obj, o)\n\t}\n\n\tif orgent == nil {\n\t\tname := strings.ToLower(o.Name)\n\t\tid := &general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.OrganizationName, name),\n\t\t\tID: name,\n\t\t\tType: general.OrganizationName,\n\t\t}\n\n\t\tif ident, err := session.Cache().CreateAsset(id); err == nil && ident != nil {\n\t\t\t_, _ = session.Cache().CreateEntityProperty(ident, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\n\t\t\to.ID = determineOrgID(name)\n\t\t\torgent, err = session.Cache().CreateAsset(o)\n\t\t\tif err != nil || orgent == nil {\n\t\t\t\treturn nil, errors.New(\"failed to create the OAM Organization asset\")\n\t\t\t}\n\n\t\t\t_, _ = session.Cache().CreateEntityProperty(orgent, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\n\t\t\tif err := createRelation(session, orgent, &general.SimpleRelation{Name: \"id\"}, ident, src); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif obj != nil && rel != nil && orgent != nil && obj.ID != orgent.ID {\n\t\tif err := createRelation(session, obj, rel, orgent, src); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn orgent, nil\n}\n\nfunc determineOrgID(name string) string {\n\tvar rec *LEIRecord\n\n\tif records, err := GLEIFSearchFuzzyCompletions(name); err == nil && records != nil && len(records.Data) > 0 {\n\t\tswg := metrics.NewSmithWatermanGotoh()\n\t\tswg.CaseSensitive = false\n\t\tswg.GapPenalty = -0.1\n\t\tswg.Substitution = metrics.MatchMismatch{\n\t\t\tMatch: 1,\n\t\t\tMismatch: -0.5,\n\t\t}\n\n\t\tvar conf int\n\t\tfor _, data := range records.Data {\n\t\t\tif data.Type != \"fuzzycompletions\" || data.Relationships.LEIRecords.Data.Type != \"lei-records\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmatch := data.Attributes.Value\n\t\t\tlei := data.Relationships.LEIRecords.Data.ID\n\t\t\tif !strings.Contains(strings.ToLower(match), strings.ToLower(name)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsim := strutil.Similarity(name, match, swg)\n\t\t\tscore := int(math.Round(sim * 30))\n\n\t\t\tif len(records.Data) == 1 {\n\t\t\t\tscore += 30\n\t\t\t}\n\n\t\t\tif score > conf {\n\t\t\t\tif r, err := GLEIFGetLEIRecord(lei); err == nil {\n\t\t\t\t\trec = r\n\t\t\t\t\tconf = score\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif rec != nil {\n\t\tresult := fmt.Sprintf(\"%s:%s:\", rec.Attributes.Entity.LegalName.Name, rec.Attributes.Entity.Jurisdiction)\n\n\t\tif val := rec.Attributes.Entity.RegisteredAs; val != \"\" {\n\t\t\tresult += val\n\t\t} else if val := rec.Attributes.Entity.RegisteredAt.Other; val != \"\" {\n\t\t\tresult += val\n\t\t} else {\n\t\t\tresult += rec.ID\n\t\t}\n\n\t\treturn result\n\t}\n\t// If no LEI record is found, generate a UUID as the identifier.\n\t// This ensures that the organization has a unique identifier even without an LEI record\n\treturn uuid.New().String()\n}\n\nfunc createRelation(session et.Session, obj *dbt.Entity, rel oam.Relation, subject *dbt.Entity, src *et.Source) error {\n\tedge, err := session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: obj,\n\t\tToEntity: subject,\n\t})\n\tif err != nil {\n\t\treturn err\n\t} else if edge == nil {\n\t\treturn errors.New(\"failed to create the edge\")\n\t}\n\n\t_, err = session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: src.Name,\n\t\tConfidence: src.Confidence,\n\t})\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/support/org/types.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage org\n\ntype SingleResponse struct {\n\tMeta struct {\n\t\tGoldenCopy struct {\n\t\t\tPublishDate string `json:\"publishDate\"`\n\t\t} `json:\"goldenCopy\"`\n\t} `json:\"meta\"`\n\tData LEIRecord `json:\"data\"`\n}\n\ntype MultipleResponse struct {\n\tMeta struct {\n\t\tGoldenCopy struct {\n\t\t\tPublishDate string `json:\"publishDate\"`\n\t\t} `json:\"goldenCopy\"`\n\t\tPagination struct {\n\t\t\tCurrentPage int `json:\"currentPage\"`\n\t\t\tPerPage int `json:\"perPage\"`\n\t\t\tFrom int `json:\"from\"`\n\t\t\tTo int `json:\"to\"`\n\t\t\tTotal int `json:\"total\"`\n\t\t\tLastPage int `json:\"lastPage\"`\n\t\t} `json:\"pagination\"`\n\t} `json:\"meta\"`\n\tLinks struct {\n\t\tFirst string `json:\"first\"`\n\t\tNext string `json:\"next\"`\n\t\tLast string `json:\"last\"`\n\t} `json:\"links\"`\n\tData []LEIRecord `json:\"data\"`\n}\n\ntype FuzzyCompletionsResponse struct {\n\tData []struct {\n\t\tType string `json:\"type\"`\n\t\tAttributes struct {\n\t\t\tValue string `json:\"value\"`\n\t\t} `json:\"attributes\"`\n\t\tRelationships struct {\n\t\t\tLEIRecords struct {\n\t\t\t\tData struct {\n\t\t\t\t\tType string `json:\"type\"`\n\t\t\t\t\tID string `json:\"id\"`\n\t\t\t\t} `json:\"data\"`\n\t\t\t\tLinks struct {\n\t\t\t\t\tRelated string `json:\"related\"`\n\t\t\t\t} `json:\"links\"`\n\t\t\t} `json:\"lei-records\"`\n\t\t} `json:\"relationships\"`\n\t} `json:\"data\"`\n}\n\ntype LEIRecord struct {\n\tType string `json:\"type\"`\n\tID string `json:\"id\"`\n\tAttributes struct {\n\t\tLEI string `json:\"lei\"`\n\t\tEntity struct {\n\t\t\tLegalName struct {\n\t\t\t\tName string `json:\"name\"`\n\t\t\t\tLanguage string `json:\"language\"`\n\t\t\t} `json:\"legalName\"`\n\t\t\tOtherNames []struct {\n\t\t\t\tName string `json:\"name\"`\n\t\t\t\tLanguage string `json:\"language\"`\n\t\t\t\tType string `json:\"type\"`\n\t\t\t} `json:\"otherNames\"`\n\t\t\tTransliteratedOtherNames []struct {\n\t\t\t\tName string `json:\"name\"`\n\t\t\t\tLanguage string `json:\"language\"`\n\t\t\t\tType string `json:\"type\"`\n\t\t\t} `json:\"transliteratedOtherNames\"`\n\t\t\tLegalAddress LEIAddress `json:\"legalAddress\"`\n\t\t\tHeadquartersAddress LEIAddress `json:\"headquartersAddress\"`\n\t\t\tRegisteredAt struct {\n\t\t\t\tID string `json:\"id\"`\n\t\t\t\tOther string `json:\"other\"`\n\t\t\t} `json:\"registeredAt\"`\n\t\t\tRegisteredAs string `json:\"registeredAs\"`\n\t\t\tJurisdiction string `json:\"jurisdiction\"`\n\t\t\tCategory string `json:\"category\"`\n\t\t\tLegalForm struct {\n\t\t\t\tID string `json:\"id\"`\n\t\t\t\tOther string `json:\"other\"`\n\t\t\t} `json:\"legalForm\"`\n\t\t\tAssociatedEntity LEIEntity `json:\"associatedEntity\"`\n\t\t\tStatus string `json:\"status\"`\n\t\t\tExpiration struct {\n\t\t\t\tDate string `json:\"date\"`\n\t\t\t\tReason string `json:\"reason\"`\n\t\t\t} `json:\"expiration\"`\n\t\t\tSuccessorEntity LEIEntity `json:\"successorEntity\"`\n\t\t\tSuccessorEntities []LEIEntity `json:\"successorEntities\"`\n\t\t\tCreationDate string `json:\"creationDate\"`\n\t\t\tSubCategory string `json:\"subCategory\"`\n\t\t\tOtherAddresses []LEIAddress `json:\"otherAddresses\"`\n\t\t\tEventGroups []struct {\n\t\t\t\tGroupType string `json:\"groupType\"`\n\t\t\t\tEvents []struct {\n\t\t\t\t\tValidationDocuments string `json:\"validationDocuments\"`\n\t\t\t\t\tValidationReference string `json:\"validationReference\"`\n\t\t\t\t\tEffectiveDate string `json:\"effectiveDate\"`\n\t\t\t\t\tRecordedDate string `json:\"recordedDate\"`\n\t\t\t\t\tType string `json:\"type\"`\n\t\t\t\t\tStatus string `json:\"status\"`\n\t\t\t\t} `json:\"events\"`\n\t\t\t} `json:\"eventGroups\"`\n\t\t} `json:\"entity\"`\n\t\tRegistration struct {\n\t\t\tInitialRegistrationDate string `json:\"initialRegistrationDate\"`\n\t\t\tLastUpdateDate string `json:\"lastUpdateDate\"`\n\t\t\tStatus string `json:\"status\"`\n\t\t\tNextRenewalDate string `json:\"nextRenewalDate\"`\n\t\t\tManagingLOU string `json:\"managingLou\"`\n\t\t\tCorroborationLevel string `json:\"corroborationLevel\"`\n\t\t\tValidatedAt struct {\n\t\t\t\tID string `json:\"id\"`\n\t\t\t\tOther string `json:\"other\"`\n\t\t\t} `json:\"validatedAt\"`\n\t\t\tValidatedAs string `json:\"validatedAs\"`\n\t\t\tOtherValidationAuthorities []struct {\n\t\t\t\tValidatedAt struct {\n\t\t\t\t\tID string `json:\"id\"`\n\t\t\t\t} `json:\"validatedAt\"`\n\t\t\t\tValidatedAs string `json:\"validatedAs\"`\n\t\t\t} `json:\"otherValidationAuthorities\"`\n\t\t} `json:\"registration\"`\n\t\tBIC []string `json:\"bic\"`\n\t\tMIC []string `json:\"mic\"`\n\t\tOCID string `json:\"ocid\"`\n\t\tSPGlobal []string `json:\"spglobal\"`\n\t\tConformityFlag string `json:\"conformityFlag\"`\n\t} `json:\"attributes\"`\n\tRelationships struct {\n\t\tManagingLOU struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"managing-lou\"`\n\t\tLEIIssuer struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"lei-issuer\"`\n\t\tFieldModifications struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"field-modifications\"`\n\t\tDirectParent struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"direct-parent\"`\n\t\tUltimateParent struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"ultimate-parent\"`\n\t\tDirectChildren struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"direct-children\"`\n\t\tUltimateChildren struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"ultimate-children\"`\n\t\tFundManager struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"fund-manager\"`\n\t\tISINs struct {\n\t\t\tLinks LEIRelationshipLinks `json:\"links\"`\n\t\t} `json:\"isins\"`\n\t} `json:\"relationships\"`\n\tLinks struct {\n\t\tSelf string `json:\"self\"`\n\t} `json:\"links\"`\n}\n\ntype LEIEntity struct {\n\tLEI string `json:\"lei\"`\n\tName string `json:\"name\"`\n}\n\ntype LEIAddress struct {\n\tLanguage string `json:\"language\"`\n\tAddressLines []string `json:\"addressLines\"`\n\tAddressNumber string `json:\"addressNumber\"`\n\tAddressNumberWithinBuilding string `json:\"addressNumberWithinBuilding\"`\n\tMailRouting string `json:\"mailRouting\"`\n\tCity string `json:\"city\"`\n\tRegion string `json:\"region\"`\n\tCountry string `json:\"country\"`\n\tPostalCode string `json:\"postalCode\"`\n}\n\ntype LEIRelationshipLinks struct {\n\tRelated string `json:\"related\"`\n\tLEIRecord string `json:\"lei-record\"`\n\tRelationshipRecord string `json:\"relationship-record\"`\n\tRelationshipRecords string `json:\"relationship-records\"`\n\tReportingException string `json:\"reporting-exception\"`\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/domain_record.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage whois\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\twhoisparser \"github.com/likexian/whois-parser\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support/org\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/owasp-amass/asset-db/cache\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamorg \"github.com/owasp-amass/open-asset-model/org\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\ntype domrec struct {\n\tname string\n\tplugin *whois\n\ttransforms []string\n}\n\nfunc (r *domrec) Name() string {\n\treturn r.name\n}\n\nfunc (r *domrec) check(e *et.Event) error {\n\t_, ok := e.Entity.Asset.(*oamreg.DomainRecord)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the DomainRecord asset\")\n\t}\n\n\tmatches, err := e.Session.Config().CheckTransformations(\n\t\tstring(oam.DomainRecord), append(r.transforms, r.plugin.name)...)\n\tif err != nil || matches.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tsrc := r.plugin.source\n\tvar findings []*support.Finding\n\tif record, ok := e.Meta.(*whoisparser.WhoisInfo); ok && record != nil {\n\t\tr.store(e, record, e.Entity, matches)\n\t} else {\n\t\tfindings = append(findings, r.lookup(e, e.Entity, src, matches)...)\n\t}\n\n\tif len(findings) > 0 {\n\t\tr.process(e, findings, src)\n\t}\n\treturn nil\n}\n\nfunc (r *domrec) lookup(e *et.Event, asset *dbt.Entity, src *et.Source, m *config.Matches) []*support.Finding {\n\tvar rtypes []string\n\tvar findings []*support.Finding\n\tsinces := make(map[string]time.Time)\n\n\tfor _, atype := range r.transforms {\n\t\tif !m.IsMatch(atype) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.DomainRecord), atype, r.plugin.name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsinces[atype] = since\n\n\t\tswitch atype {\n\t\tcase string(oam.FQDN):\n\t\t\trtypes = append(rtypes, \"name_server\", \"whois_server\")\n\t\tcase string(oam.ContactRecord):\n\t\t\trtypes = append(rtypes, \"registrant_contact\", \"admin_contact\", \"technical_contact\", \"billing_contact\")\n\t\t}\n\t}\n\n\tif edges, err := e.Session.Cache().OutgoingEdges(asset, e.Session.Cache().StartTime(), rtypes...); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\ta, err := e.Session.Cache().FindEntityById(edge.ToEntity.ID)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotype := string(a.Asset.AssetType())\n\n\t\t\tsince, ok := sinces[totype]\n\t\t\tif !ok || (ok && a.LastSeen.Before(since)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !r.oneOfSources(e, a, src, since) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdr := asset.Asset.(*oamreg.DomainRecord)\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"DomainRecord: \" + dr.Domain,\n\t\t\t\tTo: a,\n\t\t\t\tToName: a.Asset.Key(),\n\t\t\t\tRel: edge.Relation,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn findings\n}\n\nfunc (r *domrec) oneOfSources(e *et.Event, asset *dbt.Entity, src *et.Source, since time.Time) bool {\n\tif tags, err := e.Session.Cache().GetEntityTags(asset, since, src.Name); err == nil && len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (r *domrec) store(e *et.Event, resp *whoisparser.WhoisInfo, asset *dbt.Entity, m *config.Matches) {\n\tvar findings []*support.Finding\n\tdr := asset.Asset.(*oamreg.DomainRecord)\n\n\tif !m.IsMatch(string(oam.FQDN)) {\n\t\treturn\n\t}\n\n\tfor _, ns := range resp.Domain.NameServers {\n\t\tfor _, name := range support.ScrapeSubdomainNames(strings.ToLower(strings.TrimSpace(ns))) {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name}); err == nil && a != nil {\n\t\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\t\tFrom: asset,\n\t\t\t\t\tFromName: \"DomainRecord: \" + dr.Domain,\n\t\t\t\t\tTo: a,\n\t\t\t\t\tToName: name,\n\t\t\t\t\tRel: &general.SimpleRelation{Name: \"name_server\"},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\tif name := dr.WhoisServer; name != \"\" && len(support.ScrapeSubdomainNames(name)) > 0 {\n\t\tif a, err := e.Session.Cache().CreateAsset(&oamdns.FQDN{Name: name}); err == nil && a != nil {\n\t\t\tfindings = append(findings, &support.Finding{\n\t\t\t\tFrom: asset,\n\t\t\t\tFromName: \"DomainRecord: \" + dr.Domain,\n\t\t\t\tTo: a,\n\t\t\t\tToName: name,\n\t\t\t\tRel: &general.SimpleRelation{Name: \"whois_server\"},\n\t\t\t})\n\t\t}\n\t}\n\n\t// process the relations built above immediately\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n\n\tif !m.IsMatch(string(oam.ContactRecord)) {\n\t\treturn\n\t}\n\n\tbase := dr.WhoisServer + \", \" + dr.Domain + \", \"\n\tcontacts := []*domrecContact{\n\t\t{resp.Registrar, \"registrar_contact\", base + \"Registrar Contact Info\"},\n\t\t{resp.Registrant, \"registrant_contact\", base + \"Registrant Contact Info\"},\n\t\t{resp.Administrative, \"admin_contact\", base + \"Admin Contact Info\"},\n\t\t{resp.Technical, \"technical_contact\", base + \"Technical Contact Info\"},\n\t\t{resp.Billing, \"billing_contact\", base + \"Billing Contact Info\"},\n\t}\n\tfor _, c := range contacts {\n\t\tif c.WhoisContact != nil {\n\t\t\tr.storeContact(e, c, asset, m)\n\t\t}\n\t}\n}\n\ntype domrecContact struct {\n\tWhoisContact *whoisparser.Contact\n\tRelationName string\n\tDiscoveredAt string\n}\n\nfunc (r *domrec) storeContact(e *et.Event, c *domrecContact, dr *dbt.Entity, m *config.Matches) {\n\tcr, err := e.Session.Cache().CreateAsset(&contact.ContactRecord{DiscoveredAt: c.DiscoveredAt})\n\tif err != nil || cr == nil {\n\t\treturn\n\t}\n\n\tvar found bool\n\twc := c.WhoisContact\n\t// test if the address begins in the organization field\n\taddr := fmt.Sprintf(\"%s %s %s %s %s %s\",\n\t\twc.Organization, wc.Street, wc.City, wc.Province, wc.PostalCode, wc.Country)\n\tif loc := support.StreetAddressToLocation(addr); loc != nil &&\n\t\tstrings.HasPrefix(loc.Building, strings.ToLower(wc.Organization)) {\n\t\tfound = true\n\t\taddr = fmt.Sprintf(\"%s %s %s %s %s\",\n\t\t\twc.Street, wc.City, wc.Province, wc.PostalCode, wc.Country)\n\t} else {\n\t\twc.Organization = wc.Name\n\t}\n\n\tif found {\n\t\tif p := support.FullNameToPerson(wc.Name); p != nil && m.IsMatch(string(oam.Person)) {\n\t\t\tif a, err := e.Session.Cache().CreateAsset(p); err == nil && a != nil {\n\t\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"person\"}, cr, a)\n\t\t\t}\n\t\t}\n\t}\n\tif loc := support.StreetAddressToLocation(addr); loc != nil {\n\t\tif a, err := e.Session.Cache().CreateAsset(loc); err == nil && a != nil {\n\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"location\"}, cr, a)\n\t\t}\n\t}\n\tif email := strings.ToLower(wc.Email); m.IsMatch(string(oam.Identifier)) && email != \"\" {\n\t\tif a, err := e.Session.Cache().CreateAsset(&general.Identifier{\n\t\t\tUniqueID: fmt.Sprintf(\"%s:%s\", general.EmailAddress, email),\n\t\t\tID: email,\n\t\t\tType: general.EmailAddress,\n\t\t}); err == nil && a != nil {\n\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"id\"}, cr, a)\n\t\t}\n\t}\n\tif m.IsMatch(string(oam.Phone)) {\n\t\tif phone := support.PhoneToOAMPhone(wc.Phone, wc.PhoneExt, wc.Country); phone != nil {\n\t\t\tphone.Type = contact.PhoneTypeRegular\n\t\t\tif a, err := e.Session.Cache().CreateAsset(phone); err == nil && a != nil {\n\t\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"phone\"}, cr, a)\n\t\t\t}\n\t\t}\n\t\tif fax := support.PhoneToOAMPhone(wc.Fax, wc.FaxExt, wc.Country); fax != nil {\n\t\t\tfax.Type = contact.PhoneTypeFax\n\t\t\tif a, err := e.Session.Cache().CreateAsset(fax); err == nil && a != nil {\n\t\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"phone\"}, cr, a)\n\t\t\t}\n\t\t}\n\t}\n\tif u := support.RawURLToOAM(wc.ReferralURL); u != nil && m.IsMatch(string(oam.URL)) {\n\t\tif a, err := e.Session.Cache().CreateAsset(u); err == nil && a != nil {\n\t\t\tr.createSimpleEdge(e.Session.Cache(), &general.SimpleRelation{Name: \"url\"}, cr, a)\n\t\t}\n\t}\n\n\tvar findings []*support.Finding\n\trecord := dr.Asset.(*oamreg.DomainRecord)\n\tfindings = append(findings, &support.Finding{\n\t\tFrom: dr,\n\t\tFromName: \"DomainRecord: \" + record.Domain,\n\t\tTo: cr,\n\t\tToName: \"ContactRecord\" + c.DiscoveredAt,\n\t\tRel: &general.SimpleRelation{Name: c.RelationName},\n\t})\n\t// process the contact record relation immediately\n\tsupport.ProcessAssetsWithSource(e, findings, r.plugin.source, r.plugin.name, r.name)\n\n\t// the organization must come last due to a potential chicken-and-egg problem\n\tif m.IsMatch(string(oam.Organization)) {\n\t\torgent, err := org.CreateOrgAsset(e.Session, cr,\n\t\t\t&general.SimpleRelation{Name: \"organization\"},\n\t\t\t&oamorg.Organization{Name: wc.Organization}, r.plugin.source)\n\n\t\tif err == nil && orgent != nil {\n\t\t\to := orgent.Asset.(*oamorg.Organization)\n\n\t\t\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\t\t\tName: fmt.Sprintf(\"%s:%s\", o.Name, o.ID),\n\t\t\t\tEntity: orgent,\n\t\t\t\tSession: e.Session,\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc (r *domrec) process(e *et.Event, findings []*support.Finding, src *et.Source) {\n\tsupport.ProcessAssetsWithSource(e, findings, src, r.plugin.name, r.name)\n}\n\nfunc (r *domrec) createSimpleEdge(c *cache.Cache, rel oam.Relation, from, to *dbt.Entity) {\n\tif edge, err := c.CreateEdge(&dbt.Edge{\n\t\tRelation: rel,\n\t\tFromEntity: from,\n\t\tToEntity: to,\n\t}); err == nil && edge != nil {\n\t\t_, _ = c.CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\tSource: r.plugin.source.Name,\n\t\t\tConfidence: r.plugin.source.Confidence,\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/fqdn_lookup.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage whois\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"strings\"\n\t\"time\"\n\n\twhoisclient \"github.com/likexian/whois\"\n\twhoisparser \"github.com/likexian/whois-parser\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype fqdnLookup struct {\n\tname string\n\tplugin *whois\n}\n\nfunc (r *fqdnLookup) Name() string {\n\treturn r.name\n}\n\nfunc (r *fqdnLookup) check(e *et.Event) error {\n\tfqdn, ok := e.Entity.Asset.(*oamdns.FQDN)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the FQDN asset\")\n\t}\n\n\tdomlt := strings.ToLower(strings.TrimSpace(fqdn.Name))\n\tif dom, err := publicsuffix.EffectiveTLDPlusOne(domlt); err != nil || dom != domlt {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.FQDN), string(oam.DomainRecord), r.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar asset *dbt.Entity\n\tsrc := r.plugin.source\n\tvar record *whoisparser.WhoisInfo\n\tif support.AssetMonitoredWithinTTL(e.Session, e.Entity, src, since) {\n\t\tasset = r.lookup(e, fqdn.Name, src, since)\n\t} else {\n\t\tasset, record = r.query(e, fqdn.Name, e.Entity, src)\n\t\tsupport.MarkAssetMonitored(e.Session, e.Entity, src)\n\t}\n\n\tif asset != nil {\n\t\tr.process(e, record, e.Entity, asset)\n\t\tr.waitForDomRecContacts(e, asset)\n\t}\n\treturn nil\n}\n\nfunc (r *fqdnLookup) lookup(e *et.Event, name string, src *et.Source, since time.Time) *dbt.Entity {\n\tif assets := support.SourceToAssetsWithinTTL(e.Session, name, string(oam.DomainRecord), src, since); len(assets) > 0 {\n\t\treturn assets[0]\n\t}\n\treturn nil\n}\n\nfunc (r *fqdnLookup) query(e *et.Event, name string, asset *dbt.Entity, src *et.Source) (*dbt.Entity, *whoisparser.WhoisInfo) {\n\t_ = r.plugin.rlimit.Wait(context.TODO())\n\n\tresp, err := whoisclient.Whois(name)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn r.store(e, resp, asset, src)\n}\n\nfunc (r *fqdnLookup) store(e *et.Event, resp string, asset *dbt.Entity, src *et.Source) (*dbt.Entity, *whoisparser.WhoisInfo) {\n\tfqdn := asset.Asset.(*oamdns.FQDN)\n\n\tinfo, err := whoisparser.Parse(resp)\n\tif err != nil || info.Domain.Domain != fqdn.Name {\n\t\treturn nil, nil\n\t}\n\n\tdr := &oamreg.DomainRecord{\n\t\tRaw: resp,\n\t\tID: info.Domain.ID,\n\t\tDomain: info.Domain.Domain,\n\t\tPunycode: info.Domain.Punycode,\n\t\tName: info.Domain.Name,\n\t\tExtension: info.Domain.Extension,\n\t\tWhoisServer: info.Domain.WhoisServer,\n\t\tCreatedDate: info.Domain.CreatedDate,\n\t\tUpdatedDate: info.Domain.UpdatedDate,\n\t\tExpirationDate: info.Domain.ExpirationDate,\n\t\tDNSSEC: info.Domain.DNSSec,\n\t}\n\n\tdr.Status = append(dr.Status, info.Domain.Status...)\n\tif tstr := support.TimeToJSONString(info.Domain.CreatedDateInTime); tstr != \"\" {\n\t\tdr.CreatedDate = tstr\n\t}\n\tif tstr := support.TimeToJSONString(info.Domain.UpdatedDateInTime); tstr != \"\" {\n\t\tdr.UpdatedDate = tstr\n\t}\n\tif tstr := support.TimeToJSONString(info.Domain.ExpirationDateInTime); tstr != \"\" {\n\t\tdr.ExpirationDate = tstr\n\t}\n\n\tautasset, err := e.Session.Cache().CreateAsset(dr)\n\tif err == nil && autasset != nil {\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: &general.SimpleRelation{Name: \"registration\"},\n\t\t\tFromEntity: asset,\n\t\t\tToEntity: autasset,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: src.Name,\n\t\t\t\tConfidence: src.Confidence,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn autasset, &info\n}\n\nfunc (r *fqdnLookup) process(e *et.Event, record *whoisparser.WhoisInfo, fqdn, dr *dbt.Entity) {\n\td := dr.Asset.(*oamreg.DomainRecord)\n\n\tname := d.Domain + \" WHOIS domain record\"\n\t_ = e.Dispatcher.DispatchEvent((&et.Event{\n\t\tName: name,\n\t\tMeta: record,\n\t\tEntity: dr,\n\t\tSession: e.Session,\n\t}))\n\n\tfname := fqdn.Asset.(*oamdns.FQDN)\n\te.Session.Log().Info(\"relationship discovered\", \"from\", fname.Name, \"relation\",\n\t\t\"registration\", \"to\", name, slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n}\n\nfunc (r *fqdnLookup) waitForDomRecContacts(e *et.Event, dr *dbt.Entity) {\n\tt := time.NewTimer(time.Minute)\n\tdefer t.Stop()\n\ttick := time.NewTicker(10 * time.Second)\n\tdefer t.Stop()\n\n\tfor range tick.C {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\t// stop after one minute of waiting\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\trtypes := []string{\"registrant_contact\", \"admin_contact\", \"technical_contact\", \"billing_contact\"}\n\t\tif edges, err := e.Session.Cache().OutgoingEdges(dr, e.Session.Cache().StartTime(), rtypes...); err == nil && len(edges) > 0 {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage whois\n\nimport (\n\t\"log/slog\"\n\t\"time\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype whois struct {\n\tname string\n\tlog *slog.Logger\n\trlimit *rate.Limiter\n\tfqdn *fqdnLookup\n\tdomrec *domrec\n\tsource *et.Source\n}\n\nfunc NewWHOIS() et.Plugin {\n\tlimit := rate.Every(time.Second)\n\n\treturn &whois{\n\t\tname: \"WHOIS\",\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"WHOIS\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (w *whois) Name() string {\n\treturn w.name\n}\n\nfunc (w *whois) Start(r et.Registry) error {\n\tw.log = r.Log().WithGroup(\"plugin\").With(\"name\", w.name)\n\n\tw.fqdn = &fqdnLookup{\n\t\tname: w.name + \"-FQDN-Handler\",\n\t\tplugin: w,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: w,\n\t\tName: w.fqdn.name,\n\t\tPriority: 9,\n\t\tTransforms: []string{string(oam.DomainRecord)},\n\t\tEventType: oam.FQDN,\n\t\tCallback: w.fqdn.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tw.domrec = &domrec{\n\t\tname: w.name + \"-Domain-Record-Handler\",\n\t\tplugin: w,\n\t\ttransforms: []string{\n\t\t\tstring(oam.FQDN),\n\t\t\tstring(oam.URL),\n\t\t\tstring(oam.ContactRecord),\n\t\t\tstring(oam.Person),\n\t\t\tstring(oam.Organization),\n\t\t\tstring(oam.Location),\n\t\t\tstring(oam.Identifier),\n\t\t\tstring(oam.Phone),\n\t\t},\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: w,\n\t\tName: w.domrec.name,\n\t\tTransforms: w.domrec.transforms,\n\t\tEventType: oam.DomainRecord,\n\t\tCallback: w.domrec.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tw.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (w *whois) Stop() {\n\tw.log.Info(\"Plugin stopped\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/bgptools/autsys.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage bgptools\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\ntype autsys struct {\n\tsync.Mutex\n\tname string\n\tplugin *bgpTools\n}\n\nfunc (r *autsys) Name() string {\n\treturn r.name\n}\n\nfunc (r *autsys) check(e *et.Event) error {\n\tnb, ok := e.Entity.Asset.(*oamnet.Netblock)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the Netblock asset\")\n\t}\n\n\tipstr := nb.CIDR.Addr().String()\n\tif reserved, _ := amassnet.IsReservedAddress(ipstr); reserved {\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.Netblock), string(oam.AutonomousSystem), r.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tas := r.lookup(e, e.Entity, since)\n\tif as == nil {\n\t\tas = r.query(e, e.Entity)\n\t}\n\n\tif as != nil {\n\t\tr.process(e, e.Entity, as)\n\t}\n\treturn nil\n}\n\nfunc (r *autsys) lookup(e *et.Event, nb *dbt.Entity, since time.Time) *dbt.Entity {\n\tedges, err := e.Session.Cache().IncomingEdges(nb, since, \"announces\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tfor _, edge := range edges {\n\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, r.plugin.source.Name); err == nil && len(tags) > 0 {\n\t\t\tfor _, tag := range tags {\n\t\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\t\tif as, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID); err == nil && as != nil {\n\t\t\t\t\t\treturn as\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *autsys) query(e *et.Event, nb *dbt.Entity) *dbt.Entity {\n\tcidr := nb.Asset.Key()\n\n\t_, ipnet, _ := net.ParseCIDR(cidr)\n\tif ipnet == nil {\n\t\treturn nil\n\t}\n\n\tfirst, _ := amassnet.FirstLast(ipnet)\n\tif first == nil {\n\t\treturn nil\n\t}\n\n\tvar asn int\n\tsrc := r.plugin.source\n\tif entries, err := e.Session.CIDRanger().ContainingNetworks(first); err == nil && len(entries) > 0 {\n\t\tfor _, entry := range entries {\n\t\t\tif arentry, ok := entry.(*sessions.CIDRangerEntry); ok {\n\t\t\t\tif strings.EqualFold(cidr, arentry.Net.String()) {\n\t\t\t\t\tasn = arentry.ASN\n\t\t\t\t\tsrc = arentry.Src\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif asn == 0 {\n\t\targ := nb.Asset.Key()\n\n\t\tif record, err := r.plugin.whois(arg); err == nil {\n\t\t\tasn = record.ASN\n\t\t} else {\n\t\t\te.Session.Log().Error(\"failed to obtain a response from the WHOIS server\", \"err\",\n\t\t\t\terr.Error(), \"argument\", arg, slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n\t\t}\n\t}\n\n\tif asn == 0 {\n\t\treturn nil\n\t}\n\treturn r.store(e, asn, nb, src)\n}\n\nfunc (r *autsys) store(e *et.Event, asn int, nb *dbt.Entity, src *et.Source) *dbt.Entity {\n\tas, err := e.Session.Cache().CreateAsset(&oamnet.AutonomousSystem{Number: asn})\n\tif err == nil && as != nil {\n\t\t_, _ = e.Session.Cache().CreateEntityProperty(as, &general.SourceProperty{\n\t\t\tSource: src.Name,\n\t\t\tConfidence: src.Confidence,\n\t\t})\n\n\t\tif edge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\t\tRelation: &general.SimpleRelation{Name: \"announces\"},\n\t\t\tFromEntity: as,\n\t\t\tToEntity: nb,\n\t\t}); err == nil && edge != nil {\n\t\t\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\t\t\tSource: r.plugin.source.Name,\n\t\t\t\tConfidence: r.plugin.source.Confidence,\n\t\t\t})\n\t\t}\n\t}\n\treturn as\n}\n\nfunc (r *autsys) process(e *et.Event, nb, as *dbt.Entity) {\n\tasname := \"AS\" + as.Asset.Key()\n\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: asname,\n\t\tEntity: as,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", asname, \"relation\", \"announces\",\n\t\t\"to\", nb.Asset.Key(), slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/bgptools/netblock.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage bgptools\n\nimport (\n\t\"errors\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/netip\"\n\t\"time\"\n\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\ntype netblock struct {\n\tname string\n\tplugin *bgpTools\n}\n\nfunc (r *netblock) Name() string {\n\treturn r.name\n}\n\nfunc (r *netblock) check(e *et.Event) error {\n\tip, ok := e.Entity.Asset.(*oamnet.IPAddress)\n\tif !ok {\n\t\treturn errors.New(\"failed to extract the IPAddress asset\")\n\t}\n\n\tipstr := ip.Address.String()\n\tif reserved, _ := amassnet.IsReservedAddress(ipstr); reserved {\n\t\treturn nil\n\t}\n\t// check if there's a netblock associated with this IP address\n\tif found, err := e.Session.CIDRanger().Contains(net.ParseIP(ipstr)); err == nil && found {\n\t\t// the rest of the work will be done further down the pipeline\n\t\treturn nil\n\t}\n\n\tsince, err := support.TTLStartTime(e.Session.Config(), string(oam.IPAddress), string(oam.Netblock), r.plugin.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnb, as := r.lookup(e, e.Entity, since)\n\tif nb == nil || as == nil {\n\t\tnb, as = r.query(e, e.Entity)\n\t}\n\n\tif nb != nil && as != nil {\n\t\tif asnent, ok := as.Asset.(*oamnet.AutonomousSystem); ok {\n\t\t\tif _, ipnet, err := net.ParseCIDR(nb.Asset.(*oamnet.Netblock).CIDR.String()); err == nil && ipnet != nil {\n\t\t\t\t_ = e.Session.CIDRanger().Insert(&sessions.CIDRangerEntry{\n\t\t\t\t\tNet: ipnet,\n\t\t\t\t\tASN: asnent.Number,\n\t\t\t\t\tSrc: r.plugin.source,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tr.process(e, e.Entity, nb, as)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *netblock) lookup(e *et.Event, ip *dbt.Entity, since time.Time) (*dbt.Entity, *dbt.Entity) {\n\taddr, ok := ip.Asset.(*oamnet.IPAddress)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tedges, err := e.Session.Cache().IncomingEdges(ip, since, \"contains\")\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tvar size int\n\tvar nb *dbt.Entity\n\tfor _, edge := range edges {\n\t\tentity, err := e.Session.Cache().FindEntityById(edge.FromEntity.ID)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif tmp, ok := entity.Asset.(*oamnet.Netblock); ok && tmp.CIDR.Contains(addr.Address) {\n\t\t\tif s := tmp.CIDR.Masked().Bits(); s > size {\n\t\t\t\tvar found bool\n\n\t\t\t\tif tags, err := e.Session.Cache().GetEdgeTags(edge, since, r.plugin.source.Name); err == nil && len(tags) > 0 {\n\t\t\t\t\tfor _, tag := range tags {\n\t\t\t\t\t\tif _, ok := tag.Property.(*general.SourceProperty); ok {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif found {\n\t\t\t\t\tsize = s\n\t\t\t\t\tnb = entity\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar found bool\n\tvar asent *dbt.Entity\n\tif nb != nil {\n\t\tedges, err := e.Session.Cache().IncomingEdges(nb, since, \"announces\")\n\t\tif err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tasent, err = e.Session.Cache().FindEntityById(edge.FromEntity.ID)\n\n\t\t\t\tif err == nil && asent != nil {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, nil\n\t}\n\n\treturn nb, asent\n}\n\nfunc (r *netblock) query(e *et.Event, ent *dbt.Entity) (*dbt.Entity, *dbt.Entity) {\n\tip := ent.Asset.(*oamnet.IPAddress)\n\taddrstr := ip.Address.String()\n\n\trecord, err := r.plugin.whois(addrstr)\n\tif err != nil || record == nil {\n\t\te.Session.Log().Error(\"failed to obtain a response from the WHOIS server\", \"err\",\n\t\t\terr.Error(), \"argument\", addrstr, slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n\t\treturn nil, nil\n\t}\n\n\treturn r.store(e, record.Prefix, ent, record.ASN)\n}\n\nfunc (r *netblock) store(e *et.Event, cidr netip.Prefix, ip *dbt.Entity, asn int) (*dbt.Entity, *dbt.Entity) {\n\tntype := \"IPv4\"\n\tif cidr.Addr().Is6() {\n\t\tntype = \"IPv6\"\n\t}\n\n\tnb, err := e.Session.Cache().CreateAsset(&oamnet.Netblock{\n\t\tCIDR: cidr,\n\t\tType: ntype,\n\t})\n\n\tif err != nil || nb == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(nb, &general.SourceProperty{\n\t\tSource: r.plugin.source.Name,\n\t\tConfidence: r.plugin.source.Confidence,\n\t})\n\n\tedge, err := e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"contains\"},\n\t\tFromEntity: nb,\n\t\tToEntity: ip,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: r.plugin.source.Name,\n\t\tConfidence: r.plugin.source.Confidence,\n\t})\n\n\tas, err := e.Session.Cache().CreateAsset(&oamnet.AutonomousSystem{Number: asn})\n\tif err != nil || as == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEntityProperty(as, &general.SourceProperty{\n\t\tSource: r.plugin.source.Name,\n\t\tConfidence: r.plugin.source.Confidence,\n\t})\n\n\tedge, err = e.Session.Cache().CreateEdge(&dbt.Edge{\n\t\tRelation: &general.SimpleRelation{Name: \"announces\"},\n\t\tFromEntity: as,\n\t\tToEntity: nb,\n\t})\n\tif err != nil || edge == nil {\n\t\treturn nil, nil\n\t}\n\n\t_, _ = e.Session.Cache().CreateEdgeProperty(edge, &general.SourceProperty{\n\t\tSource: r.plugin.source.Name,\n\t\tConfidence: r.plugin.source.Confidence,\n\t})\n\n\treturn nb, as\n}\n\nfunc (r *netblock) process(e *et.Event, ip, nb, as *dbt.Entity) {\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: nb.Asset.Key(),\n\t\tEntity: nb,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", nb.Asset.Key(), \"relation\",\n\t\t\"contains\", \"to\", ip.Asset.Key(), slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n\n\tasname := \"AS\" + as.Asset.Key()\n\t_ = e.Dispatcher.DispatchEvent(&et.Event{\n\t\tName: asname,\n\t\tEntity: as,\n\t\tSession: e.Session,\n\t})\n\n\te.Session.Log().Info(\"relationship discovered\", \"from\", asname, \"relation\", \"announces\",\n\t\t\"to\", nb.Asset.Key(), slog.Group(\"plugin\", \"name\", r.plugin.name, \"handler\", r.name))\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/plugins/whois/bgptools/plugin.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage bgptools\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/netip\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/miekg/dns\"\n\t\"github.com/owasp-amass/amass/v5/engine/plugins/support\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"golang.org/x/time/rate\"\n)\n\ntype bgpTools struct {\n\tsync.Mutex\n\tname string\n\taddr string\n\tport int\n\tlog *slog.Logger\n\tautsys *autsys\n\tnetblock *netblock\n\trlimit *rate.Limiter\n\tsource *et.Source\n}\n\nfunc NewBGPTools() et.Plugin {\n\tlimit := rate.Every(time.Second)\n\n\treturn &bgpTools{\n\t\tname: \"BGP.Tools\",\n\t\tport: 43,\n\t\trlimit: rate.NewLimiter(limit, 1),\n\t\tsource: &et.Source{\n\t\t\tName: \"BGP.Tools\",\n\t\t\tConfidence: 100,\n\t\t},\n\t}\n}\n\nfunc (bt *bgpTools) Name() string {\n\treturn bt.name\n}\n\nfunc (bt *bgpTools) Start(r et.Registry) error {\n\tbt.log = r.Log().WithGroup(\"plugin\").With(\"name\", bt.name)\n\n\trr, err := support.PerformQuery(\"bgp.tools\", dns.TypeA)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain the BGPTools IP address: %v\", err)\n\t} else if len(rr) == 0 {\n\t\treturn errors.New(\"failed to obtain the BGPTools IP address\")\n\t}\n\n\tfor _, record := range rr {\n\t\tif record.Header().Rrtype == dns.TypeA {\n\t\t\tbt.addr = strings.TrimSpace((record.(*dns.A)).A.String())\n\t\t\tbreak\n\t\t}\n\t}\n\tif bt.addr == \"\" {\n\t\treturn errors.New(\"failed to obtain the BGPTools IP address\")\n\t}\n\n\tbt.netblock = &netblock{\n\t\tname: bt.name + \"-IP-Handler\",\n\t\tplugin: bt,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: bt,\n\t\tName: bt.netblock.name,\n\t\tPriority: 1,\n\t\tTransforms: []string{string(oam.Netblock)},\n\t\tEventType: oam.IPAddress,\n\t\tCallback: bt.netblock.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tbt.autsys = &autsys{\n\t\tname: bt.name + \"-Netblock-Handler\",\n\t\tplugin: bt,\n\t}\n\tif err := r.RegisterHandler(&et.Handler{\n\t\tPlugin: bt,\n\t\tName: bt.autsys.name,\n\t\tPriority: 1,\n\t\tMaxInstances: 10,\n\t\tTransforms: []string{string(oam.AutonomousSystem)},\n\t\tEventType: oam.Netblock,\n\t\tCallback: bt.autsys.check,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tbt.log.Info(\"Plugin started\")\n\treturn nil\n}\n\nfunc (bt *bgpTools) Stop() {\n\tbt.log.Info(\"Plugin stopped\")\n}\n\ntype bgpToolsRecord struct {\n\tASN int\n\tIP netip.Addr\n\tPrefix netip.Prefix\n\tCC string\n\tRegistry string\n\tAllocatedDate time.Time\n\tASName string\n}\n\nfunc (bt *bgpTools) whois(ipstr string) (*bgpToolsRecord, error) {\n\taddr := net.JoinHostPort(bt.addr, strconv.Itoa(bt.port))\n\n\t_ = bt.rlimit.Wait(context.TODO())\n\tconn, err := amassnet.DialContext(context.TODO(), \"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to establish a connection with the WHOIS server: %v\", err)\n\t}\n\tdefer func() { _ = conn.Close() }()\n\n\tn, err := io.WriteString(conn, fmt.Sprintf(\"begin\\n%s\\nend\", ipstr))\n\tif err != nil || n == 0 {\n\t\treturn nil, fmt.Errorf(\"failed to send the request to the WHOIS server: %v\", err)\n\t}\n\n\tdata, err := io.ReadAll(conn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading the response from the WHOIS server: %v\", err)\n\t}\n\n\trecord := strings.Split(string(data), \"|\")\n\t// Ensure the record contains the necessary details (AutonomousSystem and Netblock)\n\tif len(record) < 7 {\n\t\treturn nil, errors.New(\"received insufficient data from the WHOIS server\")\n\t}\n\n\tvar r bgpToolsRecord\n\tfor i, f := range record {\n\t\tfield := strings.TrimSpace(f)\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\tnum, err := strconv.Atoi(field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.ASN = num\n\t\tcase 1:\n\t\t\tip, err := netip.ParseAddr(field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.IP = ip\n\t\tcase 2:\n\t\t\tprefix, err := netip.ParsePrefix(field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.Prefix = prefix\n\t\tcase 3:\n\t\t\tr.CC = field\n\t\tcase 4:\n\t\t\tr.Registry = field\n\t\tcase 5:\n\t\t\tt, err := time.Parse(\"2006-01-02\", field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.AllocatedDate = t\n\t\tcase 6:\n\t\t\tr.ASName = field\n\t\t}\n\t}\n\treturn &r, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/pubsub/logger.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage pubsub\n\n// Logger provides functionality for logging and subscribing to logs.\ntype Logger struct {\n\tch chan *string // Channel used to communicate log messages.\n}\n\n// NewLogger initializes and returns a new instance of Logger.\nfunc NewLogger() *Logger {\n\treturn &Logger{\n\t\tch: make(chan *string, 100), // Initialize a buffered channel for log messages.\n\t}\n}\n\n// Publish sends a log message to the log channel.\n// It ensures that log writes are thread-safe using a mutex.\nfunc (l *Logger) Publish(msg string) {\n\tl.ch <- &msg\n}\n\n// Write allows the Logger to be used as a Writer and in structured logging.\nfunc (l *Logger) Write(p []byte) (n int, err error) {\n\tgo func() {\n\t\tl.Publish(string(p))\n\t}()\n\treturn len(p), nil\n}\n\n// Subscribe provides a read-only channel to receive log messages.\n// This allows external components to \"listen\" for new logs.\nfunc (l *Logger) Subscribe() <-chan *string {\n\treturn l.ch // Return the channel for external components to read from.\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/registry/pipelines.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage registry\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/caffix/pipeline\"\n\tmultierror \"github.com/hashicorp/go-multierror\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\nfunc (r *registry) BuildPipelines() error {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tfor k := range r.handlers {\n\t\tp, err := r.buildAssetPipeline(string(k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.pipelines[k] = p\n\t}\n\treturn nil\n}\n\nfunc (r *registry) buildAssetPipeline(atype string) (*et.AssetPipeline, error) {\n\tvar stages []pipeline.Stage\n\n\tbufsize := 1\n\tfor priority := 1; priority <= 9; priority++ {\n\t\thandlers, found := r.handlers[atype][priority]\n\t\tif !found || len(handlers) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tid := fmt.Sprintf(\"%s - Priority: %d\", atype, priority)\n\t\tif len(handlers) == 1 {\n\t\t\th := handlers[0]\n\n\t\t\tif max := h.MaxInstances; max > 0 {\n\t\t\t\tstages = append(stages, pipeline.FixedPool(id, handlerTask(h), max))\n\t\t\t\tif max > bufsize {\n\t\t\t\t\tbufsize = max\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstages = append(stages, pipeline.FIFO(id, handlerTask(h)))\n\t\t\t}\n\t\t} else {\n\t\t\tvar tasks []pipeline.Task\n\n\t\t\tfor _, handler := range handlers {\n\t\t\t\tif h := handlerTask(handler); h != nil {\n\t\t\t\t\ttasks = append(tasks, h)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstages = append(stages, pipeline.Parallel(id, tasks...))\n\t\t}\n\t}\n\n\tap := &et.AssetPipeline{\n\t\tPipeline: pipeline.NewPipeline(stages...),\n\t\tQueue: et.NewPipelineQueue(),\n\t}\n\n\tgo func(p *et.AssetPipeline) {\n\t\tif err := p.Pipeline.ExecuteBuffered(context.TODO(), p.Queue, makeSink(), bufsize); err != nil {\n\t\t\tr.logger.Error(fmt.Sprintf(\"Pipeline terminated: %v\", err), \"OAM type\", atype)\n\t\t}\n\t}(ap)\n\treturn ap, nil\n}\n\nfunc makeSink() pipeline.SinkFunc {\n\treturn pipeline.SinkFunc(func(ctx context.Context, data pipeline.Data) error {\n\t\tede, ok := data.(*et.EventDataElement)\n\t\tif !ok {\n\t\t\treturn errors.New(\"pipeline sink failed to extract the EventDataElement\")\n\t\t}\n\n\t\tede.Queue <- ede\n\t\treturn nil\n\t})\n}\n\nfunc handlerTask(h *et.Handler) pipeline.TaskFunc {\n\tif h == nil || h.Callback == nil {\n\t\treturn nil\n\t}\n\n\tr := h\n\treturn pipeline.TaskFunc(func(ctx context.Context, data pipeline.Data, tp pipeline.TaskParams) (pipeline.Data, error) {\n\t\tif data == nil {\n\t\t\treturn nil, fmt.Errorf(\"%s pipeline task received a nil data element\", h.Name)\n\t\t}\n\n\t\tede, ok := data.(*et.EventDataElement)\n\t\tif !ok || ede == nil {\n\t\t\treturn nil, fmt.Errorf(\"%s pipeline task failed to extract the EventDataElement\", h.Name)\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tede.Queue <- ede\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tif ede.Event.Session.Done() {\n\t\t\t\tede.Queue <- ede\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\n\t\tpname := h.Plugin.Name()\n\t\tfrom := string(ede.Event.Entity.Asset.AssetType())\n\t\ttransformations := transformationsByType(ede.Event.Session.Config(), from)\n\t\tif len(transformations) > 0 && !allExcludesPlugin(transformations, pname) {\n\t\t\tpmatch := tosContainPlugin(transformations, pname)\n\n\t\t\tif !pmatch {\n\t\t\t\tif _, err := ede.Event.Session.Config().CheckTransformations(from, h.Transforms...); err == nil {\n\t\t\t\t\tpmatch = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif pmatch {\n\t\t\t\tif err := r.Callback(ede.Event); err != nil {\n\t\t\t\t\tede.Error = multierror.Append(ede.Error, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data, nil\n\t})\n}\n\nfunc transformationsByType(cfg *config.Config, from string) []*config.Transformation {\n\tvar transformations []*config.Transformation\n\n\tfor _, tf := range cfg.Transformations {\n\t\tif strings.EqualFold(tf.From, from) {\n\t\t\ttransformations = append(transformations, tf)\n\t\t}\n\t}\n\n\treturn transformations\n}\n\nfunc tosContainPlugin(transformations []*config.Transformation, pname string) bool {\n\tfor _, tf := range transformations {\n\t\tif strings.EqualFold(tf.To, pname) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc allExcludesPlugin(transformations []*config.Transformation, pname string) bool {\n\tvar all *config.Transformation\n\n\tfor _, tf := range transformations {\n\t\tif strings.EqualFold(tf.To, \"all\") {\n\t\t\tall = tf\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif all == nil {\n\t\treturn false\n\t}\n\n\tfor _, ex := range all.Exclude {\n\t\tif strings.EqualFold(ex, pname) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/registry/registry.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage registry\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"sync\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype registry struct {\n\tsync.RWMutex\n\tlogger *slog.Logger\n\thandlers map[string]map[int][]*et.Handler\n\tpipelines map[string]*et.AssetPipeline\n}\n\n// Create a new instance of Registry.\nfunc NewRegistry(l *slog.Logger) et.Registry {\n\treturn ®istry{\n\t\tlogger: l,\n\t\thandlers: make(map[string]map[int][]*et.Handler),\n\t\tpipelines: make(map[string]*et.AssetPipeline),\n\t}\n}\n\nfunc (r *registry) Log() *slog.Logger {\n\treturn r.logger\n}\n\n// Register a Plugin Handler on the registry.\nfunc (r *registry) RegisterHandler(h *et.Handler) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\t// is the entry currently empty?\n\tif _, found := r.handlers[string(h.EventType)]; !found {\n\t\tr.handlers[string(h.EventType)] = make(map[int][]*et.Handler)\n\t}\n\t// has this registration been made already?\n\tvar found bool\nloop:\n\tfor _, handlers := range r.handlers[string(h.EventType)] {\n\t\tfor _, handler := range handlers {\n\t\t\tif handler.Name == h.Name {\n\t\t\t\tfound = true\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}\n\tif found {\n\t\terr := fmt.Errorf(\"handler %s already registered for EventType %s\", h.Name, h.EventType)\n\t\tr.Log().Error(fmt.Sprintf(\"Failed to register a handler: %v\", err),\n\t\t\tslog.Group(\"plugin\", \"name\", h.Plugin.Name(), \"handler\", h.Name))\n\t\treturn err\n\t}\n\n\tif h.Priority == 0 {\n\t\th.Priority = 5\n\t} else if h.Priority < 0 {\n\t\th.Priority = 1\n\t} else if h.Priority > 9 {\n\t\th.Priority = 9\n\t}\n\n\tet, p := string(h.EventType), h.Priority\n\tr.handlers[et][p] = append(r.handlers[et][p], h)\n\treturn nil\n}\n\nfunc (r *registry) GetPipeline(eventType oam.AssetType) (*et.AssetPipeline, error) {\n\tr.RLock()\n\tdefer r.RUnlock()\n\n\tif p, found := r.pipelines[string(eventType)]; found {\n\t\treturn p, nil\n\t}\n\treturn nil, fmt.Errorf(\"no handlers registered for the EventType: %s\", eventType)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/registry/registry_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage registry\n\nimport (\n\t\"log/slog\"\n\t\"os\"\n\t\"testing\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\nfunc TestNewRegistry(t *testing.T) {\n\tr := NewRegistry(slog.New(slog.NewTextHandler(os.Stdout, nil)))\n\tif r == nil {\n\t\tt.Error(\"Registry is nil\")\n\t}\n}\n\nfunc FakeHandler(e *et.Event) error {\n\treturn nil\n}\n\nfunc TestRegisterHandler(t *testing.T) {\n\tr := NewRegistry(slog.New(slog.NewTextHandler(os.Stdout, nil)))\n\n\t// Register a handler\n\terr := r.RegisterHandler(&et.Handler{\n\t\tName: \"Test-MainHandler\",\n\t\tTransforms: []string{\"Test-Transform\"},\n\t\tEventType: oam.FQDN,\n\t\tCallback: FakeHandler,\n\t})\n\tif err != nil {\n\t\tt.Error(\"No handlers registered\")\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/manager.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage sessions\n\n/*\n * Amass Engine allow users to create multiple sessions.\n * Each session has its own configuration.\n * The session manager is responsible for managing all sessions,\n * it's a singleton object and it's thread-safe.\n */\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n)\n\ntype manager struct {\n\tsync.RWMutex\n\tlogger *slog.Logger\n\tsessions map[uuid.UUID]et.Session\n}\n\n// NewManager: creates a new session storage.\nfunc NewManager(l *slog.Logger) et.SessionManager {\n\treturn &manager{\n\t\tlogger: l,\n\t\tsessions: make(map[uuid.UUID]et.Session),\n\t}\n}\n\nfunc (r *manager) NewSession(cfg *config.Config) (et.Session, error) {\n\ts, err := CreateSession(cfg)\n\tif err == nil {\n\t\terr = r.AddSession(s)\n\n\t\tif err == nil {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\treturn nil, err\n}\n\n// Add: adds a session to a session storage after checking the session config.\nfunc (r *manager) AddSession(s et.Session) error {\n\tif s == nil {\n\t\treturn errors.New(\"the provided session is nil\")\n\t}\n\n\tr.Lock()\n\tif sess, ok := s.(*Session); ok {\n\t\tr.sessions[sess.id] = sess\n\t}\n\tr.Unlock()\n\n\t// TODO: Need to add the session config checks here (using the Registry)\n\treturn nil\n}\n\n// CancelSession: cancels a session in a session storage.\nfunc (r *manager) CancelSession(id uuid.UUID) {\n\ts := r.GetSession(id)\n\tif s == nil {\n\t\treturn\n\t}\n\ts.Kill()\n\n\tt := time.NewTicker(500 * time.Millisecond)\n\tdefer t.Stop()\n\n\tfor range t.C {\n\t\tss := s.Stats()\n\t\tss.Lock()\n\t\ttotal := ss.WorkItemsTotal\n\t\tcompleted := ss.WorkItemsCompleted\n\t\tss.Unlock()\n\t\tif completed >= total {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tif qdb := r.sessions[id].Queue(); qdb != nil {\n\t\tif err := qdb.Close(); err != nil {\n\t\t\ts.Log().Error(fmt.Sprintf(\"failed to close the queue for session %s: %v\", id, err))\n\t\t}\n\t}\n\tif c := r.sessions[id].Cache(); c != nil {\n\t\t_ = c.Close()\n\t}\n\tif s, ok := r.sessions[id].(*Session); ok {\n\t\ts.ranger = nil\n\t}\n\tif dir := r.sessions[id].TmpDir(); dir != \"\" {\n\t\t_ = os.RemoveAll(dir)\n\t}\n\tif db := s.DB(); db != nil {\n\t\tif err := db.Close(); err != nil {\n\t\t\ts.Log().Error(fmt.Sprintf(\"failed to close the database for session %s: %v\", id, err))\n\t\t}\n\t}\n\tdelete(r.sessions, id)\n}\n\nfunc (r *manager) GetSessions() []et.Session {\n\tr.RLock()\n\tdefer r.RUnlock()\n\n\tsessions := make([]et.Session, 0, len(r.sessions))\n\tfor _, s := range r.sessions {\n\t\tsessions = append(sessions, s)\n\t}\n\n\treturn sessions\n}\n\n// GetSession: returns a session from a session storage.\nfunc (r *manager) GetSession(id uuid.UUID) et.Session {\n\tr.RLock()\n\tdefer r.RUnlock()\n\n\tif s, found := r.sessions[id]; found {\n\t\treturn s\n\t}\n\treturn nil\n}\n\n// Shutdown: cleans all sessions from a session storage and shutdown the session storage.\nfunc (r *manager) Shutdown() {\n\tvar list []uuid.UUID\n\n\tr.Lock()\n\tfor k := range r.sessions {\n\t\tlist = append(list, k)\n\t}\n\tr.Unlock()\n\n\tvar wg sync.WaitGroup\n\tfor _, id := range list {\n\t\twg.Add(1)\n\t\tgo func(id uuid.UUID, wg *sync.WaitGroup) {\n\t\t\tdefer wg.Done()\n\n\t\t\tr.CancelSession(id)\n\t\t}(id, &wg)\n\t}\n\twg.Wait()\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/queue.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage sessions\n\nimport (\n\t\"errors\"\n\t\"path/filepath\"\n\n\tqdb \"github.com/owasp-amass/amass/v5/engine/sessions/queuedb\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype sessionQueue struct {\n\tsession *Session\n\tdb *qdb.QueueDB\n}\n\nfunc newSessionQueue(s *Session) (*sessionQueue, error) {\n\tdbfile := filepath.Join(s.TmpDir(), \"queue.db\")\n\n\tdb, err := qdb.NewQueueDB(dbfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sessionQueue{\n\t\tsession: s,\n\t\tdb: db,\n\t}, nil\n}\n\nfunc (sq *sessionQueue) Close() error {\n\treturn sq.db.Close()\n}\n\nfunc (sq *sessionQueue) Has(e *dbt.Entity) bool {\n\tif e == nil || e.ID == \"\" {\n\t\treturn false\n\t}\n\treturn sq.db.Has(e.ID)\n}\n\nfunc (sq *sessionQueue) Append(e *dbt.Entity) error {\n\tif e == nil {\n\t\treturn errors.New(\"entity is nil\")\n\t}\n\tif e.ID == \"\" {\n\t\treturn errors.New(\"entity ID is empty\")\n\t}\n\tif e.Asset == nil {\n\t\treturn errors.New(\"asset is nil\")\n\t}\n\n\tkey := e.Asset.AssetType()\n\tif key == \"\" {\n\t\treturn errors.New(\"asset type is empty\")\n\t}\n\treturn sq.db.Append(key, e.ID)\n}\n\nfunc (sq *sessionQueue) Next(atype oam.AssetType, num int) ([]*dbt.Entity, error) {\n\tids, err := sq.db.Next(atype, num)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*dbt.Entity\n\tfor _, id := range ids {\n\t\tif e, err := sq.session.Cache().FindEntityById(id); err == nil {\n\t\t\tresults = append(results, e)\n\t\t}\n\t}\n\n\tif len(results) == 0 {\n\t\treturn nil, errors.New(\"no entities found\")\n\t}\n\treturn results, nil\n}\n\nfunc (sq *sessionQueue) Processed(e *dbt.Entity) error {\n\tif e == nil || e.ID == \"\" {\n\t\treturn errors.New(\"entity is nil or ID is empty\")\n\t}\n\treturn sq.db.Processed(e.ID)\n}\n\nfunc (sq *sessionQueue) Delete(e *dbt.Entity) error {\n\tif e == nil || e.ID == \"\" {\n\t\treturn errors.New(\"entity is nil or ID is empty\")\n\t}\n\treturn sq.db.Delete(e.ID)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/ranger.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage sessions\n\nimport (\n\t\"net\"\n\t\"sync\"\n\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\t\"github.com/yl2chen/cidranger\"\n)\n\ntype CIDRangerEntry struct {\n\tNet *net.IPNet\n\tASN int\n\tSrc *et.Source\n}\n\nfunc (r *CIDRangerEntry) Network() net.IPNet {\n\treturn *r.Net\n}\n\nfunc (r *CIDRangerEntry) AutonomousSystem() int {\n\treturn r.ASN\n}\n\nfunc (r *CIDRangerEntry) Source() *et.Source {\n\treturn r.Src\n}\n\ntype amassRanger struct {\n\tsync.Mutex\n\tranger cidranger.Ranger\n}\n\nfunc (r *amassRanger) Insert(entry cidranger.RangerEntry) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.Insert(entry)\n}\n\nfunc (r *amassRanger) Remove(network net.IPNet) (cidranger.RangerEntry, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.Remove(network)\n}\n\nfunc (r *amassRanger) Contains(ip net.IP) (bool, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.Contains(ip)\n}\n\nfunc (r *amassRanger) ContainingNetworks(ip net.IP) ([]cidranger.RangerEntry, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.ContainingNetworks(ip)\n}\n\nfunc (r *amassRanger) CoveredNetworks(network net.IPNet) ([]cidranger.RangerEntry, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.CoveredNetworks(network)\n}\n\nfunc (r *amassRanger) Len() int {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\treturn r.ranger.Len()\n}\n\nfunc NewAmassRanger() cidranger.Ranger {\n\treturn &amassRanger{ranger: cidranger.NewPCTrieRanger()}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/session.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage sessions\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/pubsub\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions/scope\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\tassetdb \"github.com/owasp-amass/asset-db\"\n\t\"github.com/owasp-amass/asset-db/cache\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\t\"github.com/owasp-amass/asset-db/repository/neo4j\"\n\t\"github.com/owasp-amass/asset-db/repository/sqlrepo\"\n\t\"github.com/yl2chen/cidranger\"\n)\n\ntype Session struct {\n\tid uuid.UUID\n\tlog *slog.Logger\n\tps *pubsub.Logger\n\tcfg *config.Config\n\tscope *scope.Scope\n\tdb repository.Repository\n\tqueue *sessionQueue\n\tdsn string\n\tdbtype string\n\tcache *cache.Cache\n\tranger cidranger.Ranger\n\ttmpdir string\n\tstats *et.SessionStats\n\tdone chan struct{}\n\tfinished bool\n}\n\n// CreateSession initializes a new Session object based on the provided configuration.\n// The session object represents the state of an active engine enumeration.\nfunc CreateSession(cfg *config.Config) (et.Session, error) {\n\t// Use default configuration if none is provided\n\tif cfg == nil {\n\t\tcfg = config.NewConfig()\n\t}\n\t// Create a new session object\n\ts := &Session{\n\t\tid: uuid.New(),\n\t\tcfg: cfg,\n\t\tscope: scope.CreateFromConfigScope(cfg),\n\t\tranger: NewAmassRanger(),\n\t\tps: pubsub.NewLogger(),\n\t\tstats: new(et.SessionStats),\n\t\tdone: make(chan struct{}),\n\t}\n\ts.log = slog.New(slog.NewJSONHandler(s.ps, nil)).With(\"session\", s.id)\n\n\terr := s.setupDB()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.tmpdir, err = s.createTemporaryDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, err := s.createFileCacheRepo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.cache, err = cache.New(c, s.db, time.Minute)\n\tif err != nil || s.cache == nil {\n\t\treturn nil, errors.New(\"failed to create the session cache\")\n\t}\n\n\ts.queue, err = newSessionQueue(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.log.Info(\"Session initialized\")\n\ts.log.Info(\"Temporary directory created\", slog.String(\"dir\", s.tmpdir))\n\ts.log.Info(\"Database connection established\", slog.String(\"dsn\", s.dsn))\n\treturn s, nil\n}\n\nfunc (s *Session) ID() uuid.UUID {\n\treturn s.id\n}\n\nfunc (s *Session) Log() *slog.Logger {\n\treturn s.log\n}\n\nfunc (s *Session) PubSub() *pubsub.Logger {\n\treturn s.ps\n}\n\nfunc (s *Session) Config() *config.Config {\n\treturn s.cfg\n}\n\nfunc (s *Session) Scope() *scope.Scope {\n\treturn s.scope\n}\n\nfunc (s *Session) DB() repository.Repository {\n\treturn s.db\n}\n\nfunc (s *Session) Cache() *cache.Cache {\n\treturn s.cache\n}\n\nfunc (s *Session) Queue() et.SessionQueue {\n\treturn s.queue\n}\n\nfunc (s *Session) CIDRanger() cidranger.Ranger {\n\treturn s.ranger\n}\n\nfunc (s *Session) TmpDir() string {\n\treturn s.tmpdir\n}\n\nfunc (s *Session) Stats() *et.SessionStats {\n\treturn s.stats\n}\n\nfunc (s *Session) Done() bool {\n\treturn s.finished\n}\n\nfunc (s *Session) Kill() {\n\tselect {\n\tcase <-s.done:\n\t\treturn\n\tdefault:\n\t}\n\tclose(s.done)\n\ts.finished = true\n}\n\nfunc (s *Session) setupDB() error {\n\tif err := s.selectDBMS(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (s *Session) selectDBMS() error {\n\t// If no graph databases are specified, use a default SQLite database.\n\tif s.cfg.GraphDBs == nil {\n\t\ts.cfg.GraphDBs = []*config.Database{\n\t\t\t{\n\t\t\t\tPrimary: true,\n\t\t\t\tSystem: \"sqlite\",\n\t\t\t},\n\t\t}\n\t}\n\t// Iterate over the GraphDBs specified in the configuration.\n\t// The goal is to determine the primary database's connection details.\n\tfor _, db := range s.cfg.GraphDBs {\n\t\tif db.Primary {\n\t\t\t// Convert the database system name to lowercase for consistent comparison.\n\t\t\tdb.System = strings.ToLower(db.System)\n\n\t\t\tswitch db.System {\n\t\t\tcase \"postgres\":\n\t\t\t\t// Construct the connection string for a Postgres database.\n\t\t\t\ts.dsn = fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s\", db.Host, db.Port, db.Username, db.Password, db.DBName)\n\t\t\t\ts.dbtype = sqlrepo.Postgres\n\t\t\tcase \"sqlite\":\n\t\t\t\tfallthrough\n\t\t\tcase \"sqlite3\":\n\t\t\t\t// Define the connection path for an SQLite database.\n\t\t\t\tpath := filepath.Join(config.OutputDirectory(s.cfg.Dir), \"assetdb.db\")\n\t\t\t\ts.dsn = path + \"?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)\"\n\t\t\t\ts.dbtype = sqlrepo.SQLite\n\t\t\tcase \"neo4j\":\n\t\t\t\tfallthrough\n\t\t\tcase \"neo4+s\":\n\t\t\t\tfallthrough\n\t\t\tcase \"neo4j+sec\":\n\t\t\t\tfallthrough\n\t\t\tcase \"bolt\":\n\t\t\t\tfallthrough\n\t\t\tcase \"bolt+s\":\n\t\t\t\tfallthrough\n\t\t\tcase \"bolt+sec\":\n\t\t\t\ts.dsn = db.URL\n\t\t\t\ts.dbtype = neo4j.Neo4j\n\t\t\t}\n\t\t\t// Break the loop once the primary database is found.\n\t\t\tbreak\n\t\t}\n\t}\n\t// Check if a valid database connection string was generated.\n\tif s.dsn == \"\" || s.dbtype == \"\" {\n\t\treturn errors.New(\"no primary database specified in the configuration\")\n\t}\n\t// Initialize the database store\n\tstore, err := assetdb.New(s.dbtype, s.dsn)\n\tif err != nil {\n\t\treturn errors.New(\"failed to initialize database store: \" + err.Error())\n\t}\n\ts.db = store\n\treturn nil\n}\n\nfunc (s *Session) createTemporaryDir() (string, error) {\n\toutdir := config.OutputDirectory()\n\tif outdir == \"\" {\n\t\treturn \"\", errors.New(\"failed to obtain the output directory\")\n\t}\n\n\tdir, err := os.MkdirTemp(outdir, \"session-\"+s.ID().String())\n\tif err != nil {\n\t\treturn \"\", errors.New(\"failed to create the temp dir\")\n\t}\n\n\treturn dir, nil\n}\n\nfunc (s *Session) createFileCacheRepo() (repository.Repository, error) {\n\tpath := filepath.Join(s.TmpDir(), \"cache.db\")\n\tdsn := path + \"?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)\"\n\n\tc, err := assetdb.New(sqlrepo.SQLite, dsn)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create the db: %s\", err.Error())\n\t}\n\treturn c, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/queuedb/queue_db.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuedb\n\nimport (\n\t\"time\"\n\n\t\"github.com/glebarez/sqlite\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"gorm.io/gorm\"\n\t\"gorm.io/gorm/logger\"\n)\n\ntype QueueDB struct {\n\tdb *gorm.DB\n}\n\ntype Element struct {\n\tID uint64 `gorm:\"primaryKey;column:id\"`\n\tCreatedAt time.Time `gorm:\"index:idx_created_at,sort:asc;column:created_at\"`\n\tUpdatedAt time.Time\n\tType string `gorm:\"index:idx_etype;column:etype\"`\n\tEntityID string `gorm:\"index:idx_entity_id,unique;column:entity_id\"`\n\tProcessed bool `gorm:\"index:idx_processed;column:processed\"`\n}\n\nfunc NewQueueDB(dbPath string) (*QueueDB, error) {\n\tdbPath += \"?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)\"\n\n\tdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{\n\t\tSkipDefaultTransaction: true,\n\t\tLogger: logger.Default.LogMode(logger.Silent),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlDB, err := db.DB()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsqlDB.SetMaxOpenConns(1)\n\tsqlDB.SetMaxIdleConns(1)\n\tsqlDB.SetConnMaxLifetime(time.Hour)\n\tsqlDB.SetConnMaxIdleTime(10 * time.Minute)\n\n\terr = db.AutoMigrate(&Element{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &QueueDB{db: db}, nil\n}\n\nfunc (r *QueueDB) Close() error {\n\tif r.db != nil {\n\t\tsqlDB, err := r.db.DB()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn sqlDB.Close()\n\t}\n\treturn nil\n}\n\nfunc (r *QueueDB) Has(eid string) bool {\n\tvar count int64\n\n\terr := r.db.Model(&Element{}).Where(\"entity_id = ?\", eid).Count(&count).Error\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn count > 0\n}\n\nfunc (r *QueueDB) Append(atype oam.AssetType, eid string) error {\n\treturn r.db.Create(&Element{\n\t\tType: string(atype),\n\t\tEntityID: eid,\n\t\tProcessed: false,\n\t}).Error\n}\n\nfunc (r *QueueDB) Next(atype oam.AssetType, num int) ([]string, error) {\n\tvar elements []Element\n\tkey := string(atype)\n\n\tr.db.Model(&Element{}).Where(\"etype = ? AND processed = ?\",\n\t\tkey, false).Order(\"created_at ASC\").Limit(num).Find(&elements)\n\n\tvar results []string\n\tfor _, element := range elements {\n\t\tresults = append(results, element.EntityID)\n\t}\n\treturn results, nil\n}\n\nfunc (r *QueueDB) Processed(eid string) error {\n\treturn r.db.Model(&Element{}).Where(\"entity_id = ?\", eid).Update(\"processed\", true).Error\n}\n\nfunc (r *QueueDB) Delete(eid string) error {\n\tvar element Element\n\n\terr := r.db.Model(&Element{}).Where(\"entity_id = ?\", eid).Find(&element).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.db.Delete(&element).Error\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/queuedb/queue_db_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuedb\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc makeTempDir() (string, error) {\n\tdir, err := os.MkdirTemp(\"\", fmt.Sprintf(\"test-%d\", rand.Intn(100)))\n\tif err != nil {\n\t\treturn \"\", errors.New(\"failed to create the temp dir\")\n\t}\n\treturn dir, nil\n}\n\nfunc TestNewQueueDB(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, queueDB, \"QueueDB should not be nil\")\n\tdefer func() { _ = queueDB.Close() }()\n\n\tfound := queueDB.db.Migrator().HasTable(&Element{})\n\tassert.True(t, found, \"Element table should exist\")\n\tfound = queueDB.db.Migrator().HasIndex(&Element{}, \"idx_created_at\")\n\tassert.True(t, found, \"Index idx_created_at should exist\")\n\tfound = queueDB.db.Migrator().HasIndex(&Element{}, \"idx_etype\")\n\tassert.True(t, found, \"Index idx_etype should exist\")\n\tfound = queueDB.db.Migrator().HasIndex(&Element{}, \"idx_entity_id\")\n\tassert.True(t, found, \"Index idx_entity_id should exist\")\n\tfound = queueDB.db.Migrator().HasIndex(&Element{}, \"idx_processed\")\n\tassert.True(t, found, \"Index idx_processed should exist\")\n}\n\nfunc TestHas(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid := \"entity1\"\n\tassert.False(t, queueDB.Has(eid), \"The element should not be in the database\")\n\n\terr = queueDB.Append(oam.FQDN, eid)\n\tassert.NoError(t, err)\n\tassert.True(t, queueDB.Has(eid), \"The element should be in the database\")\n\n\terr = queueDB.Delete(eid)\n\tassert.NoError(t, err)\n\tassert.False(t, queueDB.Has(eid), \"The element should be deleted from the database\")\n}\n\nfunc TestAppend(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid := \"entity1\"\n\terr = queueDB.Append(oam.FQDN, eid)\n\tassert.NoError(t, err)\n\n\tvar element Element\n\terr = queueDB.db.Where(\"entity_id = ?\", eid).First(&element).Error\n\tassert.NoError(t, err)\n\tassert.Equal(t, eid, element.EntityID, \"The entity ID should match\")\n\tassert.Equal(t, string(oam.FQDN), element.Type, \"The asset type should match\")\n\tassert.False(t, element.Processed, \"The processed flag should be false\")\n}\n\nfunc TestNext(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid1 := \"entity1\"\n\teid2 := \"entity2\"\n\terr = queueDB.Append(oam.FQDN, eid1)\n\tassert.NoError(t, err)\n\terr = queueDB.Append(oam.FQDN, eid2)\n\tassert.NoError(t, err)\n\n\tentities, err := queueDB.Next(oam.FQDN, 2)\n\tassert.NoError(t, err)\n\tassert.Len(t, entities, 2, \"Should return two entities\")\n\tassert.Equal(t, eid1, entities[0])\n\tassert.Equal(t, eid2, entities[1])\n}\n\nfunc TestNextWithProcessed(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid1 := \"entity1\"\n\teid2 := \"entity2\"\n\terr = queueDB.Append(oam.FQDN, eid1)\n\tassert.NoError(t, err)\n\terr = queueDB.Append(oam.FQDN, eid2)\n\tassert.NoError(t, err)\n\n\terr = queueDB.Processed(eid1)\n\tassert.NoError(t, err)\n\n\tentities, err := queueDB.Next(oam.FQDN, 2)\n\tassert.NoError(t, err)\n\tassert.Len(t, entities, 1, \"Should return one entity\")\n\tassert.Equal(t, eid2, entities[0])\n}\n\nfunc TestNextWithMultipleTypes(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid1 := \"entity1\"\n\teid2 := \"entity2\"\n\teid3 := \"entity3\"\n\terr = queueDB.Append(oam.FQDN, eid1)\n\tassert.NoError(t, err)\n\terr = queueDB.Append(oam.IPAddress, eid2)\n\tassert.NoError(t, err)\n\terr = queueDB.Append(oam.FQDN, eid3)\n\tassert.NoError(t, err)\n\n\tentitiesFQDN, err := queueDB.Next(oam.FQDN, 1)\n\tassert.NoError(t, err)\n\tassert.Len(t, entitiesFQDN, 1, \"Should return one entity for FQDN\")\n\tassert.Equal(t, eid1, entitiesFQDN[0])\n\n\tentitiesIPv4, err := queueDB.Next(oam.IPAddress, 1)\n\tassert.NoError(t, err)\n\tassert.Len(t, entitiesIPv4, 1, \"Should return one entity for IPv4\")\n\tassert.Equal(t, eid2, entitiesIPv4[0])\n\n\tentitiesFQDN2, err := queueDB.Next(oam.FQDN, 3)\n\tassert.NoError(t, err)\n\tassert.Len(t, entitiesFQDN2, 2, \"Should return two entities for FQDN\")\n\tassert.Equal(t, eid1, entitiesFQDN2[0])\n\tassert.Equal(t, eid3, entitiesFQDN2[1])\n\n\tentitiesIPv42, err := queueDB.Next(oam.IPAddress, 3)\n\tassert.NoError(t, err)\n\tassert.Len(t, entitiesIPv42, 1, \"Should return one entity for IPv4\")\n\tassert.Equal(t, eid2, entitiesIPv42[0])\n}\n\nfunc TestProcessed(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid := \"entity1\"\n\terr = queueDB.Append(oam.FQDN, eid)\n\tassert.NoError(t, err)\n\n\terr = queueDB.Processed(eid)\n\tassert.NoError(t, err)\n\n\tvar element Element\n\terr = queueDB.db.Where(\"entity_id = ?\", eid).First(&element).Error\n\tassert.NoError(t, err)\n\tassert.True(t, element.Processed, \"The processed flag should be true\")\n}\n\nfunc TestDelete(t *testing.T) {\n\tdir, err := makeTempDir()\n\tassert.NoError(t, err)\n\tdefer func() { _ = os.RemoveAll(dir) }()\n\n\tdbPath := filepath.Join(dir, \"test.sqlite\")\n\tqueueDB, err := NewQueueDB(dbPath)\n\tassert.NoError(t, err)\n\tdefer func() { _ = queueDB.Close() }()\n\n\teid := \"entity1\"\n\terr = queueDB.Append(oam.FQDN, eid)\n\tassert.NoError(t, err)\n\tassert.True(t, queueDB.Has(eid), \"The element should be in the database\")\n\n\terr = queueDB.Delete(eid)\n\tassert.NoError(t, err)\n\tassert.False(t, queueDB.Has(eid), \"The element should be deleted from the database\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/assoc.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/asset-db/cache\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\toamurl \"github.com/owasp-amass/open-asset-model/url\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\ntype Association struct {\n\tSubmission *dbt.Entity\n\tMatch *dbt.Entity\n\tRationale string\n\tConfidence int\n\tScopeChange bool\n\tImpactedAssets []*dbt.Entity\n}\n\nfunc (s *Scope) IsAssociated(c *cache.Cache, req *Association) ([]*Association, error) {\n\tif req == nil || req.Submission == nil || req.Submission.Asset == nil || req.Confidence < 0 || req.Confidence > 100 {\n\t\treturn nil, errors.New(\"invalid request\")\n\t}\n\tif atype := req.Submission.Asset.AssetType(); atype != oam.FQDN &&\n\t\tatype != oam.Identifier && atype != oam.Organization && atype != oam.Location {\n\t\treturn nil, errors.New(\"the request included a submission with an unsupported asset type\")\n\t}\n\n\t// related assets that provide association matching value\n\tassocs := s.AssetsWithAssociation(c, req.Submission)\n\t// are any of these assets in the current session scope?\n\tresults := s.checkRelatedAssetsforAssoc(c, req, assocs)\n\n\tif req.ScopeChange {\n\t\t// add all assets related to the asset found to be associated\n\t\tfor _, result := range results {\n\t\t\tvar impacted []*dbt.Entity\n\n\t\t\tfor _, im := range append(result.ImpactedAssets, result.Match) {\n\t\t\t\tif s.Add(im.Asset) {\n\t\t\t\t\timpacted = append(impacted, im)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// review all previously seen assets that provide association for scope changes\n\t\t\tfor size := len(impacted); size > 0; {\n\t\t\t\tadded := s.reviewAndUpdate(c, req)\n\n\t\t\t\tsize = len(added)\n\t\t\t\timpacted = append(impacted, added...)\n\t\t\t}\n\n\t\t\tresult.ImpactedAssets = impacted\n\t\t\tif len(result.ImpactedAssets) > 0 {\n\t\t\t\tresult.ScopeChange = true\n\t\t\t\ts.addScopeChangesToRationale(result)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(results) == 0 {\n\t\treturn nil, errors.New(\"the submission is not associated with assets in the session scope\")\n\t}\n\treturn results, nil\n}\n\nfunc (s *Scope) addScopeChangesToRationale(result *Association) {\n\tvar changes []string\n\n\tfor _, im := range result.ImpactedAssets {\n\t\tchanges = append(changes, fmt.Sprintf(\"[%s: %s]\", im.Asset.AssetType(), im.Asset.Key()))\n\t}\n\n\tresult.Rationale += \". The following assets were added to the session scope: \" + strings.Join(changes, \", \")\n}\n\nfunc (s *Scope) reviewAndUpdate(c *cache.Cache, req *Association) []*dbt.Entity {\n\tvar assocs []*dbt.Entity\n\n\tif drs, err := c.FindEntitiesByType(oam.DomainRecord, c.StartTime()); err == nil && len(drs) > 0 {\n\t\tassocs = append(assocs, drs...)\n\t}\n\tif iprecs, err := c.FindEntitiesByType(oam.IPNetRecord, c.StartTime()); err == nil && len(iprecs) > 0 {\n\t\tassocs = append(assocs, iprecs...)\n\t}\n\tif autnums, err := c.FindEntitiesByType(oam.AutnumRecord, c.StartTime()); err == nil && len(autnums) > 0 {\n\t\tassocs = append(assocs, autnums...)\n\t}\n\tif certs, err := c.FindEntitiesByType(oam.TLSCertificate, c.StartTime()); err == nil && len(certs) > 0 {\n\t\tassocs = append(assocs, certs...)\n\t}\n\n\tvar impacted []*dbt.Entity\n\tfor _, assoc := range s.checkRelatedAssetsforAssoc(c, req, assocs) {\n\t\tfor _, a := range append(assoc.ImpactedAssets, assoc.Match) {\n\t\t\tif s.Add(a.Asset) {\n\t\t\t\timpacted = append(impacted, a)\n\t\t\t}\n\t\t}\n\t}\n\treturn impacted\n}\n\nfunc (s *Scope) checkRelatedAssetsforAssoc(c *cache.Cache, req *Association, assocs []*dbt.Entity) []*Association {\n\tvar results []*Association\n\n\tfor _, assoc := range assocs {\n\t\tvar best int\n\t\tvar msg string\n\n\t\tvar impacted []*dbt.Entity\n\t\tfor _, asset := range append(s.assetsRelatedToAssetWithAssoc(c, assoc), assoc) {\n\t\t\tif req.ScopeChange {\n\t\t\t\timpacted = append(impacted, asset)\n\t\t\t}\n\t\t\tif match, conf := s.IsAssetInScope(asset.Asset, req.Confidence); conf > 0 {\n\t\t\t\tif conf > best {\n\t\t\t\t\tbest = conf\n\n\t\t\t\t\taa := assoc.Asset\n\t\t\t\t\tsa := req.Submission.Asset\n\t\t\t\t\tmsg = fmt.Sprintf(\"[%s: %s] is related to an asset with associative value [%s: %s], \", sa.AssetType(), sa.Key(), aa.AssetType(), aa.Key())\n\t\t\t\t\tmsg += fmt.Sprintf(\"which has a related asset [%s: %s] that was determined associated with [%s: %s] at a confidence of %d out of 100\",\n\t\t\t\t\t\tasset.Asset.AssetType(), asset.Asset.Key(), match.AssetType(), match.Key(), conf)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif best > 0 {\n\t\t\tresults = append(results, &Association{\n\t\t\t\tSubmission: req.Submission,\n\t\t\t\tMatch: assoc,\n\t\t\t\tRationale: msg,\n\t\t\t\tConfidence: best,\n\t\t\t\tImpactedAssets: impacted,\n\t\t\t})\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) assetsRelatedToAssetWithAssoc(c *cache.Cache, assoc *dbt.Entity) []*dbt.Entity {\n\tset := stringset.New(assoc.ID)\n\tdefer set.Close()\n\n\tvar results []*dbt.Entity\n\tfor findings := []*dbt.Entity{assoc}; len(findings) > 0; {\n\t\tassets := findings\n\t\tfindings = []*dbt.Entity{}\n\n\t\tfor _, a := range assets {\n\t\t\tvar found bool\n\n\t\t\tswitch v := a.Asset.(type) {\n\t\t\tcase *org.Organization:\n\t\t\t\tfound = true\n\t\t\t\tif cert, ok := assoc.Asset.(*oamcert.TLSCertificate); !ok || s.orgNameSimilarToCommon(v, cert) {\n\t\t\t\t\tresults = append(results, a)\n\t\t\t\t}\n\t\t\tcase *contact.Location:\n\t\t\t\tfound = true\n\t\t\t\tresults = append(results, a)\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tif f, err := s.awayFromAssetsWithAssociation(c, a); err == nil && len(f) > 0 {\n\t\t\t\t\tfor _, finding := range f {\n\t\t\t\t\t\tif !set.Has(finding.ID) {\n\t\t\t\t\t\t\tset.Insert(finding.ID)\n\t\t\t\t\t\t\tfindings = append(findings, finding)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) AssetsWithAssociation(c *cache.Cache, asset *dbt.Entity) []*dbt.Entity {\n\tset := stringset.New(asset.ID)\n\tdefer set.Close()\n\n\tvar results []*dbt.Entity\n\tfor findings := []*dbt.Entity{asset}; len(findings) > 0; {\n\t\tassets := findings\n\t\tfindings = []*dbt.Entity{}\n\n\t\tfor _, a := range assets {\n\t\t\tvar found bool\n\n\t\t\tswitch a.Asset.(type) {\n\t\t\tcase *oamreg.DomainRecord:\n\t\t\t\tfound = true\n\t\t\t\tresults = append(results, a)\n\t\t\tcase *oamreg.IPNetRecord:\n\t\t\t\tfound = true\n\t\t\t\tresults = append(results, a)\n\t\t\tcase *oamreg.AutnumRecord:\n\t\t\t\tfound = true\n\t\t\t\tresults = append(results, a)\n\t\t\tcase *oamcert.TLSCertificate:\n\t\t\t\tfound = true\n\t\t\t\t// only certificates directly used by the services are considered\n\t\t\t\tif _, err := c.IncomingEdges(a, c.StartTime(), \"certificate\"); err == nil {\n\t\t\t\t\tresults = append(results, a)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tif f, err := s.towardsAssetsWithAssociation(c, a); err == nil && len(f) > 0 {\n\t\t\t\t\tfor _, finding := range f {\n\t\t\t\t\t\tif !set.Has(finding.ID) {\n\t\t\t\t\t\t\tset.Insert(finding.ID)\n\t\t\t\t\t\t\tfindings = append(findings, finding)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) awayFromAssetsWithAssociation(c *cache.Cache, assoc *dbt.Entity) ([]*dbt.Entity, error) {\n\tvar results []*dbt.Entity\n\t// Determine relationship directions to follow on the graph\n\tvar out, in bool\n\tvar outRels, inRels []string\n\tswitch assoc.Asset.AssetType() {\n\tcase oam.FQDN:\n\t\tout = true\n\t\toutRels = append(outRels, \"port\")\n\tcase oam.IPAddress:\n\t\tout = true\n\t\toutRels = append(outRels, \"port\")\n\t\tin = true\n\t\tinRels = append(inRels, \"dns_record\")\n\tcase oam.Netblock:\n\t\tout = true\n\t\toutRels = append(outRels, \"contains\")\n\tcase oam.AutonomousSystem:\n\t\tout = true\n\t\toutRels = append(outRels, \"announces\")\n\tcase oam.DomainRecord:\n\t\tout = true\n\t\toutRels = append(outRels, \"registrant_contact\")\n\tcase oam.IPNetRecord:\n\t\tout = true\n\t\toutRels = append(outRels, \"registrant\")\n\t\tin = true\n\t\tinRels = append(inRels, \"registration\")\n\tcase oam.AutnumRecord:\n\t\tout = true\n\t\toutRels = append(outRels, \"registrant\")\n\t\tin = true\n\t\tinRels = append(inRels, \"registration\")\n\tcase oam.TLSCertificate:\n\t\tout = true\n\t\toutRels = append(outRels, \"subject_contact\")\n\tcase oam.ContactRecord:\n\t\tout = true\n\t\toutRels = append(outRels, \"organization\", \"location\")\n\t}\n\tif out {\n\t\tif edges, err := c.OutgoingEdges(assoc, c.StartTime(), outRels...); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif entity, err := c.FindEntityById(edge.ToEntity.ID); err == nil && entity != nil {\n\t\t\t\t\tresults = append(results, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif in {\n\t\tif edges, err := c.IncomingEdges(assoc, c.StartTime(), inRels...); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif entity, err := c.FindEntityById(edge.FromEntity.ID); err == nil && entity != nil {\n\t\t\t\t\tresults = append(results, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(results) == 0 {\n\t\treturn nil, errors.New(\"zero assets were found in-scope one hop forward from the provided asset\")\n\t}\n\treturn results, nil\n}\n\nfunc (s *Scope) towardsAssetsWithAssociation(c *cache.Cache, asset *dbt.Entity) ([]*dbt.Entity, error) {\n\tvar results []*dbt.Entity\n\t// Determine relationship directions to follow on the graph\n\tvar out, in bool\n\tvar outRels, inRels []string\n\tswitch asset.Asset.AssetType() {\n\tcase oam.FQDN:\n\t\tout = true\n\t\toutRels = append(outRels, \"registration\")\n\t\tin = true\n\t\tinRels = append(inRels, \"node\")\n\tcase oam.IPAddress:\n\t\tin = true\n\t\tinRels = append(inRels, \"contains\")\n\tcase oam.Netblock:\n\t\tout = true\n\t\toutRels = append(outRels, \"registration\")\n\tcase oam.AutonomousSystem:\n\t\tout = true\n\t\toutRels = append(outRels, \"registration\")\n\tcase oam.Organization:\n\t\tin = true\n\t\tinRels = append(inRels, \"organization\")\n\tcase oam.Location:\n\t\tin = true\n\t\tinRels = append(inRels, \"location\")\n\tcase oam.ContactRecord:\n\t\tin = true\n\t\tinRels = append(inRels, \"registrant\", \"registrant_contact\", \"subject_contact\")\n\tcase oam.Service:\n\t\tin = true\n\t\tinRels = append(inRels, \"port\")\n\t}\n\tif out {\n\t\tif edges, err := c.OutgoingEdges(asset, c.StartTime(), outRels...); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif entity, err := c.FindEntityById(edge.ToEntity.ID); err == nil && entity != nil {\n\t\t\t\t\tresults = append(results, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif in {\n\t\tif edges, err := c.IncomingEdges(asset, c.StartTime(), inRels...); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif entity, err := c.FindEntityById(edge.FromEntity.ID); err == nil && entity != nil {\n\t\t\t\t\tresults = append(results, entity)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(results) == 0 {\n\t\treturn nil, errors.New(\"zero assets were found in-scope one hop forward from the provided asset\")\n\t}\n\treturn results, nil\n}\n\nfunc (s *Scope) IsAddressInScope(c *cache.Cache, ip *oamnet.IPAddress) bool {\n\tif _, conf := s.IsAssetInScope(ip, 0); conf > 0 {\n\t\treturn true\n\t}\n\n\taddrs, err := c.FindEntitiesByContent(ip, c.StartTime())\n\tif err != nil || len(addrs) != 1 {\n\t\treturn false\n\t}\n\taddr := addrs[0]\n\n\trtype := 1\n\tif ip.Type == \"IPv6\" {\n\t\trtype = 28\n\t}\n\n\tif edges, err := c.IncomingEdges(addr, c.StartTime(), \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif rec, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && rec.Header.RRType == rtype {\n\t\t\t\tfrom, err := c.FindEntityById(edge.FromEntity.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif _, conf := s.IsAssetInScope(from.Asset, 0); conf > 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Scope) IsURLInScope(c *cache.Cache, u *oamurl.URL) bool {\n\tif ip, err := netip.ParseAddr(u.Host); err == nil {\n\t\tntype := \"IPv4\"\n\t\tif ip.Is6() {\n\t\t\tntype = \"IPv6\"\n\t\t}\n\n\t\treturn s.IsAddressInScope(c, &oamnet.IPAddress{\n\t\t\tAddress: ip,\n\t\t\tType: ntype,\n\t\t})\n\t}\n\n\t_, conf := s.IsAssetInScope(u, 0)\n\treturn conf > 0\n}\n\nfunc (s *Scope) orgNameSimilarToCommon(o *org.Organization, cert *oamcert.TLSCertificate) bool {\n\tswg := metrics.NewSmithWatermanGotoh()\n\tswg.CaseSensitive = false\n\tswg.GapPenalty = -0.1\n\tswg.Substitution = metrics.MatchMismatch{\n\t\tMatch: 1,\n\t\tMismatch: -0.5,\n\t}\n\n\tdom, err := publicsuffix.EffectiveTLDPlusOne(cert.SubjectCommonName)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tlabels := strings.Split(dom, \".\")\n\tif len(labels) < 2 {\n\t\treturn false\n\t}\n\n\tcommon := labels[0]\n\tif sim := strutil.Similarity(o.Name, common, swg); sim >= 0.5 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/domains.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"strings\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/dns\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nfunc (s *Scope) AddFQDN(fqdn *dns.FQDN) bool {\n\tif fqdn.Name == \"\" {\n\t\treturn false\n\t}\n\t// only registered domain names can be added to the session scope\n\tif dom, err := publicsuffix.EffectiveTLDPlusOne(\n\t\tfqdn.Name); err != nil || !strings.EqualFold(fqdn.Name, dom) {\n\t\treturn false\n\t}\n\n\ts.domLock.Lock()\n\tdefer s.domLock.Unlock()\n\n\tkey := strings.ToLower(fqdn.Name)\n\tif _, found := s.domains[key]; !found {\n\t\ts.domains[key] = fqdn\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) AddDomain(d string) bool {\n\treturn s.AddFQDN(&dns.FQDN{Name: strings.ToLower(strings.TrimSpace(d))})\n}\n\nfunc (s *Scope) FQDNs() []*dns.FQDN {\n\ts.domLock.Lock()\n\tdefer s.domLock.Unlock()\n\n\tvar results []*dns.FQDN\n\tfor _, v := range s.domains {\n\t\tif fqdn, ok := v.(*dns.FQDN); ok {\n\t\t\tresults = append(results, fqdn)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) Domains() []string {\n\ts.domLock.Lock()\n\tdefer s.domLock.Unlock()\n\n\tvar results []string\n\tfor k := range s.domains {\n\t\tresults = append(results, k)\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesDomain(fqdn *dns.FQDN) (oam.Asset, int) {\n\ts.domLock.Lock()\n\tdefer s.domLock.Unlock()\n\n\tname := strings.ToLower(strings.TrimSpace(fqdn.Name))\n\tif name == \"\" {\n\t\treturn nil, 0\n\t}\n\n\tfor k, v := range s.domains {\n\t\tif strings.HasSuffix(name, k) {\n\t\t\talen := len(name)\n\t\t\tklen := len(k)\n\n\t\t\t// check for exact match first to guard against out of bound index\n\t\t\tif alen == klen || (alen > klen && name[alen-klen-1] == '.') {\n\t\t\t\treturn v, 100\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, 0\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/fingerprints.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\ntype Fingerprint struct {\n\tType string\n\tValue string\n}\n\n/*\nfunc (s *Scope) AddFingerprint(fin *Fingerprint) bool {\n\ts.finLock.Lock()\n\tdefer s.finLock.Unlock()\n\n\tftype := strings.ToLower(fin.Type)\n\tif _, found := s.fingerprints[ftype]; !found {\n\t\ts.fingerprints[ftype] = make(map[string]*Fingerprint)\n\t}\n\n\tif _, found := s.fingerprints[ftype][fin.Value]; !found {\n\t\ts.fingerprints[ftype][fin.Value] = fin\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) Fingerprints() []*Fingerprint {\n\ts.finLock.Lock()\n\tdefer s.finLock.Unlock()\n\n\tvar results []*Fingerprint\n\tfor _, m := range s.fingerprints {\n\t\tfor _, v := range m {\n\t\t\tresults = append(results, v)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesFin(fin *Fingerprint) (oam.Asset, int) {\n\tfor _, v := range s.Fingerprints() {\n\t\tif v.Type == fin.Type && strings.EqualFold(v.Value, fin.Value) {\n\t\t\treturn nil, 100\n\t\t}\n\t}\n\treturn nil, 0\n}\n*/\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/locations.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n)\n\nfunc (s *Scope) AddLocation(loc *contact.Location) bool {\n\tkey := strings.ToLower(loc.Address)\n\tif s.isBadField(key) {\n\t\treturn false\n\t}\n\n\ts.locLock.Lock()\n\tdefer s.locLock.Unlock()\n\n\tif _, found := s.locations[key]; !found {\n\t\ts.locations[key] = loc\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) Locations() []*contact.Location {\n\ts.locLock.Lock()\n\tdefer s.locLock.Unlock()\n\n\tvar results []*contact.Location\n\tfor _, v := range s.locations {\n\t\tif loc, ok := v.(*contact.Location); ok {\n\t\t\tresults = append(results, loc)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesLocation(loc *contact.Location, conf int) (oam.Asset, int) {\n\tfor _, loc2 := range s.Locations() {\n\t\tif loc.BuildingNumber == \"\" || loc2.BuildingNumber == \"\" || loc.BuildingNumber != loc2.BuildingNumber {\n\t\t\tcontinue\n\t\t}\n\n\t\tlstr1 := fmt.Sprintf(\"%s %s %s %s %s\", loc.BuildingNumber,\n\t\t\tloc.StreetName, loc.City, loc.Province, loc.PostalCode)\n\t\tlstr2 := fmt.Sprintf(\"%s %s %s %s %s\", loc2.BuildingNumber,\n\t\t\tloc2.StreetName, loc2.City, loc2.Province, loc2.PostalCode)\n\n\t\tif strings.EqualFold(lstr1, lstr2) {\n\t\t\treturn loc2, 100\n\t\t}\n\n\t\tswg := metrics.NewSmithWatermanGotoh()\n\t\tswg.CaseSensitive = false\n\t\tswg.GapPenalty = -0.1\n\t\tswg.Substitution = metrics.MatchMismatch{\n\t\t\tMatch: 1,\n\t\t\tMismatch: -0.5,\n\t\t}\n\n\t\tif sim := strutil.Similarity(lstr1, lstr2, swg); sim >= float64(conf) {\n\t\t\treturn loc2, int(math.Round(sim))\n\t\t}\n\t}\n\treturn nil, 0\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/networks.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"net/netip\"\n\t\"strings\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\nfunc (s *Scope) AddIPAddress(ip *oamnet.IPAddress) bool {\n\tif _, conf := s.addressInScope(ip); conf > 0 {\n\t\treturn false\n\t}\n\n\ts.addrLock.Lock()\n\tdefer s.addrLock.Unlock()\n\n\tkey := ip.Address.String()\n\tif _, found := s.addresses[key]; !found {\n\t\ts.addresses[key] = ip\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) AddAddress(addr string) bool {\n\tip := &oamnet.IPAddress{Address: netip.MustParseAddr(strings.TrimSpace(addr)), Type: \"IPv4\"}\n\tif ip.Address.Is6() {\n\t\tip.Type = \"IPv6\"\n\t}\n\treturn s.AddIPAddress(ip)\n}\n\nfunc (s *Scope) IPAddresses() []*oamnet.IPAddress {\n\ts.addrLock.Lock()\n\tdefer s.addrLock.Unlock()\n\n\tvar results []*oamnet.IPAddress\n\tfor _, v := range s.addresses {\n\t\tif ip, ok := v.(*oamnet.IPAddress); ok {\n\t\t\tresults = append(results, ip)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) Addresses() []string {\n\ts.addrLock.Lock()\n\tdefer s.addrLock.Unlock()\n\n\tvar results []string\n\tfor k := range s.addresses {\n\t\tresults = append(results, k)\n\t}\n\treturn results\n}\n\nfunc (s *Scope) addressInScope(ip *oamnet.IPAddress) (oam.Asset, int) {\n\tfor _, nb := range s.Netblocks() {\n\t\tif nb.CIDR.Contains(ip.Address) {\n\t\t\treturn nb, 100\n\t\t}\n\t}\n\tfor _, addr := range s.IPAddresses() {\n\t\tif addr.Type == ip.Type && addr.Address.Compare(ip.Address) == 0 {\n\t\t\treturn addr, 100\n\t\t}\n\t}\n\treturn nil, 0\n}\n\nfunc (s *Scope) AddNetblock(nb *oamnet.Netblock) bool {\n\ts.netLock.Lock()\n\tdefer s.netLock.Unlock()\n\n\tkey := nb.CIDR.String()\n\tif _, found := s.networks[key]; !found {\n\t\ts.networks[key] = nb\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) AddCIDR(cidr string) bool {\n\tnb := &oamnet.Netblock{CIDR: netip.MustParsePrefix(strings.TrimSpace(cidr)), Type: \"IPv4\"}\n\tif nb.CIDR.Addr().Is6() {\n\t\tnb.Type = \"IPv6\"\n\t}\n\treturn s.AddNetblock(nb)\n}\n\nfunc (s *Scope) Netblocks() []*oamnet.Netblock {\n\ts.netLock.Lock()\n\tdefer s.netLock.Unlock()\n\n\tvar results []*oamnet.Netblock\n\tfor _, v := range s.networks {\n\t\tif nb, ok := v.(*oamnet.Netblock); ok {\n\t\t\tresults = append(results, nb)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) CIDRs() []string {\n\ts.netLock.Lock()\n\tdefer s.netLock.Unlock()\n\n\tvar results []string\n\tfor k := range s.networks {\n\t\tresults = append(results, k)\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesNetblock(nb *oamnet.Netblock) (oam.Asset, int) {\n\ts.netLock.Lock()\n\tdefer s.netLock.Unlock()\n\n\tkey := nb.CIDR.String()\n\tif a, found := s.networks[key]; found {\n\t\treturn a, 100\n\t}\n\n\treturn nil, 0\n}\n\nfunc (s *Scope) AddAutonomousSystem(as *oamnet.AutonomousSystem) bool {\n\ts.asLock.Lock()\n\tdefer s.asLock.Unlock()\n\n\tkey := as.Number\n\tif _, found := s.autsystems[key]; !found {\n\t\ts.autsystems[key] = as\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) AddASN(asn int) bool {\n\treturn s.AddAutonomousSystem(&oamnet.AutonomousSystem{Number: asn})\n}\n\nfunc (s *Scope) AutonomousSystems() []*oamnet.AutonomousSystem {\n\ts.asLock.Lock()\n\tdefer s.asLock.Unlock()\n\n\tvar results []*oamnet.AutonomousSystem\n\tfor _, v := range s.autsystems {\n\t\tif as, ok := v.(*oamnet.AutonomousSystem); ok {\n\t\t\tresults = append(results, as)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) ASNs() []int {\n\ts.asLock.Lock()\n\tdefer s.asLock.Unlock()\n\n\tvar results []int\n\tfor k := range s.autsystems {\n\t\tresults = append(results, k)\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesAutonomousSystem(as *oamnet.AutonomousSystem) (oam.Asset, int) {\n\ts.asLock.Lock()\n\tdefer s.asLock.Unlock()\n\n\tkey := as.Number\n\tif a, found := s.autsystems[key]; found {\n\t\treturn a, 100\n\t}\n\n\treturn nil, 0\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/orgs.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"math\"\n\t\"strings\"\n\n\t\"github.com/adrg/strutil\"\n\t\"github.com/adrg/strutil/metrics\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n)\n\nfunc (s *Scope) AddOrganization(o *org.Organization) bool {\n\tkey := strings.ToLower(o.Name)\n\tif s.isBadField(key) {\n\t\treturn false\n\t}\n\n\ts.orgLock.Lock()\n\tdefer s.orgLock.Unlock()\n\n\tif _, found := s.orgs[key]; !found {\n\t\ts.orgs[key] = o\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Scope) AddOrg(o string) bool {\n\treturn s.AddOrganization(&org.Organization{Name: o})\n}\n\nfunc (s *Scope) Organizations() []*org.Organization {\n\ts.orgLock.Lock()\n\tdefer s.orgLock.Unlock()\n\n\tvar results []*org.Organization\n\tfor _, v := range s.orgs {\n\t\tif o, ok := v.(*org.Organization); ok {\n\t\t\tresults = append(results, o)\n\t\t}\n\t}\n\treturn results\n}\n\nfunc (s *Scope) matchesOrg(o *org.Organization, conf int) (oam.Asset, int) {\n\tfor _, v := range s.Organizations() {\n\t\tif strings.EqualFold(o.Name, v.Name) {\n\t\t\treturn v, 100\n\t\t}\n\n\t\tswg := metrics.NewSmithWatermanGotoh()\n\t\tswg.CaseSensitive = false\n\t\tswg.GapPenalty = -0.1\n\t\tswg.Substitution = metrics.MatchMismatch{\n\t\t\tMatch: 1,\n\t\t\tMismatch: -0.5,\n\t\t}\n\n\t\tif sim := strutil.Similarity(o.Name, v.Name, swg); sim >= float64(conf) {\n\t\t\treturn v, int(math.Round(sim))\n\t\t}\n\t}\n\treturn nil, 0\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/scope.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"net/netip\"\n\t\"strings\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/general\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\toamurl \"github.com/owasp-amass/open-asset-model/url\"\n)\n\nfunc (s *Scope) Add(a oam.Asset) bool {\n\tvar newentry bool\n\n\tswitch v := a.(type) {\n\tcase *oamdns.FQDN:\n\t\tnewentry = s.AddFQDN(v)\n\tcase *general.Identifier:\n\t\tif domain, found := getEmailDomain(v); found {\n\t\t\tnewentry = s.AddFQDN(&oamdns.FQDN{Name: domain})\n\t\t}\n\tcase *oamnet.IPAddress:\n\t\tnewentry = s.AddIPAddress(v)\n\tcase *oamnet.Netblock:\n\t\tnewentry = s.AddNetblock(v)\n\tcase *oamnet.AutonomousSystem:\n\t\tnewentry = s.AddAutonomousSystem(v)\n\tcase *oamreg.DomainRecord:\n\t\tnewentry = s.AddDomain(v.Domain)\n\tcase *oamreg.IPNetRecord:\n\t\tnewentry = s.AddCIDR(v.CIDR.String())\n\tcase *oamreg.AutnumRecord:\n\t\tn1 := s.AddOrg(v.Name)\n\t\tn2 := s.AddASN(v.Number)\n\t\tnewentry = n1 || n2\n\tcase *oamcert.TLSCertificate:\n\t\tnewentry = s.AddDomain(v.SubjectCommonName)\n\tcase *oamurl.URL:\n\t\tif ip, err := netip.ParseAddr(v.Host); err == nil {\n\t\t\tnewentry = s.AddAddress(ip.String())\n\t\t} else {\n\t\t\tnewentry = s.AddDomain(v.Host)\n\t\t}\n\tcase *org.Organization:\n\t\tnewentry = s.AddOrganization(v)\n\tcase *contact.Location:\n\t\tnewentry = s.AddLocation(v)\n\t}\n\n\treturn newentry\n}\n\nfunc (s *Scope) IsAssetInScope(a oam.Asset, conf int) (oam.Asset, int) {\n\tvar accuracy int\n\tvar match oam.Asset\n\n\tswitch v := a.(type) {\n\tcase *oamdns.FQDN:\n\t\tmatch, accuracy = s.matchesDomain(v)\n\tcase *general.Identifier:\n\t\tif domain, found := getEmailDomain(v); found {\n\t\t\tmatch, accuracy = s.matchesDomain(&oamdns.FQDN{Name: domain})\n\t\t}\n\tcase *oamnet.IPAddress:\n\t\tmatch, accuracy = s.addressInScope(v)\n\tcase *oamnet.Netblock:\n\t\tmatch, accuracy = s.matchesNetblock(v)\n\tcase *oamnet.AutonomousSystem:\n\t\tmatch, accuracy = s.matchesAutonomousSystem(v)\n\tcase *oamreg.DomainRecord:\n\t\tmatch, accuracy = s.matchesDomain(&oamdns.FQDN{Name: v.Domain})\n\t\tif match == nil || accuracy == 0 {\n\t\t\tmatch, accuracy = s.matchesOrg(&org.Organization{Name: v.Name}, conf)\n\t\t}\n\tcase *oamreg.IPNetRecord:\n\t\tmatch, accuracy = s.matchesNetblock(&oamnet.Netblock{CIDR: v.CIDR, Type: v.Type})\n\tcase *oamreg.AutnumRecord:\n\t\tmatch, accuracy = s.matchesAutonomousSystem(&oamnet.AutonomousSystem{Number: v.Number})\n\t\tif match == nil || accuracy == 0 {\n\t\t\tmatch, accuracy = s.matchesOrg(&org.Organization{Name: v.Name}, conf)\n\t\t}\n\tcase *oamcert.TLSCertificate:\n\t\tmatch, accuracy = s.matchesDomain(&oamdns.FQDN{Name: v.SubjectCommonName})\n\tcase *oamurl.URL:\n\t\tmatch, accuracy = s.matchesDomain(&oamdns.FQDN{Name: v.Host})\n\tcase *org.Organization:\n\t\tmatch, accuracy = s.matchesOrg(v, conf)\n\tcase *contact.Location:\n\t\tmatch, accuracy = s.matchesLocation(v, conf)\n\t}\n\n\treturn match, accuracy\n}\n\nfunc (s *Scope) isBadField(field string) bool {\n\tbadstrs := []string{\"registration\", \"registry\", \"redact\", \"private\", \"privacy\", \"available\", \"domain\", \"proxy\", \"liability\"}\n\n\tfor _, bad := range badstrs {\n\t\tif strings.Contains(field, bad) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc getEmailDomain(email *general.Identifier) (string, bool) {\n\tif email == nil || email.Type != general.EmailAddress {\n\t\treturn \"\", false\n\t}\n\n\tparts := strings.Split(email.ID, \"@\")\n\n\tif len(parts) != 2 {\n\t\treturn \"\", false\n\t}\n\n\treturn parts[1], true\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/sessions/scope/type.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage scope\n\nimport (\n\t\"sync\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype Scope struct {\n\torgLock sync.Mutex\n\torgs map[string]oam.Asset\n\n\tdomLock sync.Mutex\n\tdomains map[string]oam.Asset\n\n\taddrLock sync.Mutex\n\taddresses map[string]oam.Asset\n\n\tnetLock sync.Mutex\n\tnetworks map[string]oam.Asset\n\n\tasLock sync.Mutex\n\tautsystems map[int]oam.Asset\n\n\tlocLock sync.Mutex\n\tlocations map[string]oam.Asset\n\n\t//finLock sync.Mutex\n\tfingerprints map[string]map[string]*Fingerprint\n}\n\nfunc New() *Scope {\n\treturn &Scope{\n\t\torgs: make(map[string]oam.Asset),\n\t\tdomains: make(map[string]oam.Asset),\n\t\taddresses: make(map[string]oam.Asset),\n\t\tnetworks: make(map[string]oam.Asset),\n\t\tautsystems: make(map[int]oam.Asset),\n\t\tlocations: make(map[string]oam.Asset),\n\t\tfingerprints: make(map[string]map[string]*Fingerprint),\n\t}\n}\n\nfunc CreateFromConfigScope(config *config.Config) *Scope {\n\tscope := New()\n\n\tfor _, d := range config.Domains() {\n\t\tscope.AddDomain(d)\n\t}\n\tfor _, addr := range config.Scope.Addresses {\n\t\tscope.AddAddress(addr.String())\n\t}\n\tfor _, cidr := range config.Scope.CIDRs {\n\t\tscope.AddCIDR(cidr.String())\n\t}\n\tfor _, asn := range config.Scope.ASNs {\n\t\tscope.AddASN(asn)\n\t}\n\treturn scope\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/types/events.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage types\n\nimport (\n\t\"github.com/caffix/pipeline\"\n\t\"github.com/google/uuid\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype Event struct {\n\tName string\n\tEntity *dbt.Entity\n\tMeta interface{}\n\tDispatcher Dispatcher\n\tSession Session\n}\n\ntype EmailMeta struct {\n\tVerifyAttempted bool\n\tVerified bool\n}\n\ntype Dispatcher interface {\n\tDispatchEvent(e *Event) error\n\tShutdown()\n}\n\ntype AssetData struct {\n\tOAMAsset oam.Asset `json:\"asset\"`\n\tOAMType oam.AssetType `json:\"type\"`\n}\n\ntype Asset struct {\n\tSession uuid.UUID `json:\"sessionToken,omitempty\"`\n\tName string `json:\"assetName,omitempty\"`\n\tData AssetData `json:\"data,omitempty\"`\n}\n\ntype EventDataElement struct {\n\tEvent *Event\n\tError error\n\tQueue chan *EventDataElement\n}\n\nfunc NewEventDataElement(e *Event) *EventDataElement {\n\treturn &EventDataElement{Event: e}\n}\n\nfunc (ede *EventDataElement) Clone() pipeline.Data {\n\treturn ede\n}\n\ntype Source struct {\n\tName string\n\tConfidence int\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/types/registry.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage types\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/caffix/pipeline\"\n\t\"github.com/caffix/queue\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\ntype Plugin interface {\n\tName() string\n\tStart(r Registry) error\n\tStop()\n}\n\ntype Handler struct {\n\tPlugin Plugin\n\tName string\n\tPriority int\n\tMaxInstances int\n\tEventType oam.AssetType\n\tTransforms []string\n\tCallback func(*Event) error\n}\n\ntype AssetPipeline struct {\n\tPipeline *pipeline.Pipeline\n\tQueue *PipelineQueue\n}\n\ntype Registry interface {\n\tLog() *slog.Logger\n\tRegisterHandler(h *Handler) error\n\tBuildPipelines() error\n\tGetPipeline(eventType oam.AssetType) (*AssetPipeline, error)\n}\n\ntype PipelineQueue struct {\n\tqueue.Queue\n}\n\nfunc NewPipelineQueue() *PipelineQueue {\n\treturn &PipelineQueue{queue.NewQueue()}\n}\n\n// Next implements the pipeline InputSource interface.\nfunc (pq *PipelineQueue) Next(ctx context.Context) bool {\n\tt := time.NewTicker(100 * time.Millisecond)\n\tdefer t.Stop()\n\n\tif pq.Len() > 0 {\n\t\treturn true\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase <-t.C:\n\t\t\tif pq.Len() > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase <-pq.Signal():\n\t\t\tif pq.Len() > 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Data implements the pipeline InputSource interface.\nfunc (pq *PipelineQueue) Data() pipeline.Data {\n\tfor {\n\t\telement, good := pq.Queue.Next()\n\t\tif !good {\n\t\t\tbreak\n\t\t}\n\n\t\tif ede, ok := element.(*EventDataElement); ok && !ede.Event.Session.Done() {\n\t\t\treturn ede\n\t\t}\n\t}\n\treturn nil\n}\n\n// Error implements the pipeline InputSource interface.\nfunc (pq *PipelineQueue) Error() error {\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: engine/types/sessions.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage types\n\nimport (\n\t\"log/slog\"\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/pubsub\"\n\t\"github.com/owasp-amass/amass/v5/engine/sessions/scope\"\n\t\"github.com/owasp-amass/asset-db/cache\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/yl2chen/cidranger\"\n)\n\ntype Session interface {\n\tID() uuid.UUID\n\tLog() *slog.Logger\n\tPubSub() *pubsub.Logger\n\tConfig() *config.Config\n\tScope() *scope.Scope\n\tDB() repository.Repository\n\tCache() *cache.Cache\n\tQueue() SessionQueue\n\tCIDRanger() cidranger.Ranger\n\tTmpDir() string\n\tStats() *SessionStats\n\tDone() bool\n\tKill()\n}\n\ntype SessionQueue interface {\n\tHas(e *dbt.Entity) bool\n\tAppend(e *dbt.Entity) error\n\tNext(atype oam.AssetType, num int) ([]*dbt.Entity, error)\n\tProcessed(e *dbt.Entity) error\n\tDelete(e *dbt.Entity) error\n\tClose() error\n}\n\ntype SessionStats struct {\n\tsync.Mutex\n\tWorkItemsCompleted int `json:\"workItemsCompleted\"`\n\tWorkItemsTotal int `json:\"workItemsTotal\"`\n}\n\ntype SessionManager interface {\n\tNewSession(cfg *config.Config) (Session, error)\n\tAddSession(s Session) error\n\tCancelSession(id uuid.UUID)\n\tGetSession(id uuid.UUID) Session\n\tGetSessions() []Session\n\tShutdown()\n}\n\ntype AmassRangerEntry interface {\n\tNetwork() net.IPNet\n\tAutonomousSystem() int\n\tSource() *Source\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/afmt/parse.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage afmt\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n)\n\n// ParseStrings implements the flag.Value interface.\ntype ParseStrings []string\n\n// ParseInts implements the flag.Value interface.\ntype ParseInts []int\n\n// ParseIPs implements the flag.Value interface.\ntype ParseIPs []net.IP\n\n// ParseCIDRs implements the flag.Value interface.\ntype ParseCIDRs []*net.IPNet\n\n// ParseASNs implements the flag.Value interface.\ntype ParseASNs []int\n\nfunc (p *ParseStrings) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(*p, \",\")\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseStrings) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"String parsing failed\")\n\t}\n\n\tstr := strings.Split(s, \",\")\n\tfor _, s := range str {\n\t\t*p = append(*p, strings.TrimSpace(s))\n\t}\n\treturn nil\n}\n\nfunc (p *ParseInts) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\tvar builder strings.Builder\n\tfor i, n := range *p {\n\t\tif i > 0 {\n\t\t\tbuilder.WriteRune(',')\n\t\t}\n\t\tbuilder.WriteString(strconv.Itoa(n))\n\t}\n\treturn builder.String()\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseInts) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"integer parsing failed\")\n\t}\n\n\tnums := strings.Split(s, \",\")\n\tfor _, n := range nums {\n\t\ti, err := strconv.Atoi(strings.TrimSpace(n))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*p = append(*p, i)\n\t}\n\treturn nil\n}\n\nfunc (p *ParseIPs) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\tvar builder strings.Builder\n\tfor i, ipaddr := range *p {\n\t\tif i > 0 {\n\t\t\tbuilder.WriteRune(',')\n\t\t}\n\t\tbuilder.WriteString(ipaddr.String())\n\t}\n\treturn builder.String()\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseIPs) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"IP address parsing failed\")\n\t}\n\n\tfor _, v := range strings.Split(s, \",\") {\n\t\tif start, end, ok := parseRange(v); ok {\n\t\t\tips := amassnet.RangeHosts(start, end)\n\t\t\tif len(ips) == 0 {\n\t\t\t\treturn fmt.Errorf(\"%s is not a valid IP address or range\", v)\n\t\t\t}\n\t\t\tfor _, ip := range ips {\n\t\t\t\t*p = append(*p, ip)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if ip := net.ParseIP(v); ip != nil {\n\t\t\t*p = append(*p, ip)\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"%s is not a valid IP address or range\", v)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc parseRange(s string) (start net.IP, end net.IP, ok bool) {\n\ttwoIPs := strings.Split(s, \"-\")\n\tif len(twoIPs) != 2 {\n\t\treturn\n\t}\n\tstart = net.ParseIP(twoIPs[0])\n\tif start == nil {\n\t\treturn\n\t}\n\tend = net.ParseIP(twoIPs[1])\n\tif end == nil {\n\t\tnum, err := strconv.Atoi(twoIPs[1])\n\t\tif err != nil || math.MaxUint8 < num {\n\t\t\treturn\n\t\t}\n\t\tend = make(net.IP, len(start))\n\t\tcopy(end, start)\n\t\tend[len(end)-1] = byte(num)\n\t}\n\tok = true\n\treturn\n}\n\nfunc (p *ParseCIDRs) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\n\tvar builder strings.Builder\n\tfor i, ipnet := range *p {\n\t\tif i > 0 {\n\t\t\tbuilder.WriteRune(',')\n\t\t}\n\t\tbuilder.WriteString(ipnet.String())\n\t}\n\treturn builder.String()\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseCIDRs) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"%s is not a valid CIDR\", s)\n\t}\n\n\tcidrs := strings.Split(s, \",\")\n\tfor _, cidr := range cidrs {\n\t\t_, ipnet, err := net.ParseCIDR(cidr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse %s as a CIDR\", cidr)\n\t\t}\n\n\t\t*p = append(*p, ipnet)\n\t}\n\treturn nil\n}\n\nfunc (p *ParseASNs) String() string {\n\tif p == nil {\n\t\treturn \"\"\n\t}\n\tvar builder strings.Builder\n\tfor i, n := range *p {\n\t\tif i > 0 {\n\t\t\tbuilder.WriteRune(',')\n\t\t}\n\t\tbuilder.WriteString(strconv.Itoa(n))\n\t}\n\treturn builder.String()\n}\n\n// Set implements the flag.Value interface.\nfunc (p *ParseASNs) Set(s string) error {\n\tif s == \"\" {\n\t\treturn fmt.Errorf(\"ASN parsing failed\")\n\t}\n\n\tasns := strings.Split(s, \",\")\n\tfor _, asn := range asns {\n\t\ti, err := strconv.Atoi(strings.TrimPrefix(strings.TrimSpace(asn), \"AS\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*p = append(*p, i)\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/afmt/parse_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage afmt\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestNilParseStrings(t *testing.T) {\n\tconst expected = \"\"\n\n\tif got := (*ParseStrings)(nil).String(); got != expected {\n\t\tt.Errorf(\"Got: %q; Expected: %q\", got, expected)\n\t}\n}\n\nfunc TestParseStrings(t *testing.T) {\n\tcases := []struct {\n\t\tlabel string\n\t\tinput string\n\t\tok bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlabel: \"Empty_Input\",\n\t\t\tinput: \"\",\n\t\t}, {\n\t\t\tlabel: \"Valid_Input\",\n\t\t\tinput: \"234,foo,bar\",\n\t\t\tok: true,\n\t\t\texpected: \"234,foo,bar\",\n\t\t}, {\n\t\t\tlabel: \"Extra_Comma\",\n\t\t\tinput: \"234,foo,bar,\",\n\t\t\tok: true,\n\t\t\texpected: \"234,foo,bar,\",\n\t\t}, {\n\t\t\tlabel: \"With_Whitespace\",\n\t\t\tinput: \"234 , foo ,\\tbar\",\n\t\t\tok: true,\n\t\t\texpected: \"234,foo,bar\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tf := func(t *testing.T) {\n\t\t\tvar ints ParseStrings\n\n\t\t\tif err := ints.Set(c.input); err != nil && c.ok {\n\t\t\t\tt.Errorf(\"Got: %v; Expected: \", err)\n\t\t\t} else if err == nil && !c.ok {\n\t\t\t\tt.Error(\"Got: ; Expected: some error\")\n\t\t\t} else if err == nil && c.ok {\n\t\t\t\tif got := ints.String(); got != c.expected {\n\t\t\t\t\tt.Errorf(\"Got: %q; Expected: %q\", got, c.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tt.Run(c.label, f)\n\t}\n}\n\nfunc TestNilParseInts(t *testing.T) {\n\tconst expected = \"\"\n\n\tif got := (*ParseInts)(nil).String(); got != expected {\n\t\tt.Errorf(\"Got: %q; Expected: %q\", got, expected)\n\t}\n}\n\nfunc TestParseInts(t *testing.T) {\n\tcases := []struct {\n\t\tlabel string\n\t\tinput string\n\t\tok bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlabel: \"Empty_Input\",\n\t\t\tinput: \"\",\n\t\t}, {\n\t\t\tlabel: \"Invalid_Int\",\n\t\t\tinput: \"1,sdfg,2,3\",\n\t\t}, {\n\t\t\tlabel: \"Extraneous_Comma\",\n\t\t\tinput: \"-1,2,,\",\n\t\t}, {\n\t\t\tlabel: \"Without_Whitespace\",\n\t\t\tinput: \"-1,10,42\",\n\t\t\tok: true,\n\t\t\texpected: \"-1,10,42\",\n\t\t}, {\n\t\t\tlabel: \"With_Whitespace\",\n\t\t\tinput: \"-1, 10 ,\\t42\",\n\t\t\tok: true,\n\t\t\texpected: \"-1,10,42\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tf := func(t *testing.T) {\n\t\t\tvar ints ParseInts\n\n\t\t\tif err := ints.Set(c.input); err != nil && c.ok {\n\t\t\t\tt.Errorf(\"Got: %v; Expected: \", err)\n\t\t\t} else if err == nil && !c.ok {\n\t\t\t\tt.Error(\"Got: ; Expected: some error\")\n\t\t\t} else if err == nil && c.ok {\n\t\t\t\tif got := ints.String(); got != c.expected {\n\t\t\t\t\tt.Errorf(\"Got: %q; Expected: %q\", got, c.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tt.Run(c.label, f)\n\t}\n}\n\nfunc TestNilParseIPs(t *testing.T) {\n\tconst expected = \"\"\n\n\tif got := (*ParseIPs)(nil).String(); got != expected {\n\t\tt.Errorf(\"Got: %q; Expected: %q\", got, expected)\n\t}\n}\n\nfunc TestParseIPs(t *testing.T) {\n\tcases := []struct {\n\t\tlabel string\n\t\tinput string\n\t\tok bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlabel: \"Empty_Input\",\n\t\t\tinput: \"\",\n\t\t}, {\n\t\t\tlabel: \"Single_Valid_IPv4\",\n\t\t\tinput: \"127.0.0.1\",\n\t\t\tok: true,\n\t\t\texpected: \"127.0.0.1\",\n\t\t}, {\n\t\t\tlabel: \"Single_Valid_IPv6\",\n\t\t\tinput: \"2001:0db8:85a3:0000:0000:8a2e:0370:7334\",\n\t\t\tok: true,\n\t\t\texpected: \"2001:db8:85a3::8a2e:370:7334\",\n\t\t}, {\n\t\t\tlabel: \"Single_IPv4_Byte_Overflow\",\n\t\t\tinput: \"256.0.0.1\",\n\t\t}, {\n\t\t\tlabel: \"Valid_Compact_Range\",\n\t\t\tinput: \"127.0.0.1-3\",\n\t\t\tok: true,\n\t\t\texpected: \"127.0.0.1,127.0.0.2,127.0.0.3\",\n\t\t}, {\n\t\t\tlabel: \"Valid_Range\",\n\t\t\tinput: \"127.0.0.1-127.0.0.3\",\n\t\t\tok: true,\n\t\t\texpected: \"127.0.0.1,127.0.0.2,127.0.0.3\",\n\t\t}, {\n\t\t\tlabel: \"Empty_Range\",\n\t\t\tinput: \"127.0.0.2-127.0.0.1\",\n\t\t}, {\n\t\t\tlabel: \"Range_End_Overflows_Byte\",\n\t\t\tinput: \"0.0.0.0-256\",\n\t\t}, {\n\t\t\tlabel: \"Invalid_Range_End\",\n\t\t\tinput: \"0.0.0.0-1-sdfgkjhsdfg\",\n\t\t}, {\n\t\t\tlabel: \"Invalid_Range_Start\",\n\t\t\tinput: \"foo-3\",\n\t\t}, {\n\t\t\tlabel: \"Range_And_IP\",\n\t\t\tinput: \"127.0.0.1-3,255.0.0.0\",\n\t\t\tok: true,\n\t\t\texpected: \"127.0.0.1,127.0.0.2,127.0.0.3,255.0.0.0\",\n\t\t}, {\n\t\t\tlabel: \"Extraneous_Comma\",\n\t\t\tinput: \"127.0.0.1-3,255.0.0.0,\",\n\t\t}, {\n\t\t\tlabel: \"Whitespace_After_Comma\",\n\t\t\tinput: \"127.0.0.1-3, 255.0.0.0\",\n\t\t}, {\n\t\t\tlabel: \"Whitespace_Before_Comma\",\n\t\t\tinput: \"127.0.0.1-3 ,255.0.0.0\",\n\t\t}, {\n\t\t\tlabel: \"Trailing_Whitespace\",\n\t\t\tinput: \"127.0.0.1-3,255.0.0.0 \",\n\t\t}, {\n\t\t\tlabel: \"Leading_Whitespace\",\n\t\t\tinput: \" 127.0.0.1-3,255.0.0.0\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tf := func(t *testing.T) {\n\t\t\tvar ips ParseIPs\n\n\t\t\tif err := ips.Set(c.input); err != nil && c.ok {\n\t\t\t\tt.Errorf(\"Got: %v; Expected: \", err)\n\t\t\t} else if err == nil && !c.ok {\n\t\t\t\tt.Error(\"got ; Expected: some error\")\n\t\t\t} else if err == nil && c.ok {\n\t\t\t\tif got := ips.String(); got != c.expected {\n\t\t\t\t\tt.Errorf(\"got %q; Expected: %q\", got, c.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tt.Run(c.label, f)\n\t}\n}\n\nfunc TestNilParseCIDRs(t *testing.T) {\n\tconst expected = \"\"\n\n\tif got := (*ParseCIDRs)(nil).String(); got != expected {\n\t\tt.Errorf(\"Got: %q; Expected: %q\", got, expected)\n\t}\n}\n\nfunc TestParseCIDRs(t *testing.T) {\n\tcases := []struct {\n\t\tlabel string\n\t\tinput string\n\t\tok bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlabel: \"Empty\",\n\t\t\tinput: \"\",\n\t\t}, {\n\t\t\tlabel: \"Valid_CIDRs\",\n\t\t\tinput: \"192.0.2.1/24,193.0.2.1/16\",\n\t\t\tok: true,\n\t\t\texpected: \"192.0.2.0/24,193.0.0.0/16\",\n\t\t}, {\n\t\t\tlabel: \"Invalid_CIDRs\",\n\t\t\tinput: \"192.0.2.1/24,193.0.2.1/66\",\n\t\t}, {\n\t\t\tlabel: \"Whitespace\",\n\t\t\tinput: \"\\t192.0.2.1/24, 193.0.2.1/16 \",\n\t\t}, {\n\t\t\tlabel: \"Extraneous_Comma\",\n\t\t\tinput: \"192.0.2.1/24,193.0.2.1/16,\",\n\t\t},\n\t}\n\tfor _, c := range cases {\n\t\tf := func(t *testing.T) {\n\t\t\tvar cidrs ParseCIDRs\n\n\t\t\tif err := cidrs.Set(c.input); err != nil && c.ok {\n\t\t\t\tt.Errorf(\"Got %v; Expected: \", err)\n\t\t\t} else if err == nil && !c.ok {\n\t\t\t\tt.Error(\"Got ; Expected: some error\")\n\t\t\t} else if err == nil && c.ok {\n\t\t\t\tif got := cidrs.String(); got != c.expected {\n\t\t\t\t\tt.Errorf(\"Got %q; Expected: %q\", got, c.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tt.Run(c.label, f)\n\t}\n}\n\nfunc TestParseASNs(t *testing.T) {\n\tcases := []struct {\n\t\tlabel string\n\t\tinput string\n\t\tok bool\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tlabel: \"Empty\",\n\t\t\tinput: \"\",\n\t\t}, {\n\t\t\tlabel: \"Valid_ASNs_With_And_Without_AS_Prefix\",\n\t\t\tinput: \"AS1234,AS4567,7777\",\n\t\t\tok: true,\n\t\t\texpected: \"1234,4567,7777\",\n\t\t}, {\n\t\t\tlabel: \"Invalid_ASN\",\n\t\t\tinput: \"AS1234,4567,ASABC\",\n\t\t}, {\n\t\t\tlabel: \"Whitespace\",\n\t\t\tinput: \"\\tAS1234 , 4567 \",\n\t\t\tok: true,\n\t\t\texpected: \"1234,4567\",\n\t\t}, {\n\t\t\tlabel: \"Extraneous_Comma\",\n\t\t\tinput: \"AS1234,\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tf := func(t *testing.T) {\n\t\t\tvar asns ParseASNs\n\n\t\t\tif err := asns.Set(c.input); err != nil && c.ok {\n\t\t\t\tt.Errorf(\"Got: %v; Expected: \", err)\n\t\t\t} else if err == nil && !c.ok {\n\t\t\t\tt.Error(\"Got: ; Expected: some error\")\n\t\t\t} else if err == nil && c.ok {\n\t\t\t\tif got := asns.String(); got != c.expected {\n\t\t\t\t\tt.Errorf(\"Got: %q; Expected: %q\", got, c.expected)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tt.Run(c.label, f)\n\t}\n}\n\nfunc TestParseRange(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\targs string\n\t\tstart string\n\t\tend string\n\t\tok bool\n\t}{\n\t\t{\n\t\t\tname: \"basic success - full range\",\n\t\t\targs: \"192.168.0.1-192.168.0.3\",\n\t\t\tstart: \"192.168.0.1\",\n\t\t\tend: \"192.168.0.3\",\n\t\t\tok: true,\n\t\t},\n\t\t{\n\t\t\tname: \"basic success - short-hand range\",\n\t\t\targs: \"192.168.0.1-4\",\n\t\t\tstart: \"192.168.0.1\",\n\t\t\tend: \"192.168.0.4\",\n\t\t\tok: true,\n\t\t},\n\t\t{\n\t\t\tname: \"illicit split\",\n\t\t\targs: \"192.168.0.1\",\n\t\t\tstart: \"\",\n\t\t\tend: \"\",\n\t\t\tok: false,\n\t\t},\n\t\t{\n\t\t\tname: \"illicit range\",\n\t\t\targs: \"192.168.0.255-192.168.0.260\",\n\t\t\tstart: \"192.168.0.255\",\n\t\t\tend: \"\",\n\t\t\tok: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif start, end, ok := parseRange(tt.args); fmt.Sprintf(\"%v\",\n\t\t\t\tstart) != tt.start && fmt.Sprintf(\"%v\", end) != tt.end && ok != tt.ok {\n\t\t\t\tt.Errorf(\"parseIPs.parseRange() error = %v, wantErr %v\", start, tt.start)\n\t\t\t\tt.Errorf(\"parseIPs.parseRange() error = %v, wantErr %v\", end, tt.end)\n\t\t\t\tt.Errorf(\"parseIPs.parseRange() error = %v, wantErr %v\", ok, tt.ok)\n\t\t\t}\n\t\t})\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/afmt/print.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage afmt\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/fatih/color\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n)\n\n// Banner is the ASCII art logo used within help output.\nconst Banner = ` .+++:. : .+++.\n +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+\n &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#&\n +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8\n 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#:\n WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8:\n #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8\n o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W.\n WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o\n :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+\n :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@&\n +o&&&&+. +oooo.`\n\nconst (\n\t// Version is used to display the current version of Amass.\n\tVersion = \"v5.0.0\"\n\n\t// Author is used to display the Amass Project Team.\n\tAuthor = \"OWASP Amass Project - @owaspamass\"\n\n\t// Description is the slogan for the Amass Project.\n\tDescription = \"In-depth Attack Surface Mapping and Asset Discovery\"\n\n\t// The URL to the Amass Project's Discord server.\n\tDiscordInvitation string = \"https://discord.gg/ANTyEDUXt5\"\n)\n\nvar (\n\t// Colors used to ease the reading of program output\n\tB = color.New(color.FgHiBlue)\n\tY = color.New(color.FgHiYellow)\n\tG = color.New(color.FgHiGreen)\n\tR = color.New(color.FgHiRed)\n\tFgR = color.New(color.FgRed)\n\tFgY = color.New(color.FgYellow)\n\tYellow = color.New(color.FgHiYellow).SprintFunc()\n\tGreen = color.New(color.FgHiGreen).SprintFunc()\n\tBlue = color.New(color.FgHiBlue).SprintFunc()\n\tMagenta = color.New(color.FgHiMagenta).SprintFunc()\n\tWhite = color.New(color.FgHiWhite).SprintFunc()\n)\n\n// PrintBanner outputs the Amass banner to stderr.\nfunc PrintBanner() {\n\tFprintBanner(color.Error)\n}\n\n// FprintBanner outputs the Amass banner the same for all tools.\nfunc FprintBanner(out io.Writer) {\n\trightmost := 76\n\n\tpad := func(num int) {\n\t\tfor i := 0; i < num; i++ {\n\t\t\t_, _ = fmt.Fprint(out, \" \")\n\t\t}\n\t}\n\n\t_, _ = R.Fprintf(out, \"\\n%s\\n\\n\", Banner)\n\tpad(rightmost - len(Version))\n\t_, _ = Y.Fprintln(out, Version)\n\tpad(rightmost - len(Author))\n\t_, _ = Y.Fprintln(out, Author)\n\tpad(rightmost - len(Description))\n\t_, _ = Y.Fprintf(out, \"%s\\n\\n\\n\", Description)\n}\n\n// DesiredAddrTypes removes undesired address types from the AddressInfo slice.\nfunc DesiredAddrTypes(addrs []amassnet.AddressInfo, ipv4, ipv6 bool) []amassnet.AddressInfo {\n\tvar kept []amassnet.AddressInfo\n\n\tfor _, addr := range addrs {\n\t\tif ipv4 && IsIPv4(addr.Address) {\n\t\t\tkept = append(kept, addr)\n\t\t} else if ipv6 && IsIPv6(addr.Address) {\n\t\t\tkept = append(kept, addr)\n\t\t}\n\t}\n\n\treturn kept\n}\n\n// IsIPv4 returns true when the provided net.IP address is an IPv4 address.\nfunc IsIPv4(ip net.IP) bool {\n\treturn strings.Count(ip.String(), \":\") < 2\n}\n\n// IsIPv6 returns true when the provided net.IP address is an IPv6 address.\nfunc IsIPv6(ip net.IP) bool {\n\treturn strings.Count(ip.String(), \":\") >= 2\n}\n\n// UpdateSummaryData updates the summary maps using the provided requests.Output data.\nfunc UpdateSummaryData(output *amassnet.Output, asns map[int]*amassnet.ASNSummaryData) {\n\tfor _, addr := range output.Addresses {\n\t\tif addr.CIDRStr == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata, found := asns[addr.ASN]\n\t\tif !found {\n\t\t\tasns[addr.ASN] = &amassnet.ASNSummaryData{\n\t\t\t\tName: addr.Description,\n\t\t\t\tNetblocks: make(map[string]int),\n\t\t\t}\n\t\t\tdata = asns[addr.ASN]\n\t\t}\n\t\t// Increment how many IPs were in this netblock\n\t\tdata.Netblocks[addr.CIDRStr]++\n\t}\n}\n\n// PrintEnumerationSummary outputs the summary information utilized by the command-line tools.\nfunc PrintEnumerationSummary(total int, asns map[int]*amassnet.ASNSummaryData, demo bool) {\n\tFprintEnumerationSummary(color.Error, total, asns, demo)\n}\n\n// FprintEnumerationSummary outputs the summary information utilized by the command-line tools.\nfunc FprintEnumerationSummary(out io.Writer, total int, asns map[int]*amassnet.ASNSummaryData, demo bool) {\n\tpad := func(num int, chr string) {\n\t\tfor i := 0; i < num; i++ {\n\t\t\t_, _ = B.Fprint(out, chr)\n\t\t}\n\t}\n\n\t_, _ = fmt.Fprintln(out)\n\t// Print the header information\n\ttitle := \"OWASP Amass Project \"\n\tsite := \"https://github.com/owasp-amass/amass\"\n\t_, _ = B.Fprint(out, title+Version)\n\tnum := 80 - (len(title) + len(Version) + len(site))\n\tpad(num, \" \")\n\t_, _ = B.Fprintf(out, \"%s\\n\", site)\n\tpad(8, \"----------\")\n\t_, _ = fmt.Fprintf(out, \"\\n%s%s\", Yellow(strconv.Itoa(total)), Green(\" names discovered\"))\n\t_, _ = fmt.Fprintln(out)\n\n\tif len(asns) == 0 {\n\t\treturn\n\t}\n\t// Another line gets printed\n\tpad(8, \"----------\")\n\t_, _ = fmt.Fprintln(out)\n\t// Print the ASN and netblock information\n\tfor asn, data := range asns {\n\t\tasnstr := strconv.Itoa(asn)\n\t\tdatastr := data.Name\n\n\t\tif demo && asn > 0 {\n\t\t\tasnstr = censorString(asnstr, 0, len(asnstr))\n\t\t\tdatastr = censorString(datastr, 0, len(datastr))\n\t\t}\n\t\t_, _ = fmt.Fprintf(out, \"%s%s %s %s\\n\", Blue(\"ASN: \"), Yellow(asnstr), Green(\"-\"), Green(datastr))\n\n\t\tfor cidr, ips := range data.Netblocks {\n\t\t\tcountstr := strconv.Itoa(ips)\n\t\t\tcidrstr := cidr\n\n\t\t\tif demo {\n\t\t\t\tcidrstr = censorNetBlock(cidrstr)\n\t\t\t}\n\n\t\t\tcountstr = fmt.Sprintf(\"\\t%-4s\", countstr)\n\t\t\tcidrstr = fmt.Sprintf(\"\\t%-18s\", cidrstr)\n\t\t\t_, _ = fmt.Fprintf(out, \"%s%s %s\\n\", Yellow(cidrstr), Yellow(countstr), Blue(\"Subdomain Name(s)\"))\n\t\t}\n\t}\n}\n\nfunc censorString(input string, start, end int) string {\n\trunes := []rune(input)\n\tfor i := start; i < end; i++ {\n\t\tif runes[i] == '.' ||\n\t\t\trunes[i] == '/' ||\n\t\t\trunes[i] == '-' ||\n\t\t\trunes[i] == ' ' {\n\t\t\tcontinue\n\t\t}\n\t\trunes[i] = 'x'\n\t}\n\treturn string(runes)\n}\n\nfunc censorDomain(input string) string {\n\treturn censorString(input, strings.Index(input, \".\"), len(input))\n}\n\nfunc censorIP(input string) string {\n\treturn censorString(input, 0, strings.LastIndex(input, \".\"))\n}\n\nfunc censorNetBlock(input string) string {\n\treturn censorString(input, 0, strings.Index(input, \"/\"))\n}\n\n// OutputLineParts returns the parts of a line to be printed for a requests.Output.\nfunc OutputLineParts(out *amassnet.Output, addrs, demo bool) (name, ips string) {\n\tif addrs {\n\t\tfor i, a := range out.Addresses {\n\t\t\tif i != 0 {\n\t\t\t\tips += \",\"\n\t\t\t}\n\t\t\tif demo {\n\t\t\t\tips += censorIP(a.Address.String())\n\t\t\t} else {\n\t\t\t\tips += a.Address.String()\n\t\t\t}\n\t\t}\n\t}\n\tname = out.Name\n\tif demo {\n\t\tname = censorDomain(name)\n\t}\n\treturn\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/afmt/slog.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage afmt\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc JSONLogToRecord(logstr string) (slog.Record, error) {\n\tj := make(map[string]interface{})\n\t// unmarshal the log message sent from the engine session\n\tif err := json.Unmarshal([]byte(logstr), &j); err != nil {\n\t\treturn slog.Record{}, errors.New(\"failed to unmarchal the JSON\")\n\t}\n\n\tvar ltime time.Time\n\t// cheating right now by replacing the time\n\tif _, found := j[slog.TimeKey]; found {\n\t\tltime = time.Now()\n\t}\n\tdelete(j, slog.TimeKey)\n\n\tvar level slog.Level\n\t// extract the log level for the new record\n\tif val, found := j[slog.LevelKey]; !found {\n\t\treturn slog.Record{}, errors.New(\"failed to find the level key\")\n\t} else if str, ok := val.(string); !ok {\n\t\treturn slog.Record{}, errors.New(\"failed to cast the level value\")\n\t} else if level.UnmarshalText([]byte(str)) != nil {\n\t\treturn slog.Record{}, errors.New(\"failed to unmarshal the level text\")\n\t}\n\tdelete(j, slog.LevelKey)\n\n\tvar msg string\n\t// extract the log message for the new record\n\tif val, found := j[slog.MessageKey]; !found {\n\t\treturn slog.Record{}, errors.New(\"failed to find the msg key\")\n\t} else if str, ok := val.(string); !ok {\n\t\treturn slog.Record{}, errors.New(\"failed to cast the msg value\")\n\t} else {\n\t\tmsg = str\n\t}\n\tdelete(j, slog.MessageKey)\n\n\tvar pc uintptr\n\trecord := slog.NewRecord(ltime, level, msg, pc)\n\trecord.AddAttrs(jsonToAttrs(j)...)\n\treturn record, nil\n}\n\nfunc jsonToAttrs(jmap map[string]interface{}) []slog.Attr {\n\tvar attrs []slog.Attr\n\n\tfor k, v := range jmap {\n\t\tswitch val := v.(type) {\n\t\tcase bool:\n\t\t\tattrs = append(attrs, slog.Bool(k, val))\n\t\tcase float64:\n\t\t\tattrs = append(attrs, jsonNumberToAttr(k, val))\n\t\tcase string:\n\t\t\tattrs = append(attrs, slog.String(k, val))\n\t\tcase map[string]interface{}:\n\t\t\tif a := jsonToAttrs(val); len(a) > 0 {\n\t\t\t\tattrs = append(attrs, slog.Attr{\n\t\t\t\t\tKey: k,\n\t\t\t\t\tValue: slog.GroupValue(a...),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\treturn attrs\n}\n\nfunc jsonNumberToAttr(key string, num float64) slog.Attr {\n\tif s := fmt.Sprintf(\"%f\", num); s != \"\" {\n\t\tif i, err := strconv.ParseInt(s, 10, 64); err == nil {\n\t\t\treturn slog.Int64(key, i)\n\t\t}\n\t}\n\treturn slog.Float64(key, num)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/amass_engine/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage amass_engine\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n)\n\nconst (\n\tUsageMsg = \"[options] [-log-dir path]\"\n\tDescription = \"Run the Amass collection engine to populate the OAM database\"\n)\n\ntype Args struct {\n\tHelp bool\n\tOptions struct {\n\t\tNoColor bool\n\t\tSilent bool\n\t}\n\tFilepaths struct {\n\t\tLogDir string\n\t}\n}\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"engine\", flag.ContinueOnError)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\tfs.StringVar(&args.Filepaths.LogDir, \"log-dir\", \"\", \"path to the log directory\")\n\treturn fs\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\tvar args Args\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\n\tengineBuf := new(bytes.Buffer)\n\tfs.SetOutput(engineBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, engineBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif err := fs.Parse(clArgs); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\n\tl, err := selectLogger(args.Filepaths.LogDir)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the logger: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\te, err := engine.NewEngine(l)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to start the engine: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer e.Shutdown()\n\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt, syscall.SIGTERM)\n\tdefer signal.Stop(quit)\n\t<-quit\n\tl.Info(\"Terminating the collection engine\")\n}\n\nfunc selectLogger(dir string) (*slog.Logger, error) {\n\tfilename := fmt.Sprintf(\"amass_engine_%s.log\", time.Now().Format(\"2006-01-02T15:04:05\"))\n\n\tif dir != \"\" {\n\t\treturn tools.NewFileLogger(dir, filename)\n\t}\n\tif l, err := tools.NewSyslogLogger(); err == nil && l != nil {\n\t\treturn l, nil\n\t}\n\n\tdir = config.OutputDirectory(\"\")\n\tif l, err := tools.NewFileLogger(dir, filename); err == nil && l != nil {\n\t\treturn l, nil\n\t}\n\n\treturn slog.New(slog.NewTextHandler(os.Stdout, nil)), nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/assoc/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage assoc\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n\t\"github.com/owasp-amass/asset-db/triples\"\n)\n\nconst (\n\tUsageMsg = \"[options] [-tf path] [-t1 triple] ... [-t10 triple]\"\n\tDescription = \"Query the OAM along the walk defined by the triples\"\n)\n\ntype Args struct {\n\tHelp bool\n\tTriples []string // The triples to use for the association walk\n\tOptions struct {\n\t\tNoColor bool\n\t\tSilent bool\n\t}\n\tFilepaths struct {\n\t\tConfigFile string\n\t\tDirectory string\n\t\tTripleFile string\n\t}\n}\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"assoc\", errorHandling)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.StringVar(&args.Triples[0], \"t1\", \"\", \"1st triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[1], \"t2\", \"\", \"2nd triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[2], \"t3\", \"\", \"3rd triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[3], \"t4\", \"\", \"4th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[4], \"t5\", \"\", \"5th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[5], \"t6\", \"\", \"6th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[6], \"t7\", \"\", \"7th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[7], \"t8\", \"\", \"8th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[8], \"t9\", \"\", \"9th triple to use for the association walk\")\n\tfs.StringVar(&args.Triples[9], \"t10\", \"\", \"10th triple to use for the association walk\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\tfs.StringVar(&args.Filepaths.ConfigFile, \"config\", \"\", \"Path to the YAML configuration file\")\n\tfs.StringVar(&args.Filepaths.Directory, \"dir\", \"\", \"Path to the directory containing the graph database\")\n\tfs.StringVar(&args.Filepaths.TripleFile, \"tf\", \"\", \"Path to a file containing a triples list\")\n\treturn fs\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\tvar args Args\n\targs.Triples = make([]string, 10)\n\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\tassocBuf := new(bytes.Buffer)\n\tfs.SetOutput(assocBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, assocBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := fs.Parse(clArgs); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\tif args.Filepaths.TripleFile != \"\" {\n\t\tlist, err := readTriplesTextFromFile(args.Filepaths.TripleFile)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to parse the triple file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif len(list) > 10 {\n\t\t\tlist = list[:10]\n\t\t}\n\t\tfor i, l := range list {\n\t\t\tif l == \"\" || args.Triples[i] != \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\targs.Triples[i] = l\n\t\t}\n\t}\n\tif args.Triples[0] == \"\" {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"No triples were provided for the association walk\")\n\t\tos.Exit(1)\n\t}\n\n\tcfg := config.NewConfig()\n\t// Check if a configuration file was provided, and if so, load the settings\n\tif err := config.AcquireConfig(args.Filepaths.Directory, args.Filepaths.ConfigFile, cfg); err == nil {\n\t\tif args.Filepaths.Directory == \"\" {\n\t\t\targs.Filepaths.Directory = cfg.Dir\n\t\t}\n\t} else if args.Filepaths.ConfigFile != \"\" {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to load the configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Connect with the graph database containing the enumeration data\n\tdb := tools.OpenGraphDatabase(cfg)\n\tif db == nil {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Failed to connect with the database\")\n\t\tos.Exit(1)\n\t}\n\n\tvar tris []*triples.Triple\n\tfor _, tstr := range args.Triples {\n\t\tif tstr == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\ttriple, err := triples.ParseTriple(tstr)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to parse the triple '%s': %v\\n\", tstr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttris = append(tris, triple)\n\t}\n\tif len(tris) == 0 {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"No valid triples were provided for the association walk\")\n\t\tos.Exit(1)\n\t}\n\n\tresults, err := triples.Extract(db, tris)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to extract associations: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Marshal with indentation (e.g., 2 spaces)\n\tprettyJSON, err := json.MarshalIndent(results, \"\", \" \")\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Error marshaling JSON: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\t_, _ = afmt.G.Fprintln(color.Output, string(prettyJSON))\n}\n\nfunc readTriplesTextFromFile(filePath string) ([]string, error) {\n\tvar triples []string\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() { _ = file.Close() }()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif line != \"\" {\n\t\t\ttriples = append(triples, line)\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn triples, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/db/db.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage db\n\nimport (\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n)\n\nfunc FindByFQDNScope(db repository.Repository, entity *dbt.Entity, since time.Time) ([]*dbt.Entity, error) {\n\tset := stringset.New(entity.Asset.Key())\n\tdefer set.Close()\n\n\tresults := []*dbt.Entity{entity}\n\tif edges, err := db.OutgoingEdges(entity, since, \"node\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif to, err := db.FindEntityById(edge.ToEntity.ID); err == nil && to != nil && !set.Has(to.Asset.Key()) {\n\t\t\t\tset.Insert(to.Asset.Key())\n\n\t\t\t\tif findings, err := FindByFQDNScope(db, to, since); err == nil && len(findings) > 0 {\n\t\t\t\t\tresults = append(results, findings...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/enum/assets.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enum\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net/netip\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\tet \"github.com/owasp-amass/amass/v5/engine/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\toamnet \"github.com/owasp-amass/open-asset-model/network\"\n)\n\n// returns Asset objects by converting the contests of config.Scope\nfunc makeAssets(config *config.Config) []*et.Asset {\n\tassets := convertScopeToAssets(config.Scope)\n\n\tfor i, asset := range assets {\n\t\tasset.Name = fmt.Sprintf(\"asset#%d\", i+1)\n\t}\n\treturn assets\n}\n\n// ipnet2Prefix converts a net.IPNet to a netip.Prefix.\nfunc ipnet2Prefix(ipn net.IPNet) netip.Prefix {\n\taddr, _ := netip.AddrFromSlice(ipn.IP)\n\tcidr, _ := ipn.Mask.Size()\n\treturn netip.PrefixFrom(addr, cidr)\n}\n\n// convertScopeToAssets converts all items in a Scope to a slice of *Asset.\nfunc convertScopeToAssets(scope *config.Scope) []*et.Asset {\n\tconst ipv4 = \"IPv4\"\n\tconst ipv6 = \"IPv6\"\n\tvar assets []*et.Asset\n\n\t// Convert Domains to assets.\n\tfor _, d := range scope.Domains {\n\t\tfqdn := oamdns.FQDN{Name: d}\n\t\tdata := et.AssetData{\n\t\t\tOAMAsset: fqdn,\n\t\t\tOAMType: fqdn.AssetType(),\n\t\t}\n\t\tasset := &et.Asset{\n\t\t\tData: data,\n\t\t}\n\t\tassets = append(assets, asset)\n\t}\n\n\tvar ipType string\n\t// Convert Addresses to assets.\n\tfor _, ip := range scope.Addresses {\n\t\t// Convert net.IP to net.IPAddr.\n\t\tif addr, ok := netip.AddrFromSlice(ip); ok {\n\t\t\t// Determine the IP type based on the address characteristics.\n\t\t\tif addr.Is4In6() {\n\t\t\t\taddr = netip.AddrFrom4(addr.As4())\n\t\t\t\tipType = ipv4\n\t\t\t} else if addr.Is6() {\n\t\t\t\tipType = ipv6\n\t\t\t} else {\n\t\t\t\tipType = ipv4\n\t\t\t}\n\n\t\t\t// Create an asset from the IP address and append it to the assets slice.\n\t\t\tasset := oamnet.IPAddress{Address: addr, Type: ipType}\n\t\t\tdata := et.AssetData{\n\t\t\t\tOAMAsset: asset,\n\t\t\t\tOAMType: asset.AssetType(),\n\t\t\t}\n\t\t\tassets = append(assets, &et.Asset{Data: data})\n\t\t}\n\t}\n\n\t// Convert CIDRs to assets.\n\tfor _, cidr := range scope.CIDRs {\n\t\tprefix := ipnet2Prefix(*cidr) // Convert net.IPNet to netip.Prefix.\n\n\t\t// Determine the IP type based on the address characteristics.\n\t\taddr := prefix.Addr()\n\t\tif addr.Is4In6() {\n\t\t\tipType = ipv4\n\t\t} else if addr.Is6() {\n\t\t\tipType = ipv6\n\t\t} else {\n\t\t\tipType = ipv4\n\t\t}\n\n\t\t// Create an asset from the CIDR and append it to the assets slice.\n\t\tasset := oamnet.Netblock{CIDR: prefix, Type: ipType}\n\t\tdata := et.AssetData{\n\t\t\tOAMAsset: asset,\n\t\t\tOAMType: asset.AssetType(),\n\t\t}\n\t\tassets = append(assets, &et.Asset{Data: data})\n\t}\n\n\t// Convert ASNs to assets.\n\tfor _, asn := range scope.ASNs {\n\t\tasset := oamnet.AutonomousSystem{Number: asn}\n\t\tdata := et.AssetData{\n\t\t\tOAMAsset: asset,\n\t\t\tOAMType: asset.AssetType(),\n\t\t}\n\t\tassets = append(assets, &et.Asset{Data: data})\n\t}\n\treturn assets\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/enum/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enum\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/signal\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\tpb \"github.com/cheggaaa/pb/v3\"\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/engine/api/graphql/client\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n)\n\nconst (\n\tUsageMsg string = \"[options] -d DOMAIN\"\n\tDescription string = \"Interface with the engine that performs enumerations\"\n)\n\ntype Args struct {\n\tHelp bool\n\tAddresses afmt.ParseIPs\n\tASNs afmt.ParseInts\n\tCIDRs afmt.ParseCIDRs\n\tAltWordList *stringset.Set\n\tAltWordListMask *stringset.Set\n\tBruteWordList *stringset.Set\n\tBruteWordListMask *stringset.Set\n\tBlacklist *stringset.Set\n\tDomains *stringset.Set\n\tExcluded *stringset.Set\n\tIncluded *stringset.Set\n\tInterface string\n\tMaxDNSQueries int\n\tResolverQPS int\n\tTrustedQPS int\n\tMaxDepth int\n\tMinForRecursive int\n\tNames *stringset.Set\n\tPorts afmt.ParseInts\n\tResolvers *stringset.Set\n\tTrusted *stringset.Set\n\tTimeout int\n\tOptions struct {\n\t\tActive bool\n\t\tAlterations bool\n\t\tBruteForcing bool\n\t\tDemoMode bool\n\t\tListSources bool\n\t\tNoAlts bool\n\t\tNoColor bool\n\t\tNoRecursive bool\n\t\tPassive bool\n\t\tSilent bool\n\t\tVerbose bool\n\t}\n\tFilepaths struct {\n\t\tAllFilePrefix string\n\t\tAltWordlist afmt.ParseStrings\n\t\tBlacklist string\n\t\tBruteWordlist afmt.ParseStrings\n\t\tConfigFile string\n\t\tDirectory string\n\t\tDomains afmt.ParseStrings\n\t\tExcludedSrcs string\n\t\tIncludedSrcs string\n\t\tJSONOutput string\n\t\tLogFile string\n\t\tNames afmt.ParseStrings\n\t\tResolvers afmt.ParseStrings\n\t\tTrusted afmt.ParseStrings\n\t\tScriptsDirectory string\n\t\tTermOut string\n\t}\n}\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"enum\", errorHandling)\n\n\tdefineArgumentFlags(fs, args)\n\tdefineOptionFlags(fs, args)\n\tdefineFilepathFlags(fs, args)\n\treturn fs\n}\n\nfunc defineArgumentFlags(fs *flag.FlagSet, args *Args) {\n\tfs.Var(&args.Addresses, \"addr\", \"IPs and ranges (192.168.1.1-254) separated by commas\")\n\tfs.Var(args.AltWordListMask, \"awm\", \"\\\"hashcat-style\\\" wordlist masks for name alterations\")\n\tfs.Var(&args.ASNs, \"asn\", \"ASNs separated by commas (can be used multiple times)\")\n\tfs.Var(&args.CIDRs, \"cidr\", \"CIDRs separated by commas (can be used multiple times)\")\n\tfs.Var(args.Blacklist, \"bl\", \"Blacklist of subdomain names that will not be investigated\")\n\tfs.Var(args.BruteWordListMask, \"wm\", \"\\\"hashcat-style\\\" wordlist masks for DNS brute forcing\")\n\tfs.Var(args.Domains, \"d\", \"Domain names separated by commas (can be used multiple times)\")\n\tfs.Var(args.Excluded, \"exclude\", \"Data source names separated by commas to be excluded\")\n\tfs.Var(args.Included, \"include\", \"Data source names separated by commas to be included\")\n\tfs.StringVar(&args.Interface, \"iface\", \"\", \"Provide the network interface to send traffic through\")\n\tfs.IntVar(&args.MaxDNSQueries, \"max-dns-queries\", 0, \"Deprecated flag to be replaced by dns-qps in version 4.0\")\n\tfs.IntVar(&args.MaxDNSQueries, \"dns-qps\", 0, \"Maximum number of DNS queries per second across all resolvers\")\n\tfs.IntVar(&args.ResolverQPS, \"rqps\", 0, \"Maximum number of DNS queries per second for each untrusted resolver\")\n\tfs.IntVar(&args.TrustedQPS, \"trqps\", 0, \"Maximum number of DNS queries per second for each trusted resolver\")\n\tfs.IntVar(&args.MaxDepth, \"max-depth\", 0, \"Maximum number of subdomain labels for brute forcing\")\n\tfs.IntVar(&args.MinForRecursive, \"min-for-recursive\", 1, \"Subdomain labels seen before recursive brute forcing (Default: 1)\")\n\tfs.Var(&args.Ports, \"p\", \"Ports separated by commas (default: 80, 443)\")\n\tfs.Var(args.Resolvers, \"r\", \"IP addresses of untrusted DNS resolvers (can be used multiple times)\")\n\tfs.Var(args.Resolvers, \"tr\", \"IP addresses of trusted DNS resolvers (can be used multiple times)\")\n\tfs.IntVar(&args.Timeout, \"timeout\", 0, \"Number of minutes to let enumeration run before quitting\")\n}\n\nfunc defineOptionFlags(fs *flag.FlagSet, args *Args) {\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Options.Active, \"active\", false, \"Attempt zone transfers and certificate name grabs\")\n\tfs.BoolVar(&args.Options.BruteForcing, \"brute\", false, \"Execute brute forcing after searches\")\n\tfs.BoolVar(&args.Options.DemoMode, \"demo\", false, \"Censor output to make it suitable for demonstrations\")\n\tfs.BoolVar(&args.Options.ListSources, \"list\", false, \"Print the names of all available data sources\")\n\tfs.BoolVar(&args.Options.Alterations, \"alts\", false, \"Enable generation of altered names\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.NoRecursive, \"norecursive\", false, \"Turn off recursive brute forcing\")\n\tfs.BoolVar(&args.Options.Passive, \"passive\", false, \"Deprecated since passive is the default setting\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\tfs.BoolVar(&args.Options.Verbose, \"v\", false, \"Output status / debug / troubleshooting info\")\n}\n\nfunc defineFilepathFlags(fs *flag.FlagSet, args *Args) {\n\tfs.StringVar(&args.Filepaths.AllFilePrefix, \"oA\", \"\", \"Path prefix used for naming all output files\")\n\tfs.Var(&args.Filepaths.AltWordlist, \"aw\", \"Path to a different wordlist file for alterations\")\n\tfs.StringVar(&args.Filepaths.Blacklist, \"blf\", \"\", \"Path to a file providing blacklisted subdomains\")\n\tfs.Var(&args.Filepaths.BruteWordlist, \"w\", \"Path to a different wordlist file for brute forcing\")\n\tfs.StringVar(&args.Filepaths.ConfigFile, \"config\", \"\", \"Path to the YAML configuration file. Additional details below\")\n\tfs.StringVar(&args.Filepaths.Directory, \"dir\", \"\", \"Path to the directory containing the output files\")\n\tfs.Var(&args.Filepaths.Domains, \"df\", \"Path to a file providing root domain names\")\n\tfs.StringVar(&args.Filepaths.ExcludedSrcs, \"ef\", \"\", \"Path to a file providing data sources to exclude\")\n\tfs.StringVar(&args.Filepaths.IncludedSrcs, \"if\", \"\", \"Path to a file providing data sources to include\")\n\tfs.StringVar(&args.Filepaths.LogFile, \"log\", \"\", \"Path to the log file where errors will be written\")\n\tfs.Var(&args.Filepaths.Names, \"nf\", \"Path to a file providing already known subdomain names (from other tools/sources)\")\n\tfs.Var(&args.Filepaths.Resolvers, \"rf\", \"Path to a file providing untrusted DNS resolvers\")\n\tfs.Var(&args.Filepaths.Trusted, \"trf\", \"Path to a file providing trusted DNS resolvers\")\n\tfs.StringVar(&args.Filepaths.ScriptsDirectory, \"scripts\", \"\", \"Path to a directory containing ADS scripts\")\n\tfs.StringVar(&args.Filepaths.TermOut, \"o\", \"\", \"Path to the text file containing terminal stdout/stderr\")\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\t// Extract the correct config from the user provided arguments and/or configuration file\n\tcfg, args := argsAndConfig(cmdName, clArgs)\n\tif cfg == nil {\n\t\treturn\n\t}\n\n\tif err := tools.CreateOutputDirectory(cfg.Dir); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdir := config.OutputDirectory(cfg.Dir)\n\tif dir == \"\" {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"failed to obtain the path for the output directory\")\n\t\tos.Exit(1)\n\t}\n\n\tif err := tools.CreateDefaultConfigFiles(dir); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the default config files: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Create the client that will provide a connection to the engine\n\turl := \"http://127.0.0.1:4000/graphql\"\n\tif cfg.EngineAPI != nil && cfg.EngineAPI.URL != \"\" {\n\t\turl = cfg.EngineAPI.URL\n\t}\n\n\tclient := client.NewClient(url)\n\ttoken, err := client.CreateSession(cfg)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create a session with the Amass engine: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer client.TerminateSession(token)\n\n\tlogfile := args.Filepaths.LogFile\n\tif logfile == \"\" {\n\t\tlogfile = fmt.Sprintf(\"session-%v.log\", token)\n\t}\n\n\tl, err := selectLogger(dir, logfile)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to create the logger: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Create interrupt channel and subscribe to server log messages\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\tmessages, err := client.Subscribe(token)\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to subscribe to the Amass engine log messages: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tvar count int\n\tfor _, a := range makeAssets(cfg) {\n\t\tif err := client.CreateAsset(*a, token); err == nil {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tvar progress *pb.ProgressBar\n\tif !args.Options.Silent {\n\t\tprogress = pb.Start64(int64(count))\n\t}\n\n\tdone := make(chan struct{}, 1)\n\tgo func() {\n\t\tvar finished int\n\t\tt := time.NewTicker(2 * time.Second)\n\t\tdefer t.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\tcase message := <-messages:\n\t\t\t\ttools.WriteLogMessage(l, message)\n\t\t\tcase <-t.C:\n\t\t\t\tif stats, err := client.SessionStats(token); err == nil {\n\t\t\t\t\tif !args.Options.Silent {\n\t\t\t\t\t\tprogress.SetTotal(int64(stats.WorkItemsTotal))\n\t\t\t\t\t\tprogress.SetCurrent(int64(stats.WorkItemsCompleted))\n\t\t\t\t\t}\n\n\t\t\t\t\tif stats.WorkItemsCompleted == stats.WorkItemsTotal {\n\t\t\t\t\t\tfinished++\n\t\t\t\t\t\tif finished == 5 {\n\t\t\t\t\t\t\tclose(done)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinished = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tif args.Timeout > 0 {\n\t\tgo func() {\n\t\t\tt := time.NewTimer(time.Minute * time.Duration(args.Timeout))\n\t\t\tdefer t.Stop()\n\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\tcase <-t.C:\n\t\t\t\tclose(done)\n\t\t\t}\n\t\t}()\n\t}\n\n\tselect {\n\tcase <-done:\n\tcase <-interrupt:\n\t\tclose(done)\n\t\treturn\n\t}\n\n\tif !args.Options.Silent {\n\t\tprogress.Finish()\n\t}\n}\n\nfunc argsAndConfig(cmdName string, clArgs []string) (*config.Config, *Args) {\n\targs := Args{\n\t\tAltWordList: stringset.New(),\n\t\tAltWordListMask: stringset.New(),\n\t\tBruteWordList: stringset.New(),\n\t\tBruteWordListMask: stringset.New(),\n\t\tBlacklist: stringset.New(),\n\t\tDomains: stringset.New(),\n\t\tExcluded: stringset.New(),\n\t\tIncluded: stringset.New(),\n\t\tNames: stringset.New(),\n\t\tResolvers: stringset.New(),\n\t\tTrusted: stringset.New(),\n\t}\n\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\t// set up the flag set to write errors to a buffer\n\tenumBuf := new(bytes.Buffer)\n\tfs.SetOutput(enumBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, enumBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(clArgs) < 1 {\n\t\tusage()\n\t\treturn nil, &args\n\t}\n\tif err := fs.Parse(clArgs); err != nil {\n\t\tusage()\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn nil, &args\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\tif args.AltWordListMask.Len() > 0 {\n\t\targs.AltWordList.Union(args.AltWordListMask)\n\t}\n\tif args.BruteWordListMask.Len() > 0 {\n\t\targs.BruteWordList.Union(args.BruteWordListMask)\n\t}\n\tif (args.Excluded.Len() > 0 || args.Filepaths.ExcludedSrcs != \"\") &&\n\t\t(args.Included.Len() > 0 || args.Filepaths.IncludedSrcs != \"\") {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Cannot provide both include and exclude arguments\")\n\t\tusage()\n\t\tos.Exit(1)\n\t}\n\tif err := processInputFiles(&args); err != nil {\n\t\t_, _ = fmt.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tcfg := config.NewConfig()\n\t// Check if a configuration file was provided, and if so, load the settings\n\tif err := config.AcquireConfig(args.Filepaths.Directory, args.Filepaths.ConfigFile, cfg); err == nil {\n\t\t// Check if a config file was provided that has DNS resolvers specified\n\t\tif len(cfg.Resolvers) > 0 && args.Resolvers.Len() == 0 {\n\t\t\targs.Resolvers = stringset.New(cfg.Resolvers...)\n\t\t}\n\t} else if args.Filepaths.ConfigFile != \"\" {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to load the configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Override configuration file settings with command-line arguments\n\tif err := cfg.UpdateConfig(args); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Configuration error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Some input validation\n\tif !cfg.Active && len(args.Ports) > 0 {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Ports can only be scanned in the active mode\")\n\t\tos.Exit(1)\n\t}\n\tif len(cfg.Domains()) == 0 {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Configuration error: No root domain names were provided\")\n\t\tos.Exit(1)\n\t}\n\treturn cfg, &args\n}\n\n// Setup the amass enumeration settings\nfunc (e Args) OverrideConfig(conf *config.Config) error {\n\tif len(e.Addresses) > 0 {\n\t\tconf.Scope.Addresses = e.Addresses\n\t}\n\tif len(e.ASNs) > 0 {\n\t\tconf.Scope.ASNs = e.ASNs\n\t}\n\tif len(e.CIDRs) > 0 {\n\t\tconf.Scope.CIDRs = e.CIDRs\n\t}\n\tif len(e.Ports) > 0 {\n\t\tconf.Scope.Ports = e.Ports\n\t}\n\tif e.Filepaths.Directory != \"\" {\n\t\tconf.Dir = e.Filepaths.Directory\n\t}\n\tif e.Filepaths.ScriptsDirectory != \"\" {\n\t\tconf.ScriptsDirectory = e.Filepaths.ScriptsDirectory\n\t}\n\tif e.Names.Len() > 0 {\n\t\tconf.ProvidedNames = e.Names.Slice()\n\t}\n\tif e.BruteWordList.Len() > 0 {\n\t\tconf.Wordlist = e.BruteWordList.Slice()\n\t}\n\tif e.AltWordList.Len() > 0 {\n\t\tconf.AltWordlist = e.AltWordList.Slice()\n\t}\n\tif e.Options.BruteForcing {\n\t\tconf.BruteForcing = true\n\t}\n\tif e.Options.Alterations {\n\t\tconf.Alterations = true\n\t}\n\tif e.Options.NoRecursive {\n\t\tconf.Recursive = false\n\t}\n\tif e.MinForRecursive != 1 {\n\t\tconf.MinForRecursive = e.MinForRecursive\n\t}\n\tif e.MaxDepth != 0 {\n\t\tconf.MaxDepth = e.MaxDepth\n\t}\n\tif e.Options.Active {\n\t\tconf.Active = true\n\t\tconf.Passive = false\n\t}\n\tif e.Blacklist.Len() > 0 {\n\t\tconf.Scope.Blacklist = e.Blacklist.Slice()\n\t}\n\tif e.Options.Verbose {\n\t\tconf.Verbose = true\n\t}\n\tif e.ResolverQPS > 0 {\n\t\tconf.ResolversQPS = e.ResolverQPS\n\t}\n\tif e.TrustedQPS > 0 {\n\t\tconf.TrustedQPS = e.TrustedQPS\n\t}\n\tif e.Resolvers.Len() > 0 {\n\t\tconf.SetResolvers(e.Resolvers.Slice()...)\n\t}\n\tif e.Trusted.Len() > 0 {\n\t\tconf.SetTrustedResolvers(e.Trusted.Slice()...)\n\t}\n\tif e.MaxDNSQueries > 0 {\n\t\tconf.MaxDNSQueries = e.MaxDNSQueries\n\t}\n\t// Attempt to add the provided domains to the configuration\n\tconf.AddDomains(e.Domains.Slice()...)\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/enum/files.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage enum\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"strings\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n\t\"github.com/owasp-amass/amass/v5/resources\"\n)\n\n// Obtain parameters from provided input files\nfunc processInputFiles(args *Args) error {\n\tgetList := func(fp []string, name string, s *stringset.Set) error {\n\t\tfor _, p := range fp {\n\t\t\tif p != \"\" {\n\t\t\t\tlist, err := config.GetListFromFile(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to parse the %s file: %v\", name, err)\n\t\t\t\t}\n\t\t\t\ts.InsertMany(list...)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif args.Options.BruteForcing {\n\t\tif len(args.Filepaths.BruteWordlist) > 0 {\n\t\t\tif err := getList(args.Filepaths.BruteWordlist, \"brute force wordlist\", args.BruteWordList); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif f, err := resources.GetResourceFile(\"namelist.txt\"); err == nil {\n\t\t\t\tif list, err := getWordList(f); err == nil {\n\t\t\t\t\targs.BruteWordList.InsertMany(list...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !args.Options.NoAlts {\n\t\tif len(args.Filepaths.AltWordlist) > 0 {\n\t\t\tif err := getList(args.Filepaths.AltWordlist, \"alterations wordlist\", args.AltWordList); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif f, err := resources.GetResourceFile(\"alterations.txt\"); err == nil {\n\t\t\t\tif list, err := getWordList(f); err == nil {\n\t\t\t\t\targs.AltWordList.InsertMany(list...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif err := getList([]string{args.Filepaths.Blacklist}, \"blacklist\", args.Blacklist); err != nil {\n\t\treturn err\n\t}\n\tif err := getList([]string{args.Filepaths.ExcludedSrcs}, \"exclude\", args.Excluded); err != nil {\n\t\treturn err\n\t}\n\tif err := getList([]string{args.Filepaths.IncludedSrcs}, \"include\", args.Included); err != nil {\n\t\treturn err\n\t}\n\tif err := getList(args.Filepaths.Names, \"subdomain names\", args.Names); err != nil {\n\t\treturn err\n\t}\n\tif err := getList(args.Filepaths.Domains, \"domain names\", args.Domains); err != nil {\n\t\treturn err\n\t}\n\tif err := getList(args.Filepaths.Resolvers, \"resolver\", args.Resolvers); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc selectLogger(dir, logfile string) (*slog.Logger, error) {\n\tl, err := tools.NewSyslogLogger()\n\tif err == nil {\n\t\treturn l, nil\n\t}\n\treturn tools.NewFileLogger(dir, logfile)\n}\n\nfunc getWordList(reader io.Reader) ([]string, error) {\n\tvar words []string\n\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\t// Get the next word in the list\n\t\tw := strings.TrimSpace(scanner.Text())\n\t\tif err := scanner.Err(); err == nil && w != \"\" {\n\t\t\twords = append(words, w)\n\t\t}\n\t}\n\treturn stringset.Deduplicate(words), nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/libpostal/cgo_specific.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n//go:build cgo\n// +build cgo\n\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage libpostal\n\n/*\n#cgo pkg-config: libpostal\n#include \n#include \n\n*/\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"unicode/utf8\"\n\t\"unsafe\"\n)\n\ntype ParserOptions struct {\n\tLanguage string\n\tCountry string\n}\n\nvar (\n\tpostalLock sync.Mutex\n\tpostalLibAvailable bool\n\tparserDefaultOptions = getDefaultParserOptions()\n)\n\nfunc init() {\n\tif bool(C.libpostal_setup()) && bool(C.libpostal_setup_parser()) {\n\t\tpostalLibAvailable = true\n\t}\n}\n\nfunc getDefaultParserOptions() ParserOptions {\n\treturn ParserOptions{\n\t\tLanguage: \"\",\n\t\tCountry: \"\",\n\t}\n}\n\nfunc ParseAddress(address string) ([]ParsedComponent, error) {\n\treturn ParseAddressOptions(address, parserDefaultOptions)\n}\n\nfunc ParseAddressOptions(address string, options ParserOptions) ([]ParsedComponent, error) {\n\tif !postalLibAvailable {\n\t\treturn nil, errors.New(ErrPostalLibNotAvailable)\n\t}\n\n\tif !utf8.ValidString(address) {\n\t\treturn nil, errors.New(\"address is not a valid UTF-8 string\")\n\t}\n\n\tpostalLock.Lock()\n\tdefer postalLock.Unlock()\n\n\tcAddress := C.CString(address)\n\tdefer C.free(unsafe.Pointer(cAddress))\n\n\tcOptions := C.libpostal_get_address_parser_default_options()\n\tif options.Language != \"\" {\n\t\tcLanguage := C.CString(options.Language)\n\t\tdefer C.free(unsafe.Pointer(cLanguage))\n\n\t\tcOptions.language = cLanguage\n\t}\n\n\tif options.Country != \"\" {\n\t\tcCountry := C.CString(options.Country)\n\t\tdefer C.free(unsafe.Pointer(cCountry))\n\n\t\tcOptions.country = cCountry\n\t}\n\n\tcAddressParserResponsePtr := C.libpostal_parse_address(cAddress, cOptions)\n\n\tif cAddressParserResponsePtr == nil {\n\t\treturn nil, errors.New(\"failed to parse address\")\n\t}\n\n\tcAddressParserResponse := *cAddressParserResponsePtr\n\n\tcNumComponents := cAddressParserResponse.num_components\n\tcComponents := cAddressParserResponse.components\n\tcLabels := cAddressParserResponse.labels\n\n\tnumComponents := uint64(cNumComponents)\n\n\tparsedComponents := make([]ParsedComponent, numComponents)\n\n\t// Accessing a C array\n\tcComponentsPtr := (*[1 << 30](*C.char))(unsafe.Pointer(cComponents))[:numComponents:numComponents]\n\tcLabelsPtr := (*[1 << 30](*C.char))(unsafe.Pointer(cLabels))[:numComponents:numComponents]\n\n\tvar i uint64\n\tfor i = 0; i < numComponents; i++ {\n\t\tparsedComponents[i] = ParsedComponent{\n\t\t\tLabel: C.GoString(cLabelsPtr[i]),\n\t\t\tValue: C.GoString(cComponentsPtr[i]),\n\t\t}\n\t}\n\n\tC.libpostal_address_parser_response_destroy(cAddressParserResponsePtr)\n\n\treturn parsedComponents, nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/libpostal/pure_go.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n//go:build !cgo\n// +build !cgo\n\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage libpostal\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"net/url\"\n\t\"os\"\n\n\t\"github.com/owasp-amass/amass/v5/internal/net/http\"\n)\n\ntype parsed struct {\n\tParts []ParsedComponent `json:\"parts\"`\n}\n\nvar postalHost, postalPort string\n\nfunc init() {\n\tpostalHost = os.Getenv(\"POSTAL_SERVER_HOST\")\n\tpostalPort = os.Getenv(\"POSTAL_SERVER_PORT\")\n}\n\nfunc ParseAddress(address string) ([]ParsedComponent, error) {\n\tif postalHost == \"\" || postalPort == \"\" {\n\t\treturn nil, errors.New(ErrPostalLibNotAvailable)\n\t}\n\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tURL: \"http://\" + postalHost + \":\" + postalPort + \"/parse?address=\" + url.QueryEscape(address),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p parsed\n\tif err := json.Unmarshal([]byte(\"{\\\"parts\\\":\"+resp.Body+\"}\"), &p); err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Parts, nil\n}\n\n/*\nfunc expandAddress(address string) (string, error) {\n\tif postalHost == \"\" || postalPort == \"\" {\n\t\treturn \"\", errors.New(\"no postal server information provided\")\n\t}\n\n\tresp, err := http.RequestWebPage(context.TODO(), &http.Request{\n\t\tURL: \"http://\" + postalHost + \":\" + postalPort + \"/expand?address=\" + url.QueryEscape(address),\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttype expanded struct {\n\t\tForms []string `json:\"forms\"`\n\t}\n\n\tvar ex expanded\n\tif err := json.Unmarshal([]byte(\"{\\\"forms\\\":\"+resp.Body+\"}\"), &ex); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnum := len(ex.Forms)\n\tif num == 0 {\n\t\treturn \"\", errors.New(\"the libpostal expansion returned zero normalized strings\")\n\t}\n\treturn ex.Forms[num-1], nil\n}\n*/\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/libpostal/types.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage libpostal\n\nconst ErrPostalLibNotAvailable = \"libpostal is not available\"\n\ntype ParsedComponent struct {\n\tLabel string `json:\"label\"`\n\tValue string `json:\"value\"`\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/addr.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage net\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n)\n\nfunc ReadASPrefixes(db repository.Repository, asn int, since time.Time) []string {\n\tvar prefixes []string\n\n\tfqdns, err := db.FindEntitiesByContent(&network.AutonomousSystem{Number: asn}, since)\n\tif err != nil || len(fqdns) != 1 {\n\t\treturn prefixes\n\t}\n\tfqdn := fqdns[0]\n\n\tif edges, err := db.OutgoingEdges(fqdn, since, \"announces\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif a, err := db.FindEntityById(edge.ToEntity.ID); err != nil {\n\t\t\t\tcontinue\n\t\t\t} else if netblock, ok := a.Asset.(*network.Netblock); ok {\n\t\t\t\tprefixes = append(prefixes, netblock.CIDR.String())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn prefixes\n}\n\ntype NameAddrPair struct {\n\tFQDN *oamdns.FQDN\n\tAddr *network.IPAddress\n}\n\nfunc NamesToAddrs(db repository.Repository, since time.Time, names ...string) ([]*NameAddrPair, error) {\n\tvar fqdns []*dbt.Entity\n\tfor _, name := range names {\n\t\tif ents, err := db.FindEntitiesByContent(&oamdns.FQDN{Name: name}, since); err == nil && len(ents) == 1 {\n\t\t\tfqdns = append(fqdns, ents[0])\n\t\t}\n\t}\n\n\tvar results []*NameAddrPair\n\t// get the IPs associated with SRV, NS, and MX records\nloop:\n\tfor _, fqdn := range fqdns {\n\t\tif edges, err := db.OutgoingEdges(fqdn, since, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tswitch v := edge.Relation.(type) {\n\t\t\t\tcase *oamdns.BasicDNSRelation:\n\t\t\t\t\tif v.Header.RRType == 1 || v.Header.RRType == 28 {\n\t\t\t\t\t\tif ip, err := getAddr(db, edge.ToEntity, since); err == nil {\n\t\t\t\t\t\t\tresults = append(results, &NameAddrPair{\n\t\t\t\t\t\t\t\tFQDN: fqdn.Asset.(*oamdns.FQDN),\n\t\t\t\t\t\t\t\tAddr: ip,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if v.Header.RRType == 5 {\n\t\t\t\t\t\tif ip, err := cnameQuery(db, edge.ToEntity, since); err == nil {\n\t\t\t\t\t\t\tresults = append(results, &NameAddrPair{\n\t\t\t\t\t\t\t\tFQDN: fqdn.Asset.(*oamdns.FQDN),\n\t\t\t\t\t\t\t\tAddr: ip,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase *oamdns.PrefDNSRelation:\n\t\t\t\t\tif v.Header.RRType == 2 || v.Header.RRType == 15 {\n\t\t\t\t\t\tif ip, err := oneMoreName(db, edge.ToEntity, since); err == nil {\n\t\t\t\t\t\t\tresults = append(results, &NameAddrPair{\n\t\t\t\t\t\t\t\tFQDN: fqdn.Asset.(*oamdns.FQDN),\n\t\t\t\t\t\t\t\tAddr: ip,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase *oamdns.SRVDNSRelation:\n\t\t\t\t\tif v.Header.RRType == 33 {\n\t\t\t\t\t\tif ip, err := oneMoreName(db, edge.ToEntity, since); err == nil {\n\t\t\t\t\t\t\tresults = append(results, &NameAddrPair{\n\t\t\t\t\t\t\t\tFQDN: fqdn.Asset.(*oamdns.FQDN),\n\t\t\t\t\t\t\t\tAddr: ip,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc getAddr(db repository.Repository, ip *dbt.Entity, since time.Time) (*network.IPAddress, error) {\n\tif entity, err := db.FindEntityById(ip.ID); err == nil && entity != nil {\n\t\tif ip, ok := entity.Asset.(*network.IPAddress); ok {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"failed to extract the IP address\")\n}\n\nfunc oneMoreName(db repository.Repository, fqdn *dbt.Entity, since time.Time) (*network.IPAddress, error) {\n\tif edges, err := db.OutgoingEdges(fqdn, since, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif rel, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && (rel.Header.RRType == 1 || rel.Header.RRType == 28) {\n\t\t\t\treturn getAddr(db, edge.ToEntity, since)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.New(\"failed to traverse the FQDN\")\n}\n\nfunc cnameQuery(db repository.Repository, fqdn *dbt.Entity, since time.Time) (*network.IPAddress, error) {\n\tset := stringset.New()\n\tdefer set.Close()\n\n\tnext := fqdn\nloop:\n\tfor i := 0; i < 10; i++ {\n\t\tn, err := db.FindEntityById(next.ID)\n\t\tif err != nil || set.Has(n.Asset.Key()) {\n\t\t\tbreak\n\t\t}\n\t\tset.Insert(n.Asset.Key())\n\n\t\tif edges, err := db.OutgoingEdges(n, since, \"dns_record\"); err == nil && len(edges) > 0 {\n\t\t\tfor _, edge := range edges {\n\t\t\t\tif rel, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok {\n\t\t\t\t\tif rel.Header.RRType == 1 || rel.Header.RRType == 28 {\n\t\t\t\t\t\treturn getAddr(db, edge.ToEntity, since)\n\t\t\t\t\t} else if rel.Header.RRType == 5 {\n\t\t\t\t\t\tnext = edge.ToEntity\n\t\t\t\t\t\tcontinue loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"failed to traverse the aliases\")\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/asncache.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage net\n\nimport (\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\t\"github.com/owasp-amass/open-asset-model/network\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n\t\"github.com/yl2chen/cidranger\"\n)\n\n// ASNCache builds a cache of ASN and netblock information.\ntype ASNCache struct {\n\tsync.RWMutex\n\tcache map[int]*ASNRequest\n\tranger cidranger.Ranger\n}\n\ntype cacheRangerEntry struct {\n\tIPNet net.IPNet\n\tData *ASNRequest\n}\n\n// Output contains all the output data for an enumerated DNS name.\ntype Output struct {\n\tName string `json:\"name\"`\n\tAddresses []AddressInfo `json:\"addresses\"`\n}\n\n// ASNSummaryData stores information related to discovered ASs and netblocks.\ntype ASNSummaryData struct {\n\tName string\n\tNetblocks map[string]int\n}\n\n// AddressInfo stores all network addressing info for the Output type.\ntype AddressInfo struct {\n\tAddress net.IP `json:\"ip\"`\n\tNetblock *net.IPNet `json:\"-\"`\n\tCIDRStr string `json:\"cidr\"`\n\tASN int `json:\"asn\"`\n\tDescription string `json:\"desc\"`\n}\n\n// ASNRequest handles all autonomous system information needed by Amass.\ntype ASNRequest struct {\n\tAddress string\n\tASN int\n\tPrefix string\n\tCC string\n\tRegistry string\n\tAllocationDate time.Time\n\tDescription string\n\tNetblocks []string\n}\n\nfunc (e *cacheRangerEntry) Network() net.IPNet {\n\treturn e.IPNet\n}\n\n// NewASNCache returns an empty ASNCache for saving and searching ASN and netblock information.\nfunc NewASNCache() *ASNCache {\n\treturn &ASNCache{\n\t\tcache: make(map[int]*ASNRequest),\n\t\tranger: cidranger.NewPCTrieRanger(),\n\t}\n}\n\n// Update saves the information in ASNRequest into the ASNCache.\nfunc (c *ASNCache) Update(req *ASNRequest) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tas, found := c.cache[req.ASN]\n\tif !found {\n\t\tc.cache[req.ASN] = req\n\t\tif len(req.Netblocks) == 0 {\n\t\t\treq.Netblocks = []string{req.Prefix}\n\t\t}\n\t\treturn\n\t}\n\n\t// This is additional information for an ASN entry\n\tif as.CC == \"\" && req.CC != \"\" {\n\t\tas.CC = req.CC\n\t}\n\tif as.Registry == \"\" && req.Registry != \"\" {\n\t\tas.Registry = req.Registry\n\t}\n\tif as.AllocationDate.IsZero() && !req.AllocationDate.IsZero() {\n\t\tas.AllocationDate = req.AllocationDate\n\t}\n\tif len(as.Description) < len(req.Description) {\n\t\tas.Description = req.Description\n\t}\n\n\t// Add new CIDR ranges to cached netblocks\n\tfor _, cidr := range append([]string{req.Prefix}, req.Netblocks...) {\n\t\tvar known bool\n\n\t\tfor _, prefix := range as.Netblocks {\n\t\t\tif prefix == cidr {\n\t\t\t\tknown = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !known {\n\t\t\tas.Netblocks = append(as.Netblocks, cidr)\n\t\t}\n\t}\n}\n\n// DescriptionSearch matches the provided string against description fields in the cache and\n// returns the ASN / netblock info for matching entries.\nfunc (c *ASNCache) DescriptionSearch(s string) []*ASNRequest {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tvar matches []*ASNRequest\n\tfor _, entry := range c.cache {\n\t\tif strings.Contains(entry.Description, s) {\n\t\t\tmatches = append(matches, entry)\n\t\t}\n\t}\n\treturn matches\n}\n\n// ASNSearch returns the cached ASN / netblock info associated with the provided asn parameter,\n// or nil when not found in the cache.\nfunc (c *ASNCache) ASNSearch(asn int) *ASNRequest {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\treturn c.cache[asn]\n}\n\n// AddrSearch returns the cached ASN / netblock info that the addr parameter belongs in,\n// or nil when not found in the cache.\nfunc (c *ASNCache) AddrSearch(addr string) *ASNRequest {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\treturn nil\n\t}\n\n\t// Does the address fall into a reserved address ranges?\n\tif yes, cidr := isReservedAddress(addr); yes {\n\t\treturn &ASNRequest{\n\t\t\tAddress: addr,\n\t\t\tASN: 0,\n\t\t\tPrefix: cidr,\n\t\t\tDescription: \"Reserved Network Address Blocks\",\n\t\t}\n\t}\n\n\tentry := c.searchRangerData(ip)\n\tif entry == nil {\n\t\tc.rawData2Ranger(ip)\n\n\t\tentry = c.searchRangerData(ip)\n\t\tif entry == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tprefix := entry.IPNet.String()\n\tnetblocks := stringset.New(prefix)\n\tdefer netblocks.Close()\n\n\tnetblocks.InsertMany(entry.Data.Netblocks...)\n\treturn &ASNRequest{\n\t\tAddress: addr,\n\t\tASN: entry.Data.ASN,\n\t\tCC: entry.Data.CC,\n\t\tPrefix: prefix,\n\t\tNetblocks: netblocks.Slice(),\n\t\tDescription: entry.Data.Description,\n\t}\n}\n\nfunc FillCache(cache *ASNCache, db repository.Repository) error {\n\tstart := time.Now().Add(-730 * time.Hour)\n\tassets, err := db.FindEntitiesByType(oam.AutonomousSystem, start)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, a := range assets {\n\t\tas, ok := a.Asset.(*network.AutonomousSystem)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar desc string\n\t\tedges, err := db.OutgoingEdges(a, start, \"registration\")\n\t\tif err != nil || len(edges) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, edge := range edges {\n\t\t\tif asset, err := db.FindEntityById(edge.ToEntity.ID); err == nil && asset != nil {\n\t\t\t\tif autnum, ok := asset.Asset.(*oamreg.AutnumRecord); ok && autnum != nil {\n\t\t\t\t\tdesc = autnum.Handle + \" - \" + autnum.Name\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif desc == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, prefix := range ReadASPrefixes(db, as.Number, start) {\n\t\t\tfirst, cidr, err := net.ParseCIDR(prefix)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ones, _ := cidr.Mask.Size(); ones == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcache.Update(&ASNRequest{\n\t\t\t\tAddress: first.String(),\n\t\t\t\tASN: as.Number,\n\t\t\t\tPrefix: cidr.String(),\n\t\t\t\tDescription: desc,\n\t\t\t})\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *ASNCache) searchRangerData(ip net.IP) *cacheRangerEntry {\n\tif entries, err := c.ranger.ContainingNetworks(ip); err == nil {\n\t\tfor _, e := range entries {\n\t\t\tif entry, ok := e.(*cacheRangerEntry); ok {\n\t\t\t\treturn entry\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *ASNCache) rawData2Ranger(ip net.IP) {\n\tvar cidr *net.IPNet\n\tvar data *ASNRequest\n\n\tfor _, record := range c.cache {\n\t\tfor _, netblock := range record.Netblocks {\n\t\t\t_, ipnet, err := net.ParseCIDR(netblock)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ones, _ := ipnet.Mask.Size(); ones == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ipnet.Contains(ip) {\n\t\t\t\t// Select the smallest CIDR\n\t\t\t\tif cidr != nil && compareCIDRSizes(cidr, ipnet) == 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdata = record\n\t\t\t\tcidr = ipnet\n\t\t\t}\n\t\t}\n\t}\n\n\tif cidr != nil {\n\t\t_ = c.ranger.Insert(&cacheRangerEntry{\n\t\t\tIPNet: *cidr,\n\t\t\tData: data,\n\t\t})\n\t}\n}\n\nfunc compareCIDRSizes(first, second *net.IPNet) int {\n\tvar result int\n\n\ts1, _ := first.Mask.Size()\n\ts2, _ := second.Mask.Size()\n\tif s1 > s2 {\n\t\tresult = 1\n\t} else if s2 > s1 {\n\t\tresult = -1\n\t}\n\treturn result\n}\n\nfunc isReservedAddress(addr string) (bool, string) {\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\treturn false, \"\"\n\t}\n\n\tvar cidr string\n\tfor _, block := range reservedAddrRanges {\n\t\tif block.Contains(ip) {\n\t\t\tcidr = block.String()\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif cidr != \"\" {\n\t\treturn true, cidr\n\t}\n\treturn false, \"\"\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/network.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage net\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"math/big\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n// IPv4RE is a regular expression that will match an IPv4 address.\nconst IPv4RE = \"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\"\n\n// ReservedCIDRDescription is the description used for reserved address ranges.\nconst ReservedCIDRDescription = \"Reserved Network Address Blocks\"\n\n// LocalAddr is the global option for specifying the network interface.\nvar LocalAddr net.Addr\n\n// ReservedCIDRs includes all the networks that are reserved for special use.\nvar ReservedCIDRs = []string{\n\t\"192.168.0.0/16\",\n\t\"172.16.0.0/12\",\n\t\"10.0.0.0/8\",\n\t\"127.0.0.0/8\",\n\t\"224.0.0.0/4\",\n\t\"240.0.0.0/4\",\n\t\"100.64.0.0/10\",\n\t\"198.18.0.0/15\",\n\t\"169.254.0.0/16\",\n\t\"192.88.99.0/24\",\n\t\"192.0.0.0/24\",\n\t\"192.0.2.0/24\",\n\t\"192.94.77.0/24\",\n\t\"192.94.78.0/24\",\n\t\"192.52.193.0/24\",\n\t\"192.12.109.0/24\",\n\t\"192.31.196.0/24\",\n\t\"192.0.0.0/29\",\n}\n\n// The reserved network address ranges\nvar reservedAddrRanges []*net.IPNet\n\nfunc init() {\n\tfor _, cidr := range ReservedCIDRs {\n\t\tif _, ipnet, err := net.ParseCIDR(cidr); err == nil {\n\t\t\treservedAddrRanges = append(reservedAddrRanges, ipnet)\n\t\t}\n\t}\n}\n\n// DialContext performs the dial using global variables (e.g. LocalAddr).\nfunc DialContext(ctx context.Context, network, addr string) (net.Conn, error) {\n\td := &net.Dialer{DualStack: true}\n\n\t_, p, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tport, err := strconv.Atoi(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif LocalAddr != nil {\n\t\taddr, _, err := net.ParseCIDR(LocalAddr.String())\n\n\t\tif err == nil && strings.HasPrefix(network, \"tcp\") {\n\t\t\td.LocalAddr = &net.TCPAddr{\n\t\t\t\tIP: addr,\n\t\t\t\tPort: port,\n\t\t\t}\n\t\t} else if err == nil && strings.HasPrefix(network, \"udp\") {\n\t\t\td.LocalAddr = &net.UDPAddr{\n\t\t\t\tIP: addr,\n\t\t\t\tPort: port,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn d.DialContext(ctx, network, addr)\n}\n\n// IsIPv4 returns true when the provided net.IP address is an IPv4 address.\nfunc IsIPv4(ip net.IP) bool {\n\treturn strings.Count(ip.String(), \":\") < 2\n}\n\n// IsIPv6 returns true when the provided net.IP address is an IPv6 address.\nfunc IsIPv6(ip net.IP) bool {\n\treturn strings.Count(ip.String(), \":\") >= 2\n}\n\n// IsReservedAddress checks if the addr parameter is within one of the address ranges in the ReservedCIDRs slice.\nfunc IsReservedAddress(addr string) (bool, string) {\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\treturn false, \"\"\n\t}\n\n\tvar cidr string\n\tfor _, block := range reservedAddrRanges {\n\t\tif block.Contains(ip) {\n\t\t\tcidr = block.String()\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif cidr != \"\" {\n\t\treturn true, cidr\n\t}\n\treturn false, \"\"\n}\n\n// FirstLast return the first and last IP address of the provided CIDR/netblock.\nfunc FirstLast(cidr *net.IPNet) (net.IP, net.IP) {\n\tfirstIP := cidr.IP\n\tprefixLen, bits := cidr.Mask.Size()\n\n\tif prefixLen == bits {\n\t\tlastIP := make([]byte, len(firstIP))\n\t\tcopy(lastIP, firstIP)\n\t\treturn firstIP, lastIP\n\t}\n\n\tfirstIPInt, bits := ipToInt(firstIP)\n\thostLen := uint(bits) - uint(prefixLen)\n\tlastIPInt := big.NewInt(1)\n\n\tlastIPInt.Lsh(lastIPInt, hostLen)\n\tlastIPInt.Sub(lastIPInt, big.NewInt(1))\n\tlastIPInt.Or(lastIPInt, firstIPInt)\n\n\treturn firstIP, intToIP(lastIPInt, bits)\n}\n\n// Range2CIDR turns an IP range into a CIDR.\nfunc Range2CIDR(first, last net.IP) *net.IPNet {\n\tstartip, m := ipToInt(first)\n\tendip, _ := ipToInt(last)\n\tnewip := big.NewInt(1)\n\tmask := big.NewInt(1)\n\tone := big.NewInt(1)\n\n\tif startip.Cmp(endip) == 1 {\n\t\treturn nil\n\t}\n\n\tmax := uint(m)\n\tvar bits uint = 1\n\tnewip.Set(startip)\n\ttmp := new(big.Int)\n\tfor bits < max {\n\t\ttmp.Rsh(startip, bits)\n\t\ttmp.Lsh(tmp, bits)\n\n\t\tnewip.Or(startip, mask)\n\t\tif newip.Cmp(endip) == 1 || tmp.Cmp(startip) != 0 {\n\t\t\tbits--\n\t\t\tmask.Rsh(mask, 1)\n\t\t\tbreak\n\t\t}\n\n\t\tbits++\n\t\ttmp.Lsh(mask, 1)\n\t\tmask.Add(tmp, one)\n\t}\n\n\tcidrstr := first.String() + \"/\" + strconv.Itoa(int(max-bits))\n\t_, ipnet, _ := net.ParseCIDR(cidrstr)\n\n\treturn ipnet\n}\n\n// AllHosts returns a slice containing all the IP addresses within\n// the CIDR provided by the parameter. This implementation was\n// obtained/modified from the following:\n// https://gist.github.com/kotakanbe/d3059af990252ba89a82\nfunc AllHosts(cidr *net.IPNet) []net.IP {\n\tvar ips []net.IP\n\n\tfor ip := cidr.IP.Mask(cidr.Mask); cidr.Contains(ip); IPInc(ip) {\n\t\taddr := net.ParseIP(ip.String())\n\n\t\tips = append(ips, addr)\n\t}\n\n\tif len(ips) > 2 {\n\t\t// Remove network address and broadcast address\n\t\tips = ips[1 : len(ips)-1]\n\t}\n\treturn ips\n}\n\n// RangeHosts returns all the IP addresses (inclusive) between\n// the start and stop addresses provided by the parameters.\nfunc RangeHosts(start, end net.IP) []net.IP {\n\tvar ips []net.IP\n\n\tif start == nil || end == nil {\n\t\treturn ips\n\t}\n\n\tstart16 := start.To16()\n\tend16 := end.To16()\n\t// Check that the end address is higher than the start address\n\tif r := bytes.Compare(end16, start16); r < 0 {\n\t\treturn ips\n\t} else if r == 0 {\n\t\treturn []net.IP{start}\n\t}\n\n\tstop := net.ParseIP(end.String())\n\tIPInc(stop)\n\n\tfor ip := net.ParseIP(start.String()); !ip.Equal(stop); IPInc(ip) {\n\t\tif addr := net.ParseIP(ip.String()); addr != nil {\n\t\t\tips = append(ips, addr)\n\t\t}\n\t}\n\n\treturn ips\n}\n\n// CIDRSubset returns a subset of the IP addresses contained within\n// the cidr parameter with num elements around the addr element.\nfunc CIDRSubset(cidr *net.IPNet, addr string, num int) []net.IP {\n\tfirst := net.ParseIP(addr)\n\n\tif !cidr.Contains(first) {\n\t\treturn []net.IP{first}\n\t}\n\n\toffset := num / 2\n\t// Get the first address\n\tfor i := 0; i < offset; i++ {\n\t\tIPDec(first)\n\t\t// Check that it is still within the CIDR\n\t\tif !cidr.Contains(first) {\n\t\t\tIPInc(first)\n\t\t\tbreak\n\t\t}\n\t}\n\t// Get the last address\n\tlast := net.ParseIP(addr)\n\tfor i := 0; i < offset; i++ {\n\t\tIPInc(last)\n\t\t// Check that it is still within the CIDR\n\t\tif !cidr.Contains(last) {\n\t\t\tIPDec(last)\n\t\t\tbreak\n\t\t}\n\t}\n\t// Check that the addresses are not the same\n\tif first.Equal(last) {\n\t\treturn []net.IP{first}\n\t}\n\t// Return the IP addresses within the range\n\treturn RangeHosts(first, last)\n}\n\n// IPInc increments the IP address provided.\nfunc IPInc(ip net.IP) {\n\tfor j := len(ip) - 1; j >= 0; j-- {\n\t\tip[j]++\n\t\tif ip[j] > 0 {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// IPDec decrements the IP address provided.\nfunc IPDec(ip net.IP) {\n\tfor j := len(ip) - 1; j >= 0; j-- {\n\t\tif ip[j] > 0 {\n\t\t\tip[j]--\n\t\t\tbreak\n\t\t}\n\t\tip[j]--\n\t}\n}\n\nfunc ipToInt(ip net.IP) (*big.Int, int) {\n\tval := big.NewInt(1)\n\n\tval.SetBytes([]byte(ip))\n\tif IsIPv4(ip) {\n\t\treturn val, 32\n\t} else if IsIPv6(ip) {\n\t\treturn val, 128\n\t}\n\n\treturn val, 0\n}\n\nfunc intToIP(ipInt *big.Int, bits int) net.IP {\n\tipBytes := ipInt.Bytes()\n\tret := make([]byte, bits/8)\n\n\t// Pack our IP bytes into the end of the return array,\n\t// since big.Int.Bytes() removes front zero padding\n\tfor i := 1; i <= len(ipBytes); i++ {\n\t\tret[len(ret)-i] = ipBytes[len(ipBytes)-i]\n\t}\n\n\treturn net.IP(ret)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/network_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage net\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"testing\"\n)\n\nfunc TestIsIPv4(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected bool\n\t}{\n\t\t{\"72.237.4.0\", true},\n\t\t{\"192.168.1.0\", true},\n\t\t{\"174.129.0.0:80\", true},\n\t\t{\"0.0.0.0\", true},\n\t\t{\"2620:0:860:2::\", false},\n\t\t{\"2620:0:860:2:ffff:ffff:ffff:ffff\", false},\n\t}\n\n\tfor _, test := range tests {\n\t\tif b := IsIPv4(net.ParseIP(test.Address)); b != test.Expected {\n\t\t\tt.Errorf(\"Failed on IP address %s\", test.Address)\n\t\t}\n\t}\n}\n\nfunc TestIsIPv6(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected bool\n\t}{\n\t\t{\"72.237.4.0\", false},\n\t\t{\"192.168.1.0\", false},\n\t\t{\"174.129.0.0:80\", false},\n\t\t{\"0.0.0.0\", false},\n\t\t{\"2620:0:860:2::\", true},\n\t\t{\"2620:0:860:2:ffff:ffff:ffff:ffff\", true},\n\t}\n\n\tfor _, test := range tests {\n\t\tif b := IsIPv6(net.ParseIP(test.Address)); b != test.Expected {\n\t\t\tt.Errorf(\"Failed on IP address %s\", test.Address)\n\t\t}\n\t}\n}\n\nfunc TestFirstLast(t *testing.T) {\n\ttests := []struct {\n\t\tCIDR string\n\t\tExpectedFirst string\n\t\tExpectedLast string\n\t}{\n\t\t{\"72.237.4.0/24\", \"72.237.4.0\", \"72.237.4.255\"},\n\t\t{\"192.168.1.0/24\", \"192.168.1.0\", \"192.168.1.255\"},\n\t\t{\"174.129.0.0/16\", \"174.129.0.0\", \"174.129.255.255\"},\n\t\t{\"0.0.0.0/0\", \"0.0.0.0\", \"255.255.255.255\"},\n\t\t{\"192.168.1.0/32\", \"192.168.1.0\", \"192.168.1.0\"},\n\t\t{\"2620:0:860:2::/64\", \"2620:0:860:2::\", \"2620:0:860:2:ffff:ffff:ffff:ffff\"},\n\t}\n\n\tfor _, test := range tests {\n\t\t_, ipnet, _ := net.ParseCIDR(test.CIDR)\n\n\t\tif f, l := FirstLast(ipnet); f.String() != test.ExpectedFirst || l.String() != test.ExpectedLast {\n\t\t\tt.Errorf(\"Returned first IP %s and last IP %s instead of %s and %s, respectively\",\n\t\t\t\tf.String(), l.String(), test.ExpectedFirst, test.ExpectedLast)\n\t\t}\n\t}\n}\n\nfunc TestRange2CIDR(t *testing.T) {\n\ttests := []struct {\n\t\tFirst string\n\t\tLast string\n\t\tExpected string\n\t}{\n\t\t{\"72.237.4.0\", \"72.237.4.255\", \"72.237.4.0/24\"},\n\t\t{\"192.168.1.0\", \"192.168.1.255\", \"192.168.1.0/24\"},\n\t\t{\"174.129.0.0\", \"174.129.255.255\", \"174.129.0.0/16\"},\n\t\t{\"0.0.0.0\", \"255.255.255.255\", \"0.0.0.0/0\"},\n\t\t{\"192.168.1.0\", \"192.168.1.0\", \"192.168.1.0/32\"},\n\t\t{\"2620:0:860:2::\", \"2620:0:860:2:ffff:ffff:ffff:ffff\", \"2620:0:860:2::/64\"},\n\t}\n\n\t// A start IP greater than the end IP should return nil\n\tnocidr := Range2CIDR(net.ParseIP(\"192.168.1.255\"), net.ParseIP(\"192.168.1.1\"))\n\tif nocidr != nil {\n\t\tt.Errorf(\"Failed to return nil when %s was greater than %s\", \"192.168.1.255\", \"192.168.1.1\")\n\t}\n\n\tfor _, test := range tests {\n\t\tcidr := Range2CIDR(net.ParseIP(test.First), net.ParseIP(test.Last))\n\n\t\tif cidr == nil {\n\t\t\tt.Errorf(\"First IP %s and last IP %s failed to return %s\",\n\t\t\t\ttest.First, test.Last, test.Expected)\n\t\t} else if cidr.String() != test.Expected {\n\t\t\tt.Errorf(\"First IP %s and last IP %s returned %s instead of %s\",\n\t\t\t\ttest.First, test.Last, cidr.String(), test.Expected)\n\t\t}\n\t}\n}\n\nfunc TestAllHosts(t *testing.T) {\n\t_, ipnet, _ := net.ParseCIDR(\"72.237.4.0/24\")\n\n\thosts := AllHosts(ipnet)\n\tif n := len(hosts); n != 254 {\n\t\tt.Errorf(\"%d hosts were returned instead of %d\", n, 254)\n\t}\n\n\tnum := 1\n\ts := \"72.237.4.\"\n\tfor _, host := range hosts {\n\t\tip := s + strconv.Itoa(num)\n\n\t\tif ip != host.String() {\n\t\t\tt.Errorf(\"IP address %s was missing from the slice of returned hosts\", ip)\n\t\t}\n\n\t\tnum++\n\t}\n}\n\nfunc TestRangeHosts(t *testing.T) {\n\ttests := []struct {\n\t\tFirst string\n\t\tLast string\n\t\tExpectedSize int\n\t}{\n\t\t{\"72.237.4.1\", \"72.237.4.50\", 50},\n\t\t{\"192.168.2.1\", \"192.168.2.1\", 1},\n\t\t{\"192.168.1.25\", \"192.168.1.1\", 0},\n\t\t{\"150.154.1.250\", \"150.154.2.50\", 57},\n\t\t{\"2620:0:860:2::\", \"2620:0:860:2::7d\", 126},\n\t}\n\n\tfor _, test := range tests {\n\t\thosts := RangeHosts(net.ParseIP(test.First), net.ParseIP(test.Last))\n\n\t\tif num := len(hosts); num != test.ExpectedSize {\n\t\t\tt.Errorf(\"Range %s - %s caused %d hosts to be returned instead of %d\",\n\t\t\t\ttest.First, test.Last, num, test.ExpectedSize)\n\t\t} else if num == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tip := net.ParseIP(test.First)\n\t\tfor _, host := range hosts {\n\t\t\tif ip.String() != host.String() {\n\t\t\t\tt.Errorf(\"IP address %s was missing from the slice of returned hosts\", ip.String())\n\t\t\t}\n\n\t\t\tIPInc(ip)\n\t\t}\n\n\t\tIPDec(ip)\n\t\tif ip.String() != test.Last {\n\t\t\tt.Errorf(\"The last IP %s did not match the expected IP %s\", ip.String(), test.Last)\n\t\t}\n\t}\n\n\tif num := len(RangeHosts(nil, nil)); num != 0 {\n\t\tt.Errorf(\"nil IP addresses caused %d hosts to be returned instead of 0\", num)\n\t}\n}\n\nfunc TestCIDRSubset(t *testing.T) {\n\ttests := []struct {\n\t\tCIDR string\n\t\tAddress string\n\t\tSize int\n\t\tExpectedFirst string\n\t\tExpectedLast string\n\t\tExpectedSize int\n\t}{\n\t\t{\"192.168.1.0/24\", \"192.168.1.55\", 50, \"192.168.1.30\", \"192.168.1.80\", 51},\n\t\t{\"72.237.4.0/24\", \"72.237.4.0\", 200, \"72.237.4.0\", \"72.237.4.100\", 101},\n\t\t{\"72.237.4.0/24\", \"72.237.4.250\", 200, \"72.237.4.150\", \"72.237.4.255\", 106},\n\t\t{\"192.168.1.0/24\", \"192.168.2.1\", 100, \"192.168.2.1\", \"192.168.2.1\", 1},\n\t\t{\"192.168.1.0/32\", \"192.168.1.0\", 20, \"192.168.1.0\", \"192.168.1.0\", 1},\n\t\t{\"2620:0:860:2::/64\", \"2620:0:860:2::\", 250, \"2620:0:860:2::\", \"2620:0:860:2::7d\", 126},\n\t}\n\n\tfor _, test := range tests {\n\t\t_, ipnet, _ := net.ParseCIDR(test.CIDR)\n\n\t\tsubset := CIDRSubset(ipnet, test.Address, test.Size)\n\t\tif l := len(subset); l != test.ExpectedSize {\n\t\t\tt.Errorf(\"The returned subset had %d elements instead of %d\", l, test.ExpectedSize)\n\t\t}\n\n\t\tcur := net.ParseIP(test.ExpectedFirst)\n\t\tfor _, ip := range subset {\n\t\t\tif cur.String() != ip.String() {\n\t\t\t\tt.Errorf(\"IP address %s was missing from the slice of returned addresses\", cur.String())\n\t\t\t}\n\n\t\t\tIPInc(cur)\n\t\t}\n\n\t\tIPDec(cur)\n\t\tif cur.String() != test.ExpectedLast {\n\t\t\tt.Errorf(\"The last IP in the subset %s did not match the expected IP %s\", cur.String(), test.ExpectedLast)\n\t\t}\n\t}\n}\n\nfunc TestIPInc(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected string\n\t}{\n\t\t{\"72.237.4.0\", \"72.237.4.1\"},\n\t\t{\"192.168.1.255\", \"192.168.2.0\"},\n\t\t{\"174.128.255.255\", \"174.129.0.0\"},\n\t\t{\"0.0.0.0\", \"0.0.0.1\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tip := net.ParseIP(test.Address)\n\n\t\tIPInc(ip)\n\t\tif ip.String() != test.Expected {\n\t\t\tt.Errorf(\"%s caused %s to be returned instead of %s\", test.Address, ip.String(), test.Expected)\n\t\t}\n\t}\n}\n\nfunc TestIPDec(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected string\n\t}{\n\t\t{\"72.237.4.1\", \"72.237.4.0\"},\n\t\t{\"192.168.1.0\", \"192.168.0.255\"},\n\t\t{\"174.129.0.0\", \"174.128.255.255\"},\n\t\t{\"0.0.0.1\", \"0.0.0.0\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tip := net.ParseIP(test.Address)\n\n\t\tIPDec(ip)\n\t\tif ip.String() != test.Expected {\n\t\t\tt.Errorf(\"%s caused %s to be returned instead of %s\", test.Address, ip.String(), test.Expected)\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/dns/dns.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"encoding/hex\"\n\t\"net\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n// SUBRE is a regular expression that will match on all subdomains once the domain is appended.\nconst SUBRE = \"(([a-zA-Z0-9]{1}|[_a-zA-Z0-9]{1}[_a-zA-Z0-9-]{0,61}[a-zA-Z0-9]{1})[.]{1})+\"\n\n// SubdomainRegex returns a Regexp object initialized to match\n// subdomain names that end with the domain provided by the parameter.\nfunc SubdomainRegex(domain string) *regexp.Regexp {\n\treturn regexp.MustCompile(SubdomainRegexString(domain))\n}\n\n// SubdomainRegexString returns a regular expression string that matchs\n// subdomain names ending with the domain provided by the parameter.\nfunc SubdomainRegexString(domain string) string {\n\t// Change all the periods into literal periods for the regex\n\treturn SUBRE + regexp.QuoteMeta(domain)\n}\n\n// AnySubdomainRegex returns a Regexp object initialized to match any DNS subdomain name.\nfunc AnySubdomainRegex() *regexp.Regexp {\n\treturn regexp.MustCompile(AnySubdomainRegexString())\n}\n\n// AnySubdomainRegexString returns a regular expression string to match any DNS subdomain name.\nfunc AnySubdomainRegexString() string {\n\treturn SUBRE + \"[a-zA-Z]{2,61}\"\n}\n\n// CopyString return a new string variable with the same value as the parameter.\nfunc CopyString(src string) string {\n\tstr := make([]byte, len(src))\n\n\tcopy(str, src)\n\treturn string(str)\n}\n\n// RemoveAsteriskLabel returns the provided DNS name with all asterisk labels removed.\nfunc RemoveAsteriskLabel(s string) string {\n\tstartIndex := strings.LastIndex(s, \"*.\")\n\n\tif startIndex == -1 {\n\t\treturn s\n\t}\n\n\treturn s[startIndex+2:]\n}\n\n// ReverseString returns the characters of the argument string in reverse order.\nfunc ReverseString(s string) string {\n\tchrs := []rune(s)\n\tend := len(chrs) / 2\n\n\tfor i, j := 0, len(chrs)-1; i < end; i, j = i+1, j-1 {\n\t\tchrs[i], chrs[j] = chrs[j], chrs[i]\n\t}\n\n\treturn string(chrs)\n}\n\n// ReverseIP returns an IP address that is the ip parameter with the numbers reversed.\nfunc ReverseIP(ip string) string {\n\tvar reversed []string\n\n\tparts := strings.Split(ip, \".\")\n\tli := len(parts) - 1\n\n\tfor i := li; i >= 0; i-- {\n\t\treversed = append(reversed, parts[i])\n\t}\n\n\treturn strings.Join(reversed, \".\")\n}\n\n// IPv6NibbleFormat expects an IPv6 address in the ip parameter and\n// returns the address in nibble format.\nfunc IPv6NibbleFormat(ip string) string {\n\tvar reversed []string\n\n\tip = strings.ReplaceAll(expandIPv6Addr(ip), \":\", \"\")\n\tparts := strings.Split(ip, \"\")\n\tli := len(parts) - 1\n\n\tfor i := li; i >= 0; i-- {\n\t\treversed = append(reversed, parts[i])\n\t}\n\n\treturn strings.Join(reversed, \".\")\n}\n\nfunc expandIPv6Addr(addr string) string {\n\tip := net.ParseIP(addr)\n\n\tdst := make([]byte, hex.EncodedLen(len(ip)))\n\thex.Encode(dst, ip)\n\n\treturn string(dst[0:4]) + \":\" +\n\t\tstring(dst[4:8]) + \":\" +\n\t\tstring(dst[8:12]) + \":\" +\n\t\tstring(dst[12:16]) + \":\" +\n\t\tstring(dst[16:20]) + \":\" +\n\t\tstring(dst[20:24]) + \":\" +\n\t\tstring(dst[24:28]) + \":\" +\n\t\tstring(dst[28:])\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/dns/dns_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage dns\n\nimport (\n\t\"testing\"\n)\n\nfunc TestSubdomainRegex(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tdomain string\n\t\tevent string\n\t\texpected string\n\t}{\n\n\t\t{\"Test 1: Subdomain\", \"owasp.org\", \"subdomain.owasp.org\", \"subdomain.owasp.org\"},\n\t\t{\"Test 2: Nested subdomain\", \"owasp.org\", \"sub.subdomain.owasp.org\", \"sub.subdomain.owasp.org\"},\n\t\t{\"Test 3: Subdomain-dashes\", \"owasp.org\", \"sub-domain.owasp.org\", \"sub-domain.owasp.org\"},\n\t\t{\"Test 4: Subdomain-dashes again\", \"owasp.org\", \"sub-d.sub-domain.owasp.org\", \"sub-d.sub-domain.owasp.org\"},\n\t\t{\"Test 5: Double period\", \"owasp.org\", \"sub..owasp.org\", \"\"},\n\t\t{\"Test 6: Wrong domain\", \"owasp.org\", \".sub-d.sub-domain.owasp.com\", \"\"},\n\t\t{\"Test 7: Sub end with dash\", \"owasp.org\", \"sub-.owasp.org\", \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\ts := SubdomainRegex(tt.domain)\n\n\t\tif result := s.FindString(tt.event); result != tt.expected {\n\t\t\tt.Errorf(\"Error Event %s: regex did not match %s\", tt.name, tt.event)\n\n\t\t}\n\t}\n}\n\nfunc TestAnySubdomainRegex(t *testing.T) {\n\ttests := []struct {\n\t\tValue string\n\t\tExpected bool\n\t}{\n\t\t{\"owasp.org\", true},\n\t\t{\"subdomain.owasp.org\", true},\n\t\t{\"sub-domain.owasp.org\", true},\n\t\t{\"subdomain.owasp.\", false},\n\t\t{\"sub..owasp.org\", false},\n\t\t{\".sub-d.sub-domain.owasp.com\", false},\n\t\t{\"sub-.owasp.org\", false},\n\t}\n\n\tre := AnySubdomainRegex()\n\tfor _, test := range tests {\n\t\tloc := re.FindStringIndex(test.Value)\n\n\t\tif loc == nil || (test.Value[loc[0]:loc[1]] == test.Value) != test.Expected {\n\t\t\tt.Errorf(\"The regexp did not match %s as expected\", test.Value)\n\t\t}\n\t}\n}\n\nfunc TestCopyString(t *testing.T) {\n\ttests := []string{\"\", \"owasp.org\", \"TESTING\"}\n\n\tfor _, test := range tests {\n\t\tif c := CopyString(test); c != test {\n\t\t\tt.Errorf(\"Returned %s instead of %s\", c, test)\n\t\t}\n\t}\n}\n\nfunc TestRemoveAsteriskLabel(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tevent string\n\t\texpected string\n\t}{\n\n\t\t{\"Test 1: Subdomain\", \"*.subdomain.owasp.org\", \"subdomain.owasp.org\"},\n\t\t{\"Test 2: Nested subdomain\", \"*.subdomain.owasp.org\", \"subdomain.owasp.org\"},\n\t\t{\"Test 3: Subdomain-dashes\", \"*.sub-domain.owasp.org\", \"sub-domain.owasp.org\"},\n\t\t{\"Test 4: Subdomain-dashes\", \"*.sub-d.sub-domain.owasp.org\", \"sub-d.sub-domain.owasp.org\"},\n\t\t{\"Test 5: Middle Label Asterisk\", \"sub-d.sub-domain.*.owasp.org\", \"owasp.org\"},\n\t\t{\"Test 6: Missing Asterisk Label\", \"sub-domain.owasp.org\", \"sub-domain.owasp.org\"},\n\t\t{\"Test 7: Empty string\", \"\", \"\"},\n\t}\n\tfor _, tt := range tests {\n\t\tif s := RemoveAsteriskLabel(tt.event); s != tt.expected && s != \"\" {\n\t\t\tt.Errorf(\"Error Event %s: was expecting \\\"\\\" or %s, got %s\", tt.name, tt.expected, tt.event)\n\t\t}\n\t}\n}\n\nfunc TestReverseString(t *testing.T) {\n\ttests := []struct {\n\t\tValue string\n\t\tExpected string\n\t}{\n\t\t{\"owasp\", \"psawo\"},\n\t\t{\"Test\", \"tseT\"},\n\t\t{\"*.sub-d.sub-domain.owasp.org\", \"gro.psawo.niamod-bus.d-bus.*\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif c := ReverseString(test.Value); c != test.Expected {\n\t\t\tt.Errorf(\"Returned %s instead of %s\", c, test.Expected)\n\t\t}\n\t}\n}\n\nfunc TestReverseIP(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected string\n\t}{\n\t\t{\"72.237.4.0\", \"0.4.237.72\"},\n\t\t{\"192.168.1.0\", \"0.1.168.192\"},\n\t\t{\"174.129.0.0\", \"0.0.129.174\"},\n\t\t{\"0.0.0.0\", \"0.0.0.0\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif r := ReverseIP(test.Address); r != test.Expected {\n\t\t\tt.Errorf(\"%s caused %s to be returned instead of %s\", test.Address, r, test.Expected)\n\t\t}\n\t}\n}\n\nfunc TestIPv6NibbleFormat(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected string\n\t}{\n\t\t{\"2620:0:860:2::\", \"0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.0.6.8.0.0.0.0.0.0.2.6.2\"},\n\t\t{\"2620:0:860:2:ffff:ffff:ffff:ffff\", \"f.f.f.f.f.f.f.f.f.f.f.f.f.f.f.f.2.0.0.0.0.6.8.0.0.0.0.0.0.2.6.2\"},\n\t\t{\"fdda:5cc1:23:4::1f\", \"f.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.4.0.0.0.3.2.0.0.1.c.c.5.a.d.d.f\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif r := IPv6NibbleFormat(test.Address); r != test.Expected {\n\t\t\tt.Errorf(\"%s caused %s to be returned instead of %s\", test.Address, r, test.Expected)\n\t\t}\n\t}\n}\n\nfunc TestExpandIPv6Addr(t *testing.T) {\n\ttests := []struct {\n\t\tAddress string\n\t\tExpected string\n\t}{\n\t\t{\"2620:0:860:2::\", \"2620:0000:0860:0002:0000:0000:0000:0000\"},\n\t\t{\"fdda:5cc1:23:4::1f\", \"fdda:5cc1:0023:0004:0000:0000:0000:001f\"},\n\t\t{\"2620:0:860:2:ffff:ffff:ffff:ffff\", \"2620:0000:0860:0002:ffff:ffff:ffff:ffff\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tif r := expandIPv6Addr(test.Address); r != test.Expected {\n\t\t\tt.Errorf(\"%s caused %s to be returned instead of %s\", test.Address, r, test.Expected)\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/http/http.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage http\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"github.com/geziyor/geziyor\"\n\t\"github.com/geziyor/geziyor/client\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\t\"github.com/owasp-amass/amass/v5/internal/net/dns\"\n\tbf \"github.com/tylertreat/BoomFilters\"\n)\n\nconst (\n\t// Accept is the default HTTP Accept header value used by Amass.\n\tAccept = \"text/html,application/json,application/xhtml+xml,application/xml;q=0.5,*/*;q=0.2\"\n\t// AcceptLang is the default HTTP Accept-Language header value used by Amass.\n\tAcceptLang = \"en-US,en;q=0.5\"\n\tdefaultUserAgent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36\"\n\twindowsUserAgent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36\"\n\tdarwinUserAgent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36\"\n\thttpTimeout = 10 * time.Second\n\thandshakeTimeout = 5 * time.Second\n)\n\nvar (\n\t// UserAgent is the default user agent used by Amass during HTTP requests.\n\tUserAgent string\n\tsubRE = dns.AnySubdomainRegex()\n\tnameStripRE = regexp.MustCompile(`^(u[0-9a-f]{4}|20|22|25|27|2b|2f|3d|3a|40)`)\n)\n\n// DefaultClient is the same HTTP client used by the package methods.\nvar DefaultClient *http.Client\n\n// Header represents the HTTP headers for requests and responses.\ntype Header map[string][]string\n\n// Request represents the HTTP request in the Amass preferred format.\ntype Request struct {\n\tURL string\n\tMethod string\n\tHeader Header\n\tBody string\n\tAuth *BasicAuth\n}\n\n// Response represents the HTTP response in the Amass preferred format.\ntype Response struct {\n\tStatus string\n\tStatusCode int\n\tProto string\n\tProtoMajor int\n\tProtoMinor int\n\tHeader Header\n\tBody string\n\tLength int64\n\tTLS *tls.ConnectionState\n}\n\n// BasicAuth contains the data used for HTTP basic authentication.\ntype BasicAuth struct {\n\tUsername string\n\tPassword string\n}\n\nfunc init() {\n\tjar, _ := cookiejar.New(nil)\n\tDefaultClient = &http.Client{\n\t\tTimeout: httpTimeout,\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: amassnet.DialContext,\n\t\t\tMaxIdleConns: 200,\n\t\t\tMaxConnsPerHost: 50,\n\t\t\tIdleConnTimeout: 10 * time.Second,\n\t\t\tTLSHandshakeTimeout: handshakeTimeout,\n\t\t\tExpectContinueTimeout: 5 * time.Second,\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\tJar: jar,\n\t}\n\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tUserAgent = windowsUserAgent\n\tcase \"darwin\":\n\t\tUserAgent = darwinUserAgent\n\tdefault:\n\t\tUserAgent = defaultUserAgent\n\t}\n}\n\n// HdrToAmassHeader converts a net/http Header to an Amass Header.\nfunc HdrToAmassHeader(hdr http.Header) Header {\n\th := make(Header)\n\tfor k, v := range hdr {\n\t\tif len(v) > 0 {\n\t\t\th[k] = append(h[k], v...)\n\t\t}\n\t}\n\treturn h\n}\n\n// ReqToAmassRequest converts a net/http Request to an Amass Request.\nfunc ReqToAmassRequest(req *http.Request) *Request {\n\tvar body string\n\tif req.Body != nil {\n\t\tif b, err := io.ReadAll(req.Body); err == nil {\n\t\t\tbody = string(b)\n\t\t}\n\t\t_ = req.Body.Close()\n\t}\n\n\tvar ba *BasicAuth\n\tif user, pass, ok := req.BasicAuth(); ok {\n\t\tba = &BasicAuth{\n\t\t\tUsername: user,\n\t\t\tPassword: pass,\n\t\t}\n\t}\n\n\treturn &Request{\n\t\tURL: req.URL.String(),\n\t\tMethod: req.Method,\n\t\tHeader: HdrToAmassHeader(req.Header),\n\t\tBody: body,\n\t\tAuth: ba,\n\t}\n}\n\n// RespToAmassResponse converts a net/http Response to an Amass Response.\nfunc RespToAmassResponse(resp *http.Response) *Response {\n\tvar body string\n\tif resp.Body != nil {\n\t\tif b, err := io.ReadAll(resp.Body); err == nil {\n\t\t\tbody = string(b)\n\t\t}\n\t\t_ = resp.Body.Close()\n\t}\n\n\treturn &Response{\n\t\tStatus: resp.Status,\n\t\tStatusCode: resp.StatusCode,\n\t\tProto: resp.Proto,\n\t\tProtoMajor: resp.ProtoMajor,\n\t\tProtoMinor: resp.ProtoMinor,\n\t\tHeader: HdrToAmassHeader(resp.Header),\n\t\tBody: body,\n\t\tLength: int64(len(body)),\n\t\tTLS: resp.TLS,\n\t}\n}\n\n// CopyCookies copies cookies from one domain to another. Some of our data\n// sources rely on shared auth tokens and this avoids sending extra requests\n// to have the site reissue cookies for the other domains.\nfunc CopyCookies(src string, dest string) {\n\tsrcURL, _ := url.Parse(src)\n\tdestURL, _ := url.Parse(dest)\n\tDefaultClient.Jar.SetCookies(destURL, DefaultClient.Jar.Cookies(srcURL))\n}\n\n// CheckCookie checks if a cookie exists in the cookie jar for a given host\nfunc CheckCookie(urlString string, cookieName string) bool {\n\tcookieURL, _ := url.Parse(urlString)\n\tfound := false\n\tfor _, cookie := range DefaultClient.Jar.Cookies(cookieURL) {\n\t\tif cookie.Name == cookieName {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn found\n}\n\n// RequestWebPage returns the response headers, body, and status code for the provided URL when successful.\nfunc RequestWebPage(ctx context.Context, r *Request) (*Response, error) {\n\tif r == nil {\n\t\treturn nil, errors.New(\"failed to provide a valid Amass HTTP request\")\n\t}\n\n\tif r.Method == \"\" {\n\t\tr.Method = \"GET\"\n\t} else if r.Method != \"GET\" && r.Method != \"POST\" {\n\t\treturn nil, errors.New(\"failed to provide a valid HTTP method\")\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, r.Method, r.URL, strings.NewReader(r.Body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Close = true\n\n\tif r.Auth != nil && r.Auth.Username != \"\" && r.Auth.Password != \"\" {\n\t\treq.SetBasicAuth(r.Auth.Username, r.Auth.Password)\n\t}\n\n\treq.Header.Set(\"User-Agent\", UserAgent)\n\treq.Header.Set(\"Accept\", Accept)\n\treq.Header.Set(\"Accept-Language\", AcceptLang)\n\tfor k, values := range r.Header {\n\t\tfor _, v := range values {\n\t\t\treq.Header.Set(k, v)\n\t\t}\n\t}\n\n\tresp, err := DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RespToAmassResponse(resp), nil\n}\n\n// Crawl will spider the web page at the URL argument looking while staying within the scope provided.\nfunc Crawl(ctx context.Context, u string, scope []string, max int, callback func(*Request, *Response)) error {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"the context expired\")\n\tdefault:\n\t}\n\n\tvar count int\n\tvar m sync.Mutex\n\tfilter := bf.NewDefaultStableBloomFilter(10000, 0.01)\n\tdefer filter.Reset()\n\tattrs := []string{\"action\", \"cite\", \"data\", \"formaction\",\n\t\t\"href\", \"longdesc\", \"poster\", \"src\", \"srcset\", \"xmlns\"}\n\ttags := []string{\"a\", \"area\", \"audio\", \"base\", \"blockquote\", \"button\",\n\t\t\"embed\", \"form\", \"frame\", \"frameset\", \"html\", \"iframe\", \"img\", \"input\",\n\t\t\"ins\", \"link\", \"noframes\", \"object\", \"q\", \"script\", \"source\", \"track\", \"video\"}\n\n\tg := geziyor.NewGeziyor(&geziyor.Options{\n\t\tStartURLs: []string{u},\n\t\tRobotsTxtDisabled: true,\n\t\tUserAgent: UserAgent,\n\t\tLogDisabled: true,\n\t\tConcurrentRequests: 5,\n\t\tRequestDelay: 50 * time.Millisecond,\n\t\tRequestDelayRandomize: true,\n\t\tParseFunc: func(g *geziyor.Geziyor, r *client.Response) {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tprocess := func(n string) {\n\t\t\t\tu, err := r.Request.URL.Parse(n)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif host := u.Hostname(); host == \"\" || whichDomain(host, scope) == \"\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tm.Lock()\n\t\t\t\tif s := u.String(); s != \"\" && !filter.Test([]byte(s)) {\n\t\t\t\t\tcount++\n\t\t\t\t\t// Be sure the crawl has not exceeded the maximum links to be followed\n\t\t\t\t\tif max <= 0 || count < max {\n\t\t\t\t\t\tfilter.Add([]byte(s))\n\t\t\t\t\t\tg.Get(s, g.Opt.ParseFunc)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm.Unlock()\n\t\t\t}\n\t\t\ttag := func(i int, s *goquery.Selection) {\n\t\t\t\tfor _, attr := range attrs {\n\t\t\t\t\tif name, ok := s.Attr(attr); ok {\n\t\t\t\t\t\tprocess(name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, t := range tags {\n\t\t\t\tr.HTMLDoc.Find(t).Each(tag)\n\t\t\t}\n\n\t\t\tcallback(ReqToAmassRequest(r.Request.Request), &Response{\n\t\t\t\tStatus: r.Status,\n\t\t\t\tStatusCode: r.StatusCode,\n\t\t\t\tProto: r.Proto,\n\t\t\t\tProtoMajor: r.ProtoMajor,\n\t\t\t\tProtoMinor: r.ProtoMinor,\n\t\t\t\tHeader: HdrToAmassHeader(r.Header),\n\t\t\t\tBody: string(r.Body),\n\t\t\t\tLength: r.ContentLength,\n\t\t\t\tTLS: r.TLS,\n\t\t\t})\n\t\t},\n\t})\n\tg.Client = client.NewClient(&client.Options{\n\t\tMaxBodySize: 50 * 1024 * 1024, // 50MB\n\t\tRetryTimes: 2,\n\t\tRetryHTTPCodes: []int{408, 500, 502, 503, 504, 522, 524},\n\t})\n\tg.Client.Client = DefaultClient\n\n\tg.Start()\n\treturn nil\n}\n\nfunc whichDomain(name string, scope []string) string {\n\tn := strings.TrimSpace(name)\n\n\tfor _, d := range scope {\n\t\tif strings.HasSuffix(n, d) {\n\t\t\tnlen := len(n)\n\t\t\tdlen := len(d)\n\t\t\t// Check for exact match first to guard against out of bounds index\n\t\t\tif nlen == dlen || n[nlen-dlen-1] == '.' {\n\t\t\t\treturn d\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\n// TLSConn attempts to make a TLS connection with the host on the given port.\nfunc TLSConn(ctx context.Context, host string, port int) (*tls.Conn, error) {\n\t// set the maximum time allowed for making the connection\n\ttCtx, cancel := context.WithTimeout(ctx, handshakeTimeout)\n\tdefer cancel()\n\t// obtain the connection\n\tconn, err := amassnet.DialContext(tCtx, \"tcp\", net.JoinHostPort(host, strconv.Itoa(port)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := tls.Client(conn, &tls.Config{InsecureSkipVerify: true})\n\t// attempt to acquire the certificate chain\n\tif err := c.HandshakeContext(tCtx); err != nil {\n\t\t_ = c.Close()\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\n// CleanName will clean up the names scraped from the web.\nfunc CleanName(name string) string {\n\tclean, err := strconv.Unquote(\"\\\"\" + strings.TrimSpace(name) + \"\\\"\")\n\tif err != nil {\n\t\treturn name\n\t}\n\n\tif re := subRE.FindString(clean); re != \"\" {\n\t\tclean = re\n\t}\n\n\tclean = strings.ToLower(clean)\n\tfor {\n\t\tclean = strings.Trim(clean, \"-.\")\n\n\t\ti := nameStripRE.FindStringIndex(clean)\n\t\tif i == nil {\n\t\t\tbreak\n\t\t}\n\t\tclean = clean[i[1]:]\n\t}\n\treturn clean\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/net/http/http_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage http\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\tamassdns \"github.com/owasp-amass/amass/v5/internal/net/dns\"\n)\n\nfunc TestCopyCookies(t *testing.T) {\n\tu, _ := url.Parse(\"http://owasp.org\")\n\tDefaultClient.Jar.SetCookies(u, []*http.Cookie{{\n\t\tName: \"Test\",\n\t\tValue: \"Cookie\",\n\t}})\n\tCopyCookies(\"http://owasp.org\", \"http://example.com\")\n\n\tu2, _ := url.Parse(\"http://example.com\")\n\tif c := DefaultClient.Jar.Cookies(u2); len(c) == 0 || c[0].Value != \"Cookie\" {\n\t\tt.Error(\"Failed to copy the cookie\")\n\t}\n}\n\nfunc TestCheckCookie(t *testing.T) {\n\ttype args struct {\n\t\turlString string\n\t\tcookieName string\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tinit func()\n\t\targs args\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"basic-success\",\n\t\t\tinit: func() {\n\t\t\t\tsampleURL, err := url.Parse(\"http://owasp.org\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"CheckCookie() parse error: got error = %v\", err)\n\t\t\t\t}\n\n\t\t\t\tcookies := []*http.Cookie{{Name: \"cookie1\", Value: \"sample cookie value\"}}\n\t\t\t\tDefaultClient.Jar.SetCookies(sampleURL, cookies)\n\n\t\t\t},\n\t\t\targs: args{\n\t\t\t\turlString: \"https://owasp.org\",\n\t\t\t\tcookieName: \"cookie1\",\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"basic-failure\",\n\t\t\tinit: func() {},\n\t\t\targs: args{\n\t\t\t\turlString: \"http://domain.local\",\n\t\t\t\tcookieName: \"cookie2\",\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttt.init()\n\t\t\tif got := CheckCookie(tt.args.urlString, tt.args.cookieName); got != tt.want {\n\t\t\t\tt.Errorf(\"CheckCookie() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRequestWebPage(t *testing.T) {\n\tname := \"caffix\"\n\tpass := \"OWASP\"\n\thkey := \"OWASP-Leader\"\n\tpost := \"Test Body\"\n\tsucc := \"Success\"\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif username, password, ok := r.BasicAuth(); !ok || username != name || password != pass {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t_, _ = fmt.Fprint(w, \"Authentication Failed\")\n\t\t\treturn\n\t\t}\n\t\tif val := r.Header.Get(hkey); val != name {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t_, _ = fmt.Fprint(w, \"Header value was missing\")\n\t\t\treturn\n\t\t}\n\t\tif r.Method != http.MethodPost {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t_, _ = fmt.Fprint(w, \"Method was not POST\")\n\t\t\treturn\n\t\t}\n\t\tif in, err := io.ReadAll(r.Body); err != nil || string(in) != post {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t_, _ = fmt.Fprint(w, \"POST body did not match\")\n\t\t\treturn\n\t\t}\n\t\t_, _ = fmt.Fprint(w, succ)\n\t}))\n\tdefer ts.Close()\n\n\tresp, err := RequestWebPage(context.TODO(), &Request{\n\t\tURL: ts.URL,\n\t\tAuth: &BasicAuth{name, pass},\n\t})\n\tif err == nil && (resp.StatusCode == 200 || resp.Body == succ) {\n\t\tt.Error(\"Failed to detect the bad request\")\n\t}\n\n\tresp, err = RequestWebPage(context.TODO(), &Request{\n\t\tURL: ts.URL,\n\t\tMethod: \"POST\",\n\t\tHeader: Header{hkey: []string{name}},\n\t\tBody: post,\n\t\tAuth: &BasicAuth{name, pass},\n\t})\n\tif err != nil || resp.StatusCode != 200 || resp.Body != succ {\n\t\tt.Error(resp.Status + \": \" + resp.Body)\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tcancel()\n\n\tresp, err = RequestWebPage(ctx, &Request{URL: ts.URL})\n\tif err == nil || resp != nil {\n\t\tt.Error(\"Failed to detect the expired context\")\n\t}\n}\n\nfunc TestCrawl(t *testing.T) {\n\tre, err := regexp.Compile(amassdns.AnySubdomainRegexString())\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tdepth int\n\t\twant []string\n\t}{\n\t\t{\n\t\t\tname: \"first page only\",\n\t\t\tdepth: 1,\n\t\t\twant: []string{\"example.com\", \"127.0.0.1\"},\n\t\t},\n\t\t{\n\t\t\tname: \"first and second page\",\n\t\t\tdepth: 2,\n\t\t\twant: []string{\"example.com\", \"127.0.0.1\", \"xml.owasp.org\",\n\t\t\t\t\"www.owasp.org\", \"www.example.com\", \"sub.example.com\", \"www.google.com\"},\n\t\t},\n\t\t{\n\t\t\tname: \"all of the pages\",\n\t\t\tdepth: 0,\n\t\t\twant: []string{\"example.com\", \"127.0.0.1\", \"xml.owasp.org\",\n\t\t\t\t\"www.owasp.org\", \"www.example.com\", \"sub.example.com\",\n\t\t\t\t\"www.google.com\", \"owasp.org\", \"img.owasp.org\",\n\t\t\t\t\"media.owasp.org\", \"static.owasp.org\", \"blogs.oracle.com\"},\n\t\t},\n\t}\n\n\tts := httptest.NewServer(http.FileServer(http.Dir(\"./static\")))\n\tdefer ts.Close()\n\n\tfor _, test := range tests {\n\t\tgot := stringset.New()\n\t\tdefer got.Close()\n\t\tset := stringset.New(test.want...)\n\t\tdefer set.Close()\n\n\t\terr := Crawl(context.Background(), ts.URL, []string{\"127.0.0.1\"}, test.depth, func(req *Request, resp *Response) {\n\t\t\tif u, err := url.Parse(req.URL); err == nil {\n\t\t\t\tgot.Insert(CleanName(u.Hostname()))\n\t\t\t}\n\t\t\tgot.InsertMany(re.FindAllString(resp.Body, -1)...)\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to crawl the static web content: %s: %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tset.Subtract(got)\n\t\tif set.Len() != 0 {\n\t\t\tt.Errorf(\"Test %s with max %d failed to discover the following names: %v\\n\", test.name, test.depth, set.Slice())\n\t\t}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\terr = Crawl(ctx, ts.URL, []string{\"127.0.0.1\"}, 0, func(req *Request, resp *Response) {})\n\tif err != nil && err.Error() != \"the context expired during the crawl of \"+ts.URL {\n\t\tt.Error(\"Failed to catch the expired context during the crawl\")\n\t}\n\n\terr = Crawl(ctx, ts.URL, []string{\"127.0.0.1\"}, 0, func(req *Request, resp *Response) {})\n\tif err != nil && err.Error() != \"the context expired\" {\n\t\tt.Error(\"Failed to catch the expired context before the crawl\")\n\t}\n}\n\nfunc TestCleanName(t *testing.T) {\n\ttests := []struct {\n\t\tdata string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tdata: \"3aowasp.org\",\n\t\t\twant: \"owasp.org\",\n\t\t},\n\t\t{\n\t\t\tdata: \"http://www.owasp.org/index.html\",\n\t\t\twant: \"www.owasp.org\",\n\t\t},\n\t\t{\n\t\t\tdata: \"-Sub.OWASP.org.\",\n\t\t\twant: \"sub.owasp.org\",\n\t\t},\n\t\t{\n\t\t\tdata: \"http://www.owasp.org/index.html\",\n\t\t\twant: \"www.owasp.org\",\n\t\t},\n\t\t{\n\t\t\tdata: \"http://blackhat2018.owasp.org/index.html\",\n\t\t\twant: \"blackhat2018.owasp.org\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tif got := CleanName(test.data); got != test.want {\n\t\t\tt.Errorf(\"Got: %s, Want: %s\", got, test.want)\n\t\t}\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/subs/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage subs\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\tamassdb \"github.com/owasp-amass/amass/v5/internal/db\"\n\tamassnet \"github.com/owasp-amass/amass/v5/internal/net\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n)\n\nconst (\n\tUsageMsg = \"[options]\"\n\tDescription = \"Analyze and present discovered subdomains and associated data\"\n)\n\ntype Args struct {\n\tHelp bool\n\tDomains *stringset.Set\n\tOptions struct {\n\t\tDemoMode bool\n\t\tIPs bool\n\t\tIPv4 bool\n\t\tIPv6 bool\n\t\tASNTableSummary bool\n\t\tDiscoveredNames bool\n\t\tNoColor bool\n\t\tShowAll bool\n\t\tSilent bool\n\t}\n\tFilepaths struct {\n\t\tConfigFile string\n\t\tDirectory string\n\t\tDomains string\n\t\tTermOut string\n\t}\n}\n\ntype outLookup map[string]*amassnet.Output\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"subs\", errorHandling)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.Var(args.Domains, \"d\", \"Domain names separated by commas (can be used multiple times)\")\n\tfs.BoolVar(&args.Options.DemoMode, \"demo\", false, \"Censor output to make it suitable for demonstrations\")\n\tfs.BoolVar(&args.Options.IPs, \"ip\", false, \"Show the IP addresses for discovered names\")\n\tfs.BoolVar(&args.Options.IPv4, \"ipv4\", false, \"Show the IPv4 addresses for discovered names\")\n\tfs.BoolVar(&args.Options.IPv6, \"ipv6\", false, \"Show the IPv6 addresses for discovered names\")\n\tfs.BoolVar(&args.Options.ASNTableSummary, \"summary\", false, \"Print Just ASN Table Summary\")\n\tfs.BoolVar(&args.Options.DiscoveredNames, \"names\", false, \"Print Just Discovered Names\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.ShowAll, \"show\", false, \"Print the results for the enumeration index + domains provided\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\tfs.StringVar(&args.Filepaths.ConfigFile, \"config\", \"\", \"Path to the YAML configuration file. Additional details below\")\n\tfs.StringVar(&args.Filepaths.Directory, \"dir\", \"\", \"Path to the directory containing the graph database\")\n\tfs.StringVar(&args.Filepaths.Domains, \"df\", \"\", \"Path to a file providing root domain names\")\n\tfs.StringVar(&args.Filepaths.TermOut, \"o\", \"\", \"Path to the text file containing terminal stdout/stderr\")\n\treturn fs\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\tvar args Args\n\targs.Domains = stringset.New()\n\tdefer args.Domains.Close()\n\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\tsubsBuf := new(bytes.Buffer)\n\tfs.SetOutput(subsBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, subsBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := fs.Parse(clArgs); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\tif args.Options.IPs {\n\t\targs.Options.IPv4 = true\n\t\targs.Options.IPv6 = true\n\t}\n\tif args.Filepaths.Domains != \"\" {\n\t\tlist, err := config.GetListFromFile(args.Filepaths.Domains)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to parse the domain names file: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t\targs.Domains.InsertMany(list...)\n\t}\n\n\tcfg := config.NewConfig()\n\t// Check if a configuration file was provided, and if so, load the settings\n\tif err := config.AcquireConfig(args.Filepaths.Directory, args.Filepaths.ConfigFile, cfg); err == nil {\n\t\tif args.Filepaths.Directory == \"\" {\n\t\t\targs.Filepaths.Directory = cfg.Dir\n\t\t}\n\t\tif args.Domains.Len() == 0 {\n\t\t\targs.Domains.InsertMany(cfg.Domains()...)\n\t\t}\n\t} else if args.Filepaths.ConfigFile != \"\" {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to load the configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdb := tools.OpenGraphDatabase(cfg)\n\tif db == nil {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Failed to connect with the database\")\n\t\tos.Exit(1)\n\t}\n\n\tif args.Options.ShowAll {\n\t\targs.Options.DiscoveredNames = true\n\t\targs.Options.ASNTableSummary = true\n\t}\n\tif !args.Options.DiscoveredNames && !args.Options.ASNTableSummary {\n\t\tusage()\n\t\treturn\n\t}\n\n\tvar asninfo bool\n\tif args.Options.ASNTableSummary {\n\t\tasninfo = true\n\t}\n\n\tshowData(&args, asninfo, db)\n}\n\nfunc showData(args *Args, asninfo bool, db repository.Repository) {\n\tvar total int\n\tvar err error\n\tvar outfile *os.File\n\tdomains := args.Domains.Slice()\n\n\tif args.Filepaths.TermOut != \"\" {\n\t\toutfile, err = os.OpenFile(args.Filepaths.TermOut, os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to open the text output file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer func() {\n\t\t\t_ = outfile.Sync()\n\t\t\t_ = outfile.Close()\n\t\t}()\n\t\t_ = outfile.Truncate(0)\n\t\t_, _ = outfile.Seek(0, 0)\n\t}\n\n\tvar cache *amassnet.ASNCache\n\tif asninfo {\n\t\tcache = amassnet.NewASNCache()\n\t\tif err := amassnet.FillCache(cache, db); err != nil {\n\t\t\t_, _ = afmt.R.Printf(\"Failed to populate the ASN cache: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tnames := getNames(context.Background(), domains, asninfo, db)\n\tif len(names) != 0 && (asninfo || args.Options.IPv4 || args.Options.IPv6) {\n\t\tnames = addAddresses(context.Background(), db, names, asninfo, cache)\n\t}\n\n\tasns := make(map[int]*amassnet.ASNSummaryData)\n\tfor _, out := range names {\n\t\tif len(domains) > 0 && !domainNameInScope(out.Name, domains) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif args.Options.IPv4 || args.Options.IPv6 {\n\t\t\tout.Addresses = afmt.DesiredAddrTypes(out.Addresses, args.Options.IPv4, args.Options.IPv6)\n\t\t}\n\n\t\tif l := len(out.Addresses); (args.Options.IPv4 || args.Options.IPv6) && l == 0 {\n\t\t\tcontinue\n\t\t} else if l > 0 {\n\t\t\tafmt.UpdateSummaryData(out, asns)\n\t\t}\n\n\t\ttotal++\n\t\tname, ips := afmt.OutputLineParts(out, args.Options.IPv4 || args.Options.IPv6, args.Options.DemoMode)\n\t\tif ips != \"\" {\n\t\t\tips = \" \" + ips\n\t\t}\n\n\t\tif args.Options.DiscoveredNames {\n\t\t\tvar written bool\n\t\t\tif outfile != nil {\n\t\t\t\t_, _ = fmt.Fprintf(outfile, \"%s%s\\n\", name, ips)\n\t\t\t\twritten = true\n\t\t\t}\n\t\t\tif !written {\n\t\t\t\t_, _ = fmt.Fprintf(color.Output, \"%s%s\\n\", afmt.Green(name), afmt.Yellow(ips))\n\t\t\t}\n\t\t}\n\t}\n\n\tif total == 0 {\n\t\t_, _ = afmt.R.Println(\"No names were discovered\")\n\t\treturn\n\t}\n\tif args.Options.ASNTableSummary {\n\t\tvar out io.Writer\n\t\tstatus := color.NoColor\n\n\t\tif outfile != nil {\n\t\t\tout = outfile\n\t\t\tcolor.NoColor = true\n\t\t} else if args.Options.ShowAll {\n\t\t\tout = color.Error\n\t\t} else {\n\t\t\tout = color.Output\n\t\t}\n\n\t\tafmt.FprintEnumerationSummary(out, total, asns, args.Options.DemoMode)\n\t\tcolor.NoColor = status\n\t}\n}\n\nfunc getNames(ctx context.Context, domains []string, asninfo bool, db repository.Repository) []*amassnet.Output {\n\tif len(domains) == 0 {\n\t\treturn nil\n\t}\n\n\tqtime := time.Time{}\n\tfilter := stringset.New()\n\tdefer filter.Close()\n\n\tvar assets []*dbt.Entity\n\tfor _, d := range domains {\n\t\tif ents, err := db.FindEntitiesByContent(&oamdns.FQDN{Name: d}, qtime); err == nil && len(ents) == 1 {\n\t\t\tif n, err := amassdb.FindByFQDNScope(db, ents[0], qtime); err == nil && len(n) > 0 {\n\t\t\t\tassets = append(assets, n...)\n\t\t\t}\n\t\t}\n\t}\n\tif len(assets) == 0 {\n\t\treturn nil\n\t}\n\n\tvar names []*amassnet.Output\n\tfor _, a := range assets {\n\t\tif n, ok := a.Asset.(*oamdns.FQDN); ok && !filter.Has(n.Name) {\n\t\t\tnames = append(names, &amassnet.Output{Name: n.Name})\n\t\t\tfilter.Insert(n.Name)\n\t\t}\n\t}\n\treturn names\n}\n\nfunc addAddresses(ctx context.Context, db repository.Repository, names []*amassnet.Output, asninfo bool, cache *amassnet.ASNCache) []*amassnet.Output {\n\tvar namestrs []string\n\tlookup := make(outLookup, len(names))\n\tfor _, n := range names {\n\t\tlookup[n.Name] = n\n\t\tnamestrs = append(namestrs, n.Name)\n\t}\n\n\tqtime := time.Time{}\n\tif pairs, err := amassnet.NamesToAddrs(db, qtime, namestrs...); err == nil {\n\t\tfor _, p := range pairs {\n\t\t\taddr := p.Addr.Address.String()\n\n\t\t\tif p.FQDN.Name == \"\" || addr == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif o, found := lookup[p.FQDN.Name]; found {\n\t\t\t\to.Addresses = append(o.Addresses, amassnet.AddressInfo{Address: net.ParseIP(addr)})\n\t\t\t}\n\t\t}\n\t}\n\n\tif !asninfo || cache == nil {\n\t\tvar output []*amassnet.Output\n\t\tfor _, o := range lookup {\n\t\t\tif len(o.Addresses) > 0 {\n\t\t\t\toutput = append(output, o)\n\t\t\t}\n\t\t}\n\t\treturn output\n\t}\n\treturn addInfrastructureInfo(lookup, cache)\n}\n\nfunc domainNameInScope(name string, scope []string) bool {\n\tvar discovered bool\n\n\tn := strings.ToLower(strings.TrimSpace(name))\n\tfor _, d := range scope {\n\t\td = strings.ToLower(d)\n\n\t\tif n == d || strings.HasSuffix(n, \".\"+d) {\n\t\t\tdiscovered = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn discovered\n}\n\nfunc addInfrastructureInfo(lookup outLookup, cache *amassnet.ASNCache) []*amassnet.Output {\n\toutput := make([]*amassnet.Output, 0, len(lookup))\n\n\tfor _, o := range lookup {\n\t\tvar newaddrs []amassnet.AddressInfo\n\n\t\tfor _, a := range o.Addresses {\n\t\t\ti := cache.AddrSearch(a.Address.String())\n\t\t\tif i == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, netblock, _ := net.ParseCIDR(i.Prefix)\n\t\t\tnewaddrs = append(newaddrs, amassnet.AddressInfo{\n\t\t\t\tAddress: a.Address,\n\t\t\t\tASN: i.ASN,\n\t\t\t\tCIDRStr: i.Prefix,\n\t\t\t\tNetblock: netblock,\n\t\t\t\tDescription: i.Description,\n\t\t\t})\n\t\t}\n\n\t\to.Addresses = newaddrs\n\t\tif len(o.Addresses) > 0 {\n\t\t\toutput = append(output, o)\n\t\t}\n\t}\n\treturn output\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/tools/file.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage tools\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/resources\"\n)\n\nfunc CreateOutputDirectory(dirpath string) error {\n\t// Prepare output file paths\n\tdir := config.OutputDirectory(dirpath)\n\tif dir == \"\" {\n\t\treturn errors.New(\"failed to obtain the path for the output directory\")\n\t}\n\t// If the directory does not yet exist, create it\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"mkdir failed for %s: %v\", dir, err)\n\t}\n\t// ensure that the permissions are set correctly\n\tif err := os.Chmod(dir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to set permissions to 0755 for %s: %v\", dir, err)\n\t}\n\treturn nil\n}\n\nfunc CreateDefaultConfigFiles(dirpath string) error {\n\tfor _, filename := range resources.DefaultFilesList {\n\t\tfilepath := filepath.Join(dirpath, filename)\n\t\tif _, err := os.Stat(filepath); !os.IsNotExist(err) {\n\t\t\t// If the file already exists, skip creating it\n\t\t\tcontinue\n\t\t}\n\n\t\tfile, err := resources.GetResourceFile(filename)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to obtain the embedded file %s: %v\", filename, err)\n\t\t}\n\t\tdefer func() { _ = file.Close() }()\n\n\t\t// Create the default config file in the specified directory\n\t\toutFile, err := os.Create(filepath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create the output file %s: %v\", filepath, err)\n\t\t}\n\t\tdefer func() { _ = outFile.Close() }()\n\n\t\tif _, err := io.Copy(outFile, file); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to copy the file %s: %v\", filepath, err)\n\t\t}\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/tools/graph.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage tools\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\n\t\"github.com/owasp-amass/amass/v5/config\"\n\tassetdb \"github.com/owasp-amass/asset-db\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\t\"github.com/owasp-amass/asset-db/repository/neo4j\"\n\t\"github.com/owasp-amass/asset-db/repository/sqlrepo\"\n)\n\nfunc OpenGraphDatabase(cfg *config.Config) repository.Repository {\n\t// Add the local database settings to the configuration\n\tcfg.GraphDBs = append(cfg.GraphDBs, cfg.LocalDatabaseSettings(cfg.GraphDBs))\n\n\tfor _, db := range cfg.GraphDBs {\n\t\tif db.Primary {\n\t\t\tvar dbase repository.Repository\n\n\t\t\tswitch db.System {\n\t\t\tcase \"local\":\n\t\t\t\tpath := filepath.Join(config.OutputDirectory(cfg.Dir), \"assetdb.db\")\n\t\t\t\tpath += \"?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)\"\n\t\t\t\tdbase = NewGraph(db.System, path, db.Options)\n\t\t\tcase \"postgres\":\n\t\t\t\tconnStr := fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s\", db.Host, db.Port, db.Username, db.Password, db.DBName)\n\t\t\t\tdbase = NewGraph(db.System, connStr, db.Options)\n\t\t\tdefault:\n\t\t\t\tdbase = NewGraph(db.System, db.URL, db.Options)\n\t\t\t}\n\n\t\t\tif dbase != nil {\n\t\t\t\treturn dbase\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn NewGraph(\"memory\", \"\", \"\")\n}\n\nfunc NewGraph(system, path string, options string) repository.Repository {\n\tvar dsn string\n\tvar dbtype string\n\n\tswitch system {\n\tcase \"memory\":\n\t\tdbtype = sqlrepo.SQLiteMemory\n\tcase \"local\":\n\t\tdbtype = sqlrepo.SQLite\n\t\tdsn = path\n\tcase \"postgres\":\n\t\tdbtype = sqlrepo.Postgres\n\t\tdsn = path\n\tcase \"bolt\":\n\t\tdbtype = neo4j.Neo4j\n\t\tdsn = path\n\tdefault:\n\t\treturn nil\n\t}\n\n\tif store, err := assetdb.New(dbtype, dsn); err == nil {\n\t\treturn store\n\t}\n\treturn nil\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/tools/log.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage tools\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\tafmt \"github.com/owasp-amass/amass/v5/internal/afmt\"\n\tslogcommon \"github.com/samber/slog-common\"\n\tslogsyslog \"github.com/samber/slog-syslog/v2\"\n)\n\nfunc WriteLogMessage(l *slog.Logger, message string) {\n\tlogstr := channelJSONLog(message)\n\tif logstr == \"\" {\n\t\treturn\n\t}\n\n\trecord, err := afmt.JSONLogToRecord(logstr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tctx := context.Background()\n\tif l.Handler().Enabled(ctx, record.Level) {\n\t\t_ = l.Handler().Handle(ctx, record)\n\t}\n}\n\nfunc channelJSONLog(data string) string {\n\tj := make(map[string]interface{})\n\tif err := json.Unmarshal([]byte(data), &j); err != nil {\n\t\treturn \"\"\n\t}\n\n\tvar logstr string\n\t// check that this is a log message sent over the sub channel\n\tif p, found := j[\"payload\"]; !found {\n\t\treturn \"\"\n\t} else if pmap, ok := p.(map[string]interface{}); !ok {\n\t\treturn \"\"\n\t} else if d, found := pmap[\"data\"]; !found {\n\t\treturn \"\"\n\t} else if dmap, ok := d.(map[string]interface{}); !ok {\n\t\treturn \"\"\n\t} else if lm, found := dmap[\"logMessages\"]; !found {\n\t\treturn \"\"\n\t} else if lmstr, ok := lm.(string); ok {\n\t\tlogstr = lmstr\n\t}\n\treturn logstr\n}\n\nfunc NewFileLogger(dir, logfile string) (*slog.Logger, error) {\n\tif logfile == \"\" {\n\t\treturn nil, fmt.Errorf(\"no log file specified\")\n\t}\n\n\tif dir != \"\" {\n\t\tif err := os.MkdirAll(dir, 0640); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create the log directory: %v\", err)\n\t\t}\n\t}\n\n\tf, err := os.OpenFile(filepath.Join(dir, logfile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open the log file: %v\", err)\n\t}\n\n\treturn slog.New(slog.NewJSONHandler(f, nil)), nil\n}\n\nfunc NewSyslogLogger() (*slog.Logger, error) {\n\tport := os.Getenv(\"SYSLOG_PORT\")\n\thost := strings.ToLower(os.Getenv(\"SYSLOG_HOST\"))\n\ttransport := strings.ToLower(os.Getenv(\"SYSLOG_TRANSPORT\"))\n\n\tif host == \"\" {\n\t\treturn nil, fmt.Errorf(\"no syslog host specified\")\n\t}\n\tif port == \"\" {\n\t\tport = \"514\"\n\t}\n\tif transport == \"\" {\n\t\ttransport = \"udp\"\n\t}\n\n\twriter, err := net.Dial(transport, net.JoinHostPort(host, port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create the connection to the log server: %v\", err)\n\t}\n\n\treturn slog.New(slogsyslog.Option{\n\t\tLevel: slog.LevelInfo,\n\t\tConverter: syslogConverter,\n\t\tWriter: writer,\n\t}.NewSyslogHandler()), nil\n}\n\nfunc syslogConverter(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) map[string]any {\n\tattrs := slogcommon.AppendRecordAttrsToAttrs(loggerAttr, groups, record)\n\tattrs = slogcommon.ReplaceAttrs(replaceAttr, []string{}, attrs...)\n\n\treturn map[string]any{\n\t\t\"level\": record.Level.String(),\n\t\t\"message\": record.Message,\n\t\t\"attrs\": slogcommon.AttrsToMap(attrs...),\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/track/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage track\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\tamassdb \"github.com/owasp-amass/amass/v5/internal/db\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\tdbt \"github.com/owasp-amass/asset-db/types\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n)\n\nconst (\n\tTimeFormat = \"01/02 15:04:05 2006 MST\"\n\tUsageMsg = \"[options] [-since '\" + TimeFormat + \"'] \" + \"-d domain\"\n\tDescription = \"Analyze OAM data to identify newly discovered assets\"\n)\n\ntype Args struct {\n\tHelp bool\n\tDomains *stringset.Set\n\tSince string\n\tOptions struct {\n\t\tNoColor bool\n\t\tSilent bool\n\t}\n\tFilepaths struct {\n\t\tConfigFile string\n\t\tDirectory string\n\t\tDomains string\n\t}\n}\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"track\", flag.ContinueOnError)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.Var(args.Domains, \"d\", \"Domain names separated by commas (can be used multiple times)\")\n\tfs.StringVar(&args.Since, \"since\", \"\", \"Exclude all assets discovered before (format: \"+TimeFormat+\")\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\tfs.StringVar(&args.Filepaths.ConfigFile, \"config\", \"\", \"Path to the YAML configuration file\")\n\tfs.StringVar(&args.Filepaths.Directory, \"dir\", \"\", \"Path to the directory containing the graph database\")\n\tfs.StringVar(&args.Filepaths.Domains, \"df\", \"\", \"Path to a file providing registered domain names\")\n\treturn fs\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\tvar args Args\n\targs.Domains = stringset.New()\n\tdefer args.Domains.Close()\n\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\ttrackBuf := new(bytes.Buffer)\n\tfs.SetOutput(trackBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, trackBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := fs.Parse(clArgs); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\tif args.Filepaths.Domains != \"\" {\n\t\tlist, err := config.GetListFromFile(args.Filepaths.Domains)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to parse the domain names file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\targs.Domains.InsertMany(list...)\n\t}\n\tif args.Domains.Len() == 0 {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"No root domain names were provided\")\n\t\tos.Exit(1)\n\t}\n\n\tvar err error\n\tvar start time.Time\n\tif args.Since != \"\" {\n\t\tstart, err = time.Parse(TimeFormat, args.Since)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"%s is not in the correct format: %s\\n\", args.Since, TimeFormat)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tcfg := config.NewConfig()\n\t// Check if a configuration file was provided, and if so, load the settings\n\tif err := config.AcquireConfig(args.Filepaths.Directory, args.Filepaths.ConfigFile, cfg); err == nil {\n\t\tif args.Filepaths.Directory == \"\" {\n\t\t\targs.Filepaths.Directory = cfg.Dir\n\t\t}\n\t\tif args.Domains.Len() == 0 {\n\t\t\targs.Domains.InsertMany(cfg.Domains()...)\n\t\t}\n\t} else if args.Filepaths.ConfigFile != \"\" {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to load the configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Connect with the graph database containing the enumeration data\n\tdb := tools.OpenGraphDatabase(cfg)\n\tif db == nil {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Failed to connect with the database\")\n\t\tos.Exit(1)\n\t}\n\n\tfor _, name := range getNewNames(args.Domains.Slice(), start, db) {\n\t\t_, _ = afmt.G.Fprintln(color.Output, name)\n\t}\n}\n\nfunc getNewNames(domains []string, since time.Time, db repository.Repository) []string {\n\tif len(domains) == 0 {\n\t\treturn []string{}\n\t}\n\n\tvar assets []*dbt.Entity\n\tfor _, d := range domains {\n\t\tif ents, err := db.FindEntitiesByContent(&oamdns.FQDN{Name: d}, since); err == nil && len(ents) == 1 {\n\t\t\tif n, err := amassdb.FindByFQDNScope(db, ents[0], since); err == nil && len(n) > 0 {\n\t\t\t\tassets = append(assets, n...)\n\t\t\t}\n\t\t}\n\t}\n\tif len(assets) == 0 {\n\t\treturn []string{}\n\t}\n\n\tif since.IsZero() {\n\t\tvar latest time.Time\n\n\t\tfor _, a := range assets {\n\t\t\tif _, ok := a.Asset.(*oamdns.FQDN); ok && a.LastSeen.After(latest) {\n\t\t\t\tlatest = a.LastSeen\n\t\t\t}\n\t\t}\n\n\t\tsince = latest.Truncate(24 * time.Hour)\n\t}\n\n\tres := stringset.New()\n\tdefer res.Close()\n\n\tfor _, a := range assets {\n\t\tif n, ok := a.Asset.(*oamdns.FQDN); ok && !res.Has(n.Name) &&\n\t\t\t(a.CreatedAt.Equal(since) || a.CreatedAt.After(since)) &&\n\t\t\t(a.LastSeen.Equal(since) || a.LastSeen.After(since)) {\n\t\t\tres.Insert(n.Name)\n\t\t}\n\t}\n\n\treturn res.Slice()\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/cli.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/caffix/stringset\"\n\t\"github.com/fatih/color\"\n\t\"github.com/owasp-amass/amass/v5/config\"\n\t\"github.com/owasp-amass/amass/v5/internal/afmt\"\n\t\"github.com/owasp-amass/amass/v5/internal/tools\"\n)\n\nconst (\n\tTimeFormat string = \"01/02 15:04:05 2006 MST\"\n\tUsageMsg string = \"-d3|-dot|-gexf [options] -d domain\"\n\tDescription string = \"Analyze OAM data to generate graph visualizations\"\n)\n\ntype Args struct {\n\tHelp bool\n\tDomains *stringset.Set\n\tSince string\n\tOptions struct {\n\t\tD3 bool\n\t\tDOT bool\n\t\tGEXF bool\n\t\tNoColor bool\n\t\tSilent bool\n\t}\n\tFilepaths struct {\n\t\tConfigFile string\n\t\tDirectory string\n\t\tDomains string\n\t\tOutput string\n\t\tAllFilePrefix string\n\t}\n}\n\nfunc NewFlagset(args *Args, errorHandling flag.ErrorHandling) *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"viz\", errorHandling)\n\n\tfs.BoolVar(&args.Help, \"h\", false, \"Show the program usage message\")\n\tfs.BoolVar(&args.Help, \"help\", false, \"Show the program usage message\")\n\tfs.Var(args.Domains, \"d\", \"Domain names separated by commas (can be used multiple times)\")\n\tfs.StringVar(&args.Since, \"since\", \"\", \"Include only assets validated after (format: \"+TimeFormat+\")\")\n\tfs.StringVar(&args.Filepaths.ConfigFile, \"config\", \"\", \"Path to the YAML configuration file\")\n\tfs.StringVar(&args.Filepaths.Directory, \"dir\", \"\", \"Path to the directory containing the graph database\")\n\tfs.StringVar(&args.Filepaths.Domains, \"df\", \"\", \"Path to a file providing registered domain names\")\n\tfs.StringVar(&args.Filepaths.Output, \"o\", \"\", \"Path to the directory for output files being generated\")\n\tfs.StringVar(&args.Filepaths.AllFilePrefix, \"oA\", \"\", \"Path prefix used for naming all output files\")\n\tfs.BoolVar(&args.Options.D3, \"d3\", false, \"Generate the D3 v4 force simulation HTML file\")\n\tfs.BoolVar(&args.Options.DOT, \"dot\", false, \"Generate the DOT output file\")\n\tfs.BoolVar(&args.Options.GEXF, \"gexf\", false, \"Generate the Gephi Graph Exchange XML Format (GEXF) file\")\n\tfs.BoolVar(&args.Options.NoColor, \"nocolor\", false, \"Disable colorized output\")\n\tfs.BoolVar(&args.Options.Silent, \"silent\", false, \"Disable all output during execution\")\n\treturn fs\n}\n\nfunc CLIWorkflow(cmdName string, clArgs []string) {\n\tvar args Args\n\targs.Domains = stringset.New()\n\tdefer args.Domains.Close()\n\n\tfs := NewFlagset(&args, flag.ContinueOnError)\n\tvizBuf := new(bytes.Buffer)\n\tfs.SetOutput(vizBuf)\n\n\tvar usage = func() {\n\t\tafmt.PrintBanner()\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"Usage: %s %s\\n\\n\", cmdName, UsageMsg)\n\n\t\tif args.Help {\n\t\t\tfs.PrintDefaults()\n\t\t\t_, _ = afmt.G.Fprintln(color.Error, vizBuf.String())\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = afmt.G.Fprintln(color.Error, \"Use the -h or --help flag to see the flags and default values\")\n\t\t_, _ = afmt.G.Fprintf(color.Error, \"\\nThe Amass Discord server can be found here: %s\\n\\n\", afmt.DiscordInvitation)\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tusage()\n\t\treturn\n\t}\n\tif err := fs.Parse(clArgs); err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tif args.Help {\n\t\tusage()\n\t\treturn\n\t}\n\tif args.Options.NoColor {\n\t\tcolor.NoColor = true\n\t}\n\tif args.Options.Silent {\n\t\tcolor.Output = io.Discard\n\t\tcolor.Error = io.Discard\n\t}\n\tif args.Filepaths.Domains != \"\" {\n\t\tlist, err := config.GetListFromFile(args.Filepaths.Domains)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to parse the domain names file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\targs.Domains.InsertMany(list...)\n\t}\n\tif args.Domains.Len() == 0 {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"No root domain names were provided\")\n\t\tos.Exit(1)\n\t}\n\t// Make sure at least one graph file format has been identified on the command-line\n\tif !args.Options.D3 && !args.Options.DOT && !args.Options.GEXF {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"At least one file format must be selected\")\n\t\tos.Exit(1)\n\t}\n\n\tvar err error\n\tvar start time.Time\n\tif args.Since != \"\" {\n\t\tstart, err = time.Parse(TimeFormat, args.Since)\n\t\tif err != nil {\n\t\t\t_, _ = afmt.R.Fprintf(color.Error, \"%s is not in the correct format: %s\\n\", args.Since, TimeFormat)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tcfg := config.NewConfig()\n\t// Check if a configuration file was provided, and if so, load the settings\n\tif err := config.AcquireConfig(args.Filepaths.Directory, args.Filepaths.ConfigFile, cfg); err == nil {\n\t\tif args.Filepaths.Directory == \"\" {\n\t\t\targs.Filepaths.Directory = cfg.Dir\n\t\t}\n\t\tif args.Domains.Len() == 0 {\n\t\t\targs.Domains.InsertMany(cfg.Domains()...)\n\t\t}\n\t} else if args.Filepaths.ConfigFile != \"\" {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to load the configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t// Connect with the graph database containing the enumeration data\n\tdb := tools.OpenGraphDatabase(cfg)\n\tif db == nil {\n\t\t_, _ = afmt.R.Fprintln(color.Error, \"Failed to connect with the database\")\n\t\tos.Exit(1)\n\t}\n\t// Obtain the visualization nodes & edges from the graph\n\tnodes, edges := VizData(args.Domains.Slice(), start, db)\n\t// Get the directory to save the files into\n\tdir := args.Filepaths.Directory\n\tif pwd, err := os.Getwd(); err == nil {\n\t\tdir = pwd\n\t}\n\n\t// Set output file prefix, use 'amass' if '-oA' flag is not specified\n\tprefix := args.Filepaths.AllFilePrefix\n\tif prefix == \"\" {\n\t\tprefix = \"amass\"\n\t}\n\n\tif args.Filepaths.Output != \"\" {\n\t\tif finfo, err := os.Stat(args.Filepaths.Output); os.IsNotExist(err) || !finfo.IsDir() {\n\t\t\t_, _ = afmt.R.Fprintln(color.Error, \"The output location does not exist or is not a directory\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdir = args.Filepaths.Output\n\t}\n\tif args.Options.D3 {\n\t\tpath := filepath.Join(dir, prefix+\".html\")\n\t\terr = writeGraphOutputFile(\"d3\", path, nodes, edges)\n\t}\n\tif args.Options.DOT {\n\t\tpath := filepath.Join(dir, prefix+\".dot\")\n\t\terr = writeGraphOutputFile(\"dot\", path, nodes, edges)\n\t}\n\tif args.Options.GEXF {\n\t\tpath := filepath.Join(dir, prefix+\".gexf\")\n\t\terr = writeGraphOutputFile(\"gexf\", path, nodes, edges)\n\t}\n\tif err != nil {\n\t\t_, _ = afmt.R.Fprintf(color.Error, \"Failed to write the output file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc writeGraphOutputFile(t string, path string, nodes []Node, edges []Edge) error {\n\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = f.Sync()\n\t\t_ = f.Close()\n\t}()\n\n\t_ = f.Truncate(0)\n\t_, _ = f.Seek(0, 0)\n\n\tswitch t {\n\tcase \"d3\":\n\t\terr = WriteD3Data(f, nodes, edges)\n\tcase \"dot\":\n\t\terr = WriteDOTData(f, nodes, edges)\n\tcase \"gexf\":\n\t\terr = WriteGEXFData(f, nodes, edges)\n\t}\n\treturn err\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/d3.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"strings\"\n\t\"text/template\"\n\n\toam \"github.com/owasp-amass/open-asset-model\"\n)\n\nconst d3Template = `\n\n\n\n \n OWASP Amass Network Mapping\n \n \n\n\n
\n
\n\n\n\n\n`\n\ntype d3Edge struct {\n\tSource int\n\tDestination int\n\tLabel string\n}\n\ntype d3Node struct {\n\tID int\n\tNum int\n\tLabel string\n\tColor string\n}\n\ntype d3Graph struct {\n\tName string\n\tMaxNum int\n\tNodes []d3Node\n\tEdges []d3Edge\n}\n\n// WriteD3Data generates a HTML file that displays the Amass graph using D3.\nfunc WriteD3Data(output io.Writer, nodes []Node, edges []Edge) error {\n\tcolors := map[string]string{\n\t\tstring(oam.Account): \"chocolate\",\n\t\tstring(oam.AutnumRecord): \"yellow\",\n\t\tstring(oam.AutonomousSystem): \"blue\",\n\t\tstring(oam.ContactRecord): \"cornsilk\",\n\t\tstring(oam.DomainRecord): \"yellow\",\n\t\tstring(oam.File): \"azure\",\n\t\tstring(oam.FQDN): \"green\",\n\t\tstring(oam.FundsTransfer): \"red\",\n\t\tstring(oam.Identifier): \"chocolate\",\n\t\tstring(oam.IPAddress): \"orange\",\n\t\tstring(oam.IPNetRecord): \"yellow\",\n\t\tstring(oam.Location): \"darkgray\",\n\t\tstring(oam.Netblock): \"pink\",\n\t\tstring(oam.Organization): \"aqua\",\n\t\tstring(oam.Person): \"bisque\",\n\t\tstring(oam.Phone): \"coral\",\n\t\tstring(oam.Product): \"darkslategrey\",\n\t\tstring(oam.ProductRelease): \"darkslategrey\",\n\t\tstring(oam.Service): \"darkslategrey\",\n\t\tstring(oam.TLSCertificate): \"deeppink\",\n\t\tstring(oam.URL): \"azure\",\n\t}\n\n\tgraph := &d3Graph{Name: \"OWASP Amass - Attack Surface Mapping\"}\n\n\tfor idx, node := range nodes {\n\t\tif label, err := json.Marshal(node.Title); err == nil {\n\t\t\tgraph.Nodes = append(graph.Nodes, d3Node{\n\t\t\t\tID: idx,\n\t\t\t\tLabel: strings.Trim(string(label), \"\\\"\"),\n\t\t\t\tColor: colors[node.Type],\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, edge := range edges {\n\t\tgraph.Edges = append(graph.Edges, d3Edge{\n\t\t\tSource: edge.From,\n\t\t\tDestination: edge.To,\n\t\t\tLabel: edge.Title,\n\t\t})\n\t\tgraph.Nodes[edge.From].Num++\n\t\tgraph.Nodes[edge.To].Num++\n\t}\n\n\tfor _, node := range graph.Nodes {\n\t\tif node.Num > graph.MaxNum {\n\t\t\tgraph.MaxNum = node.Num\n\t\t}\n\t}\n\n\tt := template.Must(template.New(\"graph\").Parse(d3Template))\n\treturn t.Execute(output, graph)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/dot.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"io\"\n\t\"strconv\"\n\t\"text/template\"\n)\n\nconst dotTemplate = `\ndigraph \"{{ .Name }}\" {\n\tsize = \"7.5,10\"; ranksep=\"2.5 equally\"; ratio=auto;\n\n{{ range .Nodes }}\n node [label=\"{{ .Label }}\",color=\"{{ .Color }}\",type=\"{{ .Type }}\"]; n{{ .ID }};\n{{ end }}\n\n{{ range .Edges }}\n n{{ .Source }} -> n{{ .Destination }} [label=\"{{ .Label }}\"];\n{{ end }}\n}\n`\n\ntype dotEdge struct {\n\tSource string\n\tDestination string\n\tLabel string\n}\n\ntype dotNode struct {\n\tID string\n\tLabel string\n\tColor string\n\tType string\n}\n\ntype dotGraph struct {\n\tName string\n\tNodes []dotNode\n\tEdges []dotEdge\n}\n\n// WriteDOTData generates a DOT file to display the Amass graph.\nfunc WriteDOTData(output io.Writer, nodes []Node, edges []Edge) error {\n\t// TODO: Add more OAM types and colors\n\tcolors := map[string]string{\n\t\t\"FQDN\": \"green\",\n\t\t\"domain\": \"red\",\n\t\t\"IPAddress\": \"orange\",\n\t\t\"RIROrg\": \"cyan\",\n\t\t\"Netblock\": \"pink\",\n\t\t\"ASN\": \"blue\",\n\t}\n\n\tgraph := &dotGraph{Name: \"OWASP Amass Network Mapping\"}\n\n\tfor idx, node := range nodes {\n\t\tgraph.Nodes = append(graph.Nodes, dotNode{\n\t\t\tID: strconv.Itoa(idx + 1),\n\t\t\tLabel: node.Label,\n\t\t\tColor: colors[node.Type],\n\t\t\tType: node.Type,\n\t\t})\n\t}\n\n\tfor _, edge := range edges {\n\t\tgraph.Edges = append(graph.Edges, dotEdge{\n\t\t\tSource: strconv.Itoa(edge.From + 1),\n\t\t\tDestination: strconv.Itoa(edge.To + 1),\n\t\t\tLabel: edge.Title,\n\t\t})\n\t}\n\n\tt := template.Must(template.New(\"graph\").Parse(dotTemplate))\n\treturn t.Execute(output, graph)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/dot_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestWriteDOTDataHappyPath(t *testing.T) {\n\tbuf := bytes.NewBufferString(\"\")\n\terr := WriteDOTData(buf, testNodes(), testEdges())\n\tassert.Nil(t, err)\n\n\toutput := buf.String()\n\tassert.Contains(t, output, \"digraph \\\"OWASP Amass Network Mapping\\\"\")\n\tassert.Equal(t, expectedDotOutput, output, \"Expected output to match\")\n}\n\nconst expectedDotOutput = `\ndigraph \"OWASP Amass Network Mapping\" {\n\tsize = \"7.5,10\"; ranksep=\"2.5 equally\"; ratio=auto;\n\n\n node [label=\"owasp.org\",color=\"green\",type=\"FQDN\"]; n1;\n\n node [label=\"205.251.199.98\",color=\"orange\",type=\"IPAddress\"]; n2;\n\n\n\n n1 -> n2 [label=\"a_record\"];\n\n}\n`\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/gexf.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"bufio\"\n\t\"encoding/xml\"\n\t\"io\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\txmlNS string = \"http://www.gephi.org/gexf\"\n\txmlNSVIZ string = \"http://www.gephi.org/gexf/viz\"\n\n\tclassNode string = \"node\"\n\n\tmodeStatic string = \"static\"\n\n\tedgeTypeDirected string = \"directed\"\n)\n\ntype gexfAttrValue struct {\n\tFor string `xml:\"for,attr\"`\n\tValue string `xml:\"value,attr\"`\n}\n\ntype gexfAttribute struct {\n\tID string `xml:\"id,attr\"`\n\tTitle string `xml:\"title,attr\"`\n\tType string `xml:\"type,attr\"`\n\tDefault string `xml:\"default,omitempty\"`\n}\n\ntype gexfAttributes struct {\n\tClass string `xml:\"class,attr\"`\n\tAttrs []gexfAttribute `xml:\"attribute\"`\n}\n\ntype gexfParent struct {\n\tFor string `xml:\"for,attr\"`\n}\n\ntype gexfColor struct {\n\tR uint8 `xml:\"r,attr\"`\n\tG uint8 `xml:\"g,attr\"`\n\tB uint8 `xml:\"b,attr\"`\n}\n\ntype gexfNode struct {\n\tID string `xml:\"id,attr\"`\n\tLabel string `xml:\"label,attr,omitempty\"`\n\tAttrs []gexfAttrValue `xml:\"attvalues>attvalue,omitempty\"`\n\tParents []gexfParent `xml:\"parents>parent\"`\n\tColor *gexfColor `xml:\"viz:color,omitempty\"`\n}\n\ntype gexfEdge struct {\n\tID string `xml:\"id,attr\"`\n\tLabel string `xml:\"label,attr,omitempty\"`\n\tType string `xml:\"type,attr,omitempty\"`\n\tSource string `xml:\"source,attr\"`\n\tTarget string `xml:\"target,attr\"`\n\tWeight float64 `xml:\"weight,attr,omitempty\"`\n\tAttrs []gexfAttrValue `xml:\"attvalues>attvalue,omitempty\"`\n}\n\ntype gexfMeta struct {\n\tLastModified string `xml:\"lastmodifieddate,attr\"`\n\tCreator string `xml:\"creator\"`\n\tKeywords string `xml:\"keywords,omitempty\"`\n\tDesc string `xml:\"description\"`\n}\n\ntype gexfGraph struct {\n\tMode string `xml:\"mode,attr,omitempty\"`\n\tEdgeType string `xml:\"defaultedgetype,attr,omitempty\"`\n\tAttrs gexfAttributes `xml:\"attributes,omitempty\"`\n\tNodes []gexfNode `xml:\"nodes>node,omitempty\"`\n\tEdges []gexfEdge `xml:\"edges>edge,omitempty\"`\n}\n\ntype gexf struct {\n\tXMLName xml.Name\n\tVersion string `xml:\"version,attr\"`\n\tViz string `xml:\"xmlns:viz,attr\"`\n\tMeta gexfMeta `xml:\"meta\"`\n\tGraph gexfGraph `xml:\"graph\"`\n}\n\nvar (\n\tgexfGreen = &gexfColor{R: 34, G: 153, B: 84}\n\tgexfRed = &gexfColor{R: 242, G: 44, B: 13}\n\tgexfOrange = &gexfColor{R: 243, G: 156, B: 18}\n\tgexfCyan = &gexfColor{R: 26, G: 243, B: 240}\n\tgexfPink = &gexfColor{R: 243, G: 26, B: 188}\n\tgexfBlue = &gexfColor{R: 26, G: 69, B: 243}\n)\n\n// WriteGEXFData generates a GEXF file to display the Amass graph using Gephi.\nfunc WriteGEXFData(output io.Writer, nodes []Node, edges []Edge) error {\n\tbufwr := bufio.NewWriter(output)\n\n\tif _, err := bufwr.WriteString(\"\\n\"); err != nil {\n\t\treturn err\n\t}\n\t_ = bufwr.Flush()\n\n\tdoc := &gexf{\n\t\tXMLName: xml.Name{\n\t\t\tSpace: xmlNS,\n\t\t\tLocal: \"gexf\",\n\t\t},\n\t\tVersion: \"1.3\",\n\t\tViz: xmlNSVIZ,\n\t\tMeta: gexfMeta{\n\t\t\tLastModified: time.Now().UTC().Format(\"2006-01-02\"),\n\t\t\tCreator: \"OWASP Amass - https://github.com/owasp-amass\",\n\t\t\tDesc: \"OWASP Amass Network Mapping\",\n\t\t},\n\t\tGraph: gexfGraph{\n\t\t\tMode: modeStatic,\n\t\t\tEdgeType: edgeTypeDirected,\n\t\t\tAttrs: gexfAttributes{\n\t\t\t\tClass: classNode,\n\t\t\t\tAttrs: []gexfAttribute{\n\t\t\t\t\t{ID: \"0\", Title: \"Title\", Type: \"string\"},\n\t\t\t\t\t{ID: \"1\", Title: \"Type\", Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor idx, n := range nodes {\n\t\tvar color *gexfColor\n\n\t\tswitch n.Type {\n\t\tcase \"FQDN\":\n\t\t\tcolor = gexfGreen\n\t\tcase \"domain\":\n\t\t\tcolor = gexfRed\n\t\tcase \"IPAddress\":\n\t\t\tcolor = gexfOrange\n\t\tcase \"RIROrg\":\n\t\t\tcolor = gexfCyan\n\t\tcase \"Netblock\":\n\t\t\tcolor = gexfPink\n\t\tcase \"ASN\":\n\t\t\tcolor = gexfBlue\n\t\t}\n\n\t\tdoc.Graph.Nodes = append(doc.Graph.Nodes, gexfNode{\n\t\t\tID: strconv.Itoa(idx),\n\t\t\tLabel: n.Label,\n\t\t\tAttrs: []gexfAttrValue{\n\t\t\t\t{For: \"0\", Value: n.Title},\n\t\t\t\t{For: \"1\", Value: n.Type},\n\t\t\t},\n\t\t\tColor: color,\n\t\t})\n\t}\n\n\tfor idx, e := range edges {\n\t\tdoc.Graph.Edges = append(doc.Graph.Edges, gexfEdge{\n\t\t\tID: strconv.Itoa(idx),\n\t\t\tLabel: e.Label,\n\t\t\tSource: strconv.Itoa(e.From),\n\t\t\tTarget: strconv.Itoa(e.To),\n\t\t})\n\t}\n\n\tenc := xml.NewEncoder(bufwr)\n\tenc.Indent(\" \", \" \")\n\tdefer func() { _ = bufwr.Flush() }()\n\n\treturn enc.Encode(doc)\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/gexf_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestWriteGEXFDataHappyPath(t *testing.T) {\n\tbuf := bytes.NewBufferString(\"\")\n\terr := WriteGEXFData(buf, testNodes(), testEdges())\n\tassert.Nil(t, err)\n\n\toutput := buf.String()\n\tassert.Contains(t, output, expectedGexfOutput, \"Gexf output should contain\")\n}\n\nconst expectedGexfOutput = `OWASP Amass - https://github.com/owasp-amass\n OWASP Amass Network Mapping\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n `\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/viz.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tamassdb \"github.com/owasp-amass/amass/v5/internal/db\"\n\t\"github.com/owasp-amass/asset-db/repository\"\n\t\"github.com/owasp-amass/asset-db/types\"\n\toam \"github.com/owasp-amass/open-asset-model\"\n\toamcert \"github.com/owasp-amass/open-asset-model/certificate\"\n\t\"github.com/owasp-amass/open-asset-model/contact\"\n\toamdns \"github.com/owasp-amass/open-asset-model/dns\"\n\t\"github.com/owasp-amass/open-asset-model/org\"\n\toamreg \"github.com/owasp-amass/open-asset-model/registration\"\n)\n\n// Edge represents an Amass graph edge in the viz package.\ntype Edge struct {\n\tFrom, To int\n\tLabel string\n\tTitle string\n}\n\n// Node represents an Amass graph node in the viz package.\ntype Node struct {\n\tID int\n\tType string\n\tLabel string\n\tTitle string\n}\n\n// VizData returns the current state of the Graph as viz package Nodes and Edges.\nfunc VizData(domains []string, since time.Time, db repository.Repository) ([]Node, []Edge) {\n\tif len(domains) == 0 {\n\t\treturn []Node{}, []Edge{}\n\t}\n\n\tvar next []*types.Entity\n\tfor _, d := range domains {\n\t\tif ents, err := db.FindEntitiesByContent(&oamdns.FQDN{Name: d}, since); err == nil && len(ents) == 1 {\n\t\t\tif n, err := amassdb.FindByFQDNScope(db, ents[0], since); err == nil && len(n) > 0 {\n\t\t\t\tnext = append(next, n...)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar idx int\n\tvar viznodes []Node\n\tvar vizedges []Edge\n\tnodeToIdx := make(map[string]int)\n\tfor len(next) > 0 {\n\t\tvar assets []*types.Entity\n\t\tassets = append(assets, next...)\n\t\tnext = []*types.Entity{}\n\n\t\tfor _, a := range assets {\n\t\t\tn := newNode(db, idx, a, since)\n\t\t\tif n == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Keep track of which indices nodes were assigned to\n\t\t\tid := idx\n\t\t\tif nid, found := nodeToIdx[n.Label]; !found {\n\t\t\t\tidx++\n\t\t\t\tnodeToIdx[n.Label] = id\n\t\t\t\tviznodes = append(viznodes, *n)\n\t\t\t} else {\n\t\t\t\tid = nid\n\t\t\t}\n\t\t\t// Determine relationship directions to follow on the graph\n\t\t\tvar in, out bool\n\t\t\tvar inRels, outRels []string\n\t\t\tswitch a.Asset.AssetType() {\n\t\t\tcase oam.Account:\n\t\t\t\tout = true\n\t\t\t\tin = true\n\t\t\t\tinRels = append(inRels, \"sender\", \"recipient\")\n\t\t\tcase oam.AutnumRecord:\n\t\t\t\tout = true\n\t\t\tcase oam.AutonomousSystem:\n\t\t\t\tout = true\n\t\t\t\toutRels = append(outRels, \"registration\")\n\t\t\tcase oam.ContactRecord:\n\t\t\t\tout = true\n\t\t\tcase oam.DomainRecord:\n\t\t\t\tout = true\n\t\t\tcase oam.FQDN:\n\t\t\t\tif domainNameInScope(n.Label, domains) {\n\t\t\t\t\tin = true\n\t\t\t\t\tout = true\n\t\t\t\t} else if associatedWithScope(db, a, domains, since) {\n\t\t\t\t\tout = true\n\t\t\t\t}\n\t\t\tcase oam.FundsTransfer:\n\t\t\t\tout = true\n\t\t\tcase oam.Identifier:\n\t\t\t\tout = true\n\t\t\tcase oam.IPAddress:\n\t\t\t\tin = true\n\t\t\t\tinRels = append(inRels, \"contains\")\n\t\t\t\tout = true\n\t\t\tcase oam.IPNetRecord:\n\t\t\t\tout = true\n\t\t\tcase oam.Location:\n\t\t\t\tout = true\n\t\t\tcase oam.Netblock:\n\t\t\t\tin = true\n\t\t\t\tinRels = append(inRels, \"announces\")\n\t\t\t\tout = true\n\t\t\t\toutRels = append(outRels, \"registration\")\n\t\t\tcase oam.Organization:\n\t\t\t\tout = true\n\t\t\t\tin = true\n\t\t\t\tinRels = append(inRels, \"subsidiary\")\n\t\t\tcase oam.Person:\n\t\t\t\tout = true\n\t\t\tcase oam.Phone:\n\t\t\t\tout = true\n\t\t\tcase oam.Service:\n\t\t\t\tout = true\n\t\t\tcase oam.TLSCertificate:\n\t\t\t\tout = true\n\t\t\tcase oam.URL:\n\t\t\t\tout = true\n\t\t\tdefault:\n\t\t\t}\n\t\t\t// Obtain relations to additional assets in the graph\n\t\t\tif out {\n\t\t\t\tif edges, err := db.OutgoingEdges(a, since, outRels...); err == nil && len(edges) > 0 {\n\t\t\t\t\tfromID := id\n\t\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\t\tif to, err := db.FindEntityById(edge.ToEntity.ID); err == nil {\n\t\t\t\t\t\t\ttoID := idx\n\t\t\t\t\t\t\tn2 := newNode(db, toID, to, since)\n\t\t\t\t\t\t\tif n2 == nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif id, found := nodeToIdx[n2.Label]; !found {\n\t\t\t\t\t\t\t\tidx++\n\t\t\t\t\t\t\t\tnodeToIdx[n2.Label] = toID\n\t\t\t\t\t\t\t\tviznodes = append(viznodes, *n2)\n\t\t\t\t\t\t\t\tnext = append(next, to)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttoID = id\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvizedges = append(vizedges, Edge{\n\t\t\t\t\t\t\t\tFrom: fromID,\n\t\t\t\t\t\t\t\tTo: toID,\n\t\t\t\t\t\t\t\tLabel: edge.Relation.Label(),\n\t\t\t\t\t\t\t\tTitle: edge.Relation.Label(),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif in {\n\t\t\t\tif edges, err := db.IncomingEdges(a, since, inRels...); err == nil && len(edges) > 0 {\n\t\t\t\t\ttoID := id\n\t\t\t\t\tfor _, edge := range edges {\n\t\t\t\t\t\tif from, err := db.FindEntityById(edge.FromEntity.ID); err == nil {\n\t\t\t\t\t\t\tfromID := idx\n\t\t\t\t\t\t\tn2 := newNode(db, fromID, from, since)\n\t\t\t\t\t\t\tif n2 == nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif id, found := nodeToIdx[n2.Label]; !found {\n\t\t\t\t\t\t\t\tidx++\n\t\t\t\t\t\t\t\tnodeToIdx[n2.Label] = fromID\n\t\t\t\t\t\t\t\tviznodes = append(viznodes, *n2)\n\t\t\t\t\t\t\t\tif edge.Relation.Label() != \"ptr_record\" {\n\t\t\t\t\t\t\t\t\tnext = append(next, from)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfromID = id\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvizedges = append(vizedges, Edge{\n\t\t\t\t\t\t\t\tFrom: fromID,\n\t\t\t\t\t\t\t\tTo: toID,\n\t\t\t\t\t\t\t\tLabel: edge.Relation.Label(),\n\t\t\t\t\t\t\t\tTitle: edge.Relation.Label(),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn viznodes, vizedges\n}\n\nfunc newNode(db repository.Repository, idx int, a *types.Entity, since time.Time) *Node {\n\tif a == nil || a.Asset == nil {\n\t\treturn nil\n\t}\n\tasset := a.Asset\n\n\tkey := asset.Key()\n\tif key == \"\" {\n\t\treturn nil\n\t}\n\n\tatype := string(asset.AssetType())\n\tswitch v := asset.(type) {\n\tcase *contact.ContactRecord:\n\t\tkey = \"Found->\" + key\n\tcase *oamreg.DomainRecord:\n\t\tkey = \"WHOIS: \" + key\n\tcase *contact.Location:\n\t\tparts := []string{v.BuildingNumber, v.StreetName, v.City, v.Province, v.PostalCode}\n\t\tkey = strings.Join(parts, \" \")\n\tcase *org.Organization:\n\t\tkey = fmt.Sprintf(\"%s (%s)\", v.Name, v.ID)\n\tcase *oamcert.TLSCertificate:\n\t\tkey = fmt.Sprintf(\"%s (%s)\", v.SubjectCommonName, v.SerialNumber)\n\t}\n\ttitle := fmt.Sprintf(\"%s: %s\", atype, key)\n\n\treturn &Node{\n\t\tID: idx,\n\t\tType: atype,\n\t\tLabel: strings.ReplaceAll(key, \"\\\"\", \"\"),\n\t\tTitle: title,\n\t}\n}\n\nfunc domainNameInScope(name string, scope []string) bool {\n\tvar discovered bool\n\n\tn := strings.ToLower(strings.TrimSpace(name))\n\tfor _, d := range scope {\n\t\td = strings.ToLower(d)\n\n\t\tif n == d || strings.HasSuffix(n, \".\"+d) {\n\t\t\tdiscovered = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn discovered\n}\n\nfunc associatedWithScope(db repository.Repository, asset *types.Entity, scope []string, since time.Time) bool {\n\tif edges, err := db.OutgoingEdges(asset, since, \"dns_record\", \"node\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif to, err := db.FindEntityById(edge.ToEntity.ID); err == nil {\n\t\t\t\tif n, ok := to.Asset.(*oamdns.FQDN); ok && n != nil && domainNameInScope(n.Name, scope) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\treturn followBackForScope(db, asset, scope, since)\n}\n\nfunc followBackForScope(db repository.Repository, asset *types.Entity, scope []string, since time.Time) bool {\n\tif edges, err := db.IncomingEdges(asset, since, \"dns_record\", \"node\"); err == nil && len(edges) > 0 {\n\t\tfor _, edge := range edges {\n\t\t\tif rel, ok := edge.Relation.(*oamdns.BasicDNSRelation); ok && rel.Header.RRType != 5 {\n\t\t\t\tcontinue\n\t\t\t} else if rel, ok := edge.Relation.(*oamdns.PrefDNSRelation); ok && rel.Header.RRType != 15 {\n\t\t\t\tcontinue\n\t\t\t} else if rel, ok := edge.Relation.(*oamdns.SRVDNSRelation); ok && rel.Header.RRType != 33 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif from, err := db.FindEntityById(edge.FromEntity.ID); err == nil {\n\t\t\t\tif n, ok := from.Asset.(*oamdns.FQDN); ok && n != nil && domainNameInScope(n.Name, scope) {\n\t\t\t\t\treturn true\n\t\t\t\t} else if followBackForScope(db, from, scope, since) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: internal/viz/viz_test.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage viz\n\nfunc testEdges() []Edge {\n\treturn []Edge{\n\t\t{\n\t\t\tFrom: 0,\n\t\t\tTo: 1,\n\t\t\tLabel: \"a_record\",\n\t\t\tTitle: \"a_record\",\n\t\t},\n\t}\n}\n\nfunc testNodes() []Node {\n\treturn []Node{\n\t\t{\n\t\t\tID: 0,\n\t\t\tType: \"FQDN\",\n\t\t\tLabel: \"owasp.org\",\n\t\t\tTitle: \"FQDN: owasp.org\",\n\t\t},\n\t\t{\n\t\t\tID: 1,\n\t\t\tType: \"IPAddress\",\n\t\t\tLabel: \"205.251.199.98\",\n\t\t\tTitle: \"IPAddress: 205.251.199.98\",\n\t\t},\n\t}\n}\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: resources/config.yaml\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\nscope:\n# domains: # registered domain names in scope\n# - owasp.org\n# ips: # IP addresses in scope, multiple methods of inserting IP addresses can be used\n# - 192.0.2.1\n# - 192.0.2.2\n# - 192.168.0.3-8\n# - 192.168.0.10-192.168.0.20\n# cidrs: # CIDR ranges that are in scope\n# - 192.0.2.0/24\n# - 192.0.2.128/25\n ports: # ports to be used when actively scanning services\n - 80\n - 443\n - 8000\n - 8080\n - 8443\n - 8888\n# blacklist: # subdomains to be blacklisted\n# - example.owasp.org\noptions:\n datasources: \"./datasources.yaml\"\n # engine: \"http://127.0.0.1:4000/graphql\"\n # database: \"bolt://neo4j:amass4OWASP@neo4j:7687/neo4j\"\n # database: \"postgres://amass:amass4OWASP@assetdb:5432/assetdb\"\n bruteforce:\n enabled: false\n wordlists: # wordlist(s) specific to FQDN brute forcing\n - \"./namelist.txt\"\n alterations:\n enabled: false\n wordlists: # wordlist(s) specific to name alterations\n - \"./alterations.txt\"\n default_transform_values:\n ttl: 1440 # minutes. If not specified, the default is 1440 minutes (1 day)\n confidence: 50 # 50%\n priority: 5\n\ntransformations:\n Account->ALL:\n ttl: 1080 # 7 days\n AutnumRecord->ALL:\n AutonomousSystem->ALL:\n AutonomousSystem->RDAP:\n ttl: 43200 # 30 days\n ContactRecord->ALL:\n DomainRecord->ALL:\n File->ALL:\n FQDN->ALL:\n FQDN->DNS:\n ttl: 1440\n FQDN->DomainRecord:\n ttl: 43200 # 30 days\n FundsTransfer->ALL:\n ttl: 1080 # 7 days\n Identifier->ALL:\n Identifier->GLEIF:\n ttl: 43200 # 30 days\n Identifier->RDAP:\n ttl: 43200 # 30 days\n IPAddress->ALL:\n IPNetRecord->ALL:\n Location->ALL:\n Netblock->ALL:\n Netblock->RDAP:\n ttl: 43200 # 30 days\n Organization->ALL:\n Organization->GLEIF:\n ttl: 43200 # 30 days\n Person->ALL:\n ttl: 43200 # 30 days\n Phone->ALL:\n ttl: 1080 # 7 days\n Product->ALL:\n ttl: 10080 # 7 days\n ProductRelease->ALL:\n Service->ALL:\n TLSCertificate->ALL:\n ttl: 10080 # 7 days\n URL->ALL:\n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: resources/datasources.yaml\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n# these are the global options related to data sources.\nglobal_options:\n# minimum_ttl is the default used when datasources don't specify a larger ttl value.\n minimum_ttl: 1440 #one day\n\n# uncomment and add credentials for data sources that you'd like to be used by the engine\ndatasources:\n# - name: 360PassiveDNS\n# ttl: 3600\n# creds:\n# account: \n# apikey: null\n# - name: ASNLookup\n# creds:\n# account: \n# apikey: null\n# - name: Ahrefs\n# ttl: 4320\n# creds:\n# account: \n# apikey: null\n# - name: AlienVault\n# creds:\n# account: \n# apikey: null\n# - name: BeVigil\n# creds:\n# account: \n# apikey: null\n# - name: BigDataCloud\n# creds:\n# account: \n# apikey: null\n# - name: BinaryEdge\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: BufferOver\n# creds:\n# account: \n# apikey: null\n# - name: BuiltWith\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: C99\n# ttl: 4320\n# creds:\n# account1: \n# apikey: null\n# account2: \n# apikey: null\n# - name: Chaos\n# ttl: 4320\n# creds:\n# account: \n# apikey: null\n# - name: CIRCL\n# creds:\n# account: \n# username: null\n# password: null\n# - name: CertCentral\n# creds:\n# account: \n# username: null\n# apikey: null\n# - name: DNSDB\n# ttl: 4320\n# creds:\n# account: \n# apikey: null\n# - name: DNSRepo\n# creds:\n# account: \n# apikey: null\n# - name: Detectify\n# creds:\n# account: \n# apikey: null\n# - name: FOFA\n# ttl: 10080\n# creds:\n# account: \n# username: null\n# apikey: null\n# - name: FullHunt\n# creds:\n# account: \n# apikey: null\n# - name: GitHub\n# ttl: 4320\n# creds:\n# accountname: \n# apikey: null\n# - name: GitLab\n# ttl: 4320\n# creds:\n# accountname: \n# apikey: null\n# - name: HackerTarget\n# ttl: 1440\n# creds:\n# account: \n# apikey: null\n# - name: Hunter\n# creds:\n# account: \n# apikey: null\n# - name: IntelX\n# creds:\n# account: \n# apikey: null\n# - name: IPdata\n# creds:\n# account: \n# apikey: null\n# - name: IPinfo\n# creds:\n# account: \n# apikey: null\n# - name: LeakIX\n# creds:\n# account: \n# apikey: null\n# - name: Netlas\n# creds:\n# account: \n# apikey: null\n# - name: PassiveTotal\n# ttl: 10080\n# creds:\n# account: \n# username: null\n# apikey: null\n# - name: PentestTools\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: PublicWWW\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: SecurityTrails\n# ttl: 1440\n# creds:\n# account: \n# apikey: null\n# - name: Shodan\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: URLScan\n# creds:\n# account: \n# apikey: null\n# - name: VirusTotal\n# ttl: 10080\n# creds:\n# account: \n# apikey: null\n# - name: WhoisXMLAPI\n# creds:\n# account: \n# apikey: null\n# - name: Yandex\n# ttl: 1440\n# creds:\n# account: \n# username: null\n# apikey: null\n# - name: ZETAlytics\n# ttl: 1440\n# creds:\n# account: \n# apikey: null\n# - name: ZoomEye\n# ttl: 1440\n# creds:\n# account: \n# username: null\n# password: null \n\n<|im_end|>"} {"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AMASS' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: resources/resources.go\n<|im_end|>\n<|im_start|>assistant\nREPO: AMASS\nCODE:\n// Copyright \u00a9 by Jeff Foley 2017-2025. All rights reserved.\n// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n// SPDX-License-Identifier: Apache-2.0\n\npackage resources\n\nimport (\n\t\"embed\"\n\t\"fmt\"\n\t\"io/fs\"\n)\n\n//go:embed alterations.txt config.yaml datasources.yaml namelist.txt\nvar resourceFS embed.FS\n\nvar DefaultFilesList = []string{\n\t\"alterations.txt\",\n\t\"config.yaml\",\n\t\"datasources.yaml\",\n\t\"namelist.txt\",\n}\n\nfunc GetResourceFile(path string) (fs.File, error) {\n\tfile, err := resourceFS.Open(path)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to obtain the embedded file: %s: %v\", path, err)\n\t}\n\n\treturn file, err\n}\n\nfunc GetResourceFileData(path string) ([]byte, error) {\n\treturn resourceFS.ReadFile(path)\n}\n\n<|im_end|>"}