Compare commits

...
Author SHA1 Message Date
sethsec-bf a8d2bfbfb3 Removed graph command from cobra for now 2024-04-16 14:18:47 -04:00
sethsec-bf c0e4301ef3 Add GCP to readme, fix typo 2024-04-16 14:10:51 -04:00
sethsec-bf 22417f174b spelling 2024-04-16 11:54:10 -04:00
sethsec-bf c3be95b3db cleaned up enhanced pmapper loot file 2024-04-16 11:47:31 -04:00
sethsec-bf abcc930f20 added afero fs back to output2 (needed to pass brew tests) 2024-04-16 11:29:53 -04:00
sethsec-bf 77cd08b8d5 updated gcp verbosity, updated cape command usage, switched version tracking file from main.go to internal/utils.go 2024-04-16 11:24:18 -04:00
sethsec-bf 57194ef3e0 bump to version 1.14.0, merged gcp and aws ds functionality 2024-04-16 10:32:19 -04:00
sethsec-bf 82635fd44f made aws sso like eks, where edges are not created if it's if the provider is in the same account as the role that trusts it. the edges will still show up cross account though. 2024-04-16 10:28:15 -04:00
sethsec-bf 67af1bd7fb update gcp package with vuln 2024-04-16 10:23:06 -04:00
sethsec-bf 79f3899ead update go mod 2024-04-16 10:21:33 -04:00
Seth Art 8ab4c4200a Merge branch 'main' into bastien_directoryservice_aws 2024-04-15 20:30:27 -04:00
sethsec-bf 6e52e5ee7b merge gcp stuff from main into this branch 2024-04-15 16:33:09 -04:00
Joe 9920c411c4 Merge pull request #82 from BishopFox/codeowners
Update codeowners
2024-04-15 10:58:45 -07:00
moloch-- df3fb6eae0 Update codeowners 2024-04-15 10:58:21 -07:00
David 8e94b3c46a Merge pull request #79 from BishopFox/feature/gcp-v1
Cloudfox GCP Functionality
2024-04-12 11:43:43 -04:00
David 94628aae73 i cant spel 2024-04-12 01:12:19 +00:00
David 23e8878e49 Merge branch 'main' into feature/gcp-v1 2024-04-12 01:04:49 +00:00
sethsec-bf 356d57b2de Added pmapper basepath to all relevent commands. Improved logging for cape/cape-tui. Fixed codebuld cache bug. 2024-04-10 11:49:33 -04:00
sethsec-bf 3a45583015 Got cape working without any aws calls, cleaned up logging messages 2024-04-05 16:07:37 -04:00
Bastien Faure 57832ada7c Codespell fix 2024-04-02 12:01:31 -07:00
Bastien Faure 608f07804e AWS uses a mix of clouddirectory and directoryservices for Directory services 2024-04-02 12:00:45 -07:00
Bastien Faure de492fa6e9 Add Directory Service support for AWS 2024-04-02 11:49:45 -07:00
David dee22b3ebc fix logging issue and improve whoami 2024-03-29 19:44:17 +00:00
sethsec-bf 590a94b576 changed println to printf 2024-03-28 15:10:22 -04:00
sethsec-bf fca22ceb6b renamed to cape, added hop count logic, pulled privesc function out so i can add logic to handle cobra flags 2024-03-28 15:06:41 -04:00
sethsec-bf 84369247a7 quick fix for context error. logging issue still there. 2024-03-22 14:43:52 -04:00
sethsec-bf 4ef87d8b98 updated caper to use new version of parseFederatedRoleTrusts from the role-trusts command. Also changed the way vendors and federated identities are labled 2024-03-22 08:58:05 -04:00
David 334583d3a2 save work whomai account stub 2024-03-21 22:38:02 +00:00
sethsec-bf 8fac75ed11 merged from main 2024-03-21 09:58:35 -04:00
sethsec-bf 3ff704e98f merged from main 2024-03-21 09:56:18 -04:00
Seth Art b73cd90323 Merge pull request #78 from enzowritescode/feature/aws-neptune
Feature/aws neptune
2024-03-20 15:23:20 -04:00
David 2f99a7642f working gcp functionality 2024-03-13 14:19:47 +00:00
sethsec-bf 05fd899219 Fixed bug in federeated role trust poclies where multiple subjects are trusted 2024-03-07 15:56:13 -05:00
sethsec-bf 36c9a5b795 Merged changes from neptune PR into this branch 2024-02-28 09:34:41 -05:00
sethsec-bf dd6dd291c5 playing around with saving graph state between runs 2024-02-13 16:20:37 -05:00
sethsec-bf 42b0f3a212 Merge branch 'main' of github.com:BishopFox/cloudfox into graph 2024-02-08 16:57:03 -05:00
sethsec-bf e4e548012f revert test 2024-02-08 16:56:51 -05:00
sethsec-bf 24b7076bc3 saving place in caper command 2024-02-08 16:32:15 -05:00
sethsec-bf e4f3421ea1 Added functionailty to hightlight admins in caper command 2024-02-02 13:23:49 -05:00
sethsec-bf e61a401733 Kept first draft as the graph command. Moved second take to the caper command. 2024-01-31 16:47:29 -05:00
sethsec-bf a13527a7a9 Added MakeVertices method for type Role 2024-01-25 16:25:11 -05:00
sethsec-bf aeccb6db6d Have global data in dom's graph format now. just need to write the table creation code 2024-01-25 15:24:49 -05:00
sethsec-bf 4d3c6a4c67 Merge remote-tracking branch 'origin/seth-dev' into graph 2024-01-22 21:26:47 -05:00
sethsec-bf ac1125d47e added users model 2024-01-22 15:46:19 -05:00
sethsec-bf 009321e7cb Updated pmapper output files 2024-01-22 15:44:43 -05:00
sethsec-bf 4cf58a3479 Created loot file for pmapper 2024-01-18 10:06:41 -05:00
sethsec-bf f5437b7afb Started to add knownvendoraccounts info 2024-01-17 09:03:48 -05:00
sethsec-bf ef25d8b04d Merged origin/seth-dev into graph 2024-01-03 09:10:16 -05:00
sethsec-bf 1e2eaf5576 merged from main 2023-12-19 20:15:14 -05:00
sethsec-bf 66ffc57438 go mod tidy 2023-12-19 16:15:13 -05:00
sethsec-bf c4a276e4be graph/neo4j functionali working - detecting cross account attack paths 2023-12-11 18:24:34 -05:00
sethsec-bf 4edbd3326c neo4j cross-account stuff kind of working, pmapper stuff not working 2023-12-06 15:52:49 -05:00
sethsec-bf 5c40ef45df initial ideas for graph command 2023-11-09 08:23:37 -05:00
70 changed files with 8316 additions and 329 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
@sethsec-bf carlosvendramini-bf
* @bishopfaure @dbravo-bishopfox
+5 -1
View File
@@ -71,4 +71,8 @@ cloudfox
*.json
*.csv
*.log
dist/
dist/
# graphvis files
*.gv
*.svg
+19 -2
View File
@@ -48,9 +48,9 @@ For the full documentation please refer to our [wiki](https://github.com/BishopF
| Provider| CloudFox Commands |
| - | - |
| AWS | 33 |
| AWS | 34 |
| Azure | 4 |
| GCP | Support Planned |
| GCP | 8 |
| Kubernetes | Support Planned |
@@ -111,6 +111,7 @@ Additional policy notes (as of 09/2022):
| AWS | [access-keys](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#access-keys) | Lists active access keys for all users. Useful for cross referencing a key you found with which in-scope account it belongs to. |
| AWS | [api-gw](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#api-gw) | Lists API gateway endpoints and gives you custom curl commands including API tokens if they are stored in metadata. |
| AWS | [buckets](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#filesystems) | Lists the buckets in the account and gives you handy commands for inspecting them further. |
| AWS | [cape](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#cape) | Enumerates cross-account privilege escalation paths. Requires `pmapper` to be run first |
| AWS | [cloudformation](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#cloudformation) | Lists the cloudformation stacks in the account. Generates loot file with stack details, stack parameters, and stack output - look for secrets. |
| AWS | [codebuild](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#codebuild) | Enumerate CodeBuild projects |
| AWS | [databases](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#databases) | Enumerate RDS databases. Get a loot file with connection strings. |
@@ -140,6 +141,7 @@ Additional policy notes (as of 09/2022):
| AWS | [sqs](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#sqs) | This command enumerates all of the sqs queues and gives you the commands to receive messages from a queue and send messages to a queue (if you have the permissions needed). This command also attempts to summarize queue resource policies if they exist.|
| AWS | [tags](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#tags) | List all resources with tags, and all of the tags. This can be used similar to inventory as another method to identify what types of resources exist in an account. |
| AWS | [workloads](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#workloads) | List all of the compute workloads and what role they have. Tells you if any of the roles are admin (bad) and if you have pmapper data locally, it will tell you if any of the roles can privesc to admin (also bad) |
| AWS | [ds](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#workloads) | List all of the AWS-managed directories and their attributes. Also summarizes the current trusts with their directions and types. |
# Azure Commands
@@ -151,6 +153,21 @@ Additional policy notes (as of 09/2022):
| Azure | [storage](https://github.com/BishopFox/cloudfox/wiki/Azure-Commands#storage) | The storage command is still under development. Currently it only displays limited data about the storage accounts |
| Azure | [vms](https://github.com/BishopFox/cloudfox/wiki/Azure-Commands#vms) | Enumerates useful information for Compute instances in all available resource groups and subscriptions |
# GCP Commands
| Provider | Command Name | Description
| - | - | - |
| GCP | [whoami](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#whoami) | Display the email address of the GCP authenticated user |
| GCP | [all-checks](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#all-checks) | Runs all available GCP commands |
| GCP | [artifact-registry](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#artifact-registry) | Display GCP artifact registry information |
| GCP | [bigquery](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#bigquery) | Display Bigquery datasets and tables information |
| GCP | [buckets](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#buckets) | Display GCP buckets information |
| GCP | [iam](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#iam) | Display GCP IAM information |
| GCP | [instances](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#instances) | Display GCP Compute Engine instances information |
| GCP | [secrets](https://github.com/BishopFox/cloudfox/wiki/GCP-Commands#secrets) | Display GCP secrets information |
# Authors
* [Carlos Vendramini](https://github.com/carlosvendramini-bf)
* [Seth Art (@sethsec](https://twitter.com/sethsec))
+538
View File
@@ -0,0 +1,538 @@
package aws
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var (
titleStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Right = "├"
return lipgloss.NewStyle().BorderStyle(b).Padding(0, 1)
}()
infoStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Left = "┤"
return titleStyle.Copy().BorderStyle(b)
}()
magentaStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("magenta"))
)
type model struct {
preloadedData *AllAccountData
awsAccountsTable table.Model
awsAccountsViewport viewport.Model
mainTable table.Model
mainTableViewport viewport.Model
mainTableData map[int][]table.Row
detailsData map[int]string
detailsViewport viewport.Model // Use viewport for details view
focusSelector int
defaultTableStyle table.Styles
terminalWidth int
terminalHeight int // Add terminal height to manage viewport size
awsSelectedRow int
mainSelectedRow int // Track the currently selected row for detail view updates
keys keyMap
help help.Model
lastKey string
quitting bool
}
type CapeJSON struct {
Account string `json:"account"`
Source string `json:"source"`
Summary string `json:"summary"`
Target string `json:"target"`
IsTargetAdmin string `json:"isTargetAdmin"`
}
type PerAccountData struct {
FilePath string // Path to the JSON file
PrivescPaths []CapeJSON // All records contained in the file
}
type AllAccountData struct {
Files map[string]*PerAccountData // Map of file paths to their records
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
BorderBottom(true).
Bold(false)
s.Selected = s.Selected.
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Bold(false)
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.terminalWidth = msg.Width
m.terminalHeight = msg.Height - 7 // Adjust as needed
// Calculate heights based on the specified percentages
awsAccountsHeight := int(float32(m.terminalHeight) * 0.2)
halfHeight := int(float32(m.terminalHeight) * 0.4) // For the other two viewports
// Update dimensions for all viewports
m.awsAccountsViewport.Width = m.terminalWidth - 4
m.awsAccountsViewport.Height = awsAccountsHeight
m.mainTableViewport.Width = m.terminalWidth - 4
m.mainTableViewport.Height = halfHeight
m.awsAccountsTable.SetHeight(awsAccountsHeight - 2)
m.awsAccountsTable.SetWidth(m.terminalWidth - 4)
m.awsAccountsViewport.Width = m.terminalWidth - 4
m.detailsViewport.Width = m.terminalWidth - 4
m.detailsViewport.Height = halfHeight
m.mainTable.SetHeight(halfHeight - 2)
case tea.KeyMsg:
switch {
case key.Matches(msg, m.keys.Up):
m.lastKey = "↑"
case key.Matches(msg, m.keys.Down):
m.lastKey = "↓"
case key.Matches(msg, m.keys.Left):
m.lastKey = "←"
case key.Matches(msg, m.keys.Right):
m.lastKey = "→"
case key.Matches(msg, m.keys.Help):
m.help.ShowAll = !m.help.ShowAll
case key.Matches(msg, m.keys.Tab):
// Switch focus between the the three viewports by cycling focusSelector between 0, 1, and 2
m.focusSelector = (m.focusSelector + 1) % 3
//m.focusOnTable = !m.focusOnTable
// add a case for shift and tab at the same time to to cycle the focusSelector backwards between 0, 1, and 2
case key.Matches(msg, m.keys.ShiftTab):
m.focusSelector = (m.focusSelector - 1) % 3
case key.Matches(msg, m.keys.Quit):
m.quitting = true
return m, tea.Quit
}
//var detailsData map[int]string
//var mainTable table.Model
var err error
var awsCurrentRow int
var mainCurrentRow int
switch m.focusSelector {
case 0:
m.awsAccountsTable, cmd = m.awsAccountsTable.Update(msg)
m.awsAccountsViewport.SetContent(m.awsAccountsTable.View())
awsCurrentRow = m.awsAccountsTable.Cursor()
if m.awsSelectedRow != awsCurrentRow {
m.awsSelectedRow = awsCurrentRow
// Update the viewport content based on the newly selected row
// Load the file for the selected account and show the file content in the main table
m.mainTable, m.detailsData, err = getRecordsForAccount(m.preloadedData.Files[m.awsAccountsTable.Rows()[awsCurrentRow][0]])
if err != nil {
// Handle error
break
}
m.mainTable.SetStyles(s)
m.mainTableViewport.SetContent(m.mainTable.View())
m.detailsViewport.SetContent(m.detailsData[0])
}
case 1:
m.mainTable, cmd = m.mainTable.Update(msg)
// Check if the selected row has changed
m.mainTableViewport.SetContent(m.mainTable.View())
mainCurrentRow = m.mainTable.Cursor()
if m.mainSelectedRow != mainCurrentRow {
m.mainSelectedRow = mainCurrentRow
// Update the viewport content based on the newly selected row
if detail, ok := m.detailsData[m.mainSelectedRow]; ok {
m.detailsViewport.SetContent(detail)
} else {
m.detailsViewport.SetContent(fmt.Sprintf("No details available for main row %d (aws row %d)", m.mainSelectedRow, m.awsSelectedRow))
}
}
case 2:
m.detailsViewport, cmd = m.detailsViewport.Update(msg)
}
}
return m, cmd
}
func (m model) View() string {
// Define styles for active and inactive viewports
activeBorderStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("#00FFFF")). // Cyan for active
Padding(0)
activeBorderStyle.PaddingLeft(1)
activeBorderStyle.PaddingRight(1)
inactiveBorderStyle := lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("#808080")). // Gray for inactive
Padding(0)
inactiveBorderStyle.PaddingLeft(1)
inactiveBorderStyle.PaddingRight(1)
// Conditionally apply border styles based on focus
awsTableViewStyle := activeBorderStyle
m.awsAccountsTable.SetStyles(m.defaultTableStyle)
tableViewStyle := inactiveBorderStyle
m.mainTable.SetStyles(m.defaultTableStyle)
detailsViewStyle := inactiveBorderStyle
switch m.focusSelector {
case 0:
awsTableViewStyle = activeBorderStyle
m.awsAccountsTable.SetStyles(m.defaultTableStyle)
tableViewStyle = inactiveBorderStyle
detailsViewStyle = inactiveBorderStyle
case 1:
awsTableViewStyle = inactiveBorderStyle
tableViewStyle = activeBorderStyle
m.mainTable.SetStyles(m.defaultTableStyle)
detailsViewStyle = inactiveBorderStyle
case 2:
awsTableViewStyle = inactiveBorderStyle
tableViewStyle = inactiveBorderStyle
detailsViewStyle = activeBorderStyle
}
// Render the table and details viewports with their styles (adjust based on focus)
awsAccountsView := awsTableViewStyle.Render(m.awsAccountsViewport.View())
tableView := tableViewStyle.Render(m.mainTableViewport.View())
detailsView := detailsViewStyle.Render(m.detailsViewport.View())
// Combine all views
fullView := lipgloss.JoinVertical(lipgloss.Top, awsAccountsView, tableView, detailsView)
helpView := m.help.View(m.keys)
return fmt.Sprintf("%s\n%s", fullView, helpView)
}
func calculateMaxWidths(rows []table.Row) []int {
var maxWidths []int
// make sure the length of the rows is greater than 0
if len(rows) > 0 {
maxWidths = make([]int, len(rows[0]))
} else {
maxWidths = []int{30, 30, 30, 30}
}
for _, row := range rows {
for i, cell := range row {
if len(cell) > maxWidths[i] {
maxWidths[i] = len(cell)
}
}
}
return maxWidths
}
func (m model) footerView() string {
info := infoStyle.Render(fmt.Sprintf("%3.f%%", m.detailsViewport.ScrollPercent()*100))
line := strings.Repeat("─", max(0, m.detailsViewport.Width-lipgloss.Width(info)))
return lipgloss.JoinHorizontal(lipgloss.Center, line, info)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func loadFileRecords(filePath string) (*PerAccountData, error) {
// Open the file
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
// Decode the JSON data
var records []CapeJSON
decoder := json.NewDecoder(file)
if err := decoder.Decode(&records); err != nil {
return nil, err
}
// Return a new FileRecords instance
return &PerAccountData{
FilePath: filePath,
PrivescPaths: records,
}, nil
}
func preloadData(filePaths []string) (*AllAccountData, error) {
appData := &AllAccountData{
Files: make(map[string]*PerAccountData),
}
for _, filePath := range filePaths {
fileRecords, err := loadFileRecords(filePath)
if err != nil {
return nil, err
}
appData.Files[filePath] = fileRecords
}
return appData, nil
}
func getRecordsForAccount(preloadedData *PerAccountData) (table.Model, map[int]string, error) {
// lets load the records for the first file in the list
records := preloadedData.PrivescPaths
if len(records) < 1 {
mainTable := table.New(
table.WithColumns([]table.Column{
{Title: "Account", Width: 30},
{Title: "Source", Width: 30},
{Title: "Target", Width: 30},
{Title: "isTargetAdmin", Width: 30},
}),
table.WithRows([]table.Row{{"No records found", "", "", ""}}),
table.WithFocused(true),
)
return mainTable, nil, nil
}
// Prepare rows for the table and data for the right view
rows := make([]table.Row, 0, len(records)-1)
detailsData := make(map[int]string) // Initialize the map for the fourth column's data
for i, record := range records[1:] { // Skip the header row
rows = append(rows, table.Row{record.Account, record.Source, record.Target, record.IsTargetAdmin})
detailsData[i] = expandDetailsData(record.Summary)
}
// Calculate max widths
maxWidths := calculateMaxWidths(rows)
// Define columns with calculated widths
columns := make([]table.Column, len(maxWidths))
colNames := []string{}
for _, header := range []string{"Account", "Source", "Target", "isTargetAdmin"} {
colNames = append(colNames, header)
}
for i, width := range maxWidths {
colName := colNames[i]
// if column name width is greater than the calculated width, use the column name width
if len(colName) > width {
width = len(colName)
}
columns[i] = table.Column{
Title: colName,
Width: width,
}
}
mainTable := table.New(
table.WithColumns(columns),
table.WithRows(rows),
table.WithFocused(true),
)
return mainTable, detailsData, nil
}
func CapeTUI(outputFiles []string) {
preloadData, err := preloadData(outputFiles)
if err != nil {
fmt.Printf("Error preloading data: %s\n", err)
fmt.Println("Either remove this profile from the list of profiles, or make sure cape can run successfully for this profile")
os.Exit(1)
}
var awsAccountsRows []table.Row
for _, file := range preloadData.Files {
// Extract a user-friendly account name from the file path if needed
// For simplicity, here we use the file path itself
awsAccountsRows = append(awsAccountsRows, table.Row{file.FilePath})
}
mainTable, detailsData, err := getRecordsForAccount(preloadData.Files[outputFiles[0]])
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
BorderBottom(true).
Bold(false)
s.Selected = s.Selected.
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Bold(false)
awsAccountsWidth := calculateMaxWidths(awsAccountsRows)
awsAccountsTable := table.New(
table.WithColumns([]table.Column{
{Title: "AWS Accounts", Width: awsAccountsWidth[0]},
}),
table.WithRows(awsAccountsRows),
table.WithFocused(true), // Initially unfocused
)
awsAccountsTable.SetStyles(s)
awsAccountsViewport := viewport.New(0, 0) // Initialize with 0 size; will be updated
awsAccountsViewport.SetContent(awsAccountsTable.View()) // Set initial content
mainTable.SetStyles(s)
mainTableViewport := viewport.New(0, 0) // Initialize with 0 size; it will be updated
mainTableViewport.SetContent(mainTable.View()) // Set the initial content of the table viewport
// Initialize viewport for details view
detailsViewportModel := viewport.New(0, 0) // Size will be set based on terminal size in Update
// show the first row's details by default
detailsViewportModel.SetContent(detailsData[0])
m := model{
preloadedData: preloadData,
awsAccountsTable: awsAccountsTable,
awsAccountsViewport: awsAccountsViewport,
mainTable: mainTable,
mainTableViewport: mainTableViewport,
detailsData: detailsData,
detailsViewport: detailsViewportModel,
//focusOnTable: true,
focusSelector: 0,
mainSelectedRow: 0, // Initialize selectedRow with an invalid index
awsSelectedRow: 0,
defaultTableStyle: s,
keys: keys,
help: help.New(),
}
p := tea.NewProgram(m)
if err := p.Start(); err != nil {
fmt.Printf("Error starting program: %s\n", err)
os.Exit(1)
}
}
// keyMap defines a set of keybindings. To work for help it must satisfy
// key.Map. It could also very easily be a map[string]key.Binding.
type keyMap struct {
Up key.Binding
Down key.Binding
Left key.Binding
Right key.Binding
Help key.Binding
Quit key.Binding
Tab key.Binding
ShiftTab key.Binding
}
// ShortHelp returns keybindings to be shown in the mini help view. It's part
// of the key.Map interface.
func (k keyMap) ShortHelp() []key.Binding {
return []key.Binding{k.Tab, k.ShiftTab, k.Up, k.Down, k.Help, k.Quit}
}
// FullHelp returns keybindings for the expanded help view. It's part of the
// key.Map interface.
func (k keyMap) FullHelp() [][]key.Binding {
return [][]key.Binding{
{k.Up, k.Down, k.Left, k.Right}, // first column
{k.Tab, k.ShiftTab, k.Help, k.Quit}, // second column
}
}
var keys = keyMap{
Up: key.NewBinding(
key.WithKeys("up", "k"),
key.WithHelp("↑/k", "move up"),
),
Down: key.NewBinding(
key.WithKeys("down", "j"),
key.WithHelp("↓/j", "move down"),
),
Left: key.NewBinding(
key.WithKeys("left", "h"),
key.WithHelp("←/h", "move left"),
),
Right: key.NewBinding(
key.WithKeys("right", "l"),
key.WithHelp("→/l", "move right"),
),
Help: key.NewBinding(
key.WithKeys("?"),
key.WithHelp("?", "toggle help"),
),
Quit: key.NewBinding(
key.WithKeys("q", "esc", "ctrl+c"),
key.WithHelp("q", "quit"),
),
Tab: key.NewBinding(
key.WithKeys("tab"),
key.WithHelp("tab", "Switch window focus"),
),
ShiftTab: key.NewBinding(
key.WithKeys("shift+tab"),
key.WithHelp("shift+tab", "Switch window focus"),
),
}
func expandDetailsData(input string) string {
output := ""
lines := strings.Split(input, "\n")
for _, line := range lines {
var hop, option int
var rest string
// Use Sscanf to extract hop and option values
n, err := fmt.Sscanf(line, "[Hop: %d] [Option: %d]", &hop, &option)
if err != nil || n != 2 {
fmt.Printf("Error parsing line, expected 2 got %d: %v\n", n, err)
continue
}
// Extract the rest of the line manually
restIndex := strings.Index(line, "]") + 1
restIndex = strings.Index(line[restIndex:], "]") + restIndex + 1
if restIndex > 1 && restIndex < len(line) {
rest = line[restIndex+1:] // +1 to skip the space after the second ]
}
// Construct the formatted output
formattedLine := fmt.Sprintf("[Hop: %d][Option: %d]\n\t%s\n\n", hop, option, rest)
output += formattedLine
}
return output
}
+981
View File
@@ -0,0 +1,981 @@
package aws
import (
"fmt"
"path/filepath"
"strings"
"github.com/BishopFox/cloudfox/internal"
"github.com/BishopFox/cloudfox/internal/aws/policy"
"github.com/BishopFox/cloudfox/internal/common"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/bishopfox/knownawsaccountslookup"
"github.com/dominikbraun/graph"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type CapeCommand struct {
// General configuration data
Cmd cobra.Command
Caller sts.GetCallerIdentityOutput
AWSRegions []string
Goroutines int
AWSProfile string
WrapTable bool
AWSOutputType string
AWSTableCols string
Verbosity int
AWSOutputDirectory string
AWSConfig aws.Config
Version string
SkipAdminCheck bool
GlobalGraph graph.Graph[string, string]
PmapperDataBasePath string
AnalyzedAccounts map[string]CapeJobInfo
CapeAdminOnly bool
AccountsNotAnalyzed []string
output internal.OutputData2
modLog *logrus.Entry
}
type CapeJobInfo struct {
AccountID string
Profile string
AnalyzedSuccessfully bool
AdminOnlyAnalysis bool
Source string
}
func (m *CapeCommand) RunCapeCommand() {
// These struct values are used by the output module
m.output.Verbosity = m.Verbosity
m.output.Directory = m.AWSOutputDirectory
m.output.CallingModule = "cape"
m.modLog = internal.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = internal.BuildAWSPath(m.Caller)
}
m.output.FilePath = filepath.Join(m.AWSOutputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", m.AWSProfile, aws.ToString(m.Caller.Account)))
o := internal.OutputClient{
Verbosity: m.Verbosity,
CallingModule: m.output.CallingModule,
Table: internal.TableClient{
Wrap: m.WrapTable,
},
}
o.PrefixIdentifier = m.AWSProfile
o.Table.DirectoryName = filepath.Join(m.AWSOutputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", m.AWSProfile, aws.ToString(m.Caller.Account)))
// Table #1: Inbound Privilege Escalation Paths
fmt.Printf("[%s][%s] Printing inbound privesc paths for account: %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
if !m.CapeAdminOnly {
fmt.Printf("[%s][%s] This can take a really long time if the number of vertices/edges is in the thousands. Consider stopping here and re-running cape with --admin-only to speed this step up!\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
} else {
fmt.Printf("[%s][%s] This can take a really long time if the number of vertices/edges is in the thousands.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
header, body, _ := m.generateInboundPrivEscTableData()
var fileName string
if m.CapeAdminOnly {
fileName = "inbound-privesc-paths-admin-targets-only"
} else {
fileName = "inbound-privesc-paths-all-targets"
}
o.Table.TableFiles = append(o.Table.TableFiles, internal.TableFile{
Header: header,
Body: body,
//TableCols: tableCols,
Name: fileName,
SkipPrintToScreen: false,
})
// // Table #2: Outbound Privilege Escalation Paths
// header, body, tableCols := m.generateOutBoundPrivEscTable()
// o.Table.TableFiles = append(o.Table.TableFiles, internal.TableFile{
// Header: header,
// Body: body,
// TableCols: tableCols,
// Name: "outbound-privesc-paths",
// SkipPrintToScreen: false,
// })
o.WriteFullOutput(o.Table.TableFiles, nil)
fmt.Println("The following accounts are trusted by this account, but were not analyzed as part of this run.")
fmt.Println("As a result, we cannot determine which principals in these accounts have permission to assume roles in this account.")
// for account := range m.AnalyzedAccounts {
// if m.AnalyzedAccounts[account].AnalyzedSuccessfully == false {
// fmt.Println("\t\t" + account)
// }
// }
for _, account := range m.AccountsNotAnalyzed {
fmt.Println("\t\t" + account)
}
}
func (m *CapeCommand) generateInboundPrivEscTableData() ([]string, [][]string, []string) {
var body [][]string
var tableCols []string
var header []string
header = []string{
"Account",
"Source",
"Target",
"isTargetAdmin",
"Summary",
}
// If the user specified table columns, use those.
// If the user specified -o wide, use the wide default cols for this module.
// Otherwise, use the hardcoded default cols for this module.
// If the user specified table columns, use those.
if m.AWSTableCols != "" {
tableCols = strings.Split(m.AWSTableCols, ",")
// If the user specified wide as the output format, use these columns.
} else if m.AWSOutputType == "wide" {
tableCols = []string{
"Account",
"Source",
"Target",
"isTargetAdmin",
"Summary",
}
// Otherwise, use these columns.
} else {
tableCols = []string{
"Source",
"Target",
"isTargetAdmin",
"Summary",
}
}
var privescPathsBody [][]string
allGlobalNodes, _ := m.GlobalGraph.AdjacencyMap()
for destination := range allGlobalNodes {
d, destinationVertexWithProperties, _ := m.GlobalGraph.VertexWithProperties(destination)
// if the user specified the CapeAdminOnly flag, then we only want to show paths to admin roles
if m.CapeAdminOnly {
// if the user specified the CapeAdminOnly flag, then we only want to show paths to admin roles
if destinationVertexWithProperties.Attributes["IsAdminString"] == "Yes" {
//for the destination vertex, we only want to deal with the ones that are in this account
if destinationVertexWithProperties.Attributes["AccountID"] == aws.ToString(m.Caller.Account) {
privescPathsBody = m.findPathsToThisDestination(allGlobalNodes, d, destinationVertexWithProperties)
body = append(body, privescPathsBody...)
}
}
} else {
//for the destination vertex, we only want to deal with the ones that are in this account
if destinationVertexWithProperties.Attributes["AccountID"] == aws.ToString(m.Caller.Account) {
privescPathsBody := m.findPathsToThisDestination(allGlobalNodes, d, destinationVertexWithProperties)
body = append(body, privescPathsBody...)
}
}
}
body = append(body, privescPathsBody...)
return header, body, tableCols
}
func (m *CapeCommand) findPathsToThisDestination(allGlobalNodes map[string]map[string]graph.Edge[string], d string, destinationVertexWithProperties graph.VertexProperties) [][]string {
var privescPathsBody [][]string
var paths string
// now let's look at every other vertex and see if it has a path to this destination
for source := range allGlobalNodes {
s, sourceVertexWithProperties, _ := m.GlobalGraph.VertexWithProperties(source)
//for the source vertex, we only want to deal with the ones that are NOT in this account
if sourceVertexWithProperties.Attributes["AccountID"] != aws.ToString(m.Caller.Account) {
// now let's see if there is a path from this source to our destination
path, _ := graph.ShortestPath(m.GlobalGraph, s, d)
// if we have a path, then lets document this source as having a path to our destination
if path != nil {
if s != d {
fmt.Printf("[%s][%s] Found a path from %s to %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), s, d)
// check to see if the source account was analyzed. If not, lets add it to the list of accounts that were not analyzed
if strings.Contains(s, "Not analyzed/in-scope") {
// add it to the m.AccountsNotAnalyzed if it doesn't already exist
if !internal.Contains(s, m.AccountsNotAnalyzed) {
m.AccountsNotAnalyzed = append(m.AccountsNotAnalyzed, s)
}
}
paths = ""
// if we got here there's a path. Lets print the reason and the short reason for each edge in the path to the screen
// and then lets print the full path to the screen
for i := 0; i < len(path)-1; i++ {
thisEdge, _ := m.GlobalGraph.Edge(path[i], path[i+1])
j := 0
for _, value := range thisEdge.Properties.Attributes {
value = strings.ReplaceAll(value, ",", " and")
paths += fmt.Sprintf("[Hop: %d] [Option: %d] [%s] [%s] [%s]\n", i, j, thisEdge.Source, value, thisEdge.Target)
j++
}
}
//trim the last newline from csvPaths
paths = strings.TrimSuffix(paths, "\n")
if destinationVertexWithProperties.Attributes["IsAdminString"] == "Yes" {
privescPathsBody = append(privescPathsBody, []string{
aws.ToString(m.Caller.Account),
s,
magenta(d),
magenta(destinationVertexWithProperties.Attributes["IsAdminString"]),
paths})
} else {
privescPathsBody = append(privescPathsBody, []string{
aws.ToString(m.Caller.Account),
s,
d,
destinationVertexWithProperties.Attributes["IsAdminString"],
paths})
}
}
}
}
}
return privescPathsBody
}
func ConvertIAMRoleToNode(role types.Role, vendors *knownawsaccountslookup.Vendors, analyzedAccounts map[string]CapeJobInfo) Node {
//var isAdmin, canPrivEscToAdmin string
accountId := strings.Split(aws.ToString(role.Arn), ":")[4]
trustsdoc, err := policy.ParseRoleTrustPolicyDocument(role)
if err != nil {
internal.TxtLog.Error(err.Error())
return Node{}
}
var TrustedPrincipals []TrustedPrincipal
var TrustedServices []TrustedService
var TrustedFederatedProviders []TrustedFederatedProvider
//var TrustedFederatedSubjects string
var trustedProvider string
var trustedSubjects []string
var vendorName string
var isAnalyzedAccount bool
for _, statement := range trustsdoc.Statement {
for _, principal := range statement.Principal.AWS {
if strings.Contains(principal, ":root") {
//check to see if the trustedRootAccountID is known
trustedRootAccountID := strings.Split(principal, ":")[4]
vendorName = vendors.GetVendorNameFromAccountID(trustedRootAccountID)
// check to see if trustedRootAccountID is in the m.AnalyzedAccounts map
if _, ok := analyzedAccounts[trustedRootAccountID]; ok {
isAnalyzedAccount = analyzedAccounts[trustedRootAccountID].AnalyzedSuccessfully
} else {
isAnalyzedAccount = false
}
}
TrustedPrincipals = append(TrustedPrincipals, TrustedPrincipal{
TrustedPrincipal: principal,
ExternalID: statement.Condition.StringEquals.StsExternalID,
VendorName: vendorName,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
AccountIsInAnalyzedAccountList: isAnalyzedAccount,
})
}
for _, service := range statement.Principal.Service {
TrustedServices = append(TrustedServices, TrustedService{
TrustedService: service,
AccountID: accountId,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
})
}
for _, federated := range statement.Principal.Federated {
// provider accountID
//accountId := strings.Split(federated, ":")[4]
trustedProvider, trustedSubjects = parseFederatedTrustPolicy(statement)
TrustedFederatedProviders = append(TrustedFederatedProviders, TrustedFederatedProvider{
TrustedFederatedProvider: federated,
ProviderShortName: trustedProvider,
//ProviderAccountId: accountId,
TrustedSubjects: trustedSubjects,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
})
}
}
node := Node{
Arn: aws.ToString(role.Arn),
Type: "Role",
AccountID: accountId,
Name: aws.ToString(role.RoleName),
TrustsDoc: trustsdoc,
TrustedPrincipals: TrustedPrincipals,
TrustedServices: TrustedServices,
TrustedFederatedProviders: TrustedFederatedProviders,
}
return node
}
func ConvertIAMUserToNode(user types.User) Node {
accountId := strings.Split(aws.ToString(user.Arn), ":")[4]
node := Node{
Arn: aws.ToString(user.Arn),
Type: "User",
AccountID: accountId,
Name: aws.ToString(user.UserName),
}
return node
}
func FindVerticesInRoleTrust(a Node, vendors *knownawsaccountslookup.Vendors) []Node {
var newNodes []Node
// get thisAccount id from role arn
// var thisAccount string
// if len(a.Arn) >= 25 {
// thisAccount = a.Arn[13:25]
// } else {
// fmt.Sprintf("Could not get account number from this role arn%s", a.Arn)
// }
for _, TrustedPrincipal := range a.TrustedPrincipals {
//get account id from the trusted principal arn
var trustedPrincipalAccount string
if len(TrustedPrincipal.TrustedPrincipal) >= 25 {
trustedPrincipalAccount = TrustedPrincipal.TrustedPrincipal[13:25]
} else {
fmt.Sprintf("Could not get account number from this TrustedPrincipal%s", TrustedPrincipal.TrustedPrincipal)
}
// If the role trusts a principal in this account or another account using the :root notation, then we need to iterate over all of the rows in AllPermissionsRows to find the principals that have sts:AssumeRole permissions on this role
// if the role we are looking at trusts root in it's own account
// if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", thisAccount)) {
// newNodes = append(newNodes, Node{
// Arn: a.Arn,
// Type: "Account",
// AccountID: a.AccountID,
// Name: a.Name,
// })
// } else
if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && TrustedPrincipal.VendorName != "" {
// First lets take care of vendor accounts
newNodes = append(newNodes, Node{
Arn: fmt.Sprintf("%s [%s]", TrustedPrincipal.VendorName, TrustedPrincipal.TrustedPrincipal),
//Arn: TrustedPrincipal.VendorName,
Type: "Account",
AccountID: trustedPrincipalAccount,
Name: TrustedPrincipal.VendorName,
VendorName: TrustedPrincipal.VendorName,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && !TrustedPrincipal.AccountIsInAnalyzedAccountList {
// Next lets take care of accounts that are not in the analyzed account list and add the full :root as the node
newNodes = append(newNodes, Node{
Arn: fmt.Sprintf("%s [Not analyzed/in-scope]", TrustedPrincipal.TrustedPrincipal),
Type: "Account",
AccountID: trustedPrincipalAccount,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && TrustedPrincipal.VendorName == "" {
// Now with those out of the way, lets take care of the accounts that are in the analyzed account list
newNodes = append(newNodes, Node{
Arn: TrustedPrincipal.TrustedPrincipal,
Type: "Account",
AccountID: trustedPrincipalAccount,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf(":user")) {
newNodes = append(newNodes, Node{
Arn: TrustedPrincipal.TrustedPrincipal,
Type: "User",
AccountID: trustedPrincipalAccount,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf(":role")) {
newNodes = append(newNodes, Node{
Arn: TrustedPrincipal.TrustedPrincipal,
Type: "Role",
AccountID: trustedPrincipalAccount,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf(":group")) {
newNodes = append(newNodes, Node{
Arn: TrustedPrincipal.TrustedPrincipal,
Type: "Group",
AccountID: trustedPrincipalAccount,
})
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf(":assumed-role")) {
newNodes = append(newNodes, Node{
Arn: TrustedPrincipal.TrustedPrincipal,
Type: "AssumedRole",
AccountID: trustedPrincipalAccount,
})
}
}
// pmapper takes care of this part so commenting out for now - but leaving as a placeholder
// for _, TrustedService := range a.TrustedServices {
// // make relationship from trusted service to this role of type can assume
// // make relationship from this role to trusted service of type can be assumed by
// }
for _, TrustedFederatedProvider := range a.TrustedFederatedProviders {
// make relationship from trusted federated provider to this role of type can assume
var providerAndSubject string
for _, trustedSubject := range TrustedFederatedProvider.TrustedSubjects {
if trustedSubject == "Not applicable" {
providerAndSubject = TrustedFederatedProvider.ProviderShortName
} else {
//providerAndSubject = TrustedFederatedProvider.ProviderShortName + ":" + trustedSubject
providerAndSubject = fmt.Sprintf("%s [%s]", TrustedFederatedProvider.ProviderShortName, trustedSubject)
}
//fmt.Println("TrustedFederatedProvider: ", TrustedFederatedProvider.TrustedFederatedProvider)
// if the TrustedFederatedProvider.TrustedFederatedProvider is an arn (check to see if it has at least 4 semicolons), grab the account id. Otherwise, use a.AccountID
var accountID string
if strings.Count(TrustedFederatedProvider.TrustedFederatedProvider, ":") >= 4 {
accountID = strings.Split(TrustedFederatedProvider.TrustedFederatedProvider, ":")[4]
} else {
accountID = a.AccountID
}
newNodes = append(newNodes, Node{
Arn: providerAndSubject,
Name: TrustedFederatedProvider.ProviderShortName,
Type: "FederatedIdentity",
AccountID: accountID,
})
}
}
return newNodes
}
func MergeNodes(nodes []Node) []Node {
nodeMap := make(map[string]Node)
for _, node := range nodes {
existingNode, exists := nodeMap[node.Arn]
if exists {
// fmt.Println("Found a duplicate node: %s, merging", node.Arn)
// fmt.Println("Existing node: %v", existingNode)
// fmt.Println("New node: %v", node)
mergedNode := mergeNodeData(existingNode, node)
nodeMap[node.Arn] = mergedNode
//fmt.Println("Merged node: %v", mergedNode)
} else {
nodeMap[node.Arn] = node
}
}
var mergedNodes []Node
for _, node := range nodeMap {
mergedNodes = append(mergedNodes, node)
}
return mergedNodes
}
func mergeNodeData(existingNode Node, newNode Node) Node {
if existingNode.Arn == "" {
existingNode.Arn = newNode.Arn
} else {
existingNode.Arn = existingNode.Arn
}
if existingNode.Name == "" {
existingNode.Name = newNode.Name
} else {
existingNode.Name = existingNode.Name
}
if existingNode.Type == "" {
existingNode.Type = newNode.Type
} else {
existingNode.Type = existingNode.Type
}
if existingNode.AccountID == "" {
existingNode.AccountID = newNode.AccountID
} else {
existingNode.AccountID = existingNode.AccountID
}
if existingNode.CanPrivEscToAdminString == "" {
existingNode.CanPrivEscToAdminString = newNode.CanPrivEscToAdminString
} else {
existingNode.CanPrivEscToAdminString = existingNode.CanPrivEscToAdminString
}
if existingNode.IsAdminString == "" {
existingNode.IsAdminString = newNode.IsAdminString
} else {
existingNode.IsAdminString = existingNode.IsAdminString
}
if existingNode.VendorName == "" {
existingNode.VendorName = newNode.VendorName
} else {
existingNode.VendorName = existingNode.VendorName
}
if existingNode.AccessKeys == 0 {
existingNode.AccessKeys = newNode.AccessKeys
} else {
existingNode.AccessKeys = existingNode.AccessKeys
}
if existingNode.ActivePassword == false {
existingNode.ActivePassword = newNode.ActivePassword
} else {
existingNode.ActivePassword = existingNode.ActivePassword
}
if existingNode.HasMfa == false {
existingNode.HasMfa = newNode.HasMfa
} else {
existingNode.HasMfa = existingNode.HasMfa
}
if existingNode.PathToAdmin == false {
existingNode.PathToAdmin = newNode.PathToAdmin
} else {
existingNode.PathToAdmin = existingNode.PathToAdmin
}
if existingNode.AttachedPolicies == nil {
existingNode.AttachedPolicies = newNode.AttachedPolicies
} else {
existingNode.AttachedPolicies = existingNode.AttachedPolicies
}
if existingNode.TrustedFederatedProviders == nil {
existingNode.TrustedFederatedProviders = newNode.TrustedFederatedProviders
} else {
existingNode.TrustedFederatedProviders = existingNode.TrustedFederatedProviders
}
if existingNode.TrustedPrincipals == nil {
existingNode.TrustedPrincipals = newNode.TrustedPrincipals
} else {
existingNode.TrustedPrincipals = existingNode.TrustedPrincipals
}
if existingNode.TrustedServices == nil {
existingNode.TrustedServices = newNode.TrustedServices
} else {
existingNode.TrustedServices = existingNode.TrustedServices
}
// if existingNode.TrustsDoc.Statement == nil {
// existingNode.TrustsDoc = newNode.TrustsDoc
// } else {
// }
return existingNode
}
func (a *Node) MakeRoleEdges(GlobalGraph graph.Graph[string, string]) {
// get thisAccount id from role arn
var thisAccount string
if len(a.Arn) >= 25 {
thisAccount = a.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this role arn%s", a.Arn)
}
for _, TrustedPrincipal := range a.TrustedPrincipals {
//get account id from the trusted principal arn
var trustedPrincipalAccount string
if len(TrustedPrincipal.TrustedPrincipal) >= 25 {
trustedPrincipalAccount = TrustedPrincipal.TrustedPrincipal[13:25]
} else {
fmt.Sprintf("Could not get account number from this TrustedPrincipal%s", TrustedPrincipal.TrustedPrincipal)
}
var PermissionsRowAccount string
// if the role trusts a principal in this same account explicitly, then the principal can assume the role
if thisAccount == trustedPrincipalAccount {
// make a CAN_ASSUME relationship between the trusted principal and this role
err := GlobalGraph.AddEdge(
TrustedPrincipal.TrustedPrincipal,
a.Arn,
//graph.EdgeAttribute("AssumeRole", "Same account explicit trust"),
graph.EdgeAttribute("AssumeRole", "can assume (because of an explicit same account trust) "),
)
if err != nil {
//fmt.Println(err)
//fmt.Println(TrustedPrincipal.TrustedPrincipal + a.Arn + "Same account explicit trust")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
//fmt.Println("Edge already exists")
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(TrustedPrincipal.TrustedPrincipal, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["AssumeRole"] = "can assume (because of an explicit same account trust) "
err = GlobalGraph.UpdateEdge(
TrustedPrincipal.TrustedPrincipal,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
}
// If the role trusts a principal in this account or another account using the :root notation, then we need to iterate over all of the rows in AllPermissionsRows to find the principals that have sts:AssumeRole permissions on this role
// if the role we are looking at trusts root in it's own account
if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", thisAccount)) {
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == thisAccount {
// lets only look for rows that have sts:AssumeRole permissions
if policy.MatchesAfterExpansion(PermissionsRow.Action, "sts:AssumeRole") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.Arn) {
// make a CAN_ASSUME relationship between the trusted principal and this role
//evaluate if the principal is a user or a role and set a variable accordingly
//var principalType schema.NodeLabel
if strings.EqualFold(PermissionsRow.Type, "User") || strings.EqualFold(PermissionsRow.Type, "Role") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Arn,
//graph.EdgeAttribute("AssumeRole", "Same account root trust and trusted principal has permission to assume role"),
graph.EdgeAttribute("AssumeRole", "can assume (because of a same account root trust and trusted principal has permission to assume role) "),
)
if err != nil {
// fmt.Println(err)
// fmt.Println(PermissionsRow.Arn + a.Arn + "Same account root trust and trusted principal has permission to assume role")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(PermissionsRow.Arn, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["AssumeRole"] = "can assume (because of a same account root trust and trusted principal has permission to assume role) "
err = GlobalGraph.UpdateEdge(
PermissionsRow.Arn,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
}
}
}
if strings.EqualFold(PermissionsRow.Effect, "Deny") {
// if the action is deny, we need to remove any edges between PermissionsRow.Arn and a.Arn
// if the edge exists, remove it
err := GlobalGraph.RemoveEdge(PermissionsRow.Arn, a.Arn)
if err != nil {
fmt.Println(err)
}
}
}
}
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && TrustedPrincipal.VendorName != "" {
// If the role trusts :root in another account and the trusted principal is a vendor, we will make a relationship between our role and a vendor node instead of a principal node
err := GlobalGraph.AddEdge(
//TrustedPrincipal.TrustedPrincipal,
//TrustedPrincipal.VendorName,
fmt.Sprintf("%s [%s]", TrustedPrincipal.VendorName, TrustedPrincipal.TrustedPrincipal),
a.Arn,
//graph.EdgeAttribute("VendorAssumeRole", "Cross account root trust and trusted principal is a vendor"),
graph.EdgeAttribute("VendorAssumeRole", "can assume (because of a cross account root trust and trusted principal is a vendor) "),
)
if err != nil {
// fmt.Println(err)
// fmt.Println(TrustedPrincipal.VendorName + a.Arn + "Cross account root trust and trusted principal is a vendor")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(TrustedPrincipal.VendorName, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["VendorAssumeRole"] = "can assume (because of a cross account root trust and trusted principal is a vendor) "
err := GlobalGraph.UpdateEdge(
//fmt.Sprintf("%s-%s", a.Arn, TrustedPrincipal.VendorName),
TrustedPrincipal.TrustedPrincipal,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", trustedPrincipalAccount)) && !TrustedPrincipal.AccountIsInAnalyzedAccountList {
// first lets check to see if the trustedRootAccountID is in the map of analzyeddAccounts
// if it is not, we can't iterate over the permissions, so we will just have to create an edge :root princpal and this role
err := GlobalGraph.AddEdge(
//TrustedPrincipal.TrustedPrincipal,
fmt.Sprintf("%s [Not analyzed/in-scope]", TrustedPrincipal.TrustedPrincipal),
a.Arn,
//graph.EdgeAttribute("CrossAccountRootTrust", "Cross account root trust and trusted principal is not in the analyzed account list"),
graph.EdgeAttribute("CrossAccountRootTrust", "can assume (because of a cross account root trust and trusted principal is not in the analyzed account list) "),
)
if err != nil {
// fmt.Println(err)
// fmt.Println(TrustedPrincipal.TrustedPrincipal + a.Arn + "Cross account root trust and trusted principal is not in the analyzed account list")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(TrustedPrincipal.TrustedPrincipal, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["CrossAccountRootTrust"] = "can assume (because of a cross account root trust and trusted principal is not in the analyzed account list) "
err := GlobalGraph.UpdateEdge(
TrustedPrincipal.TrustedPrincipal,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", trustedPrincipalAccount)) {
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this other account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == trustedPrincipalAccount {
// lets only look for rows that have sts:AssumeRole permissions
if policy.MatchesAfterExpansion(PermissionsRow.Action, "sts:AssumeRole") {
// if strings.EqualFold(PermissionsRow.Action, "sts:AssumeRole") ||
// strings.EqualFold(PermissionsRow.Action, "*") ||
// strings.EqualFold(PermissionsRow.Action, "sts:Assume*") ||
// strings.EqualFold(PermissionsRow.Action, "sts:*") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.Arn) {
// make a CAN_ASSUME relationship between the trusted principal and this role
if strings.EqualFold(PermissionsRow.Type, "User") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Arn,
//graph.EdgeAttribute("CrossAccountAssumeRole", "Cross account root trust and trusted principal has permission to assume role"),
graph.EdgeAttribute("CrossAccountAssumeRole", "can assume (because of a cross account root trust and trusted principal has permission to assume role) "),
)
if err != nil {
//fmt.Println(err)
//fmt.Println(PermissionsRow.Arn + a.Arn + "Cross account root trust and trusted principal has permission to assume role")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(PermissionsRow.Arn, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["CrossAccountAssumeRole"] = "can assume (because of a cross account root trust and trusted principal has permission to assume role) "
err = GlobalGraph.UpdateEdge(
PermissionsRow.Arn,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
} else if strings.EqualFold(PermissionsRow.Type, "Role") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Arn,
//graph.EdgeAttribute("CrossAccountAssumeRole", "Cross account root trust and trusted principal has permission to assume role"),
graph.EdgeAttribute("CrossAccountAssumeRole", "can assume (because of a cross account root trust and trusted principal has permission to assume role) "),
)
if err != nil {
//fmt.Println(err)
//fmt.Println(PermissionsRow.Arn + a.Arn + "Cross account root trust and trusted principal has permission to assume role")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(PermissionsRow.Arn, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["CrossAccountAssumeRole"] = "can assume (because of a cross account root trust and trusted principal has permission to assume role) "
err = GlobalGraph.UpdateEdge(
PermissionsRow.Arn,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
}
}
}
if strings.EqualFold(PermissionsRow.Effect, "Deny") {
// if the action is deny, we need to remove any edges between PermissionsRow.Arn and a.Arn
// if the edge exists, remove it
err := GlobalGraph.RemoveEdge(PermissionsRow.Arn, a.Arn)
if err != nil {
fmt.Println(err)
}
}
}
}
}
}
}
// pmapper takes care of this part so commenting out for now - but leaving as a placeholder
// for _, TrustedService := range a.TrustedServices {
// // make relationship from trusted service to this role of type can assume
// // make relationship from this role to trusted service of type can be assumed by
// }
for _, TrustedFederatedProvider := range a.TrustedFederatedProviders {
// make relationship from trusted federated provider to this role of type can assume
var providerAndSubject string
for _, trustedSubject := range TrustedFederatedProvider.TrustedSubjects {
if trustedSubject == "Not applicable" {
providerAndSubject = TrustedFederatedProvider.ProviderShortName
} else {
//providerAndSubject = TrustedFederatedProvider.ProviderShortName + ":" + trustedSubject
providerAndSubject = fmt.Sprintf("%s [%s]", TrustedFederatedProvider.ProviderShortName, trustedSubject)
}
err := GlobalGraph.AddEdge(
providerAndSubject,
a.Arn,
//graph.EdgeAttribute("FederatedAssumeRole", "Trusted federated provider"),
graph.EdgeAttribute("FederatedAssumeRole", "can assume (because of a trusted federated provider) "),
)
if err != nil {
//fmt.Println(err)
//fmt.Println(TrustedFederatedProvider.TrustedFederatedProvider + a.Arn + "Trusted federated provider")
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(TrustedFederatedProvider.TrustedFederatedProvider, a.Arn)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes["FederatedAssumeRole"] = "can assume (because of a trusted federated provider) "
err = GlobalGraph.UpdateEdge(
providerAndSubject,
a.Arn,
graph.EdgeAttributes(existingProperties.Attributes),
)
if err != nil {
fmt.Println(err)
}
}
}
}
}
}
+23 -2
View File
@@ -3,11 +3,13 @@ package aws
import (
"github.com/BishopFox/cloudfox/aws/sdk"
"github.com/BishopFox/cloudfox/internal"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/codebuild"
"github.com/aws/aws-sdk-go-v2/service/ecr"
"github.com/aws/aws-sdk-go-v2/service/efs"
"github.com/aws/aws-sdk-go-v2/service/fsx"
"github.com/aws/aws-sdk-go-v2/service/glue"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/lambda"
"github.com/aws/aws-sdk-go-v2/service/organizations"
"github.com/aws/aws-sdk-go-v2/service/s3"
@@ -17,7 +19,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/sts"
)
func initIAMSimClient(iamSimPPClient sdk.AWSIAMClientInterface, caller sts.GetCallerIdentityOutput, AWSProfile string, Goroutines int) IamSimulatorModule {
func InitIamCommandClient(iamSimPPClient sdk.AWSIAMClientInterface, caller sts.GetCallerIdentityOutput, AWSProfile string, Goroutines int) IamSimulatorModule {
iamSimMod := IamSimulatorModule{
IAMClient: iamSimPPClient,
@@ -116,7 +118,7 @@ func InitFileSystemsClient(caller sts.GetCallerIdentityOutput, AWSProfile string
return fileSystemsClient
}
func InitOrgClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVersion string, Goroutines int, AWSMFAToken string) OrgModule {
func InitOrgsClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVersion string, Goroutines int, AWSMFAToken string) OrgModule {
var AWSConfig = internal.AWSConfigFileLoader(AWSProfile, cfVersion, AWSMFAToken)
orgClient := OrgModule{
OrganizationsClient: organizations.NewFromConfig(AWSConfig),
@@ -127,6 +129,17 @@ func InitOrgClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVers
return orgClient
}
func InitPermissionsClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVersion string, Goroutines int, AWSMFAToken string) IamPermissionsModule {
var AWSConfig = internal.AWSConfigFileLoader(AWSProfile, cfVersion, AWSMFAToken)
permissionsClient := IamPermissionsModule{
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: caller,
AWSProfile: AWSProfile,
AWSRegions: internal.GetEnabledRegions(AWSProfile, cfVersion, AWSMFAToken),
}
return permissionsClient
}
func InitSecretsManagerClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVersion string, Goroutines int, AWSMFAToken string) *secretsmanager.Client {
var AWSConfig = internal.AWSConfigFileLoader(AWSProfile, cfVersion, AWSMFAToken)
return secretsmanager.NewFromConfig(AWSConfig)
@@ -136,3 +149,11 @@ func InitGlueClient(caller sts.GetCallerIdentityOutput, AWSProfile string, cfVer
var AWSConfig = internal.AWSConfigFileLoader(AWSProfile, cfVersion, AWSMFAToken)
return glue.NewFromConfig(AWSConfig)
}
func InitOrgClient(AWSConfig aws.Config) *organizations.Client {
return organizations.NewFromConfig(AWSConfig)
}
func InitIAMClient(AWSConfig aws.Config) *iam.Client {
return iam.NewFromConfig(AWSConfig)
}
+7 -6
View File
@@ -19,10 +19,11 @@ type CodeBuildModule struct {
CodeBuildClient sdk.CodeBuildClientInterface
IAMClient sdk.AWSIAMClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
PmapperDataBasePath string
Goroutines int
AWSProfile string
@@ -64,8 +65,8 @@ func (m *CodeBuildModule) PrintCodeBuildProjects(outputDirectory string, verbosi
}
fmt.Printf("[%s][%s] Enumerating CodeBuild projects for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
+276
View File
@@ -0,0 +1,276 @@
package aws
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/BishopFox/cloudfox/aws/sdk"
"github.com/BishopFox/cloudfox/internal"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sts"
dsTypes "github.com/aws/aws-sdk-go-v2/service/directoryservice/types"
"github.com/bishopfox/awsservicemap"
"github.com/sirupsen/logrus"
)
type DirectoryModule struct {
// General configuration data
DSClient sdk.AWSDSClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSProfile string
Goroutines int
WrapTable bool
AWSOutputType string
AWSTableCols string
AWSMFAToken string
AWSConfig aws.Config
AWSProfileProvided string
AWSProfileStub string
CloudFoxVersion string
Directories []Directory
CommandCounter internal.CommandCounter
output internal.OutputData2
modLog *logrus.Entry
}
type Directory struct {
DirectoryId string
DNS string
NetBios string
AccessURL string
Alias string
OsVersion string
Region string
TrustInfo string
}
func (m *DirectoryModule) PrintDirectories(outputDirectory string, verbosity int) {
// These struct values are used by the output module
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "directory-services"
m.modLog = internal.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfileProvided == "" {
m.AWSProfileStub = internal.BuildAWSPath(m.Caller)
} else {
m.AWSProfileStub = m.AWSProfileProvided
}
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", m.AWSProfileProvided, aws.ToString(m.Caller.Account)))
fmt.Printf("[%s][%s] Enumerating Cloud Directories with resource policies for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfileStub), aws.ToString(m.Caller.Account))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
// Create a channel to signal the spinner aka task status goroutine to finish
spinnerDone := make(chan bool)
//fire up the the task status spinner/updated
go internal.SpinUntil(m.output.CallingModule, &m.CommandCounter, spinnerDone, "tasks")
//create a channel to receive the objects
dataReceiver := make(chan Directory)
// Create a channel to signal to stop
receiverDone := make(chan bool)
go m.Receiver(dataReceiver, receiverDone)
for _, region := range m.AWSRegions {
wg.Add(1)
m.CommandCounter.Pending++
go m.executeChecks(region, wg, semaphore, dataReceiver)
}
wg.Wait()
// Send a message to the spinner goroutine to close the channel and stop
spinnerDone <- true
<-spinnerDone
// Send a message to the data receiver goroutine to close the channel and stop
receiverDone <- true
<-receiverDone
// add - if struct is not empty do this. otherwise, dont write anything.
m.output.Headers = []string{
"Account",
"Name",
"Alias",
"Domain",
"NetBIOS name",
"Access URL",
"Version",
"Trusts",
}
// If the user specified table columns, use those.
// If the user specified -o wide, use the wide default cols for this module.
// Otherwise, use the hardcoded default cols for this module.
var tableCols []string
// If the user specified table columns, use those.
if m.AWSTableCols != "" {
// If the user specified wide as the output format, use these columns.
// remove any spaces between any commas and the first letter after the commas
m.AWSTableCols = strings.ReplaceAll(m.AWSTableCols, ", ", ",")
m.AWSTableCols = strings.ReplaceAll(m.AWSTableCols, ", ", ",")
tableCols = strings.Split(m.AWSTableCols, ",")
} else if m.AWSOutputType == "wide" {
tableCols = []string{
"Account",
"Name",
"Alias",
"Domain",
"NetBIOS name",
"Access URL",
"Version",
"Trusts",
}
} else {
tableCols = []string{
"Account",
"Name",
"Domain",
"NetBIOS name",
"Access URL",
"Version",
"Trusts",
}
}
// Table rows
for i := range m.Directories {
m.output.Body = append(
m.output.Body,
[]string{
aws.ToString(m.Caller.Account),
m.Directories[i].DirectoryId,
m.Directories[i].Alias,
m.Directories[i].DNS,
m.Directories[i].NetBios,
m.Directories[i].AccessURL,
m.Directories[i].OsVersion,
m.Directories[i].TrustInfo,
},
)
}
if len(m.output.Body) > 0 {
o := internal.OutputClient{
Verbosity: verbosity,
CallingModule: m.output.CallingModule,
Table: internal.TableClient{
Wrap: m.WrapTable,
},
}
o.Table.TableFiles = append(o.Table.TableFiles, internal.TableFile{
Header: m.output.Headers,
Body: m.output.Body,
TableCols: tableCols,
Name: m.output.CallingModule,
})
o.PrefixIdentifier = m.AWSProfileStub
o.Table.DirectoryName = filepath.Join(outputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", m.AWSProfileStub, aws.ToString(m.Caller.Account)))
o.WriteFullOutput(o.Table.TableFiles, nil)
//m.writeLoot(o.Table.DirectoryName, verbosity)
fmt.Printf("[%s][%s] %s directories found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfileStub), strconv.Itoa(len(m.output.Body)))
//fmt.Printf("[%s][%s] Resource policies stored to: %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), m.getLootDir())
} else {
fmt.Printf("[%s][%s] No directories found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfileStub))
}
fmt.Printf("[%s][%s] For context and next steps: https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#%s\n", cyan(m.output.CallingModule), cyan(m.AWSProfileStub), m.output.CallingModule)
}
func (m *DirectoryModule) executeChecks(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Directory) {
defer wg.Done()
servicemap := &awsservicemap.AwsServiceMap{
JsonFileSource: "DOWNLOAD_FROM_AWS",
}
res, err := servicemap.IsServiceInRegion("clouddirectory", r)
if err != nil {
m.modLog.Error(err)
}
if res {
m.CommandCounter.Total++
wg.Add(1)
m.getDirectoriesPerRegion(r, wg, semaphore, dataReceiver)
}
}
func (m *DirectoryModule) Receiver(receiver chan Directory, receiverDone chan bool) {
defer close(receiverDone)
for {
select {
case data := <-receiver:
m.Directories = append(m.Directories, data)
case <-receiverDone:
receiverDone <- true
return
}
}
}
func (m *DirectoryModule) getDirectoriesPerRegion(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Directory) {
defer func() {
m.CommandCounter.Executing--
m.CommandCounter.Complete++
wg.Done()
}()
semaphore <- struct{}{}
defer func() {
<-semaphore
}()
// Get directories
directories, err := sdk.CachedDSDescribeDirectories(m.DSClient, aws.ToString(m.Caller.Account), r)
if err != nil {
m.modLog.Error(err)
}
for _, directory := range directories {
trusts, err := sdk.CachedDSDescribeTrusts(m.DSClient, aws.ToString(m.Caller.Account), r, *directory.DirectoryId)
if err != nil {
m.modLog.Error(err)
}
dataReceiver <- Directory{
DirectoryId: *directory.DirectoryId,
DNS: *directory.Name,
NetBios: *directory.ShortName,
Region: r,
AccessURL: *directory.AccessUrl,
Alias: *directory.Alias,
OsVersion: fmt.Sprintf("%s", directory.OsVersion),
TrustInfo: m.formatTrusts(trusts),
}
}
}
func (m *DirectoryModule) formatTrusts(t []dsTypes.Trust) string {
var output string = ""
for idx, trust := range t {
if idx != 0 {
output = output + "\n"
}
if trust.TrustDirection == "One-Way: Outgoing" {
output = output + "→"
} else if trust.TrustDirection == "One-Way: Ingoing" {
output = output + "←"
} else {
output = output + "↔"
}
output = fmt.Sprintf("%s %s", output, *trust.RemoteDomainName)
// check trust type (external or forest)
if trust.TrustType == "External" {
output = fmt.Sprintf("%s (%s)", output, "Domain")
} else {
output = fmt.Sprintf("%s (%s)", output, "Forest")
}
}
return output
}
+7 -6
View File
@@ -25,10 +25,11 @@ type ECSTasksModule struct {
EC2Client sdk.AWSEC2ClientInterface
IAMClient sdk.AWSIAMClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
PmapperDataBasePath string
AWSProfile string
Goroutines int
@@ -73,8 +74,8 @@ func (m *ECSTasksModule) ECSTasks(outputDirectory string, verbosity int) {
fmt.Printf("[%s][%s] Enumerating ECS tasks in all regions for account %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
// Initialized the tools we'll need to check if any workload roles are admin or can privesc to admin
//fmt.Printf("[%s][%s] Attempting to build a PrivEsc graph in memory using local pmapper data if it exists on the filesystem.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
// if m.pmapperError != nil {
// fmt.Printf("[%s][%s] No pmapper data found for this account. Using cloudfox's iam-simulator for role analysis.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
+7 -6
View File
@@ -22,10 +22,11 @@ type EKSModule struct {
EKSClient sdk.EKSClientInterface
IAMClient sdk.AWSIAMClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
PmapperDataBasePath string
Goroutines int
AWSProfile string
@@ -72,8 +73,8 @@ func (m *EKSModule) EKS(outputDirectory string, verbosity int) {
fmt.Printf("[%s][%s] Enumerating EKS clusters for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
// Initialized the tools we'll need to check if any workload roles are admin or can privesc to admin
//fmt.Printf("[%s][%s] Attempting to build a PrivEsc graph in memory using local pmapper data if it exists on the filesystem.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
// if m.pmapperError != nil {
// fmt.Printf("[%s][%s] No pmapper data found for this account. Using cloudfox's iam-simulator for role analysis.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
+418
View File
@@ -0,0 +1,418 @@
package aws
import (
"context"
"fmt"
"os"
"strings"
ingestor "github.com/BishopFox/cloudfox/aws/graph/ingester"
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema/models"
"github.com/BishopFox/cloudfox/aws/sdk"
"github.com/BishopFox/cloudfox/internal"
"github.com/BishopFox/cloudfox/internal/aws/policy"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/bishopfox/knownawsaccountslookup"
"github.com/sirupsen/logrus"
)
type GraphCommand struct {
// General configuration data
Caller sts.GetCallerIdentityOutput
AWSRegions []string
Goroutines int
AWSProfile string
WrapTable bool
AWSOutputType string
AWSTableCols string
Verbosity int
AWSOutputDirectory string
AWSConfig aws.Config
Version string
SkipAdminCheck bool
PmapperDataBasePath string
pmapperMod PmapperModule
pmapperError error
vendors *knownawsaccountslookup.Vendors
// Main module data
// Used to store output data for pretty printing
output internal.OutputData2
modLog *logrus.Entry
}
func (m *GraphCommand) RunGraphCommand() {
// These struct values are used by the output module
m.output.Verbosity = m.Verbosity
m.output.Directory = m.AWSOutputDirectory
m.output.CallingModule = "graph"
m.modLog = internal.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = internal.BuildAWSPath(m.Caller)
}
m.vendors = knownawsaccountslookup.NewVendorMap()
m.vendors.PopulateKnownAWSAccounts()
m.modLog.Info("Collecting data for graph ingestor...")
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
////////////////
// Accounts
////////////////
accounts := m.collectAccountDataForGraph()
// write data to jsonl file for ingestor to read
fileName := fmt.Sprintf("%s/graph/%s/%s.jsonl", m.output.Directory, aws.ToString(m.Caller.Account), "accounts")
// create file and directory if it doesn't exist
if err := os.MkdirAll(fmt.Sprintf("%s/graph/%s", m.output.Directory, aws.ToString(m.Caller.Account)), 0755); err != nil {
m.modLog.Error(err)
return
}
outputFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
m.modLog.Error(err)
return
}
defer outputFile.Close()
for _, account := range accounts {
if err := internal.WriteJsonlFile(outputFile, account); err != nil {
m.modLog.Error(err)
return
}
}
////////////////
// Users
////////////////
// users := m.collectUserDataForGraph()
// // write data to jsonl file for ingestor to read
// fileName = fmt.Sprintf("%s/graph/%s/%s.jsonl", m.output.Directory, aws.ToString(m.Caller.Account), "users")
// // create file and directory if it doesn't exist
// if err := os.MkdirAll(fmt.Sprintf("%s/graph/%s", m.output.Directory, aws.ToString(m.Caller.Account)), 0755); err != nil {
// m.modLog.Error(err)
// return
// }
// outputFile, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
// if err != nil {
// m.modLog.Error(err)
// return
// }
// defer outputFile.Close()
// for _, user := range users {
// if err := internal.WriteJsonlFile(outputFile, user); err != nil {
// m.modLog.Error(err)
// return
// }
// }
////////////////
// Roles
////////////////
roles := m.collectRoleDataForGraph()
// write data to jsonl file for ingestor to read
fileName = fmt.Sprintf("%s/graph/%s/%s.jsonl", m.output.Directory, aws.ToString(m.Caller.Account), "roles")
// create file and directory if it doesn't exist
if err := os.MkdirAll(fmt.Sprintf("%s/graph/%s", m.output.Directory, aws.ToString(m.Caller.Account)), 0755); err != nil {
m.modLog.Error(err)
return
}
outputFile, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
m.modLog.Error(err)
return
}
defer outputFile.Close()
for _, role := range roles {
if err := internal.WriteJsonlFile(outputFile, role); err != nil {
m.modLog.Error(err)
return
}
}
ingestor, err := ingestor.NewCloudFoxIngestor()
if err != nil {
return
}
// Pmapper hack
goCtx := context.Background()
sharedLogger.Infof("Verifying connectivity to Neo4J at %s", ingestor.Uri)
if err := ingestor.Driver.VerifyConnectivity(goCtx); err != nil {
sharedLogger.Error(err)
}
defer ingestor.Driver.Close(goCtx)
m.pmapperMod.GenerateCypherStatements(goCtx, ingestor.Driver)
// back to regular stuff
ingestor.Run(fmt.Sprintf("%s/graph/%s", m.output.Directory, aws.ToString(m.Caller.Account)))
}
func (m *GraphCommand) collectAccountDataForGraph() []models.Account {
//OrganizationsCommandClient := InitOrgClient(m.AWSConfig)
var accounts []models.Account
OrganizationsCommandClient := InitOrgClient(m.AWSConfig)
DescribeOrgOutput, err := sdk.CachedOrganizationsDescribeOrganization(OrganizationsCommandClient, aws.ToString(m.Caller.Account))
if err != nil {
m.modLog.Fatal(err)
}
if DescribeOrgOutput.MasterAccountId == nil {
m.modLog.Error("Organization is not configured")
}
// If the account is not the org mgmt account, it can only see some info about itself and some info about the org mgmt account.
// populate both of them here.
if aws.ToString(DescribeOrgOutput.MasterAccountId) != aws.ToString(m.Caller.Account) {
//create new object of type models.Account for this account
thisAccount := models.Account{
Id: aws.ToString(m.Caller.Account),
Arn: fmt.Sprintf("arn:aws:iam::%s:root", aws.ToString(m.Caller.Account)),
//Name: aws.ToString(m.Caller.Account),
IsOrgMgmt: false,
IsChildAccount: true,
OrgMgmtAccountID: aws.ToString(DescribeOrgOutput.MasterAccountId),
OrganizationID: aws.ToString(DescribeOrgOutput.Id),
}
accounts = append(accounts, thisAccount)
//create new object of type models.Account for the mgmt account
mgmtAccount := models.Account{
Id: aws.ToString(DescribeOrgOutput.MasterAccountId),
Arn: aws.ToString(DescribeOrgOutput.MasterAccountArn),
Email: aws.ToString(DescribeOrgOutput.MasterAccountEmail),
//Status: string(account.Status),
//JoinedMethod: string(account.JoinedMethod),
//JoinedTimestamp: account.JoinedTimestamp.String(),
IsOrgMgmt: true,
IsChildAccount: false,
OrgMgmtAccountID: aws.ToString(DescribeOrgOutput.MasterAccountId),
OrganizationID: aws.ToString(DescribeOrgOutput.Id),
}
accounts = append(accounts, mgmtAccount)
return accounts
} else {
// In this case we are the org mgmt account, so we can see all the accounts in the org.
ListAccounts, err := sdk.CachedOrganizationsListAccounts(OrganizationsCommandClient, aws.ToString(DescribeOrgOutput.MasterAccountId))
if err != nil {
m.modLog.Fatal(err)
}
for _, account := range ListAccounts {
var isMgmtAccount bool
var isChildAccount bool
m.modLog.Info("Account: ", aws.ToString(account.Name))
if aws.ToString(DescribeOrgOutput.MasterAccountId) == aws.ToString(account.Id) {
// this is the org mgmt account
isMgmtAccount = true
isChildAccount = false
} else if DescribeOrgOutput.MasterAccountId == nil {
// this is a standalone account
isChildAccount = false
isMgmtAccount = false
} else {
// this is a child account
isChildAccount = true
isMgmtAccount = false
}
//create new object of type models.Account
account := models.Account{
Id: aws.ToString(account.Id),
Arn: aws.ToString(account.Arn),
Name: aws.ToString(account.Name),
Email: aws.ToString(account.Email),
Status: string(account.Status),
JoinedMethod: string(account.JoinedMethod),
JoinedTimestamp: account.JoinedTimestamp.String(),
IsOrgMgmt: isMgmtAccount,
IsChildAccount: isChildAccount,
OrgMgmtAccountID: aws.ToString(DescribeOrgOutput.MasterAccountId),
OrganizationID: aws.ToString(DescribeOrgOutput.Id),
}
accounts = append(accounts, account)
}
return accounts
}
}
func (m *GraphCommand) collectRoleDataForGraph() []models.Role {
var isAdmin, canPrivEscToAdmin string
// iamClient := InitIAMClient(m.AWSConfig)
// iamSimClient := InitIamCommandClient(iamClient, m.Caller, m.AWSProfile, m.Goroutines)
// localAdminMap := make(map[string]bool)
var roles []models.Role
IAMCommandClient := InitIAMClient(m.AWSConfig)
ListRolesOutput, err := sdk.CachedIamListRoles(IAMCommandClient, aws.ToString(m.Caller.Account))
if err != nil {
m.modLog.Error(err)
}
for _, role := range ListRolesOutput {
accountId := strings.Split(aws.ToString(role.Arn), ":")[4]
trustsdoc, err := policy.ParseRoleTrustPolicyDocument(role)
if err != nil {
m.modLog.Error(err.Error())
break
}
// if m.pmapperError == nil {
// isAdmin, canPrivEscToAdmin = GetPmapperResults(m.SkipAdminCheck, m.pmapperMod, role.Arn)
// } else {
// isAdmin, canPrivEscToAdmin = GetIamSimResult(m.SkipAdminCheck, role.Arn, iamSimClient, localAdminMap)
// }
// for _, row := range m.PermissionRowsFromAllProfiles {
// if row.Arn == aws.ToString(role.Arn) {
// // look for cases where there is a permission that allows sts:assumeRole or *
// // lowercase the action and compare it against the list of checks below
// if strings.EqualFold(row.Action, "sts:AssumeRole") ||
// strings.EqualFold(row.Action, "*") ||
// strings.EqualFold(row.Action, "sts:Assume*") ||
// strings.EqualFold(row.Action, "sts:*") {
// if row.Effect == "Allow" {
// //PrivEscPermissions = append(PrivEscPermissions, "sts:AssumeRole")
// if row.Resource == "*" {
// PrivEscPermissions = append(PrivEscPermissions, "sts:AssumeRole")
// } else if strings.EqualFold(row.Resource, aws.ToString(role.Arn)) {
// PrivEscPermissions = append(PrivEscPermissions, "sts:AssumeRole")
// }
// }
// }
// if row.Effect == "Deny" {
// // Remove the string sts:AssumeRole from the PrivEscPermissions slice
// for i, v := range PrivEscPermissions {
// if v == "sts:AssumeRole" {
// PrivEscPermissions = append(PrivEscPermissions[:i], PrivEscPermissions[i+1:]...)
// }
// }
// }
// }
// }
var TrustedPrincipals []models.TrustedPrincipal
var TrustedServices []models.TrustedService
var TrustedFederatedProviders []models.TrustedFederatedProvider
//var TrustedFederatedSubjects string
var trustedProvider string
var trustedSubjects string
var vendorName string
for _, statement := range trustsdoc.Statement {
for _, principal := range statement.Principal.AWS {
if strings.Contains(principal, ":root") {
//check to see if the accountID is known
accountID := strings.Split(principal, ":")[4]
vendorName = m.vendors.GetVendorNameFromAccountID(accountID)
}
TrustedPrincipals = append(TrustedPrincipals, models.TrustedPrincipal{
TrustedPrincipal: principal,
ExternalID: statement.Condition.StringEquals.StsExternalID,
VendorName: vendorName,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
})
}
for _, service := range statement.Principal.Service {
TrustedServices = append(TrustedServices, models.TrustedService{
TrustedService: service,
AccountID: accountId,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
})
}
for _, federated := range statement.Principal.Federated {
if statement.Condition.StringLike.TokenActionsGithubusercontentComAud != "" || len(statement.Condition.StringLike.TokenActionsGithubusercontentComSub) > 0 {
trustedProvider = "GitHub"
trustedSubjects := strings.Join(statement.Condition.StringLike.TokenActionsGithubusercontentComSub, ",")
if trustedSubjects == "" {
trustedSubjects = "ALL REPOS!!!"
} else {
trustedSubjects = "Repos: " + trustedSubjects
}
} else if statement.Condition.StringEquals.SAMLAud == "https://signin.aws.amazon.com/saml" {
if strings.Contains(statement.Principal.Federated[0], "AWSSSO") {
trustedProvider = "AWS SSO" // (" + statement.Principal.Federated[0] + ")"
} else if strings.Contains(statement.Principal.Federated[0], "Okta") {
trustedProvider = "Okta" // (" + statement.Principal.Federated[0] + ")"
}
trustedSubjects = "Not applicable"
} else if statement.Condition.StringEquals.OidcEksAud != "" || statement.Condition.StringEquals.OidcEksSub != nil || statement.Condition.StringLike.OidcEksAud != "" || statement.Condition.StringLike.OidcEksSub != nil {
trustedProvider = "EKS" // (" + statement.Principal.Federated[0] + ")"
// if statement.Condition.StringEquals.OidcEksSub != "" {
// trustedSubjects = statement.Condition.StringEquals.OidcEksSub
// } else if statement.Condition.StringLike.OidcEksSub != "" {
// trustedSubjects = statement.Condition.StringLike.OidcEksSub
// } else {
// trustedSubjects = "ALL SERVICE ACCOUNTS!"
// }
trustedSubjects = "ALL SERVICE ACCOUNTS!"
} else if statement.Principal.Federated[0] == "cognito-identity.amazonaws.com" {
trustedProvider = "Cognito" // (" + statement.Principal.Federated[0] + ")"
if statement.Condition.ForAnyValueStringLike.CognitoAMR != "" {
trustedSubjects = statement.Condition.ForAnyValueStringLike.CognitoAMR
}
} else {
if trustedProvider == "" && strings.Contains(statement.Principal.Federated[0], "oidc.eks") {
trustedProvider = "EKS" // (" + statement.Principal.Federated[0] + ")"
trustedSubjects = "ALL SERVICE ACCOUNTS!"
} else if trustedProvider == "" && strings.Contains(statement.Principal.Federated[0], "AWSSSO") {
trustedProvider = "AWS SSO" // (" + statement.Principal.Federated[0] + ")"
}
trustedSubjects = "Not applicable"
}
TrustedFederatedProviders = append(TrustedFederatedProviders, models.TrustedFederatedProvider{
TrustedFederatedProvider: federated,
ProviderShortName: trustedProvider,
TrustedSubjects: trustedSubjects,
//IsAdmin: false,
//CanPrivEscToAdmin: false,
})
}
}
//create new object of type models.Role
role := models.Role{
Id: aws.ToString(role.Arn),
AccountID: accountId,
ARN: aws.ToString(role.Arn),
Name: aws.ToString(role.RoleName),
TrustsDoc: trustsdoc,
TrustedPrincipals: TrustedPrincipals,
TrustedServices: TrustedServices,
TrustedFederatedProviders: TrustedFederatedProviders,
CanPrivEscToAdmin: canPrivEscToAdmin,
IsAdmin: isAdmin,
}
roles = append(roles, role)
}
return roles
}
+1
View File
@@ -0,0 +1 @@
package collectors
+283
View File
@@ -0,0 +1,283 @@
package ingestor
import (
"bufio"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema/models"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
log "github.com/sirupsen/logrus"
)
const (
// Neo4j
MergeNodeQueryTemplate = `CALL apoc.merge.node([$labels[0]], {Id: $Id}, $properties, $properties) YIELD node as obj
CALL apoc.create.setLabels(obj, $labels) YIELD node as labeledObj
RETURN labeledObj`
MergeRelationQueryTemplate = `UNWIND $batch as row
CALL apoc.merge.node([row.sourceLabel], apoc.map.fromValues([row.sourceProperty, row.sourceNodeId])) YIELD node as from
CALL apoc.merge.node([row.targetLabel], apoc.map.fromValues([row.targetProperty, row.targetNodeId])) YIELD node as to
CALL apoc.merge.relationship(from, row.relationshipType, {}, row.properties, to) YIELD rel
RETURN rel`
// Using sprintf to insert the label name since the driver doesn't support parameters for labels here
// %[1]s is a nice way to say "insert the first parameter here"
CreateConstraintQueryTemplate = "CREATE CONSTRAINT IF NOT EXISTS FOR (n: %s) REQUIRE n.Id IS UNIQUE"
CreateIndexQueryTemplate = "CREATE INDEX %[1]s_Id IF NOT EXISTS FOR (n: %[1]s) ON (n.Id)"
PostProcessMergeQueryTemplate = `MATCH (n)
WITH n.Id AS Id, COLLECT(n) AS nodesToMerge
WHERE size(nodesToMerge) > 1
CALL apoc.refactor.mergeNodes(nodesToMerge, {properties: 'combine', mergeRels:true})
YIELD node
RETURN count(*);`
)
type Neo4jConfig struct {
Uri string
Username string
Password string
}
type CloudFoxIngestor struct {
Neo4jConfig
//ResultsFile string
Driver neo4j.DriverWithContext
TmpDir string
}
func NewCloudFoxIngestor() (*CloudFoxIngestor, error) {
config := Neo4jConfig{
Uri: "neo4j://localhost:7687",
Username: "neo4j",
Password: "cloudfox",
}
driver, err := neo4j.NewDriverWithContext(config.Uri, neo4j.BasicAuth(config.Username, config.Password, ""))
if err != nil {
return nil, err
}
return &CloudFoxIngestor{
Neo4jConfig: config,
//ResultsFile: resultsFile,
Driver: driver,
}, nil
}
// func unzipToTemp(zipFilePath string) (string, error) {
// // Create a temporary directory to extract the zip file to
// tempDir, err := os.MkdirTemp("", "cloudfox-graph")
// if err != nil {
// return "", err
// }
// // Open the zip file and extract to a temporary directory
// zipfile, err := zip.OpenReader(zipFilePath)
// if err != nil {
// return "", err
// }
// defer zipfile.Close()
// for _, file := range zipfile.File {
// path := filepath.Join(tempDir, file.Name)
// log.Debugf("Extracting file: %s", path)
// fileData, err := file.Open()
// if err != nil {
// return "", err
// }
// defer fileData.Close()
// newFile, err := os.Create(path)
// if err != nil {
// return "", err
// }
// defer newFile.Close()
// if _, err := io.Copy(newFile, fileData); err != nil {
// return "", err
// }
// }
// return tempDir, nil
// }
func (i *CloudFoxIngestor) ProcessFile(path string, info os.FileInfo) error {
log.Infof("Processing file: %s", info.Name())
switch info.Name() {
case "accounts.jsonl":
return i.ProcessFileObjects(path, schema.Account, schema.Account)
case "roles.jsonl":
return i.ProcessFileObjects(path, schema.Role, schema.Role)
// case "servicePrincipals.jsonl":
// return i.ProcessFileObjects(path, schema.GraphServicePrincipal, schema.GraphObject)
// case "applications.jsonl":
// return i.ProcessFileObjects(path, schema.GraphApplication, schema.GraphObject)
// case "devices.jsonl":
// return i.ProcessFileObjects(path, schema.GraphDevice, schema.GraphObject)
// case "directoryRoles.jsonl":
// return i.ProcessFileObjects(path, schema.GraphRole, schema.GraphObject)
// case "subscriptions.jsonl":
// return i.ProcessFileObjects(path, schema.Subscription, schema.ArmResource)
// case "tenants.jsonl":
// return i.ProcessFileObjects(path, schema.Tenant, schema.ArmResource)
// case "rbac.jsonl":
// return i.ProcessFileObjects(path, schema.AzureRbac, "")
default:
return nil
}
}
func (i *CloudFoxIngestor) ProcessFileObjects(path string, objectType schema.NodeLabel, generalType schema.NodeLabel) error {
var object = models.NodeLabelToNodeMap[objectType]
// Open the file
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
// Read the file line by line
scanner := bufio.NewScanner(file)
//Iterate over the lines and create the nodes
for scanner.Scan() {
line := strings.TrimSuffix(scanner.Text(), "\n")
// Skip empty lines
if len(line) > 0 {
if err := json.Unmarshal([]byte(line), &object); err != nil {
log.Errorf("%s : %s", err, line)
continue
}
}
relationships := object.MakeRelationships()
if err := i.InsertDBObjects(object, relationships, []schema.NodeLabel{generalType, objectType}); err != nil {
log.Error(err)
continue
}
}
return nil
}
func (i *CloudFoxIngestor) InsertDBObjects(object schema.Node, relationships []schema.Relationship, labels []schema.NodeLabel) error {
goCtx := context.Background()
var err error
// Insert the node
if object != nil {
nodeMap, err := schema.ConvertCustomTypesToNeo4j(&object)
if err != nil {
log.Errorf("Error converting custom types to neo4j: %s -- %v", err, object)
return err
}
//nodeMap := schema.AsNeo4j(&object)
nodeQueryParams := map[string]interface{}{
"Id": nodeMap["Id"],
"labels": labels,
"properties": nodeMap,
}
_, err = neo4j.ExecuteQuery(goCtx, i.Driver, MergeNodeQueryTemplate, nodeQueryParams, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
if err != nil {
log.Errorf("Error inserting node: %s -- %v", err, nodeQueryParams)
return err
}
}
// Insert the relationships
if len(relationships) > 0 {
var relationshipInterface []map[string]interface{}
// Check the default SourceProperty and TargetProperty values
for _, relationship := range relationships {
var currentRelationship map[string]interface{}
if relationship.SourceProperty == "" {
relationship.SourceProperty = "Id"
}
if relationship.TargetProperty == "" {
relationship.TargetProperty = "Id"
}
relationshipBytes, err := json.Marshal(relationship)
if err != nil {
return err
}
if err := json.Unmarshal(relationshipBytes, &currentRelationship); err != nil {
return err
}
relationshipInterface = append(relationshipInterface, currentRelationship)
}
_, err = neo4j.ExecuteQuery(goCtx, i.Driver, MergeRelationQueryTemplate, map[string]interface{}{"batch": relationshipInterface}, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
if err != nil {
log.Errorf("Error inserting relationships: %s -- %v", err, relationshipInterface)
return err
}
}
return nil
}
func (i *CloudFoxIngestor) Run(graphOutputDir string) error {
goCtx := context.Background()
log.Infof("Verifying connectivity to Neo4J at %s", i.Uri)
if err := i.Driver.VerifyConnectivity(goCtx); err != nil {
return err
}
defer i.Driver.Close(goCtx)
var err error
// Get the label to model map
// Create constraints and indexes
// log.Info("Creating constraints and indexes for labels")
// for label := range models.NodeLabelToNodeMap {
// for _, query := range []string{CreateConstraintQueryTemplate, CreateIndexQueryTemplate} {
// _, err := neo4j.ExecuteQuery(goCtx, i.Driver, fmt.Sprintf(query, label), nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
// if err != nil {
// log.Error(err)
// continue
// }
// }
// }
// Process the files in the output directory
fileWg := new(sync.WaitGroup)
filepath.Walk(graphOutputDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if graphOutputDir == path {
return nil
}
fileWg.Add(1)
go func(path string) {
defer fileWg.Done()
i.ProcessFile(path, info)
log.Infof("Finished processing file: %s", info.Name())
}(path)
return nil
})
fileWg.Wait()
log.Info("Finished processing files")
// Run the post processing merge query
log.Info("Running post processing merge query")
_, err = neo4j.ExecuteQuery(goCtx, i.Driver, PostProcessMergeQueryTemplate, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
if err != nil {
log.Error(err)
return err
}
return nil
}
@@ -0,0 +1,44 @@
package models
import "github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
type Account struct {
Id string
Arn string
Email string
Name string
Status string
JoinedMethod string
JoinedTimestamp string
IsOrgMgmt bool
IsChildAccount bool
OrgMgmtAccountID string
OrganizationID string
}
func (a *Account) MakeRelationships() []schema.Relationship {
var relationships []schema.Relationship
// make relationship from children accounts to parent org
if a.IsChildAccount {
// make relationship from child to org mgmt account
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.OrganizationID,
TargetNodeID: a.Id,
SourceLabel: schema.Organization,
TargetLabel: schema.Account,
RelationshipType: schema.Manages,
})
// make relationship from parent org mgmt account to child account
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: a.OrganizationID,
SourceLabel: schema.Account,
TargetLabel: schema.Organization,
RelationshipType: schema.MemberOf,
})
}
return relationships
}
@@ -0,0 +1,11 @@
package models
import (
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
)
var NodeLabelToNodeMap = map[schema.NodeLabel]schema.Node{
schema.Organization: &Organization{},
schema.Account: &Account{},
schema.Role: &Role{},
}
+20
View File
@@ -0,0 +1,20 @@
package models
import (
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
)
type Organization struct {
Id string
OrgId string
Arn string
MasterAccountArn string
MasterAccountId string
MasterAccountEmail string
ChildAccounts []Account
MgmtAccount Account
}
func (o *Organization) MakeRelationships() []schema.Relationship {
return []schema.Relationship{}
}
@@ -0,0 +1,5 @@
package models
type Resource struct {
ARN string
}
+647
View File
@@ -0,0 +1,647 @@
package models
import (
"fmt"
"strings"
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
"github.com/BishopFox/cloudfox/internal/aws/policy"
"github.com/BishopFox/cloudfox/internal/common"
"github.com/dominikbraun/graph"
)
type Role struct {
Id string
AccountID string
ARN string
Name string
TrustsDoc policy.TrustPolicyDocument
TrustedPrincipals []TrustedPrincipal
TrustedServices []TrustedService
TrustedFederatedProviders []TrustedFederatedProvider
CanPrivEscToAdmin string
IsAdmin string
IdValue string
IsAdminP bool
PathToAdminSameAccount bool
PathToAdminCrossAccount bool
}
type TrustedPrincipal struct {
TrustedPrincipal string
ExternalID string
VendorName string
//IsAdmin bool
//CanPrivEscToAdmin bool
}
type TrustedService struct {
TrustedService string
AccountID string
//IsAdmin bool
//CanPrivEscToAdmin bool
}
type TrustedFederatedProvider struct {
TrustedFederatedProvider string
ProviderShortName string
TrustedSubjects string
//IsAdmin bool
//CanPrivEscToAdmin bool
}
func (a *Role) MakeRelationships() []schema.Relationship {
var relationships []schema.Relationship
//instance := singleton.GetInstance()
// get thisAccount id from role arn
var thisAccount string
if len(a.ARN) >= 25 {
thisAccount = a.ARN[13:25]
} else {
fmt.Sprintf("Could not get account number from this role arn%s", a.ARN)
}
// make a relationship between each role and the account it belongs to
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: thisAccount,
SourceLabel: schema.Role,
TargetLabel: schema.Account,
RelationshipType: schema.MemberOf,
})
for _, TrustedPrincipal := range a.TrustedPrincipals {
//get account id from the trusted principal arn
var trustedPrincipalAccount string
if len(TrustedPrincipal.TrustedPrincipal) >= 25 {
trustedPrincipalAccount = TrustedPrincipal.TrustedPrincipal[13:25]
} else {
fmt.Sprintf("Could not get account number from this TrustedPrincipal%s", TrustedPrincipal.TrustedPrincipal)
}
var PermissionsRowAccount string
// make a TRUSTED_BY relationship between the role and the trusted principal. This does not mean the principal can assume this role, we need more logic to determine that (see below)
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: TrustedPrincipal.TrustedPrincipal,
// TargetNodeID: a.Id,
// SourceLabel: schema.Principal,
// TargetLabel: schema.Role,
// RelationshipType: schema.IsTrustedBy,
// })
// // make a TRUSTS relationship between the trusted principal and this role. This does not mean the principal can assume this role, we need more logic to determine that (see below)
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: a.Id,
// TargetNodeID: TrustedPrincipal.TrustedPrincipal,
// SourceLabel: schema.Role,
// TargetLabel: schema.Principal,
// RelationshipType: schema.Trusts,
// })
// // make a MEMBER_OF relationship between the role and the account
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: TrustedPrincipal.TrustedPrincipal,
// TargetNodeID: trustedPrincipalAccount,
// SourceLabel: schema.Principal,
// TargetLabel: schema.Account,
// RelationshipType: schema.MemberOf,
// })
// if the role trusts a principal in this same account explicitly, then the principal can assume the role
if thisAccount == trustedPrincipalAccount {
// make a CAN_ASSUME relationship between the trusted principal and this role
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedPrincipal.TrustedPrincipal,
TargetNodeID: a.Id,
SourceLabel: schema.Principal,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
// make a CAN_BE_ASSUMED_BY relationship between this role and the trusted principal
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: a.Id,
// TargetNodeID: TrustedPrincipal.TrustedPrincipal,
// SourceLabel: schema.Role,
// TargetLabel: schema.Principal,
// RelationshipType: schema.CanBeAssumedBy,
// })
}
// If the role trusts a principal in this account or another account using the :root notation, then we need to iterate over all of the rows in AllPermissionsRows to find the principals that have sts:AssumeRole permissions on this role
// if the role we are looking at trusts root in it's own account
if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", thisAccount)) {
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == thisAccount {
// lets only look for rows that have sts:AssumeRole permissions
if strings.EqualFold(PermissionsRow.Action, "sts:AssumeRole") ||
strings.EqualFold(PermissionsRow.Action, "*") ||
strings.EqualFold(PermissionsRow.Action, "sts:Assume*") ||
strings.EqualFold(PermissionsRow.Action, "sts:*") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.ARN) {
// make a CAN_ASSUME relationship between the trusted principal and this role
//evaluate if the princiapl is a user or a role and set a variable accordingly
//var principalType schema.NodeLabel
if strings.EqualFold(PermissionsRow.Type, "User") {
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.User,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
} else if strings.EqualFold(PermissionsRow.Type, "Role") {
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.Role,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
}
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: PermissionsRow.Arn,
// TargetNodeID: a.Id,
// SourceLabel: principalType,
// TargetLabel: schema.Role,
// RelationshipType: schema.CanAssumeTest,
// })
// make a CAN_BE_ASSUMED_BY relationship between this role and the trusted principal
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: a.Id,
// TargetNodeID: PermissionsRow.Arn,
// SourceLabel: schema.Role,
// TargetLabel: schema.Principal,
// RelationshipType: schema.CanBeAssumedByTest,
// })
}
}
}
}
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", trustedPrincipalAccount)) {
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this other account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == trustedPrincipalAccount {
// lets only look for rows that have sts:AssumeRole permissions
if strings.EqualFold(PermissionsRow.Action, "sts:AssumeRole") ||
strings.EqualFold(PermissionsRow.Action, "*") ||
strings.EqualFold(PermissionsRow.Action, "sts:Assume*") ||
strings.EqualFold(PermissionsRow.Action, "sts:*") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.ARN) {
// make a CAN_ASSUME relationship between the trusted principal and this role
if strings.EqualFold(PermissionsRow.Type, "User") {
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.User,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssumeCrossAccount,
})
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.User,
TargetLabel: schema.Role,
RelationshipType: schema.CanAccess,
})
} else if strings.EqualFold(PermissionsRow.Type, "Role") {
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.Role,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssumeCrossAccount,
})
relationships = append(relationships, schema.Relationship{
SourceNodeID: PermissionsRow.Arn,
TargetNodeID: a.Id,
SourceLabel: schema.Role,
TargetLabel: schema.Role,
RelationshipType: schema.CanAccess,
})
}
// // make a CAN_BE_ASSUMED_BY relationship between this role and the trusted principal
// relationships = append(relationships, schema.Relationship{
// SourceNodeID: a.Id,
// TargetNodeID: PermissionsRow.Arn,
// SourceLabel: schema.Role,
// TargetLabel: schema.Principal,
// RelationshipType: schema.CanBeAssumedByTest,
// })
}
}
}
}
}
// If the role trusts :root in another account and the trusted principal is a vendor, we will make a relationship between our role and a vendor node instead of a principal node
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && TrustedPrincipal.VendorName != "" {
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedPrincipal.TrustedPrincipal,
TargetNodeID: a.Id,
SourceLabel: schema.Vendor,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
}
}
for _, TrustedService := range a.TrustedServices {
// make relationship from trusted service to this role of type can assume
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedService.TrustedService + "_" + TrustedService.AccountID,
TargetNodeID: a.Id,
SourceLabel: schema.Service,
TargetLabel: schema.Role,
RelationshipType: schema.IsTrustedBy,
})
// make relationship from this role to trusted service of type can be assumed by
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: TrustedService.TrustedService + "_" + TrustedService.AccountID,
SourceLabel: schema.Role,
TargetLabel: schema.Service,
RelationshipType: schema.Trusts,
})
}
for _, TrustedFederatedProvider := range a.TrustedFederatedProviders {
// make relationship from trusted federated provider to this role of type can assume
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedFederatedProvider.TrustedFederatedProvider,
TargetNodeID: a.Id,
SourceLabel: schema.FederatedIdentity,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
// make relationship from this role to trusted federated provider of type can be assumed by
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: TrustedFederatedProvider.TrustedFederatedProvider,
SourceLabel: schema.Role,
TargetLabel: schema.FederatedIdentity,
RelationshipType: schema.CanBeAssumedBy,
})
// make relationship from trusted federated provider to this role of type can assume
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedFederatedProvider.TrustedFederatedProvider,
TargetNodeID: a.Id,
SourceLabel: schema.FederatedIdentity,
TargetLabel: schema.Role,
RelationshipType: schema.IsTrustedBy,
})
// make relationship from this role to trusted federated provider of type can be assumed by
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: TrustedFederatedProvider.TrustedFederatedProvider,
SourceLabel: schema.Role,
TargetLabel: schema.FederatedIdentity,
RelationshipType: schema.Trusts,
})
}
return relationships
}
// func (a *Node) GenerateAttributes() map[string]string {
// attributes := make(map[string]string)
// attributes["Id"] = a.Id
// attributes["Name"] = a.Name
// attributes["Type"] = "Role"
// attributes["AccountID"] = a.AccountID
// attributes["ARN"] = a.ARN
// attributes["CanPrivEscToAdmin"] = a.CanPrivEscToAdmin
// attributes["IsAdmin"] = a.IsAdmin
// attributes["IdValue"] = a.IdValue
// return attributes
// }
// func (a *Role) MergeAttributes(newAttributes map[string]string) {
// if a.Id == "" {
// a.Id = newAttributes["Id"]
// }
// if a.Name == "" {
// a.Name = newAttributes["Name"]
// }
// if a.Type == "" {
// a.Type = newAttributes["Type"]
// }
// if a.AccountID == "" {
// a.AccountID = newAttributes["AccountID"]
// }
// if a.ARN == "" {
// a.ARN = newAttributes["ARN"]
// }
// if a.CanPrivEscToAdmin == "" {
// a.CanPrivEscToAdmin = newAttributes["CanPrivEscToAdmin"]
// }
// if a.IsAdmin == "" {
// a.IsAdmin = newAttributes["IsAdmin"]
// }
// if a.IdValue == "" {
// a.IdValue = newAttributes["IdValue"]
// }
// }
func (a *Role) MakeVertices(GlobalGraph graph.Graph[string, string]) {
// make a vertex for this role as populate all of the data in the Role struct as attributes
err := GlobalGraph.AddVertex(
a.Id,
graph.VertexAttribute("Name", a.Name),
graph.VertexAttribute("Type", "Role"),
graph.VertexAttribute("AccountID", a.AccountID),
graph.VertexAttribute("ARN", a.ARN),
graph.VertexAttribute("CanPrivEscToAdmin", a.CanPrivEscToAdmin),
graph.VertexAttribute("IsAdmin", a.IsAdmin),
graph.VertexAttribute("IdValue", a.IdValue),
)
if err != nil {
if err == graph.ErrVertexAlreadyExists {
fmt.Println(a.Id + " already exists")
}
}
}
// func MakeAllVertices(GlobalRoles []Role, GlobalPmapperGraph aws.PmapperModule) (GlobalGraph graph.Graph[string, string]) {
// // for all nodes in the GlobalPmapperGraph, check to see if they exist in the GlobalRoles slice. If they do, then update the node with the new data. If they don't, then add the node to the GlobalRoles slice
// for _, node := range GlobalPmapperGraph.Nodes {
// // check to see if the node exists in the GlobalRoles slice
// var nodeExists bool
// for _, role := range GlobalRoles {
// if node.Id == role.Id {
// nodeExists = true
// }
// }
// // // make a vertex for this role as populate all of the data in the Role struct as attributes
// // err := GlobalGraph.AddVertex(
// // a.Id,
// // graph.VertexAttribute("Name", a.Name),
// // graph.VertexAttribute("Type", "Role"),
// // graph.VertexAttribute("AccountID", a.AccountID),
// // graph.VertexAttribute("ARN", a.ARN),
// // graph.VertexAttribute("CanPrivEscToAdmin", a.CanPrivEscToAdmin),
// // graph.VertexAttribute("IsAdmin", a.IsAdmin),
// // graph.VertexAttribute("IdValue", a.IdValue),
// // )
// // if err != nil {
// // if err == graph.ErrVertexAlreadyExists {
// // fmt.Println(a.Id + " already exists")
// // }
// // }
// }
func (a *Role) MakeEdges(GlobalGraph graph.Graph[string, string]) []schema.Relationship {
var relationships []schema.Relationship
// get thisAccount id from role arn
var thisAccount string
if len(a.ARN) >= 25 {
thisAccount = a.ARN[13:25]
} else {
fmt.Sprintf("Could not get account number from this role arn%s", a.ARN)
}
for _, TrustedPrincipal := range a.TrustedPrincipals {
//get account id from the trusted principal arn
var trustedPrincipalAccount string
if len(TrustedPrincipal.TrustedPrincipal) >= 25 {
trustedPrincipalAccount = TrustedPrincipal.TrustedPrincipal[13:25]
} else {
fmt.Sprintf("Could not get account number from this TrustedPrincipal%s", TrustedPrincipal.TrustedPrincipal)
}
var PermissionsRowAccount string
// if the role trusts a principal in this same account explicitly, then the principal can assume the role
if thisAccount == trustedPrincipalAccount {
// make a CAN_ASSUME relationship between the trusted principal and this role
err := GlobalGraph.AddEdge(
TrustedPrincipal.TrustedPrincipal,
a.Id,
graph.EdgeAttribute("AssumeRole", "Same account explicit trust"),
)
if err != nil {
fmt.Println(err)
fmt.Println(TrustedPrincipal.TrustedPrincipal + a.Id + "Same account explicit trust")
}
}
// If the role trusts a principal in this account or another account using the :root notation, then we need to iterate over all of the rows in AllPermissionsRows to find the principals that have sts:AssumeRole permissions on this role
// if the role we are looking at trusts root in it's own account
if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", thisAccount)) {
err := GlobalGraph.AddVertex(
a.Id,
graph.VertexAttribute("Name", a.Name),
graph.VertexAttribute("Type", "Account"),
graph.VertexAttribute("AccountID", a.AccountID),
)
if err != nil {
if err == graph.ErrVertexAlreadyExists {
fmt.Println(a.Id + " already exists")
}
}
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == thisAccount {
// lets only look for rows that have sts:AssumeRole permissions
if strings.EqualFold(PermissionsRow.Action, "sts:AssumeRole") ||
strings.EqualFold(PermissionsRow.Action, "*") ||
strings.EqualFold(PermissionsRow.Action, "sts:Assume*") ||
strings.EqualFold(PermissionsRow.Action, "sts:*") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.ARN) {
// make a CAN_ASSUME relationship between the trusted principal and this role
//evaluate if the princiapl is a user or a role and set a variable accordingly
//var principalType schema.NodeLabel
if strings.EqualFold(PermissionsRow.Type, "User") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Id,
graph.EdgeAttribute("AssumeRole", "Same account root trust and trusted principal has permission to assume role"),
)
if err != nil {
fmt.Println(err)
fmt.Println(PermissionsRow.Arn + a.Id + "Same account root trust and trusted principal has permission to assume role")
}
} else if strings.EqualFold(PermissionsRow.Type, "Role") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Id,
graph.EdgeAttribute("AssumeRole", "Same account root trust and trusted principal has permission to assume role"),
)
if err != nil {
fmt.Println(err)
fmt.Println(PermissionsRow.Arn + a.Id + "Same account root trust and trusted principal has permission to assume role")
}
}
}
}
}
}
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, ":root") && TrustedPrincipal.VendorName != "" {
err := GlobalGraph.AddVertex(
a.Id,
graph.VertexAttribute("Name", a.Name),
graph.VertexAttribute("Type", "Account"),
graph.VertexAttribute("AccountID", a.AccountID),
graph.VertexAttribute("VendorName", TrustedPrincipal.VendorName),
)
if err != nil {
if err == graph.ErrVertexAlreadyExists {
fmt.Println(a.Id + " already exists")
}
}
// If the role trusts :root in another account and the trusted principal is a vendor, we will make a relationship between our role and a vendor node instead of a principal node
relationships = append(relationships, schema.Relationship{
SourceNodeID: TrustedPrincipal.TrustedPrincipal,
TargetNodeID: a.Id,
SourceLabel: schema.Vendor,
TargetLabel: schema.Role,
RelationshipType: schema.CanAssume,
})
err = GlobalGraph.AddEdge(
//TrustedPrincipal.TrustedPrincipal,
TrustedPrincipal.VendorName,
a.Id,
graph.EdgeAttribute("VendorAssumeRole", "Cross account root trust and trusted principal is a vendor"),
)
if err != nil {
fmt.Println(err)
fmt.Println(TrustedPrincipal.VendorName + a.Id + "Cross account root trust and trusted principal is a vendor")
}
} else if strings.Contains(TrustedPrincipal.TrustedPrincipal, fmt.Sprintf("%s:root", trustedPrincipalAccount)) {
err := GlobalGraph.AddVertex(
a.Id,
graph.VertexAttribute("Name", a.Name),
graph.VertexAttribute("Type", "Account"),
graph.VertexAttribute("AccountID", a.AccountID),
)
if err != nil {
if err == graph.ErrVertexAlreadyExists {
fmt.Println(a.Id + " already exists")
}
}
// iterate over all rows in AllPermissionsRows
for _, PermissionsRow := range common.PermissionRowsFromAllProfiles {
// but we only care about the rows that have arns that are in this other account
if len(PermissionsRow.Arn) >= 25 {
PermissionsRowAccount = PermissionsRow.Arn[13:25]
} else {
fmt.Sprintf("Could not get account number from this PermissionsRow%s", PermissionsRow.Arn)
}
if PermissionsRowAccount == trustedPrincipalAccount {
// lets only look for rows that have sts:AssumeRole permissions
if strings.EqualFold(PermissionsRow.Action, "sts:AssumeRole") ||
strings.EqualFold(PermissionsRow.Action, "*") ||
strings.EqualFold(PermissionsRow.Action, "sts:Assume*") ||
strings.EqualFold(PermissionsRow.Action, "sts:*") {
// lets only focus on rows that have an effect of Allow
if strings.EqualFold(PermissionsRow.Effect, "Allow") {
// if the resource is * or the resource is this role arn, then this principal can assume this role
if PermissionsRow.Resource == "*" || strings.Contains(PermissionsRow.Resource, a.ARN) {
// make a CAN_ASSUME relationship between the trusted principal and this role
if strings.EqualFold(PermissionsRow.Type, "User") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Id,
graph.EdgeAttribute("CrossAccountAssumeRole", "Cross account root trust and trusted principal has permission to assume role"),
)
if err != nil {
fmt.Println(err)
fmt.Println(PermissionsRow.Arn + a.Id + "Cross account root trust and trusted principal has permission to assume role")
}
} else if strings.EqualFold(PermissionsRow.Type, "Role") {
err := GlobalGraph.AddEdge(
PermissionsRow.Arn,
a.Id,
graph.EdgeAttribute("CrossAccountAssumeRole", "Cross account root trust and trusted principal has permission to assume role"),
)
if err != nil {
fmt.Println(err)
fmt.Println(PermissionsRow.Arn + a.Id + "Cross account root trust and trusted principal has permission to assume role")
}
}
}
}
}
}
}
}
}
// pmapper takes care of this part so commenting out for now - but leaving as a placeholder
// for _, TrustedService := range a.TrustedServices {
// // make relationship from trusted service to this role of type can assume
// // make relationship from this role to trusted service of type can be assumed by
// }
for _, TrustedFederatedProvider := range a.TrustedFederatedProviders {
// make relationship from trusted federated provider to this role of type can assume
GlobalGraph.AddVertex(
TrustedFederatedProvider.TrustedFederatedProvider,
graph.VertexAttribute("Type", "FederatedIdentity"),
)
err := GlobalGraph.AddEdge(
TrustedFederatedProvider.TrustedFederatedProvider,
a.Id,
graph.EdgeAttribute("FederatedAssumeRole", "Trusted federated provider"),
)
if err != nil {
fmt.Println(err)
fmt.Println(TrustedFederatedProvider.TrustedFederatedProvider + a.Id + "Trusted federated provider")
}
}
return relationships
}
+71
View File
@@ -0,0 +1,71 @@
package models
import (
"fmt"
"github.com/BishopFox/cloudfox/aws/graph/ingester/schema"
)
type User struct {
Id string
ARN string
Name string
IsAdmin string
CanPrivEscToAdmin string
IdValue string
}
func (a *User) MakeRelationships() []schema.Relationship {
// make a relationship between each role and the account it belongs to
relationships := []schema.Relationship{}
// get thisAccount id from user arn
var thisAccount string
if len(a.ARN) >= 25 {
thisAccount = a.ARN[13:25]
} else {
fmt.Sprintf("Could not get account number from this user arn%s", a.ARN)
}
relationships = append(relationships, schema.Relationship{
SourceNodeID: a.Id,
TargetNodeID: thisAccount,
SourceLabel: schema.User,
TargetLabel: schema.Account,
RelationshipType: schema.MemberOf,
Properties: map[string]interface{}{},
})
return relationships
}
func (a *User) GenerateAttributes() map[string]string {
return map[string]string{
"Id": a.Id,
"ARN": a.ARN,
"Name": a.Name,
"IsAdmin": a.IsAdmin,
"CanPrivEscToAdmin": a.CanPrivEscToAdmin,
"IdValue": a.IdValue,
}
}
func (a *User) MergeAttributes(other map[string]string) {
if other["Id"] != "" {
a.Id = other["Id"]
}
if other["ARN"] != "" {
a.ARN = other["ARN"]
}
if other["Name"] != "" {
a.Name = other["Name"]
}
if other["IsAdmin"] != "" {
a.IsAdmin = other["IsAdmin"]
}
if other["CanPrivEscToAdmin"] != "" {
a.CanPrivEscToAdmin = other["CanPrivEscToAdmin"]
}
if other["IdValue"] != "" {
a.IdValue = other["IdValue"]
}
}
+148
View File
@@ -0,0 +1,148 @@
package schema
import (
"fmt"
"reflect"
"github.com/goccy/go-json"
"golang.org/x/exp/slices"
)
type RelationshipType string
type NodeLabel string
type Node interface {
MakeRelationships() []Relationship
}
type Relationship struct {
SourceNodeID string `json:"sourceNodeId"`
TargetNodeID string `json:"targetNodeId"`
SourceLabel NodeLabel `json:"sourceLabel"`
TargetLabel NodeLabel `json:"targetLabel"`
RelationshipType RelationshipType `json:"relationshipType"`
Properties map[string]interface{} `json:"properties"`
SourceProperty string `json:"sourceProperty"`
TargetProperty string `json:"targetProperty"`
}
const (
// Relationships
AssociatedTo RelationshipType = "AssociatedTo"
AttachedTo RelationshipType = "AttachedTo"
Authenticates RelationshipType = "Authenticates"
ConnectedTo RelationshipType = "ConnectedTo"
Contains RelationshipType = "Contains"
Exposes RelationshipType = "Exposes"
HasAccess RelationshipType = "HasAccess"
HasConfig RelationshipType = "HasConfig"
HasDisk RelationshipType = "HasDisk"
HasInstance RelationshipType = "HasInstance"
HasRbac RelationshipType = "HasRbac"
HasRole RelationshipType = "HasRole"
Manages RelationshipType = "Manages"
MemberOf RelationshipType = "MemberOf"
Owns RelationshipType = "Owns"
Represents RelationshipType = "Represents"
Trusts RelationshipType = "Trusts"
IsTrustedBy RelationshipType = "IsTrustedBy"
CanAssume RelationshipType = "CanAssume"
CanAssumeCrossAccount RelationshipType = "CanAssumeCrossAccount"
CanBeAssumedBy RelationshipType = "CanBeAssumedBy"
CanBeAssumedByTest RelationshipType = "CanBeAssumedByTest"
CanAssumeTest RelationshipType = "CanAssumeTest"
CanAccess RelationshipType = "CAN_ACCESS"
)
const (
// Node labels
Resource NodeLabel = "Resource"
Account NodeLabel = "Account"
Organization NodeLabel = "Org"
Service NodeLabel = "Service"
Principal NodeLabel = "Principal"
Vendor NodeLabel = "Vendor"
Role NodeLabel = "Role"
Group NodeLabel = "Group"
User NodeLabel = "User"
FederatedIdentity NodeLabel = "FederatedIdentity"
)
func AsNeo4j(object *Node) map[string]interface{} {
// We don't want to include these fields in the map
fieldsToExclude := []string{"members", "owners", "appRoles", "registeredUsers"}
objectMap, err := json.Marshal(object)
if err != nil {
return nil
}
var objectMapInterface map[string]interface{}
json.Unmarshal(objectMap, &objectMapInterface)
for _, field := range fieldsToExclude {
delete(objectMapInterface, field)
}
// We need to convert flatten maps to an array
// We'll want to keep order of the keys for things like extensionAttributes
for key, value := range objectMapInterface {
_, isMap := value.(map[string]interface{})
if isMap {
var valueArray []string
var keys []string
for k := range value.(map[string]interface{}) {
keys = append(keys, k)
}
slices.Sort(keys)
for _, k := range keys {
valueString := value.(map[string]interface{})[k].(string)
if valueString != "" {
valueArray = append(valueArray, k, valueString)
}
}
objectMapInterface[key] = valueArray
}
}
return objectMapInterface
}
func ConvertCustomTypesToNeo4j(node interface{}) (map[string]interface{}, error) {
result := make(map[string]interface{})
val := reflect.ValueOf(node)
// Handling pointers to structs or interfaces
for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
val = val.Elem()
}
// Check if the value is valid and if it's a struct
if !val.IsValid() || val.Kind() != reflect.Struct {
return nil, fmt.Errorf("invalid input: not a struct or a pointer to a struct")
}
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := val.Type().Field(i) // Get the StructField
// Check if the field is a struct or slice of structs and not one of the basic types
if (fieldType.Type.Kind() == reflect.Struct ||
(fieldType.Type.Kind() == reflect.Slice && fieldType.Type.Elem().Kind() == reflect.Struct)) &&
fieldType.Type != reflect.TypeOf([]string{}) &&
fieldType.Type != reflect.TypeOf([]int{}) &&
fieldType.Type != reflect.TypeOf([]bool{}) {
// Convert complex field to JSON string
jsonStr, err := json.Marshal(field.Interface())
if err != nil {
return nil, err
}
result[fieldType.Name] = string(jsonStr)
} else {
// Directly use the field for primitive types
result[fieldType.Name] = field.Interface()
}
}
return result, nil
}
+9 -8
View File
@@ -24,12 +24,13 @@ import (
type InstancesModule struct {
// General configuration data
EC2Client sdk.AWSEC2ClientInterface
IAMClient sdk.AWSIAMClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
EC2Client sdk.AWSEC2ClientInterface
IAMClient sdk.AWSIAMClientInterface
Caller sts.GetCallerIdentityOutput
AWSRegions []string
AWSOutputType string
AWSTableCols string
PmapperDataBasePath string
Goroutines int
UserDataAttributesOnly bool
@@ -94,8 +95,8 @@ func (m *InstancesModule) Instances(filter string, outputDirectory string, verbo
// Initialized the tools we'll need to check if any workload roles are admin or can privesc to admin
//fmt.Printf("[%s][%s] Attempting to build a PrivEsc graph in memory using local pmapper data if it exists on the filesystem.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
// if m.pmapperError != nil {
// fmt.Printf("[%s][%s] No pmapper data found for this account. Using cloudfox's iam-simulator for role analysis.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
+11 -9
View File
@@ -31,13 +31,15 @@ type LambdasModule struct {
AWSOutputType string
AWSTableCols string
Goroutines int
AWSProfile string
SkipAdminCheck bool
WrapTable bool
pmapperMod PmapperModule
pmapperError error
iamSimClient IamSimulatorModule
Goroutines int
AWSProfile string
SkipAdminCheck bool
WrapTable bool
pmapperMod PmapperModule
pmapperError error
PmapperDataBasePath string
iamSimClient IamSimulatorModule
// Main module data
Lambdas []Lambda
@@ -75,8 +77,8 @@ func (m *LambdasModule) PrintLambdas(outputDirectory string, verbosity int) {
fmt.Printf("[%s][%s] Enumerating lambdas for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
//fmt.Printf("[%s][%s] Attempting to build a PrivEsc graph in memory using local pmapper data if it exists on the filesystem.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
// if m.pmapperError != nil {
// fmt.Printf("[%s][%s] No pmapper data found for this account. Using cloudfox's iam-simulator for role analysis.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
+132 -1
View File
@@ -50,6 +50,7 @@ type OutboundAssumeRoleEntry struct {
SourcePrincipal string
DestinationAccount string
DestinationPrincipal string
Action string
LogTimestamp string
}
@@ -117,6 +118,24 @@ type CloudTrailEvent struct {
} `json:"tlsDetails"`
}
var interestingCrossAccountEventNames = []string{
"AssumeRole",
"AssumeRoleWithSAML",
"AssumeRoleWithWebIdentity",
"GetObject",
"ListBuckets",
"BatchGetImage",
"GetDownloadUrlForLayer",
"SendMessage",
"GetQueueUrl",
"Invoke20150331",
"RunInstances",
"RunTask",
"StartTask",
"CreateTask",
"CreateTaskSet",
}
func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputDirectory string, verbosity int) {
// These struct values are used by the output module
m.output.Verbosity = verbosity
@@ -171,6 +190,7 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputDir
"Source Principal",
//"Destination Account",
"Destination Principal",
"Action",
"Log Entry Timestamp",
}
@@ -194,6 +214,7 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputDir
"Source Principal",
//"Destination Account",
"Destination Principal",
"Action",
"Log Entry Timestamp",
}
// Otherwise, use the default columns.
@@ -206,6 +227,7 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputDir
"Source Principal",
//"Destination Account",
"Destination Principal",
"Action",
"Log Entry Timestamp",
}
}
@@ -222,6 +244,7 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputDir
m.OutboundAssumeRoleEntries[i].SourcePrincipal,
//m.OutboundAssumeRoleEntries[i].DestinationAccount,
m.OutboundAssumeRoleEntries[i].DestinationPrincipal,
m.OutboundAssumeRoleEntries[i].Action,
m.OutboundAssumeRoleEntries[i].LogTimestamp,
},
)
@@ -279,9 +302,12 @@ func (m *OutboundAssumedRolesModule) executeChecks(r string, wg *sync.WaitGroup,
m.modLog.Error(err)
}
if res {
// wg.Add(1)
// m.CommandCounter.Total++
// m.getAssumeRoleLogEntriesPerRegion(r, wg, semaphore, dataReceiver)
wg.Add(1)
m.CommandCounter.Total++
m.getAssumeRoleLogEntriesPerRegion(r, wg, semaphore, dataReceiver)
m.getCrossAccountBatchGetImageEntriesPerRegion(r, wg, semaphore, dataReceiver)
}
}
@@ -359,6 +385,7 @@ func (m *OutboundAssumedRolesModule) getAssumeRoleLogEntriesPerRegion(r string,
SourcePrincipal: sourcePrincipal,
DestinationAccount: destinationAccount,
DestinationPrincipal: destinationPrincipal,
Action: "sts:AssumeRole",
LogTimestamp: logTimestamp,
}
}
@@ -376,3 +403,107 @@ func (m *OutboundAssumedRolesModule) getAssumeRoleLogEntriesPerRegion(r string,
}
}
// get cross account batch get image entries
func (m *OutboundAssumedRolesModule) getCrossAccountBatchGetImageEntriesPerRegion(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan OutboundAssumeRoleEntry) {
defer func() {
m.CommandCounter.Executing--
m.CommandCounter.Complete++
wg.Done()
}()
semaphore <- struct{}{}
defer func() {
<-semaphore
}()
// "PaginationMarker" is a control variable used for output continuity, as AWS return the output in pages.
var PaginationControl *string
//var LookupAttributes []types.LookupAttributes
//var LookupAttribute types.LookupAttribute
var pages int
days := 0 - m.Days
endTime := aws.Time(time.Now())
startTime := endTime.AddDate(0, 0, days)
for {
LookupEvents, err := m.CloudTrailClient.LookupEvents(
context.TODO(),
&cloudtrail.LookupEventsInput{
EndTime: endTime,
StartTime: &startTime,
// LookupAttributes: []cloudtrailTypes.LookupAttribute{
// {
// AttributeKey: cloudtrailTypes.LookupAttributeKeyEventName,
// AttributeValue: aws.String("BatchGetImage"),
// },
// },
NextToken: PaginationControl,
},
func(o *cloudtrail.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
for _, event := range LookupEvents.Events {
//eventData := *event.CloudTrailEvent
//fmt.Println(eventData)
var sourceAccount, sourcePrincipal, destinationAccount, destinationPrincipal, userType string
cloudtrailEvent := CloudTrailEvent{}
json.Unmarshal([]byte(*event.CloudTrailEvent), &cloudtrailEvent)
for _, eventName := range interestingCrossAccountEventNames {
if aws.ToString(event.EventName) == eventName {
// extract the source account and principal
if cloudtrailEvent.UserIdentity.Type == "AssumedRole" || cloudtrailEvent.UserIdentity.Type == "IAMUser" || cloudtrailEvent.UserIdentity.Type == "Role" {
if cloudtrailEvent.UserIdentity.Type == "AssumedRole" {
sourcePrincipal = cloudtrailEvent.UserIdentity.SessionContext.SessionIssuer.Arn
} else {
sourcePrincipal = cloudtrailEvent.UserIdentity.Arn
}
userType = cloudtrailEvent.UserIdentity.Type
sourceAccount = cloudtrailEvent.UserIdentity.AccountID
//fmt.Printf("%s,%s,%s,%s\n", sourceAccount, sourcePrincipal, destinationAccount, destinationPrincipal)
if cloudtrailEvent.Resources != nil {
destinationAccount = cloudtrailEvent.Resources[0].AccountID
destinationPrincipal = cloudtrailEvent.Resources[0].Arn
if sourceAccount != destinationAccount {
logTimestamp := cloudtrailEvent.EventTime.Format("2006-01-02 15:04:05")
dataReceiver <- OutboundAssumeRoleEntry{
AWSService: "CloudTrail",
Region: r,
Type: userType,
SourceAccount: sourceAccount,
SourcePrincipal: sourcePrincipal,
DestinationAccount: destinationAccount,
DestinationPrincipal: destinationPrincipal,
Action: aws.ToString(event.EventName),
LogTimestamp: logTimestamp,
}
}
}
}
}
}
}
// The "NextToken" value is nil when there's no more data to return.
if LookupEvents.NextToken != nil {
PaginationControl = LookupEvents.NextToken
pages++
} else {
PaginationControl = nil
break
}
}
}
+15 -24
View File
@@ -11,6 +11,7 @@ import (
"github.com/BishopFox/cloudfox/aws/sdk"
"github.com/BishopFox/cloudfox/internal"
"github.com/BishopFox/cloudfox/internal/aws/policy"
"github.com/BishopFox/cloudfox/internal/common"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
@@ -36,7 +37,7 @@ type IamPermissionsModule struct {
Users []GAADUser
Roles []GAADRole
Groups []GAADGroup
Rows []PermissionsRow
Rows []common.PermissionsRow
CommandCounter internal.CommandCounter
// Used to store output data for pretty printing
output internal.OutputData2
@@ -71,20 +72,6 @@ type GAADGroup struct {
InlinePolicies []types.PolicyDetail
}
type PermissionsRow struct {
AWSService string
Type string
Name string
Arn string
PolicyType string
PolicyName string
PolicyArn string
Effect string
Action string
Resource string
Condition string
}
func (m *IamPermissionsModule) PrintIamPermissions(outputDirectory string, verbosity int, principal string) {
// These struct values are used by the output module
m.output.Verbosity = verbosity
@@ -104,8 +91,8 @@ func (m *IamPermissionsModule) PrintIamPermissions(outputDirectory string, verbo
filename = filepath.Join(fmt.Sprintf("%s-custom-%s", m.output.CallingModule, strconv.FormatInt((time.Now().Unix()), 10)))
}
m.getGAAD()
m.parsePermissions(principal)
m.GetGAAD()
m.ParsePermissions(principal)
m.output.Headers = []string{
"Account",
@@ -206,10 +193,10 @@ func (m *IamPermissionsModule) PrintIamPermissions(outputDirectory string, verbo
fmt.Printf("[%s][%s] For context and next steps: https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#%s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), m.output.CallingModule)
}
func (m *IamPermissionsModule) getGAAD() {
func (m *IamPermissionsModule) GetGAAD() {
GAAD, err := sdk.CachedIAMGetAccountAuthorizationDetails(m.IAMClient, aws.ToString(m.Caller.Account))
if err != nil {
m.modLog.Error(err.Error())
TxtLogger.Error(err.Error())
m.CommandCounter.Error++
return
}
@@ -297,7 +284,7 @@ func (m *IamPermissionsModule) getPrincipalArn(principal string) string {
return arn
}
func (m *IamPermissionsModule) parsePermissions(principal string) {
func (m *IamPermissionsModule) ParsePermissions(principal string) {
var inputArn string
for i := range m.Roles {
if principal == "" {
@@ -422,6 +409,10 @@ func (m *IamPermissionsModule) getPermissionsFromAttachedPolicy(arn string, atta
//parsedPolicyDocument, _ := parsePolicyDocument(d.Document)
document, _ := url.QueryUnescape(aws.ToString(d.Document))
parsedPolicyDocument, _ := policy.ParseJSONPolicy([]byte(document))
// hasStsAssumeRole := parsedPolicyDocument.DoesPolicyHaveMatchingStatement("Allow", "sts:AssumeRole", "*")
// fmt.Println(hasStsAssumeRole)
for _, s = range parsedPolicyDocument.Statement {
//version := parsedPolicyDocument.Version
effect := s.Effect
@@ -435,7 +426,7 @@ func (m *IamPermissionsModule) getPermissionsFromAttachedPolicy(arn string, atta
}
m.Rows = append(
m.Rows,
PermissionsRow{
common.PermissionsRow{
AWSService: AWSService,
Arn: arn,
Name: name,
@@ -462,7 +453,7 @@ func (m *IamPermissionsModule) getPermissionsFromAttachedPolicy(arn string, atta
}
m.Rows = append(
m.Rows,
PermissionsRow{
common.PermissionsRow{
AWSService: AWSService,
Arn: arn,
Name: name,
@@ -508,7 +499,7 @@ func (m *IamPermissionsModule) getPermissionsFromInlinePolicy(arn string, inline
}
m.Rows = append(
m.Rows,
PermissionsRow{
common.PermissionsRow{
AWSService: AWSService,
Arn: arn,
Name: name,
@@ -534,7 +525,7 @@ func (m *IamPermissionsModule) getPermissionsFromInlinePolicy(arn string, inline
}
m.Rows = append(
m.Rows,
PermissionsRow{
common.PermissionsRow{
AWSService: AWSService,
Arn: arn,
Name: name,
+354 -23
View File
@@ -1,6 +1,7 @@
package aws
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
@@ -10,9 +11,11 @@ import (
"strings"
"github.com/BishopFox/cloudfox/internal"
"github.com/BishopFox/cloudfox/internal/aws/policy"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/dominikbraun/graph"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
"github.com/sirupsen/logrus"
)
@@ -28,15 +31,22 @@ type PmapperModule struct {
WrapTable bool
// Main module data
pmapperGraph graph.Graph[string, string]
Nodes []Node
Edges []Edge
CommandCounter internal.CommandCounter
PmapperDataBasePath string
pmapperGraph graph.Graph[string, string]
Nodes []Node
Edges []Edge
CommandCounter internal.CommandCounter
// Used to store output data for pretty printing
output internal.OutputData2
modLog *logrus.Entry
}
type PmapperOutputRow struct {
Start string
End string
Paths []string
}
type Edge struct {
Source string `json:"source"`
Destination string `json:"destination"`
@@ -45,19 +55,54 @@ type Edge struct {
}
type Node struct {
Arn string `json:"arn"`
IDValue string `json:"id_value"`
AttachedPolicies []AttachedPolicies `json:"attached_policies"`
GroupMemberships []interface{} `json:"group_memberships"`
TrustPolicy interface{} `json:"trust_policy"`
InstanceProfile interface{} `json:"instance_profile"`
ActivePassword bool `json:"active_password"`
AccessKeys int `json:"access_keys"`
IsAdmin bool `json:"is_admin"`
PermissionsBoundary interface{} `json:"permissions_boundary"`
HasMfa bool `json:"has_mfa"`
Tags Tags `json:"tags"`
PathToAdmin bool
Arn string `json:"arn"`
Type string
AccountID string
Name string
IDValue string `json:"id_value"`
AttachedPolicies []AttachedPolicies `json:"attached_policies"`
GroupMemberships []interface{} `json:"group_memberships"`
TrustPolicy interface{} `json:"trust_policy"`
TrustsDoc policy.TrustPolicyDocument
TrustedPrincipals []TrustedPrincipal
TrustedServices []TrustedService
TrustedFederatedProviders []TrustedFederatedProvider
InstanceProfile interface{} `json:"instance_profile"`
ActivePassword bool `json:"active_password"`
AccessKeys int `json:"access_keys"`
IsAdmin bool `json:"is_admin"`
PathToAdmin bool
PermissionsBoundary interface{} `json:"permissions_boundary"`
HasMfa bool `json:"has_mfa"`
Tags Tags `json:"tags"`
CanPrivEscToAdminString string
IsAdminString string
VendorName string
}
type TrustedPrincipal struct {
TrustedPrincipal string
ExternalID string
VendorName string
AccountIsInAnalyzedAccountList bool
//IsAdmin bool
//CanPrivEscToAdmin bool
}
type TrustedService struct {
TrustedService string
AccountID string
//IsAdmin bool
//CanPrivEscToAdmin bool
}
type TrustedFederatedProvider struct {
TrustedFederatedProvider string
ProviderAccountId string
ProviderShortName string
TrustedSubjects []string
//IsAdmin bool
//CanPrivEscToAdmin bool
}
type AttachedPolicies struct {
@@ -79,9 +124,16 @@ func (m *PmapperModule) initPmapperGraph() error {
for i := range m.Nodes {
if m.doesNodeHavePathToAdmin(m.Nodes[i]) {
m.Nodes[i].PathToAdmin = true
m.Nodes[i].CanPrivEscToAdminString = "Yes"
//fmt.Println(m.Nodes[i].Arn, m.Nodes[i].IsAdmin, m.Nodes[i].PathToAdmin)
} else {
m.Nodes[i].PathToAdmin = false
m.Nodes[i].CanPrivEscToAdminString = "No"
}
if m.Nodes[i].IsAdmin {
m.Nodes[i].IsAdminString = "Yes"
} else {
m.Nodes[i].IsAdminString = "No"
}
}
@@ -107,7 +159,39 @@ func (m *PmapperModule) createAndPopulateGraph() graph.Graph[string, string] {
}
for _, edge := range m.Edges {
_ = pmapperGraph.AddEdge(edge.Source, edge.Destination)
err := pmapperGraph.AddEdge(
edge.Source,
edge.Destination,
graph.EdgeAttribute(edge.ShortReason, edge.Reason),
)
if err != nil {
if err == graph.ErrEdgeAlreadyExists {
// update the edge by copying the existing graph.Edge with attributes and add the new attributes
//fmt.Println("Edge already exists, but adding a new one!")
// get the existing edge
existingEdge, _ := pmapperGraph.Edge(edge.Source, edge.Destination)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes[edge.ShortReason] = edge.Reason
//Update the edge
pmapperGraph.UpdateEdge(
edge.Source,
edge.Destination,
graph.EdgeAttributes(existingProperties.Attributes),
)
}
//fmt.Println(edge.Reason)
}
}
//internal.Cache.Set(cacheKey, pmapperGraph, cache.DefaultExpiration)
@@ -119,7 +203,11 @@ func (m *PmapperModule) DoesPrincipalHavePathToAdmin(principal string) bool {
for i := range m.Nodes {
if m.Nodes[i].Arn == principal {
if m.Nodes[i].PathToAdmin {
m.Nodes[i].CanPrivEscToAdminString = "Yes"
return true
} else {
m.Nodes[i].CanPrivEscToAdminString = "No"
return false
}
}
@@ -131,7 +219,11 @@ func (m *PmapperModule) DoesPrincipalHaveAdmin(principal string) bool {
for i := range m.Nodes {
if m.Nodes[i].Arn == principal {
if m.Nodes[i].IsAdmin {
m.Nodes[i].IsAdminString = "Yes"
return true
} else {
m.Nodes[i].IsAdminString = "No"
return false
}
}
@@ -234,6 +326,9 @@ func (m *PmapperModule) PrintPmapperData(outputDirectory string, verbosity int)
Table: internal.TableClient{
Wrap: m.WrapTable,
},
Loot: internal.LootClient{
DirectoryName: m.output.FilePath,
},
}
o.Table.TableFiles = append(o.Table.TableFiles, internal.TableFile{
Header: m.output.Headers,
@@ -243,7 +338,21 @@ func (m *PmapperModule) PrintPmapperData(outputDirectory string, verbosity int)
})
o.PrefixIdentifier = m.AWSProfile
o.Table.DirectoryName = filepath.Join(outputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", m.AWSProfile, aws.ToString(m.Caller.Account)))
o.WriteFullOutput(o.Table.TableFiles, nil)
header, body := m.createPmapperTableData(outputDirectory)
o.Table.TableFiles = append(o.Table.TableFiles, internal.TableFile{
Header: header,
Body: body,
Name: "pmapper-privesc-paths-enhanced",
SkipPrintToScreen: true,
})
loot := m.writeLoot(o.Table.DirectoryName, verbosity)
o.Loot.LootFiles = append(o.Loot.LootFiles, internal.LootFile{
Name: m.output.CallingModule,
Contents: loot,
})
o.WriteFullOutput(o.Table.TableFiles, o.Loot.LootFiles)
//m.writeLoot(o.Table.DirectoryName, verbosity)
fmt.Printf("[%s][%s] %s principals who are admin or have a path to admin identified.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
@@ -264,9 +373,6 @@ func (m *PmapperModule) doesNodeHavePathToAdmin(startNode Node) bool {
for _, p := range path {
if p != "" {
if startNode.Arn != destNode.Arn {
// if we got here there is a path
//fmt.Printf("%s has a path %s who is an admin.\n", startNode.Arn, destNode.Arn)
//fmt.Println(path)
return true
}
@@ -278,9 +384,136 @@ func (m *PmapperModule) doesNodeHavePathToAdmin(startNode Node) bool {
return false
}
func (m *PmapperModule) createPmapperTableData(outputDirectory string) ([]string, [][]string) {
var header []string
var body [][]string
header = []string{
"Start",
"End",
"Path(s)",
}
var paths string
var admins, privescPathsBody [][]string
for _, startNode := range m.Nodes {
if startNode.IsAdmin {
admins = append(admins, []string{startNode.Arn, "", "ADMIN"})
} else {
for _, destNode := range m.Nodes {
if destNode.IsAdmin {
path, _ := graph.ShortestPath(m.pmapperGraph, startNode.Arn, destNode.Arn)
// if we have a path,
if len(path) > 0 {
if startNode.Arn != destNode.Arn {
paths = ""
// if we got herethere's a path. Lets print the reason and the short reason for each edge in the path to the screen
for i := 0; i < len(path)-1; i++ {
for _, edge := range m.Edges {
if edge.Source == path[i] && edge.Destination == path[i+1] {
//Some pmapper reasons have commas in them so lets get rid of them in the csvOutputdata
edge.Reason = strings.ReplaceAll(edge.Reason, ",", " and")
paths += fmt.Sprintf("%s %s %s\n", path[i], edge.Reason, path[i+1])
}
}
}
//trim the last newline from csvPaths
paths = strings.TrimSuffix(paths, "\n")
privescPathsBody = append(privescPathsBody, []string{startNode.Arn, destNode.Arn, paths})
}
}
}
}
}
}
// create body by first adding the admins and then the privesc paths
body = append(body, admins...)
body = append(body, privescPathsBody...)
return header, body
}
func (m *PmapperModule) writeLoot(outputDirectory string, verbosity int) string {
path := filepath.Join(outputDirectory, "loot")
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
panic(err.Error())
}
lootFilePath := filepath.Join(path, "pmapper.txt")
var admins, out string
for _, startNode := range m.Nodes {
if startNode.IsAdmin {
admins += fmt.Sprintf("ADMIN FOUND: %s\n", startNode.Arn)
} else {
for _, destNode := range m.Nodes {
if destNode.IsAdmin {
path, _ := graph.ShortestPath(m.pmapperGraph, startNode.Arn, destNode.Arn)
// if we have a path,
if len(path) > 0 {
if startNode.Arn != destNode.Arn {
// if we got here there is a path
out += fmt.Sprintf("PATH TO ADMIN FOUND\n Start: %s\n End: %s\n Path(s):\n", startNode.Arn, destNode.Arn)
//fmt.Println(path)
// if we got herethere's a path. Lets print the reason and the short reason for each edge in the path to the screen
for i := 0; i < len(path)-1; i++ {
for _, edge := range m.Edges {
if edge.Source == path[i] && edge.Destination == path[i+1] {
// print it like this: [start node] [reason] [end node]
out += fmt.Sprintf(" %s %s %s\n", path[i], edge.Reason, path[i+1])
}
// shortest path only finds the shortest path. We want to find all paths. So we need to find all paths that have the same start and end nodes from the path, but going back to the main edges slice
//for _, edge := range GlobalPmapperEdges {
// if edge.Source == path[i] && edge.Destination == path[i+1] {
// // print it like this: [start node] [reason] [end node]
// out += fmt.Sprintf(" %s %s %s\n", path[i], edge.Reason, path[i+1])
// }
// }
}
}
out += fmt.Sprintf("\n")
}
}
}
}
}
}
out = admins + "\n\n" + out
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Beginning of loot file"))
fmt.Print(out)
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file"))
}
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), magenta(fmt.Sprintf("Loot file with ALL potential paths written to: [%s]", lootFilePath)))
return out
}
func (m *PmapperModule) readPmapperData(accountID *string) error {
e, n := generatePmapperDataBasePaths(accountID)
var e, n string
if m.PmapperDataBasePath == "" {
e, n = generatePmapperDataBasePaths(accountID)
} else {
e = filepath.Join(m.PmapperDataBasePath, aws.ToString(accountID), "graph", "edges.json")
n = filepath.Join(m.PmapperDataBasePath, aws.ToString(accountID), "graph", "nodes.json")
}
nodesFile, err := os.Open(n)
if err != nil {
@@ -301,3 +534,101 @@ func (m *PmapperModule) readPmapperData(accountID *string) error {
return nil
}
func (m *PmapperModule) GenerateCypherStatements(goCtx context.Context, driver neo4j.DriverWithContext) error {
// Insert nodes
for i, node := range m.Nodes {
query, params := m.generateNodeCreateStatement(node, i)
if err := m.executeCypherQuery(goCtx, driver, query, params); err != nil {
return err
}
}
// Insert edges
for i, edge := range m.Edges {
query, params := m.generateEdgeCreateStatement(edge, i)
if err := m.executeCypherQuery(goCtx, driver, query, params); err != nil {
return err
}
}
return nil
}
func (m *PmapperModule) generateNodeCreateStatement(node Node, i int) (string, map[string]interface{}) {
var ptype, label, query string
var params map[string]any
if strings.Contains(node.Arn, "role") {
label = GetResourceNameFromArn(node.Arn)
ptype = "Role"
params = map[string]any{
"Id": node.Arn,
"ARN": node.Arn,
"Name": GetResourceNameFromArn(node.Arn),
"IdValue": node.IDValue,
"IsAdminP": node.IsAdmin,
"PathToAdmin": node.PathToAdmin,
}
} else if strings.Contains(node.Arn, "user") {
label = GetResourceNameFromArn(node.Arn)
ptype = "User"
//node.TrustPolicy = ""
params = map[string]any{
"Id": node.Arn,
"ARN": node.Arn,
"Name": GetResourceNameFromArn(node.Arn),
"IdValue": node.IDValue,
"IsAdminP": node.IsAdmin,
"PathToAdmin": node.PathToAdmin,
}
} else if strings.Contains(node.Arn, "group") {
label = GetResourceNameFromArn(node.Arn)
ptype = "Group"
}
label = strings.ReplaceAll(label, "-", "_")
label = strings.ReplaceAll(label, ".", "_")
query = `MERGE (%s:%s {Id: $Id, ARN: $ARN, Name: $Name, IdValue: $IdValue, IsAdminP: $IsAdminP, PathToAdmin: $PathToAdmin})`
//sanitizedArn := sanitizeArnForNeo4jLabel(node.Arn)
//id := fmt.Sprintf("%s_%s", sanitizedArn, ptype)
fmt.Println(fmt.Sprintf(query, label, ptype), params)
return fmt.Sprintf(query, label, ptype), params
}
func (m *PmapperModule) generateEdgeCreateStatement(edge Edge, i int) (string, map[string]interface{}) {
// Sanitize ARNs for matching nodes
//srcArnSanitized := sanitizeArnForNeo4jLabel(edge.Source)
//destArnSanitized := sanitizeArnForNeo4jLabel(edge.Destination)
query := `MATCH (a {ARN: $srcArn}), (b {ARN: $destArn}) CREATE (a)-[:CAN_ACCESS {reason: $reason, shortReason: $shortReason}]->(b)`
params := map[string]any{
"srcArn": edge.Source,
"destArn": edge.Destination,
"reason": edge.Reason,
"shortReason": edge.ShortReason,
}
fmt.Println(query, params)
return query, params
}
func (m *PmapperModule) executeCypherQuery(ctx context.Context, driver neo4j.DriverWithContext, query string, params map[string]interface{}) error {
_, err := neo4j.ExecuteQuery(ctx, driver, query, params, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("neo4j"))
if err != nil {
sharedLogger.Errorf("Error executing query: %s -- %v", err, params)
return err
}
return nil
}
func sanitizeArnForNeo4jLabel(arn string) string {
// Replace non-allowed characters with underscores or other allowed characters
sanitized := strings.ReplaceAll(arn, ":", "_")
sanitized = strings.ReplaceAll(sanitized, "-", "_")
// Add more replacements if needed
return sanitized
}
+19 -7
View File
@@ -31,8 +31,10 @@ type RoleTrustsModule struct {
AWSOutputType string
AWSTableCols string
pmapperMod PmapperModule
pmapperError error
pmapperMod PmapperModule
pmapperError error
PmapperDataBasePath string
iamSimClient IamSimulatorModule
// Main module data
@@ -83,8 +85,8 @@ func (m *RoleTrustsModule) PrintRoleTrusts(outputDirectory string, verbosity int
fmt.Printf("[%s][%s] Enumerating role trusts for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
//fmt.Printf("[%s][%s] Looking for pmapper data for this account and building a PrivEsc graph in golang if it exists.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
// if m.pmapperError != nil {
// fmt.Printf("[%s][%s] No pmapper data found for this account. Using cloudfox's iam-simulator for role analysis\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
// } else {
@@ -467,7 +469,11 @@ func parseFederatedTrustPolicy(statement policy.RoleTrustStatementEntry) (string
subjects = append(subjects, "ALL REPOS!!!")
}
case strings.Contains(statement.Principal.Federated[0], "oidc.eks"):
provider = "EKS"
// extract accountId from statement.Principal.Federated[0]
accountId := strings.Split(statement.Principal.Federated[0], ":")[4]
provider = fmt.Sprintf("EKS-%s", accountId)
//provider = "EKS"
//provider = statement.Principal.Federated[0]
if len(statement.Condition.StringLike.OidcEksSub) > 0 {
subjects = append(subjects, statement.Condition.StringLike.OidcEksSub...)
} else if len(statement.Condition.StringEquals.OidcEksSub) > 0 {
@@ -496,9 +502,11 @@ func parseFederatedTrustPolicy(statement policy.RoleTrustStatementEntry) (string
subjects = append(subjects, "ALL ISSUERS")
}
// AWS SSO case
///AWS SSO case
case strings.Contains(statement.Principal.Federated[0], "AWSSSO"):
provider = "AWS SSO"
//provider = "AWS SSO"
accountId := strings.Split(statement.Principal.Federated[0], ":")[4]
provider = fmt.Sprintf("AWSSSO-%s", accountId)
subjects = append(subjects, "Not applicable")
// okta case
@@ -553,6 +561,10 @@ func parseFederatedTrustPolicy(statement policy.RoleTrustStatementEntry) (string
} else {
subjects = append(subjects, "ALL PROJECTS")
}
case strings.Contains(statement.Principal.Federated[0], "saml-provider"):
// the provider name is the last part of the ARN
provider = strings.Split(statement.Principal.Federated[0], ":saml-provider/")[1]
subjects = append(subjects, "Not applicable")
default:
provider = "Unknown Federated Provider"
+1
View File
@@ -20,6 +20,7 @@ type CodeBuildClientInterface interface {
func init() {
gob.Register(codeBuildTypes.Project{})
gob.Register([]codeBuildTypes.Project{})
}
+95
View File
@@ -0,0 +1,95 @@
package sdk
import (
"context"
"encoding/gob"
"fmt"
"github.com/patrickmn/go-cache"
"github.com/BishopFox/cloudfox/internal"
"github.com/aws/aws-sdk-go-v2/service/directoryservice"
dsTypes "github.com/aws/aws-sdk-go-v2/service/directoryservice/types"
)
type AWSDSClientInterface interface {
DescribeDirectories(context.Context, *directoryservice.DescribeDirectoriesInput, ...func(*directoryservice.Options)) (*directoryservice.DescribeDirectoriesOutput, error)
DescribeTrusts(context.Context, *directoryservice.DescribeTrustsInput, ...func(*directoryservice.Options)) (*directoryservice.DescribeTrustsOutput, error)
}
func init() {
gob.Register([]dsTypes.DirectoryDescription{})
gob.Register([]dsTypes.Trust{})
}
func CachedDSDescribeDirectories(client AWSDSClientInterface, accountID string, region string) ([]dsTypes.DirectoryDescription, error) {
var PaginationControl *string
var directories []dsTypes.DirectoryDescription
cacheKey := fmt.Sprintf("%s-ds-DescribeDirectories-%s", accountID, region)
cached, found := internal.Cache.Get(cacheKey)
if found {
return cached.([]dsTypes.DirectoryDescription), nil
}
for {
DescribeDirectories, err := client.DescribeDirectories(
context.TODO(),
&directoryservice.DescribeDirectoriesInput{
NextToken: PaginationControl,
},
func(o *directoryservice.Options) {
o.Region = region
},
)
if err != nil {
return directories, err
}
directories = append(directories, DescribeDirectories.DirectoryDescriptions...)
//pagination
if DescribeDirectories.NextToken == nil {
break
}
PaginationControl = DescribeDirectories.NextToken
}
internal.Cache.Set(cacheKey, directories, cache.DefaultExpiration)
return directories, nil
}
func CachedDSDescribeTrusts(client AWSDSClientInterface, accountID string, region string, directoryId string) ([]dsTypes.Trust, error) {
var PaginationControl *string
var trusts []dsTypes.Trust
cacheKey := fmt.Sprintf("%s-ds-DescribeTrusts-%s-%s", accountID, region, directoryId)
cached, found := internal.Cache.Get(cacheKey)
if found {
return cached.([]dsTypes.Trust), nil
}
for {
DescribeDirectoryTrusts, err := client.DescribeTrusts(
context.TODO(),
&directoryservice.DescribeTrustsInput{
DirectoryId: &directoryId,
NextToken: PaginationControl,
},
func(o *directoryservice.Options) {
o.Region = region
},
)
if err != nil {
return trusts, err
}
trusts = append(trusts, DescribeDirectoryTrusts.Trusts...)
//pagination
if DescribeDirectoryTrusts.NextToken == nil {
break
}
PaginationControl = DescribeDirectoryTrusts.NextToken
}
internal.Cache.Set(cacheKey, trusts, cache.DefaultExpiration)
return trusts, nil
}
+5 -4
View File
@@ -77,11 +77,12 @@ func isRoleAdmin(iamSimMod IamSimulatorModule, principal *string) bool {
}
func initPmapperGraph(Caller sts.GetCallerIdentityOutput, AWSProfile string, Goroutines int) (PmapperModule, error) {
func InitPmapperGraph(Caller sts.GetCallerIdentityOutput, AWSProfile string, Goroutines int, PmapperDataBasePath string) (PmapperModule, error) {
pmapperMod := PmapperModule{
Caller: Caller,
AWSProfile: AWSProfile,
Goroutines: Goroutines,
Caller: Caller,
AWSProfile: AWSProfile,
Goroutines: Goroutines,
PmapperDataBasePath: PmapperDataBasePath,
}
err := pmapperMod.initPmapperGraph()
if err != nil {
+6 -4
View File
@@ -40,8 +40,10 @@ type WorkloadsModule struct {
//LightsailClient sdk.MockedLightsailClient
//SagemakerClient *sagemaker.Client
pmapperMod PmapperModule
pmapperError error
pmapperMod PmapperModule
pmapperError error
PmapperDataBasePath string
iamSimClient IamSimulatorModule
InstanceProfileToRolesMap map[string][]iamTypes.Role
@@ -82,8 +84,8 @@ func (m *WorkloadsModule) PrintWorkloads(outputDirectory string, verbosity int)
fmt.Printf("[%s][%s] Enumerating compute workloads in all regions for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Supported Services: App Runner, EC2, ECS, Lambda \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
m.pmapperMod, m.pmapperError = initPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines)
m.iamSimClient = initIAMSimClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
m.pmapperMod, m.pmapperError = InitPmapperGraph(m.Caller, m.AWSProfile, m.Goroutines, m.PmapperDataBasePath)
m.iamSimClient = InitIamCommandClient(m.IAMClient, m.Caller, m.AWSProfile, m.Goroutines)
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
+618 -146
View File
@@ -10,6 +10,7 @@ import (
"github.com/BishopFox/cloudfox/aws"
"github.com/BishopFox/cloudfox/aws/sdk"
"github.com/BishopFox/cloudfox/internal"
"github.com/BishopFox/cloudfox/internal/common"
"github.com/aws/aws-sdk-go-v2/service/apigateway"
"github.com/aws/aws-sdk-go-v2/service/apigatewayv2"
"github.com/aws/aws-sdk-go-v2/service/apprunner"
@@ -23,6 +24,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/codecommit"
"github.com/aws/aws-sdk-go-v2/service/codedeploy"
"github.com/aws/aws-sdk-go-v2/service/datapipeline"
"github.com/aws/aws-sdk-go-v2/service/directoryservice"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ecr"
@@ -58,6 +60,8 @@ import (
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/aws/smithy-go/ptr"
"github.com/bishopfox/knownawsaccountslookup"
"github.com/dominikbraun/graph"
"github.com/fatih/color"
"github.com/kyokomi/emoji"
"github.com/spf13/cobra"
@@ -67,15 +71,17 @@ var (
cyan = color.New(color.FgCyan).SprintFunc()
green = color.New(color.FgGreen).SprintFunc()
red = color.New(color.FgRed).SprintFunc()
magenta = color.New(color.FgMagenta).SprintFunc()
defaultOutputDir = ptr.ToString(internal.GetLogDirPath())
AWSProfile string
AWSProfilesList string
AWSAllProfiles bool
AWSProfiles []string
AWSConfirm bool
AWSOutputType string
AWSTableCols string
AWSProfile string
AWSProfilesList string
AWSAllProfiles bool
AWSProfiles []string
AWSConfirm bool
AWSOutputType string
AWSTableCols string
PmapperDataBasePath string
AWSOutputDirectory string
AWSSkipAdminCheck bool
@@ -83,8 +89,9 @@ var (
AWSUseCache bool
AWSMFAToken string
Goroutines int
Verbosity int
Goroutines int
Verbosity int
AWSCommands = &cobra.Command{
Use: "aws",
Short: "See \"Available Commands\" for AWS Modules",
@@ -131,6 +138,20 @@ var (
PostRun: awsPostRun,
}
CapeAdminOnly bool
CapeJobName string
CapeCommand = &cobra.Command{
Use: "cape",
Aliases: []string{"CAPE"},
Short: "Cross-Account Privilege Escalation Route finder. Needs to be run with multiple profiles using -l or -a flag. Needs pmapper data to be present",
Long: "\nUse case examples:\n" +
os.Args[0] + " aws cape -l file_with_profile_names.txt --admin-only" +
os.Args[0] + " aws cape -l file_with_profile_names.txt # This default mode shows all inbound paths but is very slow when there are many accounts)",
PreRun: awsPreRun,
Run: runCapeCommand,
PostRun: awsPostRun,
}
CloudformationCommand = &cobra.Command{
Use: "cloudformation",
Aliases: []string{"cf", "cfstacks", "stacks"},
@@ -442,7 +463,6 @@ var (
Run: runTagsCommand,
PostRun: awsPostRun,
}
PmapperCommand = &cobra.Command{
Use: "pmapper",
@@ -455,6 +475,16 @@ var (
PostRun: awsPostRun,
}
GraphCommand = &cobra.Command{
Use: "graph",
Short: "INACTIVE (Use cape command instead) Graph the relationships between resources and insert into local Neo4j db",
Long: "\nUse case examples:\n" +
os.Args[0] + " aws graph -l /path/to/profiles",
PreRun: awsPreRun,
Run: runGraphCommand,
PostRun: awsPostRun,
}
WorkloadsCommand = &cobra.Command{
Use: "workloads",
Short: "Finds workloads with admin permissions or a path to admin permissions",
@@ -464,6 +494,15 @@ var (
PostRun: awsPostRun,
}
DirectoryServicesCommand = &cobra.Command{
Use: "ds",
Short: "Enumerate AWS-managed Active Directory instances and trusts",
Long: "\nUse case examples:\n" + os.Args[0] + " aws clouddirectory --profile readonly_profile",
PreRun: awsPreRun,
Run: runDirectoryServicesCommand,
PostRun: awsPostRun,
}
AllChecksCommand = &cobra.Command{
Use: "all-checks",
@@ -542,7 +581,7 @@ func awsPreRun(cmd *cobra.Command, args []string) {
continue
}
orgModuleClient := aws.InitOrgClient(*caller, profile, cmd.Root().Version, Goroutines, AWSMFAToken)
orgModuleClient := aws.InitOrgsClient(*caller, profile, cmd.Root().Version, Goroutines, AWSMFAToken)
isPartOfOrg := orgModuleClient.IsCallerAccountPartOfAnOrg()
if isPartOfOrg {
isMgmtAccount := orgModuleClient.IsManagementAccount(orgModuleClient.DescribeOrgOutput, ptr.ToString(caller.Account))
@@ -602,7 +641,7 @@ func FindOrgMgmtAccountAndReorderAccounts(AWSProfiles []string, version string)
fmt.Printf("[%s][%s] Loaded cached AWS data for to %s\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)), cyan(profile), ptr.ToString(caller.Account))
}
}
orgModuleClient := aws.InitOrgClient(*caller, profile, version, Goroutines, AWSMFAToken)
orgModuleClient := aws.InitOrgsClient(*caller, profile, version, Goroutines, AWSMFAToken)
orgModuleClient.DescribeOrgOutput, err = sdk.CachedOrganizationsDescribeOrganization(orgModuleClient.OrganizationsClient, ptr.ToString(caller.Account))
if err != nil {
continue
@@ -713,15 +752,16 @@ func runCodeBuildCommand(cmd *cobra.Command, args []string) {
continue
}
m := aws.CodeBuildModule{
CodeBuildClient: codebuild.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
CodeBuildClient: codebuild.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.PrintCodeBuildProjects(AWSOutputDirectory, Verbosity)
}
@@ -818,14 +858,15 @@ func runEKSCommand(cmd *cobra.Command, args []string) {
IAMClient: iam.NewFromConfig(AWSConfig),
EKSClient: eks.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.EKS(AWSOutputDirectory, Verbosity)
}
@@ -917,6 +958,378 @@ func runFilesystemsCommand(cmd *cobra.Command, args []string) {
}
}
func runGraphCommand(cmd *cobra.Command, args []string) {
for _, profile := range AWSProfiles {
//var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version)
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
//instantiate a permissions client and populate the permissions data
fmt.Printf("[%s][%s] Getting account authorization details (GAAD) for account: %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
PermissionsCommandClient := aws.InitPermissionsClient(*caller, profile, cmd.Root().Version, Goroutines, AWSMFAToken)
PermissionsCommandClient.GetGAAD()
PermissionsCommandClient.ParsePermissions("")
common.PermissionRowsFromAllProfiles = append(common.PermissionRowsFromAllProfiles, PermissionsCommandClient.Rows...)
}
for _, profile := range AWSProfiles {
var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
graphCommandClient := aws.GraphCommand{
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
AWSOutputDirectory: AWSOutputDirectory,
Verbosity: Verbosity,
AWSConfig: AWSConfig,
Version: cmd.Root().Version,
SkipAdminCheck: AWSSkipAdminCheck,
PmapperDataBasePath: PmapperDataBasePath,
}
graphCommandClient.RunGraphCommand()
}
}
func runCapeCommand(cmd *cobra.Command, args []string) {
// map of all unique accountIDs and if they are included in the analysis or not
//analyzedAccounts := make(map[string]bool)
analyzedAccounts := make(map[string]aws.CapeJobInfo)
GlobalGraph := graph.New(graph.StringHash, graph.Directed())
//var PermissionRowsFromAllProfiles []common.PermissionsRow
var GlobalPmapperData aws.PmapperModule
var GlobalNodes []aws.Node
vendors := knownawsaccountslookup.NewVendorMap()
vendors.PopulateKnownAWSAccounts()
for _, profile := range AWSProfiles {
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
_, err = internal.InitializeCloudFoxRunData(profile, cmd.Root().Version, AWSMFAToken, AWSOutputDirectory)
if err != nil {
continue
}
// add account number to analyzedAccounts map and set the value to true
//analyzedAccounts[ptr.ToString(caller.Account)] = true
analyzedAccounts[ptr.ToString(caller.Account)] = aws.CapeJobInfo{AccountID: ptr.ToString(caller.Account), Profile: profile, AnalyzedSuccessfully: true, AdminOnlyAnalysis: CapeAdminOnly, Source: "user"}
}
pmapperData := make(map[string]aws.PmapperModule)
for _, profile := range AWSProfiles {
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
fmt.Printf("[%s][%s] Importing Pmapper data for: %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
pmapperMod, pmapperError := aws.InitPmapperGraph(*caller, AWSProfile, Goroutines, PmapperDataBasePath)
if pmapperError != nil {
fmt.Println("Error importing pmapper data " + pmapperError.Error())
analyzedAccounts[ptr.ToString(caller.Account)] = aws.CapeJobInfo{AnalyzedSuccessfully: false}
// give the user the option to continue or not
// if they choose to continue, we will skip the pmapper data and continue with the rest of the analysis
// if they choose to not continue, we will exit the program
fmt.Printf("Would you like to continue with the analysis without the pmapper data for profile %s? (y/n)", profile)
var continueAnalysis string
fmt.Scanln(&continueAnalysis)
if continueAnalysis == "y" {
continue
} else {
os.Exit(1)
}
}
pmapperData[profile] = pmapperMod
}
for _, profile := range AWSProfiles {
var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
//Gather all Permissions data
fmt.Printf("[%s][%s] Getting account authorization details (GAAD) for account: %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
PermissionsCommandClient := aws.InitPermissionsClient(*caller, profile, cmd.Root().Version, Goroutines, AWSMFAToken)
PermissionsCommandClient.GetGAAD()
PermissionsCommandClient.ParsePermissions("")
if PermissionsCommandClient.Rows != nil {
common.PermissionRowsFromAllProfiles = append(common.PermissionRowsFromAllProfiles, PermissionsCommandClient.Rows...)
} else {
fmt.Println("Error gathering permissions for " + profile)
//analyzedAccounts[ptr.ToString(caller.Account)] = false
analyzedAccounts[ptr.ToString(caller.Account)] = aws.CapeJobInfo{AnalyzedSuccessfully: false}
}
// Gather all Pmapper data.
//fmt.Printf("[%s][%s] Importing Pmapper for: %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
// pmapperMod, pmapperError := aws.InitPmapperGraph(*caller, AWSProfile, Goroutines)
// if pmapperError != nil {
// fmt.Println("Error importing pmapper data " + pmapperError.Error())
// //analyzedAccounts[ptr.ToString(caller.Account)] = false
// analyzedAccounts[ptr.ToString(caller.Account)] = aws.CapeJobInfo{AnalyzedSuccessfully: false}
// }
pmapperMod := pmapperData[profile]
// add pmapper nodes to GlobalNodes (which will also soon include iam roles and users)
for _, node := range pmapperMod.Nodes {
// add node to GlobalPmapperData
//GlobalPmapperData.Nodes = append(GlobalPmapperData.Nodes, node)
GlobalNodes = append(GlobalNodes, node)
}
fmt.Printf("[%s][%s] Added %d vertices from pmapper for %s\n", cyan("cape"), cyan(profile), len(pmapperMod.Nodes), ptr.ToString(caller.Account))
// same for adding pmapper edges to GlobalPmapperData
for _, edge := range pmapperMod.Edges {
// add edge to GlobalPmapperData
GlobalPmapperData.Edges = append(GlobalPmapperData.Edges, edge)
}
fmt.Printf("[%s][%s] Added %d edges from pmapper for %s\n", cyan("cape"), cyan(profile), len(pmapperMod.Edges), ptr.ToString(caller.Account))
//Gather all role data so we can later process all of the role trusts and add external nodes not looked at by pmapper
fmt.Printf("[%s][%s] Getting IAM roles for %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
IAMCommandClient := aws.InitIAMClient(AWSConfig)
ListRolesOutput, err := sdk.CachedIamListRoles(IAMCommandClient, ptr.ToString(caller.Account))
if err != nil {
internal.TxtLog.Error(err)
}
for _, role := range ListRolesOutput {
//node := aws.ConvertIAMRoleToNode(role, vendors)
node := aws.ConvertIAMRoleToNode(role, vendors, analyzedAccounts)
// First insert the role itself into the Nodes slice
GlobalNodes = append(GlobalNodes, node)
// Then insert all of the vertices that are in the role's trust policy
GlobalNodes = append(GlobalNodes, aws.FindVerticesInRoleTrust(node, vendors)...)
}
//Gather all user data
// Currently, there is no need to parse groups and build group-user relationships because
// the permissions command (and common.PermissionRowsFromAllProfiles above already has mapped/assigned group permissions to users within the group
fmt.Printf("[%s][%s] Getting IAM users for %s\n", cyan("cape"), cyan(profile), ptr.ToString(caller.Account))
ListUsersOutput, err := sdk.CachedIamListUsers(IAMCommandClient, ptr.ToString(caller.Account))
if err != nil {
internal.TxtLog.Error(err)
}
for _, user := range ListUsersOutput {
GlobalNodes = append(GlobalNodes, aws.ConvertIAMUserToNode(user))
}
}
//GlobalGraph := models.MakeAllVertices(GlobalRoles, GlobalPmapperData)
// make vertices
// you can't update vertices - so we need to make all of the vertices that are roles in the in-scope accounts
// all at once to make sure they have the most information possible
fmt.Printf("[%s] Making vertices for all profiles\n", cyan("cape"))
// for _, role := range GlobalRoles {
// role.MakeVertices(GlobalGraph)
// }
mergedNodes := aws.MergeNodes(GlobalNodes)
for _, node := range mergedNodes {
GlobalGraph.AddVertex(
node.Arn,
graph.VertexAttribute("Type", node.Type),
graph.VertexAttribute("Name", node.Name),
graph.VertexAttribute("VendorName", node.VendorName),
graph.VertexAttribute("IsAdminString", node.IsAdminString),
graph.VertexAttribute("CanPrivEscToAdminString", node.CanPrivEscToAdminString),
graph.VertexAttribute("AccountID", node.AccountID),
)
// for every node, check to see if the accountId exists in the analyzedAccounts map. If it does not, add it to the map and set the value to false only if the node.VendorName is empty
if _, ok := analyzedAccounts[node.AccountID]; !ok {
if node.VendorName == "" {
if node.AccountID != "" {
analyzedAccounts[node.AccountID] = aws.CapeJobInfo{AccountID: node.AccountID, Profile: "", AnalyzedSuccessfully: false, AdminOnlyAnalysis: CapeAdminOnly, Source: "cloudfox"}
}
}
}
}
// make pmapper edges
//you can update edges, so we can just merge attributes as needed
// first we add the edges that already exist in pmapper, then later we will make more edges based on the cloudfox role trusts logic
for _, edge := range GlobalPmapperData.Edges {
err := GlobalGraph.AddEdge(
edge.Source,
edge.Destination,
graph.EdgeAttribute(edge.ShortReason, edge.Reason),
)
if err != nil {
if err == graph.ErrEdgeAlreadyExists {
// update theedge by copying the existing graph.Edge with attributes and add the new attributes
//fmt.Println("Edge already exists")
// get the existing edge
existingEdge, _ := GlobalGraph.Edge(edge.Source, edge.Destination)
// get the map of attributes
existingProperties := existingEdge.Properties
// add the new attributes to attributes map within the properties struct
// Check if the Attributes map is initialized, if not, initialize it
if existingProperties.Attributes == nil {
existingProperties.Attributes = make(map[string]string)
}
// Add or update the attribute
existingProperties.Attributes[edge.ShortReason] = edge.Reason
GlobalGraph.UpdateEdge(
edge.Source,
edge.Destination,
graph.EdgeAttributes(existingProperties.Attributes),
)
}
}
}
//making edges
// these are the cloudfox created edges mainly based on role trusts
// at least for now, we don't need to make edges for users, groups, or anything else because pmapper already has all of the edges we need
fmt.Printf("[%s] Making edges for all profiles\n", cyan("cape"))
//fmt.Printf("[%s] Total vertices from pmapper and cape: %d \n", cyan("cape"), len(mergedNodes))
for _, node := range mergedNodes {
if node.Type == "Role" {
node.MakeRoleEdges(GlobalGraph)
}
}
// count the edges in the graph
edges, _ := GlobalGraph.Edges()
fmt.Printf("[%s] Total edges from pmapper and cape: %d \n", cyan("cape"), len(mergedNodes))
fmt.Printf("[%s] Total edges from pmapper and cape: %d \n", cyan("cape"), len(edges))
for _, profile := range AWSProfiles {
var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
capeCommandClient := aws.CapeCommand{
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
AWSOutputDirectory: AWSOutputDirectory,
Verbosity: Verbosity,
AWSConfig: AWSConfig,
Version: cmd.Root().Version,
SkipAdminCheck: AWSSkipAdminCheck,
GlobalGraph: GlobalGraph,
PmapperDataBasePath: PmapperDataBasePath,
AnalyzedAccounts: analyzedAccounts,
CapeAdminOnly: CapeAdminOnly,
}
capeCommandClient.RunCapeCommand()
// write a json file with job information to the output directory. Use the CapeJobName for the file name, and have the data include the list of AWSProfiles that were analyzed
// this will be used by a TUI to match a job name to the list of accounts that were analyzed
// if CapeJobName == "" {
// // create random job name in the format of cape-timmefromepoch
// CapeJobName = fmt.Sprintf("cape-%s", time.Now().Format("2006-01-02-15-04-05"))
// }
// filename := fmt.Sprintf("%s.json", CapeJobName)
// filepath := filepath.Join(AWSOutputDirectory, "aws", "capeJobs")
// err = os.MkdirAll(filepath, 0755)
// if err != nil {
// fmt.Println("Error creating directory: " + err.Error())
// }
// file, _ := os.Create(filepath + "/" + filename)
// defer file.Close()
// encoder := json.NewEncoder(file)
// encoder.SetIndent("", " ")
// err = encoder.Encode(analyzedAccounts)
// if err != nil {
// fmt.Println("Error writing job data to file: " + err.Error())
// } else {
// fmt.Printf("[%s] Job output written to %s\n", cyan("cape"), file.Name())
// fmt.Printf("[%s] %s\n\n", cyan("cape"), magenta("The results of the cape command are best viewed in the cape terminal user interface (TUI). Use the command below:"))
// fmt.Printf("[%s] \tcloudfox aws -l %s cape tui\n\n", cyan("cape"), AWSProfilesList)
// }
// playing around with creating a graphviz file for image rendering.
// the goal here is to be able to export this graph data to a format that can be easily imported in neo4j.
// this is a work in progress and not yet complete
// filename := fmt.Sprintf("./mygraph-%s-%s.gv", ptr.ToString(caller.Account), time.Now().Format("2006-01-02-15-04-05"))
// file, _ := os.Create(filename)
// _ = draw.DOT(GlobalGraph, file, draw.GraphAttribute(
// "ranksep", "3",
// ))
}
fmt.Printf("[%s] %s\n\n", cyan("cape"), magenta("The results of the cape command are best viewed in the cape terminal user interface (TUI). Use the command below:"))
if CapeAdminOnly {
fmt.Printf("\t\tcloudfox aws -l %s cape tui --admin-only\n\n", AWSProfilesList)
} else {
fmt.Printf("\t\tcloudfox aws -l %s cape tui\n\n", AWSProfilesList)
}
}
func runCapeTUICommand(cmd *cobra.Command, args []string) {
var capeOutputFileLocations []string
for i, profile := range AWSProfiles {
cloudfoxRunData, err := internal.InitializeCloudFoxRunData(profile, cmd.Root().Version, AWSMFAToken, AWSOutputDirectory)
//caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
var fileName string
if CapeAdminOnly {
fileName = "inbound-privesc-paths-admin-targets-only.json"
} else {
fileName = "inbound-privesc-paths-all-targets.json"
}
capeOutputFileLocations = append(capeOutputFileLocations, filepath.Join(cloudfoxRunData.OutputLocation, "json", fileName))
//check to see if file exists, and if it doesn't, remove the profile from the list of profiles to analyze and print a message to the console
if _, err := os.Stat(filepath.Join(cloudfoxRunData.OutputLocation, "json", fileName)); os.IsNotExist(err) {
fmt.Printf("[%s] Could not retrieve CAPE data for profile %s.\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", cmd.Root().Version)), profile)
//remove the profile from the list of profiles to analyze
AWSProfiles = append(AWSProfiles[:i], AWSProfiles[i+1:]...)
}
}
if len(capeOutputFileLocations) == 0 {
fmt.Printf("[%s] Could not retrieve CAPE data.\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", cmd.Root().Version)))
os.Exit(1)
}
aws.CapeTUI(capeOutputFileLocations)
}
func runIamSimulatorCommand(cmd *cobra.Command, args []string) {
for _, profile := range AWSProfiles {
var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)
@@ -956,6 +1369,7 @@ func runInstancesCommand(cmd *cobra.Command, args []string) {
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.Instances(InstancesFilter, AWSOutputDirectory, Verbosity)
}
@@ -1029,16 +1443,17 @@ func runLambdasCommand(cmd *cobra.Command, args []string) {
continue
}
m := aws.LambdasModule{
LambdaClient: lambda.NewFromConfig(AWSConfig),
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
LambdaClient: lambda.NewFromConfig(AWSConfig),
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.PrintLambdas(AWSOutputDirectory, Verbosity)
}
@@ -1112,12 +1527,13 @@ func runPmapperCommand(cmd *cobra.Command, args []string) {
continue
}
m := aws.PmapperModule{
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.PrintPmapperData(AWSOutputDirectory, Verbosity)
}
@@ -1195,14 +1611,15 @@ func runRoleTrustCommand(cmd *cobra.Command, args []string) {
continue
}
m := aws.RoleTrustsModule{
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.PrintRoleTrusts(AWSOutputDirectory, Verbosity)
}
@@ -1283,24 +1700,46 @@ func runWorkloadsCommand(cmd *cobra.Command, args []string) {
continue
}
m := aws.WorkloadsModule{
ECSClient: ecs.NewFromConfig(AWSConfig),
EC2Client: ec2.NewFromConfig(AWSConfig),
LambdaClient: lambda.NewFromConfig(AWSConfig),
AppRunnerClient: apprunner.NewFromConfig(AWSConfig),
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
SkipAdminCheck: AWSSkipAdminCheck,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
ECSClient: ecs.NewFromConfig(AWSConfig),
EC2Client: ec2.NewFromConfig(AWSConfig),
LambdaClient: lambda.NewFromConfig(AWSConfig),
AppRunnerClient: apprunner.NewFromConfig(AWSConfig),
IAMClient: iam.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
SkipAdminCheck: AWSSkipAdminCheck,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.PrintWorkloads(AWSOutputDirectory, Verbosity)
}
}
func runDirectoryServicesCommand(cmd *cobra.Command, args []string) {
for _, profile := range AWSProfiles {
var AWSConfig = internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
if err != nil {
continue
}
m := aws.DirectoryModule{
DSClient: directoryservice.NewFromConfig(AWSConfig),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
}
m.PrintDirectories(AWSOutputDirectory, Verbosity)
}
}
func runECSTasksCommand(cmd *cobra.Command, args []string) {
for _, profile := range AWSProfiles {
caller, err := internal.AWSWhoami(profile, cmd.Root().Version, AWSMFAToken)
@@ -1312,14 +1751,15 @@ func runECSTasksCommand(cmd *cobra.Command, args []string) {
ECSClient: ecs.NewFromConfig(internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)),
IAMClient: iam.NewFromConfig(internal.AWSConfigFileLoader(profile, cmd.Root().Version, AWSMFAToken)),
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
m.ECSTasks(AWSOutputDirectory, Verbosity)
}
@@ -1516,6 +1956,7 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
instances.Instances(InstancesFilter, AWSOutputDirectory, Verbosity)
route53 := aws.Route53Module{
@@ -1528,16 +1969,17 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
}
lambdasMod := aws.LambdasModule{
LambdaClient: lambdaClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
LambdaClient: lambdaClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
lambdasMod.PrintLambdas(AWSOutputDirectory, Verbosity)
@@ -1618,14 +2060,15 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
ECSClient: ecsClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
ecstasks.ECSTasks(AWSOutputDirectory, Verbosity)
@@ -1633,14 +2076,15 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
EKSClient: eksClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
AWSProfile: profile,
Goroutines: Goroutines,
SkipAdminCheck: AWSSkipAdminCheck,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
eksCommand.EKS(AWSOutputDirectory, Verbosity)
@@ -1812,14 +2256,15 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
resourceTrustsCommand.PrintResources(AWSOutputDirectory, Verbosity)
codeBuildCommand := aws.CodeBuildModule{
CodeBuildClient: codeBuildClient,
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
CodeBuildClient: codeBuildClient,
Caller: *caller,
AWSProfile: profile,
Goroutines: Goroutines,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
codeBuildCommand.PrintCodeBuildProjects(AWSOutputDirectory, Verbosity)
@@ -1888,19 +2333,20 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
iamSimulator.PrintIamSimulator(SimulatorPrincipal, SimulatorAction, SimulatorResource, AWSOutputDirectory, Verbosity)
workloads := aws.WorkloadsModule{
ECSClient: ecsClient,
EC2Client: ec2Client,
LambdaClient: lambdaClient,
AppRunnerClient: appRunnerClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
SkipAdminCheck: AWSSkipAdminCheck,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
ECSClient: ecsClient,
EC2Client: ec2Client,
LambdaClient: lambdaClient,
AppRunnerClient: appRunnerClient,
IAMClient: iamClient,
Caller: *caller,
AWSRegions: internal.GetEnabledRegions(profile, cmd.Root().Version, AWSMFAToken),
SkipAdminCheck: AWSSkipAdminCheck,
AWSProfile: profile,
Goroutines: Goroutines,
WrapTable: AWSWrapTable,
AWSOutputType: AWSOutputType,
AWSTableCols: AWSTableCols,
PmapperDataBasePath: PmapperDataBasePath,
}
workloads.PrintWorkloads(AWSOutputDirectory, Verbosity)
@@ -1909,6 +2355,17 @@ func runAllChecksCommand(cmd *cobra.Command, args []string) {
}
}
var CapeTuiCmd = &cobra.Command{
Use: "tui",
Aliases: []string{"TUI", "view", "report"},
Short: "View Cape's output in a TUI",
Long: "\nUse case examples:\n" +
os.Args[0] + " aws cape tui -l /path/to/profiles-used-for-cape.txt",
//PreRun: awsPreRun,
Run: runCapeTUICommand,
//PostRun: awsPostRun,
}
func init() {
cobra.OnInitialize(initAWSProfiles)
@@ -1932,7 +2389,7 @@ func init() {
SNSCommand.Flags().BoolVarP(&StoreSNSAccessPolicies, "policies", "", false, "Store all flagged access policies along with the output")
// outbound-assumed-roles module flags
OutboundAssumedRolesCommand.Flags().IntVarP(&OutboundAssumedRolesDays, "days", "d", 7, "How many days of CloudTrail events should we go back and look at.")
OutboundAssumedRolesCommand.Flags().IntVarP(&OutboundAssumedRolesDays, "days", "d", -7, "How many days of CloudTrail events should we go back and look at.")
// iam-simulator module flags
IamSimulatorCommand.Flags().StringVar(&SimulatorPrincipal, "principal", "", "Principal Arn")
@@ -1948,6 +2405,13 @@ func init() {
// buckets command flags (for bucket policies)
BucketsCommand.Flags().BoolVarP(&CheckBucketPolicies, "with-policies", "", false, "Analyze bucket policies (this is already done in the resource-trusts command)")
// cape command flags
CapeCommand.Flags().BoolVar(&CapeAdminOnly, "admin-only", false, "Only return paths that lead to an admin role - much faster")
//CapeCommand.Flags().StringVar(&CapeJobName, "job-name", "", "Name of the cape job")
// cape tui command flags
CapeTuiCmd.Flags().BoolVar(&CapeAdminOnly, "admin-only", false, "Only return paths that lead to an admin role - much faster")
// Global flags for the AWS modules
AWSCommands.PersistentFlags().StringVarP(&AWSProfile, "profile", "p", "", "AWS CLI Profile Name")
AWSCommands.PersistentFlags().StringVarP(&AWSProfilesList, "profiles-list", "l", "", "File containing a AWS CLI profile names separated by newlines")
@@ -1962,41 +2426,49 @@ func init() {
AWSCommands.PersistentFlags().BoolVarP(&AWSUseCache, "cached", "c", false, "Load cached data from disk. Faster, but if changes have been recently made you'll miss them")
AWSCommands.PersistentFlags().StringVarP(&AWSTableCols, "cols", "t", "", "Comma separated list of columns to display in table output")
AWSCommands.PersistentFlags().StringVar(&AWSMFAToken, "mfa-token", "", "MFA Token")
AWSCommands.PersistentFlags().StringVar(&PmapperDataBasePath, "pmapper-data-basepath", "", "Supply the base path for the pmapper data files (useful if you have copied them from another machine)\nPoint to the parent directory that contains all of the pmapper data by account numbers. \n\tExample: /path/to/com.nccgroup.principalmapper/\n\tExample: ./pmapperdata/")
AWSCommands.AddCommand(
AccessKeysCommand,
AllChecksCommand,
ApiGwCommand,
RoleTrustCommand,
AccessKeysCommand,
InstancesCommand,
ECSTasksCommand,
ElasticNetworkInterfacesCommand,
InventoryCommand,
EndpointsCommand,
SecretsCommand,
Route53Command,
ECRCommand,
SQSCommand,
SNSCommand,
EKSCommand,
OutboundAssumedRolesCommand,
EnvsCommand,
PrincipalsCommand,
IamSimulatorCommand,
FilesystemsCommand,
BucketsCommand,
PermissionsCommand,
CapeCommand,
CloudformationCommand,
CodeBuildCommand,
RAMCommand,
TagsCommand,
DatabasesCommand,
ECSTasksCommand,
ECRCommand,
EKSCommand,
ElasticNetworkInterfacesCommand,
EndpointsCommand,
EnvsCommand,
FilesystemsCommand,
//GraphCommand,
IamSimulatorCommand,
InstancesCommand,
InventoryCommand,
LambdasCommand,
NetworkPortsCommand,
PmapperCommand,
ResourceTrustsCommand,
OrgsCommand,
DatabasesCommand,
OutboundAssumedRolesCommand,
PermissionsCommand,
PrincipalsCommand,
PmapperCommand,
RAMCommand,
ResourceTrustsCommand,
RoleTrustCommand,
Route53Command,
SQSCommand,
SNSCommand,
SecretsCommand,
TagsCommand,
WorkloadsCommand,
DirectoryServicesCommand,
)
CapeCommand.AddCommand(
CapeTuiCmd,
)
}
+109
View File
@@ -0,0 +1,109 @@
package cli
import (
"context"
"fmt"
"github.com/BishopFox/cloudfox/gcp/commands"
oauthservice "github.com/BishopFox/cloudfox/gcp/services/oauthService"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var (
// GCP resources filtering options
GCPOrganization string
GCPProjectID string
GCPProjectIDsFilePath string
GCPProjectIDs []string
// Output formatting options
GCPOutputFormat string
GCPOutputDirectory string
GCPVerbosity int
GCPWrapTable bool
// misc options
// GCPIgnoreCache bool
// logger
GCPLogger = internal.NewLogger()
// GCP root command
GCPCommands = &cobra.Command{
Use: "gcp",
Aliases: []string{"gcloud"},
Long: `See "Available Commands" for GCP Modules below`,
Short: "See \"Available Commands\" for GCP Modules below",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if GCPProjectID != "" {
GCPProjectIDs = append(GCPProjectIDs, GCPProjectID)
} else if GCPProjectIDsFilePath != "" {
GCPProjectIDs = internal.LoadFileLinesIntoArray(GCPProjectIDsFilePath)
} else {
GCPLogger.InfoM("project or project-list flags not given, commands requiring a project ID will fail", "gcp")
}
// Create a context with this value to share it with subcommands at runtime
ctx := context.WithValue(context.Background(), "projectIDs", GCPProjectIDs)
// Set the context for this command which all subcommands can access via [SUBCMD].Parent().Context()
// cmd.SetContext(ctx)
os := oauthservice.NewOAuthService()
principal, err := os.WhoAmI()
if err != nil {
GCPLogger.FatalM(fmt.Sprintf("could not determine default user credential with error %s. \n\nPlease use default application default credentials: https://cloud.google.com/docs/authentication/application-default-credentials", err.Error()), "gcp")
}
ctx = context.WithValue(ctx, "account", principal.Email)
cmd.SetContext(ctx)
},
}
)
// New RunAllGCPCommands function to execute all child commands
var GCPAllChecksCommand = &cobra.Command{
Use: "all-checks",
Short: "Runs all available GCP commands",
Long: `Executes all available GCP commands to collect and display information from all supported GCP services.`,
Run: func(cmd *cobra.Command, args []string) {
for _, childCmd := range GCPCommands.Commands() {
if childCmd == cmd { // Skip the run-all command itself to avoid infinite recursion
continue
}
GCPLogger.InfoM(fmt.Sprintf("Running command: %s", childCmd.Use), "all-checks")
childCmd.Run(cmd, args)
}
},
}
func init() {
// Globals flags for the GCP commands
// Allow selection of non-default account to be used when accessing gcloud API
// TODO
// Resource filtering options
// GCPCommands.PersistentFlags().StringVarP(&GCPOrganization, "organization", "o", "", "Organization name or number, repetable")
GCPCommands.PersistentFlags().StringVarP(&GCPProjectID, "project", "p", "", "GCP project ID")
GCPCommands.PersistentFlags().StringVarP(&GCPProjectIDsFilePath, "project-list", "l", "", "Path to a file containing a list of project IDs separated by newlines")
// GCPCommands.PersistentFlags().BoolVarP(&GCPAllProjects, "all-projects", "a", false, "Use all project IDs available to activated gloud account or given gcloud account")
// GCPCommands.PersistentFlags().BoolVarP(&GCPConfirm, "yes", "y", false, "Non-interactive mode (like apt/yum)")
// GCPCommands.PersistentFlags().StringVarP(&GCPOutputFormat, "output", "", "brief", "[\"brief\" | \"wide\" ]")
GCPCommands.PersistentFlags().IntVarP(&Verbosity, "verbosity", "v", 2, "1 = Print control messages only\n2 = Print control messages, module output\n3 = Print control messages, module output, and loot file output\n")
// defaultOutputDir is defined in cli.aws
GCPCommands.PersistentFlags().StringVar(&GCPOutputDirectory, "outdir", defaultOutputDir, "Output Directory ")
// GCPCommands.PersistentFlags().IntVarP(&Goroutines, "max-goroutines", "g", 30, "Maximum number of concurrent goroutines")
GCPCommands.PersistentFlags().BoolVarP(&GCPWrapTable, "wrap", "w", false, "Wrap table to fit in terminal (complicates grepping)")
// Available commands
GCPCommands.AddCommand(
commands.GCPBucketsCommand,
commands.GCPArtifactRegistryCommand,
commands.GCPBigQueryCommand,
commands.GCPSecretsCommand,
commands.GCPIAMCommand,
commands.GCPInstancesCommand,
commands.GCPWhoAmICommand,
GCPAllChecksCommand,
)
}
+172
View File
@@ -0,0 +1,172 @@
package commands
import (
"fmt"
artifactregistry "cloud.google.com/go/artifactregistry/apiv1"
ArtifactRegistryService "github.com/BishopFox/cloudfox/gcp/services/artifactRegistryService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPArtifactRegistryCommand = &cobra.Command{
Use: globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME,
Aliases: []string{},
Short: "Display GCP artifact registry information",
Args: cobra.MinimumNArgs(0),
Long: `
Display available artifact registry resource information:
cloudfox gcp artfact-registry`,
Run: runGCPArtifactRegistryCommand,
}
// Code needed to output fields from buckets results using generic HandleOutput function
// Results struct that implements the internal.OutputInterface
type GCPArtifactRegistryResults struct {
ArtifactData []ArtifactRegistryService.ArtifactInfo
RepositoryData []ArtifactRegistryService.RepositoryInfo
}
// Decide what format the name, header and body of the CSV & JSON files will be
func (g GCPArtifactRegistryResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
repoHeader := []string{
"Name",
"Format",
"Description",
"Size",
"Location",
"ProjectID",
}
var repoBody [][]string
for _, value := range g.RepositoryData {
repoBody = append(
repoBody,
[]string{
value.Name,
value.Format,
value.Description,
value.SizeBytes,
value.Location,
value.ProjectID,
},
)
}
repoTableFile := internal.TableFile{
Header: repoHeader,
Body: repoBody,
Name: fmt.Sprintf("%s-repos", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME),
}
tableFiles = append(tableFiles, repoTableFile)
artifactHeader := []string{
"Name",
"Format",
"Version",
"Location",
"Repository",
"Size",
"Updated",
"ProjectID",
}
var artifactBody [][]string
for _, value := range g.ArtifactData {
artifactBody = append(
artifactBody,
[]string{
value.Name,
value.Format,
value.Version,
value.Location,
value.Repository,
value.SizeBytes,
value.Updated,
value.ProjectID,
},
)
}
artifactTableFile := internal.TableFile{
Header: artifactHeader,
Body: artifactBody,
Name: fmt.Sprintf("%s-artifacts", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME),
}
tableFiles = append(tableFiles, artifactTableFile)
return tableFiles
}
// Decide what is loot based on resource information
func (g GCPArtifactRegistryResults) LootFiles() []internal.LootFile {
// TODO consider a loot file of the URLs to the all docker image artifacts. Maybe sample commands to pull the images
return []internal.LootFile{}
}
// Houses high-level logic that retrieves resources and writes to output
func runGCPArtifactRegistryCommand(cmd *cobra.Command, args []string) {
// Retrieve projectIDs from parent (gcp command) ctx
var projectIDs []string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
}
client, err := artifactregistry.NewClient(ctx)
if err != nil {
logger.ErrorM(fmt.Sprintf("failed to create secret manager client: %v", err), globals.GCP_SECRETS_MODULE_NAME)
return
}
defer client.Close()
// Get the artifact repositories and artifacts using the projectIDs and ArtifactRegistryService
ars := ArtifactRegistryService.New(client)
var artifactResults []ArtifactRegistryService.ArtifactInfo
var repoRestuls []ArtifactRegistryService.RepositoryInfo
// Set output params leveraging parent (gcp) pflag values
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving all artifact repositories and supported artifacts in all locations from project: %s", projectID), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
result, err := ars.RepositoriesAndArtifacts(projectID)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
return
}
artifactResults = append(artifactResults, result.Artifacts...)
repoRestuls = append(repoRestuls, result.Repositories...)
logger.InfoM(fmt.Sprintf("Done retrieving artifact repository resource data from project: %s", projectID), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
cloudfoxOutput := GCPArtifactRegistryResults{ArtifactData: artifactResults, RepositoryData: repoRestuls}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("Done writing output for project %s", projectID), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
}
}
+134
View File
@@ -0,0 +1,134 @@
package commands
import (
"fmt"
"time"
BigQueryService "github.com/BishopFox/cloudfox/gcp/services/bigqueryService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPBigQueryCommand = &cobra.Command{
Use: "bigquery",
Aliases: []string{},
Short: "Display Bigquery datasets and tables information",
Args: cobra.MinimumNArgs(0),
Long: `
Display available Bigquery datasets and tables resource information:
cloudfox gcp bigquery`,
Run: runGCPBigQueryCommand,
}
// GCPBigQueryResults struct that implements the internal.OutputInterface
type GCPBigQueryResults struct {
DatasetsData []BigQueryService.BigqueryDataset
TablesData []BigQueryService.BigqueryTable
}
// Define the format for CSV & JSON output
func (g GCPBigQueryResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
// For Datasets
datasetHeader := []string{"Name", "DatasetID", "Description", "CreationTime", "LastModifiedTime", "Location", "ProjectID"}
var datasetBody [][]string
for _, dataset := range g.DatasetsData {
datasetBody = append(datasetBody, []string{
dataset.Name,
dataset.DatasetID,
dataset.Description,
dataset.CreationTime.Format(time.RFC3339),
dataset.LastModifiedTime.Format(time.RFC3339),
dataset.Location,
dataset.ProjectID,
})
}
datasetTableFile := internal.TableFile{
Header: datasetHeader,
Body: datasetBody,
Name: "bigquery-datasets",
}
tableFiles = append(tableFiles, datasetTableFile)
// For Tables
tableHeader := []string{"TableID", "DatasetID", "Description", "CreationTime", "LastModifiedTime", "NumBytes", "Location", "ProjectID"}
var tableBody [][]string
for _, table := range g.TablesData {
tableBody = append(tableBody, []string{
table.TableID,
table.DatasetID,
table.Description,
table.CreationTime.Format(time.RFC3339),
table.LastModifiedTime.Format(time.RFC3339),
fmt.Sprintf("%d", table.NumBytes),
table.Location,
table.ProjectID,
})
}
tableTableFile := internal.TableFile{
Header: tableHeader,
Body: tableBody,
Name: "bigquery-tables",
}
tableFiles = append(tableFiles, tableTableFile)
return tableFiles
}
func (g GCPBigQueryResults) LootFiles() []internal.LootFile {
// Implement if there's specific data considered as loot
return []internal.LootFile{}
}
func runGCPBigQueryCommand(cmd *cobra.Command, args []string) {
var projectIDs []string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_BIGQUERY_MODULE_NAME)
return
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_BIGQUERY_MODULE_NAME)
}
bqService := BigQueryService.New()
var datasetsResults []BigQueryService.BigqueryDataset
var tablesResults []BigQueryService.BigqueryTable
// Set output params leveraging parent (gcp) pflag values
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving BigQuery datasets and tables from project: %s", projectID), globals.GCP_BIGQUERY_MODULE_NAME)
result, err := bqService.BigqueryDatasetsAndTables(projectID)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_BIGQUERY_MODULE_NAME)
return
}
datasetsResults = append(datasetsResults, result.Datasets...)
tablesResults = append(tablesResults, result.Tables...)
cloudfoxOutput := GCPBigQueryResults{DatasetsData: datasetsResults, TablesData: tablesResults}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_BIGQUERY_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_BIGQUERY_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("Done writing output for project %s", projectID), globals.GCP_BIGQUERY_MODULE_NAME)
}
}
+115
View File
@@ -0,0 +1,115 @@
package commands
import (
"fmt"
CloudStorageService "github.com/BishopFox/cloudfox/gcp/services/cloudStorageService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPBucketsCommand = &cobra.Command{
Use: globals.GCP_BUCKETS_MODULE_NAME,
Aliases: []string{},
Short: "Display GCP buckets information",
Args: cobra.MinimumNArgs(0),
Long: `
Display available bucket information:
cloudfox gcp buckets`,
Run: runGCPBucketsCommand,
}
// Code needed to output fields from buckets results using generic HandleOutput function
// Results struct that implements the internal.OutputInterface
type GCPBucketsResults struct {
Data []CloudStorageService.BucketInfo
}
// Decide what format the name, header and body of the CSV & JSON files will be
func (g GCPBucketsResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
header := []string{
"Name",
"Location",
"ProjectID",
}
var body [][]string
for _, value := range g.Data {
body = append(
body,
[]string{
value.Name,
value.Location,
value.ProjectID,
},
)
}
tableFile := internal.TableFile{
Header: header,
Body: body,
Name: globals.GCP_BUCKETS_MODULE_NAME,
}
tableFiles = append(tableFiles, tableFile)
return tableFiles
}
// Decide what is loot based on resource information
func (g GCPBucketsResults) LootFiles() []internal.LootFile {
return []internal.LootFile{}
}
// Houses high-level logic that retrieves resources and writes to output
func runGCPBucketsCommand(cmd *cobra.Command, args []string) {
// Retrieve projectIDs from parent (gcp command) ctx
var projectIDs []string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_BUCKETS_MODULE_NAME)
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_BUCKETS_MODULE_NAME)
}
// Get the bucket info using the projectIDs and CloudStorageService
cs := CloudStorageService.New()
var results []CloudStorageService.BucketInfo
// Set output params leveraging parent (gcp) pflag values
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving all buckets from project: %s", projectID), globals.GCP_BUCKETS_MODULE_NAME)
result, err := cs.Buckets(projectID)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_BUCKETS_MODULE_NAME)
return
}
results = append(results, result...)
logger.InfoM(fmt.Sprintf("Done retrieving all buckets from project: %s", projectID), globals.GCP_BUCKETS_MODULE_NAME)
cloudfoxOutput := GCPBucketsResults{Data: results}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_BUCKETS_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_BUCKETS_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("Done writing output for project %s", projectID), globals.GCP_BUCKETS_MODULE_NAME)
}
}
+122
View File
@@ -0,0 +1,122 @@
package commands
import (
"fmt"
IAMService "github.com/BishopFox/cloudfox/gcp/services/iamService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPIAMCommand = &cobra.Command{
Use: globals.GCP_IAM_MODULE_NAME,
Aliases: []string{},
Short: "Display GCP IAM information",
Args: cobra.MinimumNArgs(0),
Long: `
Display IAM principals and their roles information within GCP resources:
cloudfox gcp iam`,
Run: runGCPIAMCommand,
}
// Results struct for IAM command that implements the internal.OutputInterface
type GCPIAMResults struct {
Data []IAMService.PrincipalWithRoles
}
// TableFiles formats the data for table output, CSV & JSON files
func (g GCPIAMResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
header := []string{
"Name",
"Principal Type",
"Role",
"PolicyResourceType",
"PolicyResourceID",
}
var body [][]string
for _, principal := range g.Data {
for _, binding := range principal.PolicyBindings {
body = append(body, []string{
principal.Name,
principal.Type,
binding.Role,
principal.ResourceType,
principal.ResourceID,
})
}
}
tableFile := internal.TableFile{
Header: header,
Body: body,
Name: globals.GCP_IAM_MODULE_NAME,
}
tableFiles = append(tableFiles, tableFile)
return tableFiles
}
// LootFiles can be implemented if needed
func (g GCPIAMResults) LootFiles() []internal.LootFile {
return []internal.LootFile{}
}
// Houses high-level logic that retrieves IAM information and writes to output
func runGCPIAMCommand(cmd *cobra.Command, args []string) {
// Retrieve projectIDs and resource type from parent (gcp command) ctx
var projectIDs []string
var resourceType string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_IAM_MODULE_NAME)
return
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_IAM_MODULE_NAME)
}
// TODO fix once folders or organizations are supported as input for project root
resourceType = "project"
// Initialize IAMService and fetch principals with roles for the given projectIDs and resource type
iamService := IAMService.New()
var results []IAMService.PrincipalWithRoles
// Set output params leveraging parent (gcp) pflag values
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving IAM information for resource: %s of type %s", projectID, resourceType), globals.GCP_IAM_MODULE_NAME)
principals, err := iamService.PrincipalsWithRoles(projectID, resourceType)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_IAM_MODULE_NAME)
return
}
results = append(results, principals...)
logger.InfoM(fmt.Sprintf("Done retrieving IAM information for resource: %s of type %s", projectID, resourceType), globals.GCP_IAM_MODULE_NAME)
cloudfoxOutput := GCPIAMResults{Data: results}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_IAM_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_IAM_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("Done writing output for project %s", projectID), globals.GCP_IAM_MODULE_NAME)
}
}
+126
View File
@@ -0,0 +1,126 @@
package commands
import (
"fmt"
ComputeEngineService "github.com/BishopFox/cloudfox/gcp/services/computeEngineService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPInstancesCommand = &cobra.Command{
Use: globals.GCP_INSTANCES_MODULE_NAME, // This should be defined in the globals package
Aliases: []string{},
Short: "Display GCP Compute Engine instances information",
Args: cobra.MinimumNArgs(0),
Long: `
Display available Compute Engine instances information:
cloudfox gcp instances`,
Run: runGCPInstancesCommand,
}
// GCPInstancesResults implements internal.OutputInterface for Compute Engine instances
type GCPInstancesResults struct {
Data []ComputeEngineService.ComputeEngineInfo
}
func (g GCPInstancesResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
header := []string{
"Name",
"ID",
"State",
"ExternalIP",
"InternalIP",
"ServiceAccount", // Adding ServiceAccount to the header
"Zone",
"ProjectID",
}
var body [][]string
for _, instance := range g.Data {
// Initialize an empty string to aggregate service account emails
var serviceAccountEmails string
for _, serviceAccount := range instance.ServiceAccounts {
// Assuming each instance can have multiple service accounts, concatenate their emails
if serviceAccountEmails != "" {
serviceAccountEmails += "; " // Use semicolon as a delimiter for multiple emails
}
serviceAccountEmails += serviceAccount.Email
}
body = append(body, []string{
instance.Name,
instance.ID,
instance.State,
instance.ExternalIP,
instance.InternalIP,
serviceAccountEmails, // Add the aggregated service account emails to the output
instance.Zone,
instance.ProjectID,
})
}
tableFiles = append(tableFiles, internal.TableFile{
Name: globals.GCP_INSTANCES_MODULE_NAME,
Header: header,
Body: body,
})
return tableFiles
}
func (g GCPInstancesResults) LootFiles() []internal.LootFile {
// Define any loot files if applicable
return []internal.LootFile{}
}
func runGCPInstancesCommand(cmd *cobra.Command, args []string) {
var projectIDs []string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_INSTANCES_MODULE_NAME)
return
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_IAM_MODULE_NAME)
}
ces := ComputeEngineService.New()
var results []ComputeEngineService.ComputeEngineInfo
// Set output params leveraging parent (gcp) pflag values
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving all instances from project: %s", projectID), globals.GCP_INSTANCES_MODULE_NAME)
result, err := ces.Instances(projectID)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_INSTANCES_MODULE_NAME)
return
}
results = append(results, result...)
logger.InfoM(fmt.Sprintf("Done retrieving all instances from project: %s", projectID), globals.GCP_INSTANCES_MODULE_NAME)
cloudfoxOutput := GCPInstancesResults{Data: results}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_INSTANCES_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_INSTANCES_MODULE_NAME)
return
}
logger.InfoM("Done writing output", globals.GCP_INSTANCES_MODULE_NAME)
}
}
+120
View File
@@ -0,0 +1,120 @@
package commands
import (
"fmt"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
SecretsService "github.com/BishopFox/cloudfox/gcp/services/secretsService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPSecretsCommand = &cobra.Command{
Use: globals.GCP_SECRETS_MODULE_NAME,
Aliases: []string{},
Short: "Display GCP secrets information",
Args: cobra.MinimumNArgs(0),
Long: `
Display available secrets information:
cloudfox gcp secrets`,
Run: runGCPSecretsCommand,
}
// GCPSecretsResults struct that implements the internal.OutputInterface
type GCPSecretsResults struct {
Data []SecretsService.SecretInfo
}
func (g GCPSecretsResults) TableFiles() []internal.TableFile {
var tableFiles []internal.TableFile
header := []string{
"Name",
"CreationTime",
"Labels",
"Rotation",
"ProjectID",
// Add more fields as necessary
}
var body [][]string
for _, value := range g.Data {
body = append(body, []string{
value.Name,
value.CreationTime,
fmt.Sprintf("%v", value.Labels),
value.Rotation,
value.ProjectID,
})
}
tableFile := internal.TableFile{
Header: header,
Body: body,
Name: globals.GCP_SECRETS_MODULE_NAME,
}
tableFiles = append(tableFiles, tableFile)
return tableFiles
}
func (g GCPSecretsResults) LootFiles() []internal.LootFile {
// Define any specific data considered as loot
return []internal.LootFile{}
}
func runGCPSecretsCommand(cmd *cobra.Command, args []string) {
var projectIDs []string
var account string
parentCmd := cmd.Parent()
ctx := cmd.Context()
logger := internal.NewLogger()
if value, ok := ctx.Value("projectIDs").([]string); ok && len(value) > 0 {
projectIDs = value
} else {
logger.ErrorM("Could not retrieve projectIDs from flag value or value is empty", globals.GCP_SECRETS_MODULE_NAME)
return
}
if value, ok := ctx.Value("account").(string); ok {
account = value
} else {
logger.ErrorM("Could not retrieve account email from command", globals.GCP_IAM_MODULE_NAME)
}
client, err := secretmanager.NewClient(ctx)
if err != nil {
logger.ErrorM(fmt.Sprintf("failed to create secret manager client: %v", err), globals.GCP_SECRETS_MODULE_NAME)
return
}
defer client.Close()
ss := SecretsService.New(client)
var results []SecretsService.SecretInfo
// Set output params from parentCmd
verbosity, _ := parentCmd.PersistentFlags().GetInt("verbosity")
wrap, _ := parentCmd.PersistentFlags().GetBool("wrap")
outputDirectory, _ := parentCmd.PersistentFlags().GetString("outdir")
format, _ := parentCmd.PersistentFlags().GetString("output")
for _, projectID := range projectIDs {
logger.InfoM(fmt.Sprintf("Retrieving all secrets from project: %s", projectID), globals.GCP_SECRETS_MODULE_NAME)
result, err := ss.Secrets(projectID)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_SECRETS_MODULE_NAME)
return
}
results = append(results, result...)
logger.InfoM(fmt.Sprintf("Done retrieving all secrets from project: %s", projectID), globals.GCP_SECRETS_MODULE_NAME)
cloudfoxOutput := GCPSecretsResults{Data: results}
err = internal.HandleOutput("gcp", format, outputDirectory, verbosity, wrap, globals.GCP_SECRETS_MODULE_NAME, account, projectID, cloudfoxOutput)
if err != nil {
logger.ErrorM(err.Error(), globals.GCP_SECRETS_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("Done writing output for project %s", projectID), globals.GCP_SECRETS_MODULE_NAME)
}
}
+34
View File
@@ -0,0 +1,34 @@
package commands
import (
"fmt"
OAuthService "github.com/BishopFox/cloudfox/gcp/services/oauthService"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/spf13/cobra"
)
var GCPWhoAmICommand = &cobra.Command{
Use: globals.GCP_WHOAMI_MODULE_NAME,
Short: "Display the email address of the GCP authenticated user",
Args: cobra.NoArgs,
Run: runGCPWhoAmICommand,
}
func runGCPWhoAmICommand(cmd *cobra.Command, args []string) {
logger := internal.NewLogger()
// Initialize the OAuthService
oauthService := OAuthService.NewOAuthService()
// Call the WhoAmI function
principal, err := oauthService.WhoAmI()
if err != nil {
logger.ErrorM(fmt.Sprintf("Error retrieving token info: %v", err), globals.GCP_WHOAMI_MODULE_NAME)
return
}
logger.InfoM(fmt.Sprintf("authenticated user email: %s", principal.Email), globals.GCP_WHOAMI_MODULE_NAME)
}
@@ -0,0 +1,236 @@
package artifactregistryservice
import (
"context"
"fmt"
"strings"
artifactregistry "cloud.google.com/go/artifactregistry/apiv1"
artifactregistrypb "cloud.google.com/go/artifactregistry/apiv1/artifactregistrypb"
"github.com/BishopFox/cloudfox/gcp/services/models"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
locationpb "google.golang.org/genproto/googleapis/cloud/location"
)
// New creates a new instance of the ArtifactRegistryService using an artifactregistry.Client
func New(client *artifactregistry.Client) ArtifactRegistryService {
ars := ArtifactRegistryService{
Client: &ArtifactRegistryClientWrapper{
Closer: client.Close,
RepositoryLister: func(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.Repository] {
return client.ListRepositories(ctx, req, opts...)
},
LocationLister: func(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) models.GenericIterator[locationpb.Location] {
return client.ListLocations(ctx, req, opts...)
},
RepositoryGetter: func(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) {
return client.GetRepository(ctx, req, opts...)
},
DockerImageLister: func(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.DockerImage] {
return client.ListDockerImages(ctx, req, opts...)
},
},
}
return ars
}
var logger internal.Logger
// RepositoriesAndArtifacts retrieves both repositories and their artifacts for a given projectID.
func (ars *ArtifactRegistryService) RepositoriesAndArtifacts(projectID string) (CombinedRepoArtifactInfo, error) {
var combinedInfo CombinedRepoArtifactInfo
// Retrieve repositories.
repos, err := ars.Repositories(projectID)
if err != nil {
return combinedInfo, fmt.Errorf("failed to retrieve repositories: %v", err)
}
combinedInfo.Repositories = repos
// Iterate over repositories to fetch artifacts.
for _, repo := range repos {
// Extract location and repository name from the repository Name.
parts := strings.Split(repo.Name, "/")
if len(parts) < 6 {
logger.InfoM("Unexpected repository name format, skipping artifacts retrieval", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
continue
}
location := parts[3]
repositoryName := parts[5]
// Fetch artifacts for the current repository.
artifacts, err := ars.Artifacts(projectID, location, repositoryName)
if err != nil {
logger.InfoM(fmt.Sprintf("Failed to retrieve artifacts for repository %s: %v", repositoryName, err), globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
continue // Optionally continue to the next repository or handle error differently.
}
combinedInfo.Artifacts = append(combinedInfo.Artifacts, artifacts...)
}
return combinedInfo, nil
}
// RepositoriesAndArtifacts returns a list of repositories and artifacts given projectID.
// TODO consider putting location as input, so that we can put Locations iteration before it & potentially filter by location at top level of GCP module
func (ars *ArtifactRegistryService) Repositories(projectID string) ([]RepositoryInfo, error) {
// Get the list of available locations for the given project.
locations, err := ars.projectLocations(projectID)
if err != nil {
return nil, err
}
var repositories []RepositoryInfo
ctx := context.Background()
// Construct the request for listing repositories.
for _, location := range locations {
req := &artifactregistrypb.ListRepositoriesRequest{
Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
}
it := ars.Client.ListRepositories(ctx, req)
for {
repo, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
repositories = append(repositories, RepositoryInfo{
Name: repo.Name,
Format: repo.Format.String(),
Description: repo.Description,
SizeBytes: fmt.Sprintf("%d", repo.SizeBytes),
ProjectID: projectID,
Location: location,
})
}
}
return repositories, nil
}
// Artifacts fetches the artifacts for a given repository, handling different formats.
func (ars *ArtifactRegistryService) Artifacts(projectID string, location string, repositoryName string) ([]ArtifactInfo, error) {
ctx := context.Background()
// client, err := artifactregistry.NewClient(ctx)
// if err != nil {
// return nil, fmt.Errorf("failed to create artifact registry client: %v", err)
// }
// defer client.Close()
repoFullName := fmt.Sprintf("projects/%s/locations/%s/repositories/%s", projectID, location, repositoryName)
// Fetch repository details to determine its format
repo, err := ars.Client.GetRepository(ctx, &artifactregistrypb.GetRepositoryRequest{Name: repoFullName})
if err != nil {
return nil, fmt.Errorf("failed to get repository details: %v", err)
}
// Handle different repository formats
switch repo.Format {
case artifactregistrypb.Repository_DOCKER:
return ars.DockerImages(repoFullName)
// Placeholder for other formats
// case artifactregistrypb.Repository_MAVEN:
// return listMavenArtifacts(ctx, client, repoFullName)
// case artifactregistrypb.Repository_NPM:
// return listNpmPackages(ctx, client, repoFullName)
default:
logger.InfoM("Repository format is unsupported, so no artifacts were retrieved.", globals.GCP_ARTIFACT_RESGISTRY_MODULE_NAME)
return nil, nil
}
}
// parseDockerImageName parses the Docker image name string and returns the extracted details.
func parseDockerImageName(imageName string) DockerImageDetails {
// Split the image name by '/'
parts := strings.Split(imageName, "/")
// Extract details based on the known structure of the image name.
// Assuming the format is always consistent as described.
projectID := parts[1]
location := parts[3]
repository := parts[5]
// The image name and digest are after the last '/', separated by '@'
imageAndDigest := strings.Split(parts[7], "@")
imageName = imageAndDigest[0]
digest := imageAndDigest[1]
return DockerImageDetails{
ProjectID: projectID,
Location: location,
Repository: repository,
ImageName: imageName,
Digest: digest,
}
}
// listDockerImages specifically lists Docker images within a given repository.
func (ars *ArtifactRegistryService) DockerImages(repositoryName string) ([]ArtifactInfo, error) {
ctx := context.Background()
var artifacts []ArtifactInfo
req := &artifactregistrypb.ListDockerImagesRequest{
Parent: repositoryName,
}
it := ars.Client.ListDockerImages(ctx, req)
for {
image, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
// Parse image name to extract detailed information.
details := parseDockerImageName(image.Name)
// Populate the ArtifactInfo structure with Docker image details.
artifacts = append(artifacts, ArtifactInfo{
Name: details.ImageName,
Format: "DOCKER",
Location: details.Location,
Repository: details.Repository,
SizeBytes: fmt.Sprintf("%d", image.ImageSizeBytes),
Updated: image.UpdateTime.AsTime().String(),
Digest: details.Digest,
ProjectID: details.ProjectID,
})
}
return artifacts, nil
}
// listProjectLocations returns a list of available locations for the given project ID.
func (ars *ArtifactRegistryService) projectLocations(projectID string) ([]string, error) {
// Define the request to list locations.
req := &locationpb.ListLocationsRequest{
Name: fmt.Sprintf("projects/%s", projectID),
}
// Initialize an empty slice to hold the locations.
var locations []string
// Call the ListLocations method and handle pagination.
ctx := context.Background()
it := ars.Client.ListLocations(ctx, req)
for {
loc, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("failed to list locations: %w", err)
}
locations = append(locations, loc.LocationId)
}
return locations, nil
}
@@ -0,0 +1,252 @@
package artifactregistryservice_test
import (
"context"
"fmt"
"reflect"
"testing"
artifactRegistryService "github.com/BishopFox/cloudfox/gcp/services/artifactRegistryService"
"github.com/BishopFox/cloudfox/gcp/services/models"
artifactregistrypb "cloud.google.com/go/artifactregistry/apiv1/artifactregistrypb"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
locationpb "google.golang.org/genproto/googleapis/cloud/location"
)
// Mock structure for ArtifactRegistryClientWrapper
type mockArtifactRegistryClient struct {
repositories []*artifactregistrypb.Repository
locations []*locationpb.Location
dockerImages []*artifactregistrypb.DockerImage
}
func (m *mockArtifactRegistryClient) Close() error {
return nil
}
// Mock iterator for repositories
type mockRepoIterator struct {
repositories []*artifactregistrypb.Repository
index int
}
func (it *mockRepoIterator) Next() (*artifactregistrypb.Repository, error) {
if it.index < len(it.repositories) {
repo := it.repositories[it.index]
it.index++
return repo, nil
}
return nil, iterator.Done
}
// Mock iterator for locations
type mockLocationIterator struct {
locations []*locationpb.Location
index int
}
func (it *mockLocationIterator) Next() (*locationpb.Location, error) {
if it.index < len(it.locations) {
loc := it.locations[it.index]
it.index++
return loc, nil
}
return nil, iterator.Done
}
// Mock iterator for Docker images
type mockDockerImageIterator struct {
dockerImages []*artifactregistrypb.DockerImage
index int
}
func (it *mockDockerImageIterator) Next() (*artifactregistrypb.DockerImage, error) {
if it.index < len(it.dockerImages) {
img := it.dockerImages[it.index]
it.index++
return img, nil
}
return nil, iterator.Done
}
// Mock methods
func (m *mockArtifactRegistryClient) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.Repository] {
return &mockRepoIterator{repositories: m.repositories}
}
func (m *mockArtifactRegistryClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) models.GenericIterator[locationpb.Location] {
return &mockLocationIterator{locations: m.locations}
}
func (m *mockArtifactRegistryClient) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) {
for _, repo := range m.repositories {
if repo.Name == req.Name {
return repo, nil
}
}
return nil, fmt.Errorf("repository not found")
}
func (m *mockArtifactRegistryClient) ListDockerImages(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.DockerImage] {
return &mockDockerImageIterator{dockerImages: m.dockerImages}
}
var mockClient = mockArtifactRegistryClient{}
var ars = artifactRegistryService.ArtifactRegistryService{
Client: &artifactRegistryService.ArtifactRegistryClientWrapper{
Closer: mockClient.Close,
RepositoryLister: func(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.Repository] {
return mockClient.ListRepositories(ctx, req, opts...)
},
LocationLister: func(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) models.GenericIterator[locationpb.Location] {
return mockClient.ListLocations(ctx, req, opts...)
},
RepositoryGetter: func(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) {
return mockClient.GetRepository(ctx, req, opts...)
},
DockerImageLister: func(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.DockerImage] {
return mockClient.ListDockerImages(ctx, req, opts...)
},
},
}
// Tests go here
func TestArtifacts(t *testing.T) {
cases := []struct {
name string
projectID string
location string
repositoryName string
setupMockClient func(client *mockArtifactRegistryClient)
expectedArtifacts []artifactRegistryService.ArtifactInfo
expectError bool
}{
{
name: "Valid artifacts retrieval",
projectID: "project1",
location: "us-central1",
repositoryName: "repo1",
setupMockClient: func(client *mockArtifactRegistryClient) {
client.dockerImages = []*artifactregistrypb.DockerImage{
{
Name: "projects/project1/locations/us-central1/repositories/repo1/dockerImages/image1@sha256:e9954c1fc875017be1c3e36eca16be2d9e9bccc4bf072163515467d6a823c7cf",
Uri: "us-central1-docker.pkg.dev/project1/repo1/image1@sha256:e9954c1fc875017be1c3e36eca16be2d9e9bccc4bf072163515467d6a823c7cf",
ImageSizeBytes: 1024,
},
}
client.locations = []*locationpb.Location{
{
LocationId: "us-central1",
},
}
client.repositories = []*artifactregistrypb.Repository{{
Name: "projects/project1/locations/us-central1/repositories/repo1",
Format: artifactregistrypb.Repository_DOCKER,
},
}
},
expectedArtifacts: []artifactRegistryService.ArtifactInfo{
{
Name: "image1",
Format: "DOCKER",
Location: "us-central1",
Repository: "repo1",
SizeBytes: "1024",
ProjectID: "project1",
Digest: "sha256:e9954c1fc875017be1c3e36eca16be2d9e9bccc4bf072163515467d6a823c7cf",
Updated: "1970-01-01 00:00:00 +0000 UTC",
},
},
expectError: false,
},
// Add more test cases here
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Reset mockClient state
mockClient.repositories = nil
mockClient.locations = nil
mockClient.dockerImages = nil
// Setup mock client for the current test case
tc.setupMockClient(&mockClient)
artifacts, err := ars.Artifacts(tc.projectID, tc.location, tc.repositoryName)
if (err != nil) != tc.expectError {
t.Errorf("Artifacts() error = %v, expectError %v", err, tc.expectError)
return
}
if !reflect.DeepEqual(artifacts, tc.expectedArtifacts) {
t.Errorf("Artifacts() = %v, expected %v", artifacts, tc.expectedArtifacts)
}
})
}
}
func TestRepositories(t *testing.T) {
cases := []struct {
name string
projectID string
setupMockClient func(client *mockArtifactRegistryClient)
expectedRepositories []artifactRegistryService.RepositoryInfo
expectError bool
}{
{
name: "Valid repositories retrieval",
projectID: "project1",
setupMockClient: func(client *mockArtifactRegistryClient) {
client.repositories = []*artifactregistrypb.Repository{
{
Name: "projects/project1/locations/us-central1/repositories/repo1",
Format: artifactregistrypb.Repository_DOCKER,
Description: "Test repository",
},
}
client.locations = []*locationpb.Location{
{
LocationId: "us-central1",
},
}
},
expectedRepositories: []artifactRegistryService.RepositoryInfo{
{
Name: "projects/project1/locations/us-central1/repositories/repo1",
Format: "DOCKER",
Description: "Test repository",
SizeBytes: "0",
ProjectID: "project1",
Location: "us-central1",
},
},
expectError: false,
},
// Add more test cases here
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Reset mockClient state
mockClient.repositories = nil
mockClient.locations = nil
mockClient.dockerImages = nil
// Setup mock client for the current test case
tc.setupMockClient(&mockClient)
repositories, err := ars.Repositories(tc.projectID)
if (err != nil) != tc.expectError {
t.Errorf("Repositories() error = %v, expectError %v", err, tc.expectError)
return
}
if !reflect.DeepEqual(repositories, tc.expectedRepositories) {
t.Errorf("Repositories() = %v, expected %v", repositories, tc.expectedRepositories)
}
})
}
}
@@ -0,0 +1,78 @@
package artifactregistryservice
import (
"context"
artifactregistrypb "cloud.google.com/go/artifactregistry/apiv1/artifactregistrypb"
"github.com/BishopFox/cloudfox/gcp/services/models"
"github.com/googleapis/gax-go/v2"
locationpb "google.golang.org/genproto/googleapis/cloud/location"
)
// CombinedRepoArtifactInfo holds the combined information of repositories and their respective artifacts.
type CombinedRepoArtifactInfo struct {
Repositories []RepositoryInfo `json:"repositories"`
Artifacts []ArtifactInfo `json:"artifacts"`
}
// ArtifactInfo represents the basic information of an artifact within a registry.
type ArtifactInfo struct {
Name string `json:"name"`
Format string `json:"format"`
Version string `json:"version"`
Location string `json:"location"`
Repository string `json:"repository"`
SizeBytes string `json:"virtualSize"`
Updated string `json:"updated"`
Digest string `json:"digest"`
ProjectID string `json:"projectID"`
}
// RepositoryInfo holds information about a repository and its artifacts.
type RepositoryInfo struct {
Name string `json:"name"`
Format string `json:"format"`
Description string `json:"description"`
SizeBytes string `json:"sizeBytes"`
ProjectID string `json:"projectID"`
Location string `json:"location"`
}
// DockerImageDetails holds the extracted parts from a Docker image name.
type DockerImageDetails struct {
ProjectID string `json:"projectID"`
Location string `json:"location"`
Repository string `json:"repository"`
ImageName string `json:"name"`
Digest string `json:"digest"`
}
// Function calls to the API are wrapped to facilitate mocking
type ArtifactRegistryClientWrapper struct {
Closer func() error
RepositoryLister func(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.Repository]
LocationLister func(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) models.GenericIterator[locationpb.Location]
RepositoryGetter func(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error)
DockerImageLister func(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.DockerImage]
}
func (w *ArtifactRegistryClientWrapper) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.Repository] {
return w.RepositoryLister(ctx, req, opts...)
}
func (w *ArtifactRegistryClientWrapper) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) models.GenericIterator[locationpb.Location] {
return w.LocationLister(ctx, req, opts...)
}
func (w *ArtifactRegistryClientWrapper) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) {
return w.RepositoryGetter(ctx, req, opts...)
}
func (w *ArtifactRegistryClientWrapper) ListDockerImages(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) models.GenericIterator[artifactregistrypb.DockerImage] {
return w.DockerImageLister(ctx, req, opts...)
}
// ArtifactRegistryService provides methods to interact with Artifact Registry resources.
type ArtifactRegistryService struct {
Client *ArtifactRegistryClientWrapper
}
@@ -0,0 +1,150 @@
package bigqueryservice
import (
"context"
"time"
"cloud.google.com/go/bigquery"
"google.golang.org/api/iterator"
)
// BigqueryDataset represents a dataset in BigQuery
type BigqueryDataset struct {
DatasetID string
Location string
CreationTime time.Time
LastModifiedTime time.Time
Description string
Name string
ProjectID string
}
// BigqueryTable represents a table in BigQuery
type BigqueryTable struct {
TableID string
DatasetID string
Location string
CreationTime time.Time
LastModifiedTime time.Time
NumBytes int64
Description string
ProjectID string
}
// CombinedBigqueryData represents both datasets and tables within a project
type CombinedBigqueryData struct {
Datasets []BigqueryDataset
Tables []BigqueryTable
}
type BigQueryService struct {
// Placeholder for any required services or configuration
}
// New creates a new instance of BigQueryService
func New() *BigQueryService {
return &BigQueryService{}
}
// gcloud alpha bq datasets list
// gcloud alpha bq datasets describe terragoat_dev_dataset
// gcloud alpha bq tables list --dataset terragoat_dev_dataset
// gcloud alpha bq tables describe bar --dataset terragoat_dev_dataset
// BigqueryDatasetsAndTables retrieves all datasets and their tables for a given projectID
func (bq *BigQueryService) BigqueryDatasetsAndTables(projectID string) (CombinedBigqueryData, error) {
// Initialize the combined struct to hold datasets and tables
combinedData := CombinedBigqueryData{}
// Retrieve all datasets
datasets, err := bq.BigqueryDatasets(projectID)
if err != nil {
return combinedData, err
}
combinedData.Datasets = datasets
// Iterate over each dataset to retrieve its tables
for _, dataset := range datasets {
tables, err := bq.BigqueryTables(projectID, dataset.DatasetID)
if err != nil {
return combinedData, err
}
combinedData.Tables = append(combinedData.Tables, tables...)
}
return combinedData, nil
}
// BigqueryDatasets retrieves datasets from the given projectID across all locations
func (bq *BigQueryService) BigqueryDatasets(projectID string) ([]BigqueryDataset, error) {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, projectID)
if err != nil {
return nil, err
}
defer client.Close()
var datasets []BigqueryDataset
it := client.Datasets(ctx)
for {
ds, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
meta, err := ds.Metadata(ctx)
if err != nil {
return nil, err
}
datasets = append(datasets, BigqueryDataset{
DatasetID: ds.DatasetID,
Location: meta.Location,
CreationTime: meta.CreationTime,
LastModifiedTime: meta.LastModifiedTime,
Description: meta.Description,
Name: meta.Name,
ProjectID: projectID,
})
}
return datasets, nil
}
// BigqueryTables retrieves tables from the given projectID and dataset across all locations
func (bq *BigQueryService) BigqueryTables(projectID string, datasetID string) ([]BigqueryTable, error) {
ctx := context.Background()
client, err := bigquery.NewClient(ctx, projectID)
if err != nil {
return nil, err
}
defer client.Close()
var tables []BigqueryTable
ds := client.Dataset(datasetID)
it := ds.Tables(ctx)
for {
table, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
meta, err := table.Metadata(ctx)
if err != nil {
return nil, err
}
tables = append(tables, BigqueryTable{
TableID: table.TableID,
DatasetID: datasetID,
Location: meta.Location,
CreationTime: meta.CreationTime,
LastModifiedTime: meta.LastModifiedTime,
NumBytes: meta.NumBytes,
Description: meta.Description,
ProjectID: projectID,
})
}
return tables, nil
}
@@ -0,0 +1 @@
package bigqueryservice_test
@@ -0,0 +1,117 @@
package cloudstorageservice
import (
"context"
"fmt"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
)
type CloudStorageService struct {
// DataStoreService datastoreservice.DataStoreService
}
func New() *CloudStorageService {
return &CloudStorageService{}
}
// type ObjectInfo struct {
// ObjectName string `json:"objecttName"`
// ObjectSizeBytes float64 `json:"objectSizeBytes"`
// IsPublic bool `json:"isPublic"`
// }
type BucketInfo struct {
Name string `json:"name"`
Location string `json:"location"`
ProjectID string `json:"projectID"`
}
func (cs *CloudStorageService) Buckets(projectID string) ([]BucketInfo, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("Failed to create client: %v", err)
}
defer client.Close()
var buckets []BucketInfo
bucketIterator := client.Buckets(ctx, projectID)
for {
battrs, err := bucketIterator.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
bucket := BucketInfo{Name: battrs.Name, Location: battrs.Location, ProjectID: projectID}
buckets = append(buckets, bucket)
}
return buckets, nil
}
// func (cs *CloudStorageService) BucketsWithMetaData(projectID string) (map[string][]BucketInfo, error) {
// buckets, _ := cs.Buckets(projectID)
// bucketInfos := make(map[string][]BucketInfo)
// ctx := context.Background()
// client, err := storage.NewClient(ctx)
// if err != nil {
// return nil, fmt.Errorf("Failed to create client: %v", err)
// }
// for {
// bucketAttrs, err := buckets.Next()
// if err == iterator.Done {
// break
// }
// if err != nil {
// return nil, fmt.Errorf("failed to list buckets: %v", err)
// }
// bucketName := bucketAttrs.Name
// log.Printf("Working on bucket %s", bucketName)
// // List all objects in the bucket and calculate total size
// totalSize := int64(0)
// var objects []ObjectInfo
// it := client.Bucket(bucketName).Objects(ctx, nil)
// for {
// objectAttrs, err := it.Next()
// if err == iterator.Done {
// break
// }
// if err != nil {
// return nil, fmt.Errorf("failed to list objects in bucket %s: %v", bucketName, err)
// }
// // Get size
// objectSize := objectAttrs.Size
// totalSize += objectSize
// // Check if public
// isPublic := false
// for _, rule := range objectAttrs.ACL {
// if rule.Entity == storage.AllUsers {
// isPublic = true
// break
// }
// }
// objects = append(objects, ObjectInfo{ObjectName: objectAttrs.Name, ObjectSizeBytes: float64(objectSize), IsPublic: isPublic})
// if totalSize > 3221225472 { // 3 GiB in bytes
// log.Printf("%s bucket is over 3 GiB. Skipping remaining objects in this bucket...", bucketName)
// break
// }
// }
// bucketSizeMB := float64(totalSize) / 1024 / 1024
// bucketInfos[projectID] = append(bucketInfos[projectID], BucketInfo{BucketName: bucketName, BucketSizeMB: bucketSizeMB, Objects: objects})
// }
// log.Printf("Sorting resulting list of buckets in descending order %s", projectID)
// sort.Slice(bucketInfos[projectID], func(i, j int) bool {
// return bucketInfos[projectID][i].BucketSizeMB > bucketInfos[projectID][j].BucketSizeMB
// })
// return bucketInfos, nil
// }
@@ -0,0 +1 @@
package cloudstorageservice_test
@@ -0,0 +1,99 @@
package computeengineservice
import (
"context"
"fmt"
"strings"
"google.golang.org/api/compute/v1"
)
type ComputeEngineService struct {
// DataStoreService datastoreservice.DataStoreService
}
func New() *ComputeEngineService {
return &ComputeEngineService{}
}
type ComputeEngineInfo struct {
Name string
ID string
Zone string
State string
ExternalIP string
InternalIP string
ServiceAccounts []*compute.ServiceAccount // Assuming role is derived from service accounts
NetworkInterfaces []*compute.NetworkInterface
Tags *compute.Tags
ProjectID string
}
// Retrieves instances from all regions and zones for a project without using concurrency.
func (ces *ComputeEngineService) Instances(projectID string) ([]ComputeEngineInfo, error) {
ctx := context.Background()
computeService, err := compute.NewService(ctx)
if err != nil {
return nil, err
}
regions, err := computeService.Regions.List(projectID).Do()
if err != nil {
return nil, err
}
var instanceInfos []ComputeEngineInfo
for _, region := range regions.Items {
for _, zoneURL := range region.Zones {
zone := getZoneNameFromURL(zoneURL)
instanceList, err := computeService.Instances.List(projectID, zone).Do()
if err != nil {
return nil, fmt.Errorf("error retrieving instances from zone %s: %v", zone, err)
}
for _, instance := range instanceList.Items {
info := ComputeEngineInfo{
Name: instance.Name,
ID: fmt.Sprintf("%v", instance.Id),
Zone: zoneURL,
State: instance.Status,
ExternalIP: getExternalIP(instance),
InternalIP: getInternalIP(instance),
ServiceAccounts: instance.ServiceAccounts,
NetworkInterfaces: instance.NetworkInterfaces,
Tags: instance.Tags,
ProjectID: projectID,
}
instanceInfos = append(instanceInfos, info)
}
}
}
return instanceInfos, nil
}
// Returns the zone from a GCP URL string with the zone in it
func getZoneNameFromURL(zoneURL string) string {
splits := strings.Split(zoneURL, "/")
return splits[len(splits)-1]
}
// getExternalIP extracts the external IP address from an instance if available.
func getExternalIP(instance *compute.Instance) string {
for _, iface := range instance.NetworkInterfaces {
for _, accessConfig := range iface.AccessConfigs {
if accessConfig.NatIP != "" {
return accessConfig.NatIP
}
}
}
return ""
}
// getInternalIP extracts the internal IP address from an instance.
func getInternalIP(instance *compute.Instance) string {
if len(instance.NetworkInterfaces) > 0 {
return instance.NetworkInterfaces[0].NetworkIP
}
return ""
}
// TODO consider just getting the emails of the service account and returning a []string
@@ -0,0 +1 @@
package computeengineservice
+93
View File
@@ -0,0 +1,93 @@
package iamservice
// import (
// "fmt"
// "strings"
// "time"
// "github.com/fatih/color"
// "github.com/BishopFox/cloudfox/internal/gcp"
// "github.com/BishopFox/cloudfox/internal"
// "github.com/BishopFox/cloudfox/globals"
// )
// type AccessTokensModule struct {
// // Filtering data
// Organizations []string
// Folders []string
// Projects []string
// }
// // Be incorportated in iam.go
// func (m *AccessTokensModule) PrintAccessTokens(outputFormat string, outputDirectory string, verbosity int) error {
// GCPLogger.InfoM(fmt.Sprintf("Enumerating GCP local access tokens (%s, %s)...", color.CyanString("default user token"), color.RedString("application-default token")), globals.GCP_ACCESSTOKENS_MODULE_NAME)
// tokens := gcp.ReadRefreshTokens()
// accessTokens := gcp.ReadAccessTokens()
// applicationdefaulthash := gcp.GetDefaultApplicationHash()
// activeAccount := gcp.GetActiveAccount()
// var tableHead = []string{"Account", "Credential Type", "Validity", "Refresh Token", "Refresh Token needs password"}
// var tableBody [][]string
// for _, accessToken := range accessTokens {
// // prepare token's associated ID (email or hash)
// var emailinfo string
// if (accessToken.AccountID == activeAccount) {
// emailinfo = color.BlueString(accessToken.AccountID)
// } else {
// emailinfo = accessToken.AccountID
// }
// // format expiration time
// Exp, _ := time.Parse(time.RFC3339, accessToken.TokenExpiry)
// var timeinfo string
// if Exp.After(time.Now()) {
// timeinfo = Exp.Format(time.RFC1123)
// } else {
// timeinfo = "EXPIRED"
// }
// // display token type, user or application credential
// var tokentype string
// if (strings.Contains(accessToken.AccountID, "@")) {
// tokentype = "User"
// } else {
// tokentype = "Application"
// }
// // is there an associated refres htoken ?
// var refreshtokeninfo string
// refreshtokeninfo = "No"
// for _, refreshtoken := range tokens {
// if (accessToken.AccountID == refreshtoken.Email) {
// refreshtokeninfo = "Yes"
// } else if (accessToken.AccountID == applicationdefaulthash) {
// refreshtokeninfo = "Yes"
// emailinfo = color.RedString(emailinfo)
// }
// }
// // is there a proof of reauthentication to use the refresh
// // token ? If not, password is needed
// var raptinfo string
// if refreshtokeninfo == "No" {
// raptinfo = "-"
// } else if accessToken.RaptToken.Valid {
// raptinfo = "No"
// } else {
// if (tokentype == "Application") {
// raptinfo = "TBD"
// } else {
// raptinfo = "Yes"
// }
// }
// tableBody = append(
// tableBody,
// []string{
// emailinfo,
// tokentype,
// timeinfo,
// refreshtokeninfo,
// raptinfo,
// })
// }
// internal.PrintTableToScreen(tableHead, tableBody, false)
// return nil
// }
+189
View File
@@ -0,0 +1,189 @@
package iamservice
import (
"context"
"fmt"
"strings"
iampb "cloud.google.com/go/iam/apiv1/iampb"
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb"
"github.com/BishopFox/cloudfox/globals"
"github.com/BishopFox/cloudfox/internal"
)
type IAMService struct {
// DataStoreService datastoreservice.DataStoreService
}
func New() *IAMService {
return &IAMService{}
}
// AncestryResource represents a single resource in the project's ancestry.
type AncestryResource struct {
Type string `json:"type"`
Id string `json:"id"`
}
// PolicyBindings represents IAM policy bindings.
type PolicyBinding struct {
Role string `json:"role"`
Members []string `json:"members"`
ResourceID string `json:"resourceID"`
ResourceType string
PolicyName string `json:"policyBindings"`
Condition string
}
type PrincipalWithRoles struct {
Name string
Type string
PolicyBindings []PolicyBinding
ResourceID string
ResourceType string
}
var logger internal.Logger
func projectAncestry(projectID string) ([]AncestryResource, error) {
ctx := context.Background()
projectsClient, err := resourcemanager.NewProjectsClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create projects client: %v", err)
}
defer projectsClient.Close()
foldersClient, err := resourcemanager.NewFoldersClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to create folders client: %v", err)
}
defer foldersClient.Close()
resourceID := "projects/" + projectID
var ancestry []AncestryResource
for {
if strings.HasPrefix(resourceID, "organizations/") {
ancestry = append(ancestry, AncestryResource{Type: "organization", Id: strings.TrimPrefix(resourceID, "organizations/")})
break
} else if strings.HasPrefix(resourceID, "folders/") {
resp, err := foldersClient.GetFolder(ctx, &resourcemanagerpb.GetFolderRequest{Name: resourceID})
if err != nil {
logger.ErrorM(fmt.Sprintf("failed to access folder %s, %v", resourceID, err), globals.GCP_IAM_MODULE_NAME)
break // Stop processing further if a folder is inaccessible
}
ancestry = append(ancestry, AncestryResource{Type: "folder", Id: strings.TrimPrefix(resp.Name, "folders/")})
resourceID = resp.Parent
} else if strings.HasPrefix(resourceID, "projects/") {
resp, err := projectsClient.GetProject(ctx, &resourcemanagerpb.GetProjectRequest{Name: resourceID})
if err != nil {
logger.ErrorM(fmt.Sprintf("failed to access project %s, %v", resourceID, err), globals.GCP_IAM_MODULE_NAME)
return nil, fmt.Errorf("failed to get project: %v", err)
}
ancestry = append(ancestry, AncestryResource{Type: "project", Id: strings.TrimPrefix(resp.Name, "projects/")})
resourceID = resp.Parent
} else {
return nil, fmt.Errorf("unknown resource type for: %s", resourceID)
}
}
// Reverse the slice as we've built it from child to ancestor
for i, j := 0, len(ancestry)-1; i < j; i, j = i+1, j-1 {
ancestry[i], ancestry[j] = ancestry[j], ancestry[i]
}
return ancestry, nil
}
// Policies fetches IAM policy for a given resource and all policies in resource ancestry
func (s *IAMService) Policies(resourceID string, resourceType string) ([]PolicyBinding, error) {
ctx := context.Background()
client, err := resourcemanager.NewProjectsClient(ctx)
if err != nil {
return nil, fmt.Errorf("resourcemanager.NewProjectsClient: %v", err)
}
defer client.Close()
var resourceName string
switch resourceType {
case "project":
resourceName = "projects/" + resourceID
case "folder":
resourceName = "folders/" + resourceID
case "organization":
resourceName = "organizations/" + resourceID
default:
return nil, fmt.Errorf("unsupported resource type: %s", resourceType)
}
req := &iampb.GetIamPolicyRequest{
Resource: resourceName,
}
// Fetch the IAM policy for the resource
policy, err := client.GetIamPolicy(ctx, req)
if err != nil {
return nil, fmt.Errorf("client.GetIamPolicy: %v", err)
}
// Assemble the policy bindings
var policyBindings []PolicyBinding
for _, binding := range policy.Bindings {
policyBinding := PolicyBinding{
Role: binding.Role,
Members: binding.Members,
ResourceID: resourceID,
ResourceType: resourceType,
Condition: binding.Condition.String(),
PolicyName: resourceName + "_policyBindings",
}
policyBindings = append(policyBindings, policyBinding)
}
return policyBindings, nil
}
func determinePrincipalType(member string) string {
if strings.HasPrefix(member, "user:") {
return "User"
} else if strings.HasPrefix(member, "serviceAccount:") {
return "ServiceAccount"
} else if strings.HasPrefix(member, "group:") {
return "Group"
} else {
return "Unknown"
}
}
func (s *IAMService) PrincipalsWithRoles(resourceID string, resourceType string) ([]PrincipalWithRoles, error) {
policyBindings, err := s.Policies(resourceID, resourceType)
if err != nil {
return nil, err
}
principalMap := make(map[string]*PrincipalWithRoles)
for _, pb := range policyBindings {
for _, member := range pb.Members {
principalType := determinePrincipalType(member) // Implement this function based on member prefix
if principal, ok := principalMap[member]; ok {
principal.PolicyBindings = append(principal.PolicyBindings, pb)
} else {
principalMap[member] = &PrincipalWithRoles{
Name: member,
Type: principalType,
PolicyBindings: []PolicyBinding{pb},
ResourceID: resourceID,
ResourceType: resourceType,
}
}
}
}
var principals []PrincipalWithRoles
for _, principal := range principalMap {
principals = append(principals, *principal)
}
return principals, nil
}
@@ -0,0 +1 @@
package iamservice_test
+5
View File
@@ -0,0 +1,5 @@
package models
type GenericIterator[T any] interface {
Next() (*T, error)
}
@@ -0,0 +1,260 @@
package networkservice
import (
"context"
"log"
"net"
"strings"
ComputeEngineService "github.com/BishopFox/cloudfox/gcp/services/computeEngineService"
"google.golang.org/api/compute/v1"
)
// VPC / network / subnets
// gcloud compute networks list
// gcloud compute networks get-effective-firewalls terragoat-dev-network
// gcloud compute networks subnets list
// FirewallRule structure for JSON output
// firewall-rules
// gcloud compute firewall-rules list - `terragoat-dev-firewall`
// forwarding rules (load balancers)
// gcloud compute forwarding-rules list
// Router & NAT gateways
// gcloud compute routers list
// gcloud compute routers nats list --router
// Global network firewall policy
// gcloud compute network-firewall-policies
// gcloud compute network-firewall-policies rules list
// gcloud compute network-firewall-policies associations list
type FirewallRule struct {
FWName string `json:"fw_name"`
Description string `json:"description"`
Direction string `json:"direction"`
Allowed map[string][]string `json:"allowed"`
Denied map[string][]string `json:"denied"`
SourceRanges []string `json:"source_ranges"`
TargetTag string `json:"target_tag"`
AllowedTraffic Traffic `json:"allowed_traffic"`
ExposedEndpoints []Endpoint `json:"exposed_endpoints"`
DestinationRanges []string `json:"destinatioRanges"`
TargetTags []string `json:"targetTags"`
}
type Traffic struct {
TCP []string `json:"tcp"`
UDP []string `json:"udp"`
}
type Endpoint struct {
IP string `json:"ip"`
Ports []string `json:"ports"`
Protocol string `json:"protocol"`
}
type NetwworkService struct {
// DataStoreService datastoreservice.DataStoreService
}
func New() *NetwworkService {
return &NetwworkService{}
}
// Returns firewall rules for a project.
func (ns *NetwworkService) FirewallRules(projectID string) ([]*compute.Firewall, error) {
ctx := context.Background()
computeService, err := compute.NewService(ctx)
if err != nil {
return nil, err
}
firewallList, err := computeService.Firewalls.List(projectID).Do()
if err != nil {
return nil, err
}
return firewallList.Items, nil
}
// Returns firewall rules with additional logic to tag rules that expose resources to the public
func (ns *NetwworkService) FirewallRulesWithPublicExposure(projectID string) ([]FirewallRule, error) {
var results []FirewallRule
log.Printf("Retrieving firewall rules for project %s", projectID)
firewalls, err := ns.FirewallRules(projectID)
log.Print("Done")
if err != nil {
log.Printf("Error fetching firewall rules for project %s: %v", projectID, err)
return nil, err
}
log.Print("Parsing firewall rules")
for _, fw := range firewalls {
parsedRule, err := parseFirewallRule(fw, projectID)
if err != nil {
log.Printf("Error parsing firewall rule for project %s: %v", projectID, err)
continue
}
results = append(results, parsedRule)
}
log.Print("Done")
return results, nil
}
// Returns a list of IPs that are mapped to a given tag. Uses a list of instances
func getIPAddressesForTargetTag(instances []ComputeEngineService.ComputeEngineInfo, tag string) ([]string, error) {
var ips []string
for _, instance := range instances {
if contains(instance.Tags.Items, tag) {
ips = append(ips, instance.NetworkInterfaces[0].NetworkIP)
}
}
return ips, nil
}
// Returns the zone from a GCP URL string with the zone in it
func getZoneNameFromURL(zoneURL string) string {
splits := strings.Split(zoneURL, "/")
return splits[len(splits)-1]
}
// Returns true of a string is in the given list of strings. Else false
func contains(slice []string, item string) bool {
for _, a := range slice {
if a == item {
return true
}
}
return false
}
// Returns true if a string in compute.Firewall.SourceRanges is "0.0.0.0/0"
func isExposedToInternet(fw *compute.Firewall) bool {
for _, rangeVal := range fw.SourceRanges {
if rangeVal == "0.0.0.0/0" {
return true
}
}
return false
}
// Returns true if the IP is an internal ipv4 or ipv6 IP
func IsInternalIP(cidr string) bool {
ip, _, err := net.ParseCIDR(cidr)
if err != nil {
// Try parsing as just an IP (not CIDR)
ip = net.ParseIP(cidr)
if ip == nil {
log.Printf("Error parsing input %s\n", cidr)
return false
}
}
// Check for IPv4 private ranges
if ip.To4() != nil {
for _, privateCIDR := range []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
} {
_, block, _ := net.ParseCIDR(privateCIDR)
if block.Contains(ip) {
return true
}
}
return false
}
// Check for IPv6 ULA range fc00::/7
// This checks if the first byte of the address is in the range 0xfc to 0xfd
if ip[0] == 0xfc || ip[0] == 0xfd {
return true
}
return false
}
// getPublicEndpoints fetches the endpoints exposed to the internet
// and, if a TargetTag is provided, gets the IP associated with it.
func getPublicEndpoints(fw *compute.Firewall, projectID string) ([]Endpoint, error) {
var exposedEndpoints []Endpoint
ces := ComputeEngineService.New()
if isExposedToInternet(fw) {
for _, allowed := range fw.Allowed {
// Handle destination ranges
for _, destRange := range fw.DestinationRanges {
if !IsInternalIP(destRange) {
exposed := Endpoint{
IP: destRange,
Ports: allowed.Ports,
Protocol: allowed.IPProtocol,
}
exposedEndpoints = append(exposedEndpoints, exposed)
}
}
// If TargetTag is provided, fetch the associated IP addresses.
if len(fw.TargetTags) > 0 {
log.Printf("Target tags found, getting their IP...")
instances, err := ces.Instances(projectID)
if err != nil {
log.Printf("Error retrieving instances: %v", err)
return nil, err
}
for _, tag := range fw.TargetTags {
ips, err := getIPAddressesForTargetTag(instances, tag)
if err != nil {
return nil, err
}
for _, ip := range ips {
if !IsInternalIP(ip) {
exposed := Endpoint{
IP: ip,
Ports: allowed.Ports,
Protocol: allowed.IPProtocol,
}
exposedEndpoints = append(exposedEndpoints, exposed)
}
}
}
}
}
}
return exposedEndpoints, nil
}
// The original parseFirewallRule function
func parseFirewallRule(fw *compute.Firewall, projectID string) (FirewallRule, error) {
var exposedEndpoints []Endpoint
trafficAllowed := make(map[string][]string)
trafficDenied := make(map[string][]string)
for _, allowed := range fw.Allowed {
trafficAllowed[allowed.IPProtocol] = append(trafficAllowed[allowed.IPProtocol], allowed.Ports...)
}
exposedEndpoints, err := getPublicEndpoints(fw, projectID)
if err != nil {
return FirewallRule{}, err
}
for _, denied := range fw.Denied {
trafficDenied[denied.IPProtocol] = append(trafficDenied[denied.IPProtocol], denied.Ports...)
}
return FirewallRule{
FWName: fw.Name,
Description: fw.Description,
Direction: fw.Direction,
Allowed: trafficAllowed,
Denied: trafficDenied,
SourceRanges: fw.SourceRanges,
TargetTag: strings.Join(fw.TargetTags, ","),
ExposedEndpoints: exposedEndpoints,
}, nil
}
// TODO
// func (ns *NetworkService) ForwardingRules() {}
@@ -0,0 +1,35 @@
package networkservice_test
import (
"testing"
networkservice "github.com/BishopFox/cloudfox/gcp/services/networkService"
)
func TestIsInternalIP(t *testing.T) {
tests := []struct {
input string
expect bool
}{
// IPv4 tests
{"10.1.2.3", true}, // falls within 10.0.0.0/8
{"172.17.0.1", true}, // falls within 172.16.0.0/12
{"192.168.10.1", true}, // falls within 192.168.0.0/16
{"11.1.2.3", false}, // public IP
{"172.32.0.1", false}, // public IP
{"192.169.0.1", false}, // public IP
{"8.8.8.8", false}, // public IP
// IPv6 tests
{"fc00::1", true}, // falls within fc00::/7
{"fd00::1", true}, // falls within fd00::/8
{"fe80::1", false}, // link-local address, not ULA
{"2001:0db8:85a3::8a2e", false}, // public IP
}
for _, test := range tests {
result := networkservice.IsInternalIP(test.input)
if result != test.expect {
t.Errorf("IsInternalIP(%s) = %v; want %v", test.input, result, test.expect)
}
}
}
+84
View File
@@ -0,0 +1,84 @@
package oauthservice
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"golang.org/x/oauth2/google"
)
// Principal struct modified to map JSON response fields.
type Principal struct {
Email string `json:"email"`
Scope []string
}
// Temporary struct to match the JSON structure.
type tokenInfoResponse struct {
Email string `json:"email"`
Scope string `json:"scope"` // Keep as string to match JSON.
}
// OAuthService struct definition (unchanged)
type OAuthService struct {
// This struct can be expanded in the future if necessary.
}
// NewOAuthService creates a new instance of OAuthService.
func NewOAuthService() *OAuthService {
return &OAuthService{}
}
// WhoAmI function returns the Principal struct showing the email and scope of the currently authenticated user by generating an oauth token
func (s *OAuthService) WhoAmI() (*Principal, error) {
ctx := context.Background()
ts, err := google.DefaultTokenSource(ctx, "")
if err != nil {
return nil, fmt.Errorf("failed to obtain default token source: %v", err)
}
token, err := ts.Token()
if err != nil {
return nil, fmt.Errorf("failed to get token from token source: %v", err)
}
tokenInfo, err := queryTokenInfo(token.AccessToken)
if err != nil {
return nil, fmt.Errorf(fmt.Sprintf("failed to retrieve metada of the token with error: %s", err.Error()))
}
// Split the scope string into a slice of strings.
scopes := strings.Split(tokenInfo.Scope, " ")
return &Principal{
Email: tokenInfo.Email,
Scope: scopes,
}, nil
}
// queryTokenInfo function modified to return (*Principal, error).
func queryTokenInfo(accessToken string) (*tokenInfoResponse, error) {
url := fmt.Sprintf("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s", accessToken)
resp, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("error making request to tokeninfo endpoint: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading tokeninfo response body: %v", err)
}
var response tokenInfoResponse
// Unmarshal the JSON response body into the Principal struct.
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("error unmarshalling tokeninfo response body: %v", err)
}
return &response, nil
}
@@ -0,0 +1,83 @@
package secretservice
import (
"context"
"fmt"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
secretmanagerpb "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
)
// Wrappers and abstracting types to facilitate mocking the client responses
type Iterator interface {
Next() (*secretmanagerpb.Secret, error)
}
type SecretsManagerClientWrapper struct {
Closer func() error
SecretLister func(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) Iterator
}
func (w *SecretsManagerClientWrapper) Close() error {
return w.Closer()
}
func (w *SecretsManagerClientWrapper) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) Iterator {
return w.SecretLister(ctx, req, opts...)
}
type SecretsService struct {
Client *SecretsManagerClientWrapper
}
// New function to facilitate using the ss client
func New(client *secretmanager.Client) SecretsService {
ss := SecretsService{
Client: &SecretsManagerClientWrapper{
Closer: client.Close,
SecretLister: func(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) Iterator {
return client.ListSecrets(ctx, req, opts...)
},
},
}
return ss
}
type SecretInfo struct {
Name string `json:"name"`
ProjectID string `json:"projectID"`
CreationTime string `json:"creationTime"`
Labels map[string]string `json:"labels"`
Rotation string `json:"rotation,omitempty"`
}
func (ss *SecretsService) Secrets(projectID string) ([]SecretInfo, error) {
var secrets []SecretInfo
req := &secretmanagerpb.ListSecretsRequest{
Parent: fmt.Sprintf("projects/%s", projectID),
}
ctx := context.Background()
it := ss.Client.ListSecrets(ctx, req)
for {
resp, err := it.Next() //Here it errors out
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("failed to list secrets: %v", err)
}
secrets = append(secrets, SecretInfo{
Name: resp.Name,
ProjectID: projectID,
CreationTime: resp.CreateTime.AsTime().String(),
Labels: resp.Labels,
Rotation: resp.Rotation.String(),
})
}
return secrets, nil
}
@@ -0,0 +1,157 @@
package secretservice_test
import (
"context"
"reflect"
"testing"
"time"
secretmanagerpb "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
secretservice "github.com/BishopFox/cloudfox/gcp/services/secretsService"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
"google.golang.org/protobuf/types/known/timestamppb"
)
type mockSecretManagerClient struct {
secrets []*secretmanagerpb.Secret
}
func (m *mockSecretManagerClient) Close() error {
return nil
}
// SecretIterator simulates the iterator over secrets.
type SecretIterator struct {
secrets []*secretmanagerpb.Secret // Current secrets batch
nextIndex int // Index of the next secret to return
InternalFetch func(pageSize int, pageToken string) (results []*secretmanagerpb.Secret, nextPageToken string, err error)
currentPageToken string
}
func (it *SecretIterator) Next() (*secretmanagerpb.Secret, error) {
// If we have reached the end of the current secrets batch, attempt to fetch the next batch
if it.nextIndex >= len(it.secrets) {
var err error
it.secrets, it.currentPageToken, err = it.InternalFetch(10, it.currentPageToken) // Assuming a fixed page size for simplicity
if err != nil {
return nil, err // Propagate errors from fetch
}
it.nextIndex = 0 // Reset the index for the new batch
// If the fetched batch is empty, we have reached the end of the iteration
if len(it.secrets) == 0 {
return nil, iterator.Done
}
}
// Retrieve the next secret and increment the index
secret := it.secrets[it.nextIndex]
it.nextIndex++
return secret, nil
}
// ListSecrets simulates the ListSecrets method of the SecretManagerClient interface.
func (m *mockSecretManagerClient) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) secretservice.Iterator {
it := &SecretIterator{}
// Copy secrets to avoid modifying the original slice
allSecrets := make([]*secretmanagerpb.Secret, len(m.secrets))
copy(allSecrets, m.secrets)
// Simulate internal fetch by setting InternalFetch to a function that returns the next set of secrets
nextIndex := 0
it.InternalFetch = func(pageSize int, pageToken string) (results []*secretmanagerpb.Secret, nextPageToken string, err error) {
// Check if we have reached the end of the secrets slice
if nextIndex >= len(allSecrets) {
return nil, "", iterator.Done
}
// Determine the slice of secrets to return
endIndex := nextIndex + pageSize
if endIndex > len(allSecrets) {
endIndex = len(allSecrets)
}
results = allSecrets[nextIndex:endIndex]
nextIndex = endIndex
// Simulate the nextPageToken logic (omitted for brevity, always return empty string in this mock)
nextPageToken = ""
return results, nextPageToken, nil
}
return it
}
func TestSecrets(t *testing.T) {
mockClient := &mockSecretManagerClient{}
ss := secretservice.SecretsService{
Client: &secretservice.SecretsManagerClientWrapper{
Closer: mockClient.Close,
SecretLister: func(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) secretservice.Iterator {
return mockClient.ListSecrets(ctx, req, opts...)
},
},
}
tests := []struct {
name string
projectID string
secrets []*secretmanagerpb.Secret
want []secretservice.SecretInfo
wantErr bool
}{
{
name: "Retrieve secrets successfully",
projectID: "my-project",
secrets: []*secretmanagerpb.Secret{
{
Name: "projects/my-project/secrets/secret1",
Labels: map[string]string{"env": "test"},
CreateTime: timestamppb.New(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)),
},
},
want: []secretservice.SecretInfo{
{
Name: "projects/my-project/secrets/secret1",
ProjectID: "my-project",
CreationTime: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).String(),
Labels: map[string]string{"env": "test"},
},
},
wantErr: false,
},
{
name: "No secrets found",
projectID: "empty-project",
secrets: []*secretmanagerpb.Secret{},
want: []secretservice.SecretInfo{},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockClient.secrets = tt.secrets
got, err := ss.Secrets(tt.projectID) // Adapt this call to match the actual method signature
if (err != nil) != tt.wantErr {
t.Errorf("[%s] Secrets() error = %v, wantErr %v", tt.name, err, tt.wantErr)
return
}
if len(got) != len(tt.want) {
t.Errorf("[%s] Secrets() got length = %v, want length %v", tt.name, len(got), len(tt.want))
return
}
for i, g := range got {
w := tt.want[i]
// Compare Name, Labels, and CreationTime as string
if g.Name != w.Name || !reflect.DeepEqual(g.Labels, w.Labels) || g.CreationTime != w.CreationTime {
t.Errorf("Secrets() got = %v, want %v", g, w)
}
}
})
}
}
+17
View File
@@ -0,0 +1,17 @@
package globals
// Module names
// const GCP_WHOAMI_MODULE_NAME = "whoami"
const GCP_ARTIFACT_RESGISTRY_MODULE_NAME string = "artifact-registry"
const GCP_BIGQUERY_MODULE_NAME string = "bigquery"
const GCP_BUCKETS_MODULE_NAME string = "buckets"
const GCP_INSTANCES_MODULE_NAME string = "instances"
const GCP_IAM_MODULE_NAME string = "iam"
const GCP_SECRETS_MODULE_NAME string = "secrets"
const GCP_WHOAMI_MODULE_NAME string = "whoami"
// const GCP_INVENTORY_MODULE_NAME string = "inventory"
// const GCP_GCLOUD_REFRESH_TOKENS_DB_PATH = ".config/gcloud/credentials.db"
// const GCP_GCLOUD_ACCESS_TOKENS_DB_PATH = ".config/gcloud/access_tokens.db"
// const GCP_GCLOUD_DEFAULT_CONFIG_PATH = ".config/gcloud/configurations/config_default"
// const GCP_GCLOUD_APPLICATION_DEFAULT_PATH = ".config/gcloud/application_default_credentials.json"
+1
View File
@@ -4,3 +4,4 @@ const CLOUDFOX_USER_AGENT = "cloudfox"
const CLOUDFOX_LOG_FILE_DIR_NAME = ".cloudfox"
const CLOUDFOX_BASE_DIRECTORY = "cloudfox-output"
const LOOT_DIRECTORY_NAME = "loot"
const CLOUDFOX_VERSION = "1.14.0"
+77 -16
View File
@@ -2,7 +2,15 @@ module github.com/BishopFox/cloudfox
go 1.21.2
toolchain go1.21.6
require (
cloud.google.com/go/artifactregistry v1.14.6
cloud.google.com/go/bigquery v1.57.1
cloud.google.com/go/iam v1.1.5
cloud.google.com/go/resourcemanager v1.9.4
cloud.google.com/go/secretmanager v1.11.4
cloud.google.com/go/storage v1.35.1
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0
@@ -10,16 +18,24 @@ require (
github.com/Azure/go-autorest/autorest v0.11.29
github.com/Azure/go-autorest/autorest/azure/auth v0.5.12
github.com/aquasecurity/table v1.8.0
github.com/aws/aws-sdk-go-v2 v1.24.1
github.com/aws/aws-sdk-go-v2 v1.26.1
github.com/aws/aws-sdk-go-v2/config v1.26.2
github.com/aws/aws-sdk-go-v2/credentials v1.16.13
github.com/aws/aws-sdk-go-v2/service/apigateway v1.21.6
github.com/aws/aws-sdk-go-v2/service/apigatewayv2 v1.18.6
github.com/aws/aws-sdk-go-v2/service/apprunner v1.25.5
github.com/aws/aws-sdk-go-v2/service/athena v1.37.3
github.com/aws/aws-sdk-go-v2/service/cloud9 v1.22.5
github.com/aws/aws-sdk-go-v2/service/cloudformation v1.42.5
github.com/aws/aws-sdk-go-v2/service/cloudfront v1.32.5
github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.35.6
github.com/aws/aws-sdk-go-v2/service/codeartifact v1.23.5
github.com/aws/aws-sdk-go-v2/service/codebuild v1.26.5
github.com/aws/aws-sdk-go-v2/service/codecommit v1.20.0
github.com/aws/aws-sdk-go-v2/service/codedeploy v1.22.2
github.com/aws/aws-sdk-go-v2/service/datapipeline v1.19.5
github.com/aws/aws-sdk-go-v2/service/directoryservice v1.24.4
github.com/aws/aws-sdk-go-v2/service/docdb v1.29.5
github.com/aws/aws-sdk-go-v2/service/dynamodb v1.26.7
github.com/aws/aws-sdk-go-v2/service/ec2 v1.142.0
github.com/aws/aws-sdk-go-v2/service/ecr v1.24.6
@@ -27,12 +43,15 @@ require (
github.com/aws/aws-sdk-go-v2/service/efs v1.26.5
github.com/aws/aws-sdk-go-v2/service/eks v1.37.0
github.com/aws/aws-sdk-go-v2/service/elasticache v1.34.6
github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk v1.20.5
github.com/aws/aws-sdk-go-v2/service/elasticloadbalancing v1.21.6
github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.26.6
github.com/aws/aws-sdk-go-v2/service/emr v1.35.6
github.com/aws/aws-sdk-go-v2/service/fsx v1.40.0
github.com/aws/aws-sdk-go-v2/service/glue v1.73.0
github.com/aws/aws-sdk-go-v2/service/grafana v1.18.5
github.com/aws/aws-sdk-go-v2/service/iam v1.28.5
github.com/aws/aws-sdk-go-v2/service/kinesis v1.24.6
github.com/aws/aws-sdk-go-v2/service/lambda v1.49.6
github.com/aws/aws-sdk-go-v2/service/lightsail v1.32.5
github.com/aws/aws-sdk-go-v2/service/mq v1.20.6
@@ -46,15 +65,18 @@ require (
github.com/aws/aws-sdk-go-v2/service/s3 v1.47.7
github.com/aws/aws-sdk-go-v2/service/sagemaker v1.122.0
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.0
github.com/aws/aws-sdk-go-v2/service/sfn v1.24.6
github.com/aws/aws-sdk-go-v2/service/sns v1.26.6
github.com/aws/aws-sdk-go-v2/service/sqs v1.29.6
github.com/aws/aws-sdk-go-v2/service/ssm v1.44.6
github.com/aws/aws-sdk-go-v2/service/sts v1.26.6
github.com/aws/smithy-go v1.19.0
github.com/aws/smithy-go v1.20.2
github.com/bishopfox/awsservicemap v1.0.3
github.com/bishopfox/knownawsaccountslookup v0.0.0-20231228165844-c37ef8df33cb
github.com/dominikbraun/graph v0.23.0
github.com/fatih/color v1.16.0
github.com/goccy/go-json v0.10.2
github.com/googleapis/gax-go/v2 v2.12.0
github.com/jedib0t/go-pretty v4.3.0+incompatible
github.com/kyokomi/emoji v2.2.4+incompatible
github.com/patrickmn/go-cache v2.1.0+incompatible
@@ -62,14 +84,35 @@ require (
github.com/spf13/afero v1.11.0
github.com/spf13/cobra v1.8.0
golang.org/x/crypto v0.17.0
golang.org/x/exp v0.0.0-20231226003508-02704c960a9b
)
require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
github.com/golang-jwt/jwt/v5 v5.2.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
golang.org/x/sync v0.5.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
golang.org/x/oauth2 v0.15.0
google.golang.org/api v0.152.0
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17
google.golang.org/protobuf v1.33.0
)
require (
cloud.google.com/go v0.110.10 // indirect
cloud.google.com/go/compute v1.23.3 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
cloud.google.com/go/longrunning v0.5.4 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 // indirect
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
@@ -81,51 +124,69 @@ require (
github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 // indirect
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/apache/arrow/go/v12 v12.0.0 // indirect
github.com/apache/thrift v0.16.0 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.4 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.16.13
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.9 // indirect
github.com/aws/aws-sdk-go-v2/service/athena v1.37.3
github.com/aws/aws-sdk-go-v2/service/codeartifact v1.23.5
github.com/aws/aws-sdk-go-v2/service/codecommit v1.20.0
github.com/aws/aws-sdk-go-v2/service/codedeploy v1.22.2
github.com/aws/aws-sdk-go-v2/service/datapipeline v1.19.5
github.com/aws/aws-sdk-go-v2/service/docdb v1.29.5
github.com/aws/aws-sdk-go-v2/service/elasticbeanstalk v1.20.5
github.com/aws/aws-sdk-go-v2/service/emr v1.35.6
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.2.9 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.8.10 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.10 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.16.9 // indirect
github.com/aws/aws-sdk-go-v2/service/kinesis v1.24.6
github.com/aws/aws-sdk-go-v2/service/sfn v1.24.6
github.com/aws/aws-sdk-go-v2/service/sso v1.18.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5 // indirect
github.com/charmbracelet/bubbles v0.18.0
github.com/charmbracelet/bubbletea v0.25.0
github.com/charmbracelet/lipgloss v0.9.1
github.com/dimchansky/utfbom v1.1.1 // indirect
github.com/go-openapi/errors v0.21.0 // indirect
github.com/go-openapi/strfmt v0.21.10 // indirect
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/flatbuffers v2.0.8+incompatible // indirect
github.com/google/s2a-go v0.1.7 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/klauspost/asmfmt v1.3.2 // indirect
github.com/klauspost/compress v1.15.9 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 // indirect
github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/neo4j/neo4j-go-driver/v5 v5.14.0
github.com/oklog/ulid v1.3.1 // indirect
github.com/pierrec/lz4/v4 v4.1.15 // indirect
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/rivo/uniseg v0.4.6 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/zeebo/xxh3 v1.0.2 // indirect
go.mongodb.org/mongo-driver v1.13.1 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/term v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.16.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f // indirect
google.golang.org/grpc v1.59.0 // indirect
)
+226 -16
View File
@@ -1,3 +1,26 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.110.10 h1:LXy9GEO+timppncPIAZoOj3l58LIU9k+kn48AN7IO3Y=
cloud.google.com/go v0.110.10/go.mod h1:v1OoFqYxiBkUrruItNM3eT4lLByNjxmJSV/xDKJNnic=
cloud.google.com/go/artifactregistry v1.14.6 h1:/hQaadYytMdA5zBh+RciIrXZQBWK4vN7EUsrQHG+/t8=
cloud.google.com/go/artifactregistry v1.14.6/go.mod h1:np9LSFotNWHcjnOgh8UVK0RFPCTUGbO0ve3384xyHfE=
cloud.google.com/go/bigquery v1.57.1 h1:FiULdbbzUxWD0Y4ZGPSVCDLvqRSyCIO6zKV7E2nf5uA=
cloud.google.com/go/bigquery v1.57.1/go.mod h1:iYzC0tGVWt1jqSzBHqCr3lrRn0u13E8e+AqowBsDgug=
cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk=
cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI=
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
cloud.google.com/go/datacatalog v1.18.3 h1:zmdxP6nOjN5Qb1rtu9h4kbEVwerQ6Oshf+t747QJUew=
cloud.google.com/go/datacatalog v1.18.3/go.mod h1:5FR6ZIF8RZrtml0VUao22FxhdjkoG+a0866rEnObryM=
cloud.google.com/go/iam v1.1.5 h1:1jTsCu4bcsNsE4iiqNT5SHwrDRCfRmIaaaVFhRveTJI=
cloud.google.com/go/iam v1.1.5/go.mod h1:rB6P/Ic3mykPbFio+vo7403drjlgvoWfYpJhMXEbzv8=
cloud.google.com/go/longrunning v0.5.4 h1:w8xEcbZodnA2BbW6sVirkkoC+1gP8wS57EUUgGS0GVg=
cloud.google.com/go/longrunning v0.5.4/go.mod h1:zqNVncI0BOP8ST6XQD1+VcvuShMmq7+xFSzOL++V0dI=
cloud.google.com/go/resourcemanager v1.9.4 h1:JwZ7Ggle54XQ/FVYSBrMLOQIKoIT/uer8mmNvNLK51k=
cloud.google.com/go/resourcemanager v1.9.4/go.mod h1:N1dhP9RFvo3lUfwtfLWVxfUWq8+KUQ+XLlHLH3BoFJ0=
cloud.google.com/go/secretmanager v1.11.4 h1:krnX9qpG2kR2fJ+u+uNyNo+ACVhplIAS4Pu7u+4gd+k=
cloud.google.com/go/secretmanager v1.11.4/go.mod h1:wreJlbS9Zdq21lMzWmJ0XhWW2ZxgPeahsqeV/vZoJ3w=
cloud.google.com/go/storage v1.35.1 h1:B59ahL//eDfx2IIKFBeT5Atm9wnNmj3+8xG/W4WB//w=
cloud.google.com/go/storage v1.35.1/go.mod h1:M6M/3V/D3KpzMTJyPOR/HU6n2Si5QdaXYEsng2xgOs8=
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU=
github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ=
@@ -45,12 +68,21 @@ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUM
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 h1:hVeq+yCyUi+MsoO/CU95yqCIcdzra5ovzk8Q2BBpV2M=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c h1:RGWPOewvKIROun94nF7v2cua9qP+thov/7M50KEoeSU=
github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/apache/arrow/go/v12 v12.0.0 h1:xtZE63VWl7qLdB0JObIXvvhGjoVNrQ9ciIHG2OK5cmc=
github.com/apache/arrow/go/v12 v12.0.0/go.mod h1:d+tV/eHZZ7Dz7RPrFKtPK02tpr+c9/PEd/zm8mDS9Vg=
github.com/apache/thrift v0.16.0 h1:qEy6UW60iVOlUy+b9ZR0d5WzUWYGOo4HfopoyBaNmoY=
github.com/apache/thrift v0.16.0/go.mod h1:PHK3hniurgQaNMZYaCLEqXKsYK8upmhPbmdP2FXSqgU=
github.com/aquasecurity/table v1.8.0 h1:9ntpSwrUfjrM6/YviArlx/ZBGd6ix8W+MtojQcM7tv0=
github.com/aquasecurity/table v1.8.0/go.mod h1:eqOmvjjB7AhXFgFqpJUEE/ietg7RrMSJZXyTN8E/wZw=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/aws/aws-sdk-go-v2 v1.24.1 h1:xAojnj+ktS95YZlDf0zxWBkbFtymPeDP+rvUQIH3uAU=
github.com/aws/aws-sdk-go-v2 v1.24.1/go.mod h1:LNh45Br1YAkEKaAqvmE1m8FUx6a5b/V0oAKV7of29b4=
github.com/aws/aws-sdk-go-v2 v1.26.1 h1:5554eUqIYVWpU0YmeeYZ0wU64H2VLBs8TlhRB2L+EkA=
github.com/aws/aws-sdk-go-v2 v1.26.1/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.4 h1:OCs21ST2LrepDfD3lwlQiOqIGp6JiEUqG84GzTDoyJs=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.4/go.mod h1:usURWEKSNNAcAZuzRn/9ZYPT8aZQkR7xcCtunK/LkJo=
github.com/aws/aws-sdk-go-v2/config v1.26.2 h1:+RWLEIWQIGgrz2pBPAUoGgNGs1TOyF4Hml7hCnYj2jc=
@@ -59,10 +91,10 @@ github.com/aws/aws-sdk-go-v2/credentials v1.16.13 h1:WLABQ4Cp4vXtXfOWOS3MEZKr6AA
github.com/aws/aws-sdk-go-v2/credentials v1.16.13/go.mod h1:Qg6x82FXwW0sJHzYruxGiuApNo31UEtJvXVSZAXeWiw=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10 h1:w98BT5w+ao1/r5sUuiH6JkVzjowOKeOJRHERyy1vh58=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10/go.mod h1:K2WGI7vUvkIv1HoNbfBA1bvIZ+9kL3YVmWxeKuLQsiw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10 h1:vF+Zgd9s+H4vOXd5BMaPWykta2a6Ih0AKLq/X6NYKn4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10/go.mod h1:6BkRjejp/GR4411UGqkX8+wFMbFbqsUIimfK4XjOKR4=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10 h1:nYPe006ktcqUji8S2mqXf9c/7NdiKriOwMvWQHgYztw=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10/go.mod h1:6UV4SZkVvmODfXKql4LCbaZUpF7HO2BX38FgBf9ZOLw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5 h1:aw39xVGeRWlWx9EzGVnhOR4yOjQDHPQ6o6NmBlscyQg=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5/go.mod h1:FSaRudD0dXiMPK2UjknVwwTYyZMRsHv3TtkabsZih5I=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5 h1:PG1F3OD1szkuQPzDw3CIQsRIrtTlUC3lP84taWzHlq0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5/go.mod h1:jU1li6RFryMz+so64PpKtudI+QzbKoIEivqdf6LNpOc=
github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2 h1:GrSw8s0Gs/5zZ0SX+gX4zQjRnRsMJDJ2sLur1gRBhEM=
github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2/go.mod h1:6fQQgfuGmw8Al/3M2IgIllycxV7ZW7WCdVSqfBeUiCY=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.9 h1:ugD6qzjYtB7zM5PN/ZIeaAIyefPaD82G8+SJopgvUpw=
@@ -93,6 +125,8 @@ github.com/aws/aws-sdk-go-v2/service/codedeploy v1.22.2 h1:3b8fwDhM0bJoOVglvM1w4
github.com/aws/aws-sdk-go-v2/service/codedeploy v1.22.2/go.mod h1:RiusqJl55/p7S8LNMh2J3ZsDHDqxRiPdsfIaZRKeEUo=
github.com/aws/aws-sdk-go-v2/service/datapipeline v1.19.5 h1:zkIKbco/gM4fmbU90ajz4ah3ErgAgot7aTE0PpIxNuE=
github.com/aws/aws-sdk-go-v2/service/datapipeline v1.19.5/go.mod h1:+G+TF84SIgMdGDjZKKYPpx6LwXSN4QcywQGa8e2vJ1U=
github.com/aws/aws-sdk-go-v2/service/directoryservice v1.24.4 h1:XBgx3sdaA0SoPXsZSNSUL14H0UnYnTSVArieaYNv0EI=
github.com/aws/aws-sdk-go-v2/service/directoryservice v1.24.4/go.mod h1:Lm/qj7nCC0zEFoAdjbun8xLkflPFNbbspQVZgQQiOz8=
github.com/aws/aws-sdk-go-v2/service/docdb v1.29.5 h1:txsajy47TIyoL7/BQt0VwqmzLPIsfAT/RWI9iD4q5vU=
github.com/aws/aws-sdk-go-v2/service/docdb v1.29.5/go.mod h1:8d1RpdlgxFU6VO2aWru1ckR0Vsm4EgqCZgOamw5OHpw=
github.com/aws/aws-sdk-go-v2/service/dynamodb v1.26.7 h1:X60rMbnylU1xmmhv4+/N78t+lKOCC4ELst5eR25dyqg=
@@ -177,12 +211,25 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5 h1:2k9KmFawS63euAkY4/ixVNsY
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5/go.mod h1:W+nd4wWDVkSUIox9bacmkBP5NMFQeTJ/xqNabpzSR38=
github.com/aws/aws-sdk-go-v2/service/sts v1.26.6 h1:HJeiuZ2fldpd0WqngyMR6KW7ofkXNLyOaHwEIGm39Cs=
github.com/aws/aws-sdk-go-v2/service/sts v1.26.6/go.mod h1:XX5gh4CB7wAs4KhcF46G6C8a2i7eupU19dcAAE+EydU=
github.com/aws/smithy-go v1.19.0 h1:KWFKQV80DpP3vJrrA9sVAHQ5gc2z8i4EzrLhLlWXcBM=
github.com/aws/smithy-go v1.19.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE=
github.com/aws/smithy-go v1.20.2 h1:tbp628ireGtzcHDDmLT/6ADHidqnwgF57XOXZe6tp4Q=
github.com/aws/smithy-go v1.20.2/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/bishopfox/awsservicemap v1.0.3 h1:0T+mJLwG+vQV9+o3dzwzxhWJWE40VpoCLWtaPBwixYc=
github.com/bishopfox/awsservicemap v1.0.3/go.mod h1:oy9Fyqh6AozQjShSx+zRNouTlp7k3z3YEMoFkN8rquc=
github.com/bishopfox/knownawsaccountslookup v0.0.0-20231228165844-c37ef8df33cb h1:ot96tC/kdm0GKV1kl+aXJorqJbyx92R9bjRQvbBmLKU=
github.com/bishopfox/knownawsaccountslookup v0.0.0-20231228165844-c37ef8df33cb/go.mod h1:2OnSqu4B86+2xGSIE5D4z3Rze9yJ/LNNjNXHhwMR+vY=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/charmbracelet/bubbles v0.18.0 h1:PYv1A036luoBGroX6VWjQIE9Syf2Wby2oOl/39KLfy0=
github.com/charmbracelet/bubbles v0.18.0/go.mod h1:08qhZhtIwzgrtBjAcJnij1t1H0ZRjwHyGsy6AL11PSw=
github.com/charmbracelet/bubbletea v0.25.0 h1:bAfwk7jRz7FKFl9RzlIULPkStffg5k6pNt5dywy4TcM=
github.com/charmbracelet/bubbletea v0.25.0/go.mod h1:EN3QDR1T5ZdWmdfDzYcqOCAps45+QIJbLOBxmVNWNNg=
github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg=
github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -193,24 +240,69 @@ github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
github.com/dominikbraun/graph v0.23.0 h1:TdZB4pPqCLFxYhdyMFb1TBdFxp8XLcJfTTBQucVPgCo=
github.com/dominikbraun/graph v0.23.0/go.mod h1:yOjYyogZLY1LSG9E33JWZJiq5k83Qy2C6POAuiViluc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/go-openapi/errors v0.21.0 h1:FhChC/duCnfoLj1gZ0BgaBmzhJC2SL/sJr8a2vAobSY=
github.com/go-openapi/errors v0.21.0/go.mod h1:jxNTMUxRCKj65yb/okJGEtahVd7uvWnuWfj53bse4ho=
github.com/go-openapi/strfmt v0.21.10 h1:JIsly3KXZB/Qf4UzvzJpg4OELH/0ASDQsyk//TTBDDk=
github.com/go-openapi/strfmt v0.21.10/go.mod h1:vNDMwbilnl7xKiO/Ve/8H8Bb2JIInBnH+lqiw6QWgis=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw=
github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/flatbuffers v2.0.8+incompatible h1:ivUb1cGomAB101ZM1T0nOiWz9pSrTMoa9+EiY7igmkM=
github.com/google/flatbuffers v2.0.8+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw=
github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas=
github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jedib0t/go-pretty v4.3.0+incompatible h1:CGs8AVhEKg/n9YbUenWmNStRW2PHJzaeDodcfvRAbIo=
@@ -219,38 +311,69 @@ github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9Y
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4=
github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/kyokomi/emoji v2.2.4+incompatible h1:np0woGKwx9LiHAQmwZx79Oc0rHpNw3o+3evou4BEPv4=
github.com/kyokomi/emoji v2.2.4+incompatible/go.mod h1:mZ6aGCD7yk8j6QY6KICwnZ2pxoszVseX1DNoGtU2tBA=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs=
github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY=
github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 h1:+n/aFZefKZp7spd8DFdX7uMikMLXX4oubIzJF4kv/wI=
github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/neo4j/neo4j-go-driver/v5 v5.14.0 h1:5x3vD4HkXQIktlG63jSG8v9iweGjmObIPU7Y9U0ThUI=
github.com/neo4j/neo4j-go-driver/v5 v5.14.0/go.mod h1:Vff8OwT7QpLm7L2yYr85XNWe9Rbqlbeb9asNXJTHO4k=
github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0=
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.6 h1:Sovz9sDSwbOz9tgUy8JpT+KgCkPYJEN/oYzlJiYTNLg=
github.com/rivo/uniseg v0.4.6/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
@@ -267,6 +390,7 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
@@ -275,9 +399,17 @@ github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3k
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.mongodb.org/mongo-driver v1.13.1 h1:YIc7HTYsKndGK4RFzJ3covLz1byri52x0IoMB0Pt/vk=
go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
@@ -285,17 +417,43 @@ golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20231226003508-02704c960a9b h1:kLiC65FbiHWFAOu+lxwNPujcsl8VYyTYYEZnsOO1WK4=
golang.org/x/exp v0.0.0-20231226003508-02704c960a9b/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.15.0 h1:s8pnnxNVzjWyrvYdFUQq5llS1PX2zhPXmccZv99h7uQ=
golang.org/x/oauth2 v0.15.0/go.mod h1:q48ptWNTY5XWf+JNten23lcvHpLJ0ZSxF5ttTHKVCAM=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -304,6 +462,7 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
@@ -314,6 +473,7 @@ golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
@@ -321,17 +481,67 @@ golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.16.0 h1:GO788SKMRunPIBCXiQyo2AaexLstOrVhuAL5YwsckQM=
golang.org/x/tools v0.16.0/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
gonum.org/v1/gonum v0.11.0 h1:f1IJhK4Km5tBJmaiJXtk/PkL4cdVX6J+tGiM187uT5E=
gonum.org/v1/gonum v0.11.0/go.mod h1:fSG4YDCxxUZQJ7rKsQrj0gMOg00Il0Z96/qMA4bVQhA=
google.golang.org/api v0.152.0 h1:t0r1vPnfMc260S2Ci+en7kfCZaLOPs5KI0sVV/6jZrY=
google.golang.org/api v0.152.0/go.mod h1:3qNJX5eOmhiWYc67jRA/3GsDw97UFb5ivv7Y2PrriAY=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 h1:wpZ8pe2x1Q3f2KyT5f8oP/fa9rHAKgFPr/HZdNuS+PQ=
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:J7XzRzVy1+IPwWHZUzoD0IccYZIrXILAQpc+Qy9CMhY=
google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17 h1:JpwMPBpFN3uKhdaekDpiNlImDdkUAyiJ6ez/uxGaUSo=
google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:0xJLfVdJqpAPl8tDg1ujOCGzx6LFLttXT5NhllGOXY4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f h1:ultW7fxlIvee4HYrtnaRPon9HpEgFk5zYpmfMgtKB5I=
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f/go.mod h1:L9KNLi232K1/xB6f7AlSX692koaRnKaWSR0stBki0Yc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=
google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+109 -35
View File
@@ -3,8 +3,11 @@ package internal
import (
"bufio"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
@@ -18,6 +21,7 @@ import (
"github.com/aws/smithy-go/ptr"
"github.com/bishopfox/awsservicemap"
"github.com/kyokomi/emoji"
"github.com/patrickmn/go-cache"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
)
@@ -30,11 +34,95 @@ var (
ConfigMap = map[string]aws.Config{}
)
type CloudFoxRunData struct {
Profile string
AccountID string
OutputLocation string
}
func init() {
gob.Register(aws.Config{})
gob.Register(sts.GetCallerIdentityOutput{})
gob.Register(CloudFoxRunData{})
}
func InitializeCloudFoxRunData(AWSProfile string, version string, AwsMfaToken string, AWSOutputDirectory string) (CloudFoxRunData, error) {
var runData CloudFoxRunData
cacheDirectory := filepath.Join(AWSOutputDirectory, "cached-data", "aws")
filename := filepath.Join(cacheDirectory, fmt.Sprintf("CloudFoxRunData-%s.json", AWSProfile))
if _, err := os.Stat(filename); err == nil {
// unmarshall the data from the file into type CloudFoxRunData
// Open the file (this is not actually needed if you use os.ReadFile, so you can skip this)
file, err := os.Open(filename)
if err != nil {
return CloudFoxRunData{}, err
}
defer file.Close()
// Read the file content
jsonData, err := os.ReadFile(filename)
if err != nil {
return CloudFoxRunData{}, err
}
// Unmarshal jsonData into runData (make sure to pass a pointer to runData)
err = json.Unmarshal(jsonData, &runData)
if err != nil {
return CloudFoxRunData{}, err
}
return runData, nil
}
CallerIdentity, err := AWSWhoami(AWSProfile, version, AwsMfaToken)
if err != nil {
return CloudFoxRunData{}, err
}
outputLocation := filepath.Join(AWSOutputDirectory, "cloudfox-output", "aws", fmt.Sprintf("%s-%s", AWSProfile, ptr.ToString(CallerIdentity.Account)))
runData = CloudFoxRunData{
Profile: AWSProfile,
AccountID: aws.ToString(CallerIdentity.Account),
OutputLocation: outputLocation,
}
// Marshall the data to a file
err = os.MkdirAll(cacheDirectory, 0755)
if err != nil {
return CloudFoxRunData{}, err
}
file, err := os.Create(filename)
if err != nil {
return CloudFoxRunData{}, err
}
defer file.Close()
jsonData, err := json.Marshal(runData)
if err != nil {
return CloudFoxRunData{}, err
}
_, err = file.Write(jsonData)
if err != nil {
return CloudFoxRunData{}, err
}
return runData, nil
}
func AWSConfigFileLoader(AWSProfile string, version string, AwsMfaToken string) aws.Config {
// Loads the AWS config file and returns a config object
var cfg aws.Config
var err error
// cacheKey := fmt.Sprintf("AWSConfigFileLoader-%s", AWSProfile)
// cached, found := Cache.Get(cacheKey)
// if found {
// cfg = cached.(aws.Config)
// return cfg
// }
// Check if the profile is already in the config map. If not, load it and retrieve the credentials. If it is, return the cached config object
// The AssumeRoleOptions below are used to pass the MFA token to the AssumeRole call (when applicable)
if _, ok := ConfigMap[AWSProfile]; !ok {
@@ -81,6 +169,7 @@ func AWSConfigFileLoader(AWSProfile string, version string, AwsMfaToken string)
// update the config map with the new config for future lookups
ConfigMap[AWSProfile] = cfg
//return the config object for this first iteration
//Cache.Set(cacheKey, cfg, cache.DefaultExpiration)
return cfg
}
@@ -89,10 +178,21 @@ func AWSConfigFileLoader(AWSProfile string, version string, AwsMfaToken string)
cfg = ConfigMap[AWSProfile]
return cfg
}
//Cache.Set(cacheKey, cfg, cache.DefaultExpiration)
return cfg
}
func AWSWhoami(awsProfile string, version string, AwsMfaToken string) (*sts.GetCallerIdentityOutput, error) {
cacheKey := fmt.Sprintf("sts-getCallerIdentity-%s", awsProfile)
if cached, found := Cache.Get(cacheKey); found {
// Correct type assertion: assert the type, not a variable.
if cachedValue, ok := cached.(*sts.GetCallerIdentityOutput); ok {
return cachedValue, nil
}
// Handle the case where type assertion fails, if necessary.
}
// Connects to STS and checks caller identity. Same as running "aws sts get-caller-identity"
//fmt.Printf("[%s] Retrieving caller's identity\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)))
STSService := sts.NewFromConfig(AWSConfigFileLoader(awsProfile, version, AwsMfaToken))
@@ -103,10 +203,18 @@ func AWSWhoami(awsProfile string, version string, AwsMfaToken string) (*sts.GetC
return CallerIdentity, err
}
// Convert CallerIdentity to something i can store using the cache
Cache.Set(cacheKey, CallerIdentity, cache.DefaultExpiration)
return CallerIdentity, err
}
func GetEnabledRegions(awsProfile string, version string, AwsMfaToken string) []string {
cacheKey := fmt.Sprintf("GetEnabledRegions-%s", awsProfile)
cached, found := Cache.Get(cacheKey)
if found {
return cached.([]string)
}
var enabledRegions []string
ec2Client := ec2.NewFromConfig(ConfigMap[awsProfile])
regions, err := ec2Client.DescribeRegions(
@@ -130,45 +238,11 @@ func GetEnabledRegions(awsProfile string, version string, AwsMfaToken string) []
for _, region := range regions.Regions {
enabledRegions = append(enabledRegions, *region.RegionName)
}
Cache.Set(cacheKey, enabledRegions, cache.DefaultExpiration)
return enabledRegions
}
// func GetRegionsForService(awsProfile string, service string) []string {
// SSMClient := ssm.NewFromConfig(AWSConfigFileLoader(awsProfile))
// var PaginationControl *string
// var supportedRegions []string
// path := fmt.Sprintf("/aws/service/global-infrastructure/services/%s/regions", service)
// ServiceRegions, err := SSMClient.GetParametersByPath(
// context.TODO(),
// &(ssm.GetParametersByPathInput{
// NextToken: PaginationControl,
// Path: &path,
// }),
// )
// if err != nil {
// fmt.Println(err.Error())
// }
// if ServiceRegions.Parameters != nil {
// for _, region := range ServiceRegions.Parameters {
// name := *region.Value
// supportedRegions = append(supportedRegions, name)
// }
// // The "NextToken" value is nil when there's no more data to return.
// if ServiceRegions.NextToken != nil {
// PaginationControl = ServiceRegions.NextToken
// } else {
// PaginationControl = nil
// }
// }
// return supportedRegions
// }
// txtLogger - Returns the txt logger
func TxtLogger() *logrus.Logger {
var txtFile *os.File
+87
View File
@@ -3,6 +3,8 @@ package policy
import (
"encoding/json"
"fmt"
"regexp"
"strings"
)
type Policy struct {
@@ -79,3 +81,88 @@ func contains(list []string, elem string) bool {
return false
}
// source: https://github.com/nccgroup/PMapper/blob/master/principalmapper/querying/local_policy_simulation.py
func composePattern(stringToTransform string) *regexp.Regexp {
// Escape special characters and replace wildcards
escaped := strings.ReplaceAll(stringToTransform, ".", "\\.")
escaped = strings.ReplaceAll(escaped, "*", ".*")
escaped = strings.ReplaceAll(escaped, "?", ".")
escaped = strings.ReplaceAll(escaped, "$", "\\$")
escaped = strings.ReplaceAll(escaped, "^", "\\^")
// Compile the regular expression, ignoring case
pattern, err := regexp.Compile("(?i)^" + escaped + "$")
if err != nil {
panic("regexp compile error: " + err.Error())
}
return pattern
}
// source: https://github.com/nccgroup/PMapper/blob/master/principalmapper/querying/local_policy_simulation.py
// MatchesAfterExpansion checks the stringToCheck against stringToCheckAgainst.
func MatchesAfterExpansion(stringFromPolicyToCheck, stringToCheckAgainst string) bool {
// Transform the stringToCheckAgainst into a regex pattern
pattern := composePattern(stringToCheckAgainst)
// Check if the pattern matches stringToCheck
return pattern.MatchString(stringFromPolicyToCheck)
}
func (p *Policy) DoesPolicyHaveMatchingStatement(effect string, actionToCheck string, resourceToCheck string) bool {
for _, statement := range p.Statement {
if statement.Effect == effect {
matchesAction, matchesResource := false, false
for _, action := range statement.Action {
if MatchesAfterExpansion(actionToCheck, action) {
matchesAction = true
if resourceToCheck != "" {
for _, resource := range statement.Resource {
if MatchesAfterExpansion(resourceToCheck, resource) {
matchesResource = true
}
}
for _, notResource := range statement.NotResource {
if MatchesAfterExpansion(resourceToCheck, notResource) {
matchesResource = false
}
}
}
}
}
for _, notAction := range statement.NotAction {
matchesAction = true
if notAction == "*" {
matchesAction = false
}
if notAction == actionToCheck {
matchesAction = false
}
if MatchesAfterExpansion(actionToCheck, notAction) {
matchesAction = false
}
if resourceToCheck != "" {
for _, resource := range statement.Resource {
if MatchesAfterExpansion(resourceToCheck, resource) {
matchesResource = true
}
}
for _, notResource := range statement.NotResource {
if MatchesAfterExpansion(resourceToCheck, notResource) {
matchesResource = false
}
}
}
}
if matchesAction && matchesResource {
return true
}
}
}
return false
}
+72
View File
@@ -150,3 +150,75 @@ func getTestFixure(filename string) (*Policy, error) {
return &policy, nil
}
func TestDoesPolicyHaveMatchingStatement(t *testing.T) {
p := &Policy{
Statement: []PolicyStatement{
{
Effect: "Allow",
Action: []string{"ec2:*"},
Resource: []string{"*"},
},
{
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::bucket/*"},
},
{
Effect: "Deny",
Action: []string{"s3:*"},
Resource: []string{"arn:aws:s3:::bucket2/*"},
},
},
}
tests := []struct {
effect string
actionToCheck string
resourceToCheck string
want bool
}{
{
effect: "Allow",
actionToCheck: "ec2:DescribeInstances",
resourceToCheck: "arn:aws:ec2:us-west-2:123456789012:instance/*",
want: true,
},
{
effect: "Allow",
actionToCheck: "s3:GetObject",
resourceToCheck: "arn:aws:s3:::bucket/file.txt",
want: true,
},
{
effect: "Allow",
actionToCheck: "s3:PutObject",
resourceToCheck: "arn:aws:s3:::bucket/file.txt",
want: false,
},
{
effect: "Deny",
actionToCheck: "s3:GetObject",
resourceToCheck: "arn:aws:s3:::bucket2/file.txt",
want: true,
},
{
effect: "Deny",
actionToCheck: "s3:PutObject",
resourceToCheck: "arn:aws:s3:::bucket2/file.txt",
want: true,
},
{
effect: "Deny",
actionToCheck: "s3:GetObject",
resourceToCheck: "arn:aws:s3:::bucket/file.txt",
want: false,
},
}
for _, tt := range tests {
actual := p.DoesPolicyHaveMatchingStatement(tt.effect, tt.actionToCheck, tt.resourceToCheck)
if tt.want != actual {
t.Errorf("DoesPolicyHaveMatchingStatement(%s, %s, %s) is %v but should be %v", tt.effect, tt.actionToCheck, tt.resourceToCheck, actual, tt.want)
}
}
}
+8 -7
View File
@@ -6,13 +6,14 @@ import (
)
type PolicyStatement struct {
Sid string `json:"Sid,omitempty"`
Effect string `json:"Effect"`
Principal PolicyStatementPrincipal `json:"Principal,omitempty"`
Action ListOrString `json:"Action"`
NotAction ListOrString `json:"NotAction,omitempty"`
Resource ListOrString `json:"Resource,omitempty"`
Condition PolicyStatementCondition `json:"Condition,omitempty"`
Sid string `json:"Sid,omitempty"`
Effect string `json:"Effect"`
Principal PolicyStatementPrincipal `json:"Principal,omitempty"`
Action ListOrString `json:"Action"`
NotAction ListOrString `json:"NotAction,omitempty"`
Resource ListOrString `json:"Resource,omitempty"`
NotResource ListOrString `json:"NotResource,omitempty"`
Condition PolicyStatementCondition `json:"Condition,omitempty"`
}
func (ps *PolicyStatement) IsEmpty() bool {
+33 -1
View File
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/dominikbraun/graph"
"github.com/patrickmn/go-cache"
)
@@ -23,7 +24,6 @@ func SaveCacheToFiles(directory string, accountID string) error {
}
for key, item := range Cache.Items() {
// only if the key contains the accountID
if accountID != "" && strings.Contains(key, accountID) {
entry := cacheEntry{
Value: item.Object,
@@ -41,6 +41,7 @@ func SaveCacheToFiles(directory string, accountID string) error {
return err
}
}
}
return nil
}
@@ -89,6 +90,12 @@ type cacheEntry struct {
Exp int64
}
type CacheableAWSConfig struct {
Region string
//Credentials aws.CredentialsProvider
//ConfigSources []interface{}
}
func SaveCacheToGobFiles(directory string, accountID string) error {
err := os.MkdirAll(directory, 0755)
if err != nil {
@@ -96,6 +103,7 @@ func SaveCacheToGobFiles(directory string, accountID string) error {
}
for key, item := range Cache.Items() {
// only if the key contains the accountID
if accountID != "" && strings.Contains(key, accountID) {
entry := cacheEntry{
@@ -116,6 +124,7 @@ func SaveCacheToGobFiles(directory string, accountID string) error {
sharedLogger.Errorf("Could not encode the following key: %s", key)
return err
}
// }
}
}
return nil
@@ -171,3 +180,26 @@ func LoadCacheFromGobFiles(directory string) error {
//fmt.Println("Cache loaded from files.")
return nil
}
func SaveGraphToGob[K comparable, T any](directory string, name string, g *graph.Graph[K, T]) error {
err := os.MkdirAll(directory, 0755)
if err != nil {
return err
}
filename := filepath.Join(directory, name+".gob")
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(g)
if err != nil {
sharedLogger.Errorf("Could not encode the following graph: %s", name)
return err
}
return nil
}
+17
View File
@@ -0,0 +1,17 @@
package common
type PermissionsRow struct {
AWSService string
Type string
Name string
Arn string
PolicyType string
PolicyName string
PolicyArn string
Effect string
Action string
Resource string
Condition string
}
var PermissionRowsFromAllProfiles []PermissionsRow
+55
View File
@@ -1,6 +1,7 @@
package internal
import (
"fmt"
"log"
"os"
"os/user"
@@ -8,7 +9,10 @@ import (
"github.com/BishopFox/cloudfox/globals"
"github.com/aws/smithy-go/ptr"
"github.com/fatih/color"
"github.com/jedib0t/go-pretty/text"
"github.com/kyokomi/emoji"
"github.com/sirupsen/logrus"
)
func init() {
@@ -30,3 +34,54 @@ func GetLogDirPath() *string {
}
return ptr.String(dir)
}
type Logger struct {
version string
txtLog *logrus.Logger
}
func NewLogger() Logger {
var logger = Logger{
version: globals.CLOUDFOX_VERSION,
txtLog: TxtLog,
}
return logger
}
func (l *Logger) Info(text string) {
l.InfoM(text, "config")
}
func (l *Logger) InfoM(text string, module string) {
var cyan = color.New(color.FgCyan).SprintFunc()
fmt.Printf("[%s][%s] %s\n", cyan(emoji.Sprintf(":fox:cloudfox %s :fox:", l.version)), cyan(module), text)
}
func (l *Logger) Success(text string) {
l.SuccessM(text, "config")
}
func (l *Logger) SuccessM(text string, module string) {
var green = color.New(color.FgGreen).SprintFunc()
fmt.Printf("[%s][%s] %s\n", green(emoji.Sprintf(":fox:cloudfox %s :fox:", l.version)), green(module), text)
}
func (l *Logger) Error(text string) {
l.ErrorM(text, "config")
}
func (l *Logger) ErrorM(text string, module string) {
var red = color.New(color.FgRed).SprintFunc()
fmt.Printf("[%s][%s] %s\n", red(emoji.Sprintf(":fox:cloudfox %s :fox:", l.version)), red(module), text)
l.txtLog.Printf("[%s] %s", module, text)
}
func (l *Logger) Fatal(text string) {
l.FatalM(text, "config")
}
func (l *Logger) FatalM(text string, module string) {
var red = color.New(color.FgRed).SprintFunc()
l.txtLog.Printf("[%s] %s", module, text)
fmt.Printf("[%s][%s] %s\n", red(emoji.Sprintf(":fox:cloudfox %s :fox:", l.version)), red(module), text)
os.Exit(1)
}
+60 -2
View File
@@ -7,6 +7,7 @@ import (
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
@@ -59,6 +60,49 @@ type LootFile struct {
Contents string
}
// TODO support datastructures that enable brief or wide format
type CloudfoxOutput interface {
TableFiles() []TableFile
LootFiles() []LootFile
}
// HandleOutput dynamically handles the output based on the provided arguments.
// TODO support brief of wide
func HandleOutput(
cloudProvider string,
format string,
outputDirectory string,
verbosity int,
wrap bool,
baseCloudfoxModule string,
principal string,
resultsIdentifier string,
dataToOutput CloudfoxOutput,
) error {
// Update OutputClient fields based on arguments
outDirectoryPath := filepath.Join(outputDirectory, "cloudfox-output", cloudProvider, fmt.Sprintf("%s-%s", principal, resultsIdentifier), baseCloudfoxModule)
tables := dataToOutput.TableFiles()
lootFiles := dataToOutput.LootFiles()
outputClient := OutputClient{
Verbosity: verbosity,
CallingModule: baseCloudfoxModule,
Table: TableClient{
Wrap: wrap,
DirectoryName: outDirectoryPath,
TableFiles: tables,
},
Loot: LootClient{
DirectoryName: outDirectoryPath,
LootFiles: lootFiles,
},
}
// Handle output based on the verbosity level
outputClient.WriteFullOutput(tables, lootFiles)
return nil
}
func removeColorCodes(input string) string {
// Regular expression to match ANSI color codes
ansiRegExp := regexp.MustCompile(`\x1b\[[0-9;]*m`)
@@ -97,7 +141,7 @@ func removeColorCodesFromNestedSlice(input [][]string) [][]string {
}
func (o *OutputClient) WriteFullOutput(tables []TableFile, lootFiles []LootFile) {
logger := NewLogger()
switch o.Verbosity {
case 2:
o.Table.printTablesToScreen(tables)
@@ -127,7 +171,8 @@ func (o *OutputClient) WriteFullOutput(tables []TableFile, lootFiles []LootFile)
}
for _, path := range outputPaths {
fmt.Printf("[%s][%s] Output written to %s\n", cyan(o.CallingModule), cyan(o.PrefixIdentifier), path)
logger.InfoM(fmt.Sprintf("Output written to %s", path), o.CallingModule)
// fmt.Printf("[%s][%s] Output written to %s\n", cyan(o.CallingModule), cyan(o.PrefixIdentifier), path)
}
}
@@ -174,6 +219,7 @@ func (l *LootClient) writeLootFiles() []string {
contents := []byte(file.Contents)
fullPath := path.Join(l.DirectoryName, "loot", file.Name)
err := afero.WriteFile(fileSystem, fullPath, contents, 0644) // Use Afero's WriteFile
//err := os.WriteFile(fullPath, contents, 0644)
if err != nil {
log.Fatalf("error writing loot file %s: %s", file.Name, err)
}
@@ -461,3 +507,15 @@ func adjustBodyForTable(tableHeaders []string, fullHeaders []string, fullBody []
return adjustedBody, selectedHeaders
}
func WriteJsonlFile(file *os.File, data interface{}) error {
bytes, err := json.Marshal(data)
if err != nil {
return err
}
if _, err := file.Write(append(bytes, "\n"...)); err != nil {
return err
}
return nil
}
+3 -2
View File
@@ -4,17 +4,18 @@ import (
"os"
"github.com/BishopFox/cloudfox/cli"
"github.com/BishopFox/cloudfox/globals"
"github.com/spf13/cobra"
)
var (
rootCmd = &cobra.Command{
Use: os.Args[0],
Version: "1.14.0-prerelease",
Version: globals.CLOUDFOX_VERSION,
}
)
func main() {
rootCmd.AddCommand(cli.AWSCommands, cli.AzCommands)
rootCmd.AddCommand(cli.AWSCommands, cli.AzCommands, cli.GCPCommands)
rootCmd.Execute()
}