Compare commits

..
29 Commits
Author SHA1 Message Date
sethsec-bf 118ed625d6 fixed bug in lambda loot where it was missing a parameter 2022-10-19 16:16:49 -04:00
carlosvendramini-bf 530dcbdb67 Merge pull request #15 from BishopFox/seth-dev
v1.8.0 to main
2022-10-19 10:46:56 -04:00
sethsec-bf 79eb720e72 updated readme 2022-10-19 10:09:18 -04:00
sethsec-bf c3dac71f1d updated version to 1.8.0 in main.go 2022-10-19 10:05:40 -04:00
sethsec-bf ecdd33c522 removed public col from lambda -- not ready yet 2022-10-19 10:01:03 -04:00
Seth Art 1c243c73dc Update README.md 2022-10-19 09:46:47 -04:00
sethsec-bf ca7df5a039 update image in readme 2022-10-19 09:16:34 -04:00
sethsec-bf 8850384fc0 pre 1..8.0 release cleanup 2022-10-19 09:12:13 -04:00
sethsec-bf 775c233858 updated cloudfox permissions policy 2022-10-18 14:03:15 -04:00
sethsec-bf 9fc38f5e64 alphabetize module names and client order 2022-10-18 13:46:09 -04:00
sethsec-bf d20b2b1099 remove debug test 2022-10-18 13:45:31 -04:00
sethsec-bf eb95e887de finally got ram command working 2022-10-17 20:34:59 -04:00
sethsec-bf 064f285652 cleaned up instances table 2022-10-17 07:58:14 -04:00
sethsec-bf 3e0718636f got admin check working on instances 2022-10-16 22:42:21 -04:00
sethsec-bf f672c34806 updated lambda admin lookup map to that we can check local map to see if we know if the role is an admin already 2022-10-16 13:46:23 -04:00
sethsec-bf 6ace00021b fixed panic in all profiles mode when either credentials or config do not exist. 2022-10-13 22:46:01 -04:00
sethsec-bf 5183b32d75 fixed panic when file with list of profiles is not present 2022-10-13 22:33:59 -04:00
sethsec-bf ffa8e09fbe added profile name to stdout messages 2022-10-13 22:15:13 -04:00
Seth Art 26562574c3 Update README.md 2022-10-12 17:21:51 -04:00
sethsec-bf 2e82cc895d updated readme 2022-10-12 17:16:15 -04:00
sethsec-bf dadef384c0 updated lambda to include isAdmin check, fixed some bugs wtih all profiles, updated logrus so it could support one method calling another 2022-10-12 15:41:17 -04:00
sethsec-bf 40d7a3c2d0 added loot to lambda command, added unique resource total for tags command, bumped version to 1.8.0 2022-10-07 21:13:04 -04:00
sethsec-bf 8ce9a00697 fixed bug in outbound-assumed-roles - missing add to wg counter 2022-10-07 10:47:57 -04:00
sethsec-bf 7d8ebc27c7 first draft of lambda commandd 2022-10-06 23:19:20 -04:00
sethsec-bf 45e548cf0b cleaned up tags command a bit 2022-10-06 23:18:54 -04:00
sethsec-bf 9498d2db13 first draft of a tags command 2022-10-06 11:18:32 -04:00
sethsec-bf 71e85c29d2 merged pr #8 into this branch and added the new for loop logic to cloudformation command 2022-10-05 15:30:57 -04:00
sethsec-bf 5525266855 Merge remote-tracking branch 'origin/main' into seth-dev 2022-10-05 14:28:59 -04:00
sethsec-bf 7c8afb6fef added cloudformation command 2022-09-25 13:52:11 -04:00
28 changed files with 1789 additions and 580 deletions

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 434 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

+20 -5
View File
@@ -4,21 +4,32 @@ CloudFox helps you gain situational awareness in unfamiliar cloud environments.
#### CloudFox helps you answer the following common questions (and many more):
* What regions is this AWS account using and roughly how many resources are in the account?
* What secrets are lurking in EC2 userdata or service specific environment variables?
* What secrets are lurking in EC2 userdata or service specific environment variables?
* What workloads have administrative permissions attached?
* What actions/permissions does this [principal] have?
* What roles trusts are overly permissive or allow cross-account assumption?
* What role trusts are overly permissive or allow cross-account assumption?
* What endpoints/hostnames/IPs can I attack from an external starting point (public internet)?
* What endpoints/hostnames/IPs can I attack from an internal starting point (assumed breach within the VPC)?
* What filesystems can I potentially mount from a compromised resource inside the VPC?
## Demos, Examples, Walkthroughs
* [Blog - Introducing: CloudFox](https://bishopfox.com/blog/introducing-cloudfox)
* [Video - CloudFox Intro Demo's](https://www.youtube.com/watch?v=ReWoUgpUuiQ)
* [Video - Tool Talk: CloudFox AWS sub-command walkthroughs](https://youtu.be/KKsYfL5uVU4?t=360)
## Quick Start
CloudFox is modular (you can run one command at a time), but there is an aws `all-checks` command that will run the other aws commands for you with sane defaults:
`cloudfox aws --profile [profile-name] all-checks`
![](/.github/images/cloudfox-output.png)
![](/.github/images/cloudfox-output-p1.png)
![](/.github/images/cloudfox-output-p2.png)
CloudFox is designed to be executed by a principal with limited read-only permissions, but it's purpose is to help you find attack paths that can be exploited in simulated compromise scenarios (aka, objective based penetration testing).
### White Box Enumeration
CloudFox was designed to be executed by a principal with limited read-only permissions, but it's purpose is to help you find attack paths that can be exploited in simulated compromise scenarios (aka, objective based penetration testing).
### Black Box Enumeration
CloudFox can be with "found" credentials, similar to how you would use [weirdAAL](https://github.com/carnal0wnage/weirdAAL) or [enumerate-iam](https://github.com/andresriancho/enumerate-iam). Checks that fail, do so silently, so any data returned means your "found" creds have the access needed to retrieve it.
For the full documentation please refer to our [wiki](https://github.com/BishopFox/CloudFox/wiki).
@@ -27,7 +38,7 @@ For the full documentation please refer to our [wiki](https://github.com/BishopF
| Provider| CloudFox Commands |
| - | - |
| AWS | 15 |
| AWS | 19 |
| Azure | 2 (alpha) |
| GCP | Support Planned |
| Kubernetes | Support Planned |
@@ -75,6 +86,7 @@ Additional policy notes (as of 09/2022):
| AWS | [all-checks](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#all-checks) | Run all of the other commands using reasonable defaults. You'll still want to check out the non-default options of each command, but this is a great place to start. |
| 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 | [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 | [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 | [ecr](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#ecr) | List the most recently pushed image URI from all repositories. Use the loot file to pull selected images down with docker/nerdctl for inspection. |
| AWS | [endpoints](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#endpoints) | Enumerates endpoints from various services. Scan these endpoints from both an internal and external position to look for things that don't require authentication, are misconfigured, etc. |
| AWS | [env-vars](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#env-vars) | Grabs the environment variables from services that have them (App Runner, ECS, Lambda, Lightsail containers, Sagemaker are supported. If you find a sensitive secret, use `cloudfox iam-simulator` AND `pmapper` to see who has access to them. |
@@ -82,12 +94,15 @@ Additional policy notes (as of 09/2022):
| AWS | [iam-simulator](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#iam-simulator) | Like pmapper, but uses the IAM policy simulator. It uses AWS's evaluation logic, but notably, it doesn't consider transitive access via privesc, which is why you should also always also use pmapper. |
| AWS | [instances](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#instances) | Enumerates useful information for EC2 Instances in all regions like name, public/private IPs, and instance profiles. Generates loot files you can feed to nmap and other tools for service enumeration. |
| AWS | [inventory](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#inventory) | Gain a rough understanding of size of the account and preferred regions. |
| AWS | [lambda](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#lambda) | Lists the lambda functions in the account, including which one's have admin roles attached. Also gives you handy commands for downloading each function. |
| AWS | [outbound-assumed-roles](#outbound-assumed-roles) | List the roles that have been assumed by principals in this account. This is an excellent way to find outbound attack paths that lead into other accounts. |
| AWS | [permissions](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#permissions) | Enumerates IAM permissions associated with all users and roles. Grep this output to figure out what permissions a particular principal has rather than logging into the AWS console and painstakingly expanding each policy attached to the principal you are investigating. |
| AWS | [principals](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#principals) | Enumerates IAM users and Roles so you have the data at your fingertips. |
| AWS | [ram](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#ram) | List all resources in this account that are shared with other accounts, or resources from other accounts that are shared with this account. Useful for cross-account attack paths. |
| AWS | [role-trusts](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#role-trusts) | Enumerates IAM role trust policies so you can look for overly permissive role trusts or find roles that trust a specific service. |
| AWS | [route53](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#route53) | Enumerate all records from all route53 managed zones. Use this for application and service enumeration. |
| AWS | [secrets](https://github.com/BishopFox/cloudfox/wiki/AWS-Commands#secrets) | List secrets from SecretsManager and SSM. Look for interesting secrets in the list and then see who has access to them using use `cloudfox iam-simulator` and/or `pmapper`. |
| 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. |
| Azure | [instances-map](https://github.com/BishopFox/cloudfox/wiki/Azure-Commands#instances-map) | Enumerates useful information for Compute instances in all available resource groups and subscriptions |
| Azure | [rbac-map](https://github.com/BishopFox/cloudfox/wiki/Azure-Commands#rbac-map) | Enumerates Role Assignments for all tenants |
+7 -7
View File
@@ -42,7 +42,7 @@ func (m *AccessKeysModule) PrintAccessKeys(filter string, outputFormat string, o
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "access-keys"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
},
)
@@ -51,7 +51,7 @@ func (m *AccessKeysModule) PrintAccessKeys(filter string, outputFormat string, o
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Mapping user access keys for account: %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Mapping user access keys for account: %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
m.getAccessKeysForAllUsers()
// Variables used to draw table output
@@ -76,17 +76,17 @@ func (m *AccessKeysModule) PrintAccessKeys(filter string, outputFormat string, o
if len(m.output.Body) > 0 {
// Pretty prints output
fmt.Printf("[%s] Only active access keys are shown.\n", cyan(m.output.CallingModule))
//fmt.Printf("[%s] Preparing output.\n\n")
fmt.Printf("[%s][%s] Only active access keys are shown.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
//fmt.Printf("[%s][%s] Preparing output.\n\n")
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s access keys found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s access keys found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No access keys found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No access keys found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -109,7 +109,7 @@ func (m *AccessKeysModule) writeLoot(outputDirectory string, verbosity int) {
if err != nil {
m.modLog.Error(err.Error())
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), f)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), f)
}
+7 -7
View File
@@ -47,7 +47,7 @@ func (m *BucketsModule) PrintBuckets(outputFormat string, outputDirectory string
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "buckets"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
@@ -55,7 +55,7 @@ func (m *BucketsModule) PrintBuckets(outputFormat string, outputDirectory string
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating buckets for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating buckets for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -104,10 +104,10 @@ func (m *BucketsModule) PrintBuckets(outputFormat string, outputDirectory string
////m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity, m.AWSProfile)
fmt.Printf("[%s] %s buckets found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s buckets found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No buckets found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No buckets found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -170,12 +170,12 @@ func (m *BucketsModule) writeLoot(outputDirectory string, verbosity int, profile
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Use the commands below to manually inspect certain buckets of interest."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Use the commands below to manually inspect certain buckets of interest."))
fmt.Print(out)
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), pullFile)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), pullFile)
}
+300
View File
@@ -0,0 +1,300 @@
package aws
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"sync"
"github.com/BishopFox/cloudfox/console"
"github.com/BishopFox/cloudfox/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudformation"
"github.com/aws/aws-sdk-go-v2/service/cloudformation/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/sirupsen/logrus"
)
type CloudformationModule struct {
// General configuration data
CloudFormationClient *cloudformation.Client
Caller sts.GetCallerIdentityOutput
AWSRegions []string
OutputFormat string
Goroutines int
AWSProfile string
// Main module data
CFStacks []CFStack
CommandCounter console.CommandCounter
// Used to store output data for pretty printing
output utils.OutputData2
modLog *logrus.Entry
}
type CFStack struct {
AWSService string
Region string
Name string
Role string
Outputs []types.Output
Parameters []types.Parameter
Template string
}
func (m *CloudformationModule) PrintCloudformationStacks(outputFormat string, outputDirectory string, verbosity int) {
// These stuct values are used by the output module
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "cloudformation"
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s][%s] Enumerating cloudformation stacks for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), 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 console.SpinUntil(m.output.CallingModule, &m.CommandCounter, spinnerDone, "regions")
//create a channel to receive the objects
dataReceiver := make(chan CFStack)
// 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{
"Service",
"Region",
"Name",
"Role",
// "Parameters",
// "Outputs",
}
// Table rows
for i := range m.CFStacks {
// var isParameters string
// var isOutputs string
// if m.CFStacks[i].Parameters != nil {
// isParameters = "Y"
// } else {
// isParameters = "N"
// }
// if m.CFStacks[i].Outputs != nil {
// isOutputs = "Y"
// } else {
// isOutputs = "N"
// }
m.output.Body = append(
m.output.Body,
[]string{
m.CFStacks[i].AWSService,
m.CFStacks[i].Region,
m.CFStacks[i].Name,
m.CFStacks[i].Role,
// isParameters,
// isOutputs,
},
)
}
if len(m.output.Body) > 0 {
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s][%s] %s cloudformation stacks found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s][%s] No cloudformation stacks found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
func (m *CloudformationModule) executeChecks(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan CFStack) {
defer wg.Done()
m.CommandCounter.Total++
wg.Add(1)
m.getCFStacksPerRegion(r, wg, semaphore, dataReceiver)
}
func (m *CloudformationModule) Receiver(receiver chan CFStack, receiverDone chan bool) {
defer close(receiverDone)
for {
select {
case data := <-receiver:
m.CFStacks = append(m.CFStacks, data)
case <-receiverDone:
receiverDone <- true
return
}
}
}
func (m *CloudformationModule) writeLoot(outputDirectory string, verbosity int) {
path := filepath.Join(outputDirectory, "loot")
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
pullFile := filepath.Join(path, "cloudformation-data.txt")
var out string
out = out + fmt.Sprintln("#############################################")
out = out + fmt.Sprintln("# Look for secrets. Use something like trufflehog")
out = out + fmt.Sprintln("#############################################")
out = out + fmt.Sprintln("")
for _, stack := range m.CFStacks {
out = out + fmt.Sprintf("=============================================\n")
out = out + fmt.Sprintf("Stack Name: %s\n\n", stack.Name)
out = out + fmt.Sprintf("Stack Outputs:\n\n")
for _, output := range stack.Outputs {
outputDescription := aws.ToString(output.Description)
outputExport := aws.ToString(output.ExportName)
outputKey := aws.ToString(output.OutputKey)
outputValue := aws.ToString(output.OutputValue)
out = out + fmt.Sprintf("Stack Output Description: %s\n", outputDescription)
out = out + fmt.Sprintf("Stack Output Name: %s\n", outputExport)
out = out + fmt.Sprintf("Stack Output Key: %s\n", outputKey)
out = out + fmt.Sprintf("Stack Output Value: %s\n\n", outputValue)
}
out = out + fmt.Sprintf("Stack Parameters:\n\n")
for _, param := range stack.Parameters {
paramKey := aws.ToString(param.ParameterKey)
paramValue := aws.ToString(param.ParameterValue)
out = out + fmt.Sprintf("Stack Parameter Key: %s\n", paramKey)
out = out + fmt.Sprintf("Stack Parameter Value: %s\n\n", paramValue)
}
//out = out + fmt.Sprintf("Stack Parameters:\n %s\n", stack.Parameters)
out = out + fmt.Sprintf("Stack Template:\n %s\n", stack.Template)
out = out + fmt.Sprintf("=============================================\n")
}
err = os.WriteFile(pullFile, []byte(out), 0644)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Look for secrets. Use something like trufflehog"))
fmt.Print(out)
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Look for secrets. Use something like trufflehog"))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), pullFile)
}
func (m *CloudformationModule) getCFStacksPerRegion(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan CFStack) {
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
for {
DescribeStacks, err := m.CloudFormationClient.DescribeStacks(
context.TODO(),
&cloudformation.DescribeStacksInput{
NextToken: PaginationControl,
},
func(o *cloudformation.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
//var stackOutputs []types.Output
for _, stack := range DescribeStacks.Stacks {
stackName := aws.ToString(stack.StackName)
stackRole := aws.ToString(stack.RoleARN)
stackOutputs := stack.Outputs
stackParameters := stack.Parameters
for {
GetTemplate, err := m.CloudFormationClient.GetTemplate(
context.TODO(),
&cloudformation.GetTemplateInput{
StackName: &stackName,
},
func(o *cloudformation.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
stackTemplateBody := aws.ToString(GetTemplate.TemplateBody)
dataReceiver <- CFStack{
AWSService: "cloudformation",
Name: stackName,
Region: r,
Role: stackRole,
Outputs: stackOutputs,
Parameters: stackParameters,
Template: stackTemplateBody,
}
// }
break
}
}
// The "NextToken" value is nil when there's no more data to return.
if DescribeStacks.NextToken != nil {
PaginationControl = DescribeStacks.NextToken
} else {
PaginationControl = nil
break
}
}
}
+8 -8
View File
@@ -52,14 +52,14 @@ func (m *ECRModule) PrintECR(outputFormat string, outputDirectory string, verbos
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "ecr"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating container repositories for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating container repositories for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -123,9 +123,9 @@ func (m *ECRModule) PrintECR(outputFormat string, outputDirectory string, verbos
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s repositories found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s repositories found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No repositories found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No repositories found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -186,14 +186,14 @@ func (m *ECRModule) writeLoot(outputDirectory string, verbosity int) {
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Use the commands below to authenticate to ECR and download the images that look interesting"))
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("You will need the ecr:GetAuthorizationToken on the registry to authenticate and this is not part of the SecurityAudit permissions policy"))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Use the commands below to authenticate to ECR and download the images that look interesting"))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("You will need the ecr:GetAuthorizationToken on the registry to authenticate and this is not part of the SecurityAudit permissions policy"))
fmt.Print(out)
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), pullFile)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), pullFile)
}
+10 -10
View File
@@ -84,16 +84,16 @@ func (m *EndpointsModule) PrintEndpoints(outputFormat string, outputDirectory st
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "endpoints"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating endpoints for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Supported Services: App Runner, APIGateway, ApiGatewayV2, Cloudfront, EKS, ELB, ELBv2, Grafana, \n", cyan(m.output.CallingModule))
fmt.Printf("[%s] \t\t\tLambda, MQ, OpenSearch, Redshift, RDS\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] Enumerating endpoints for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Supported Services: App Runner, APIGateway, ApiGatewayV2, Cloudfront, EKS, ELB, ELBv2, Grafana, \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
fmt.Printf("[%s][%s] \t\t\tLambda, MQ, OpenSearch, Redshift, RDS\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -170,9 +170,9 @@ func (m *EndpointsModule) PrintEndpoints(outputFormat string, outputDirectory st
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s endpoints found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s endpoints found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No endpoints found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No endpoints found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
// This works great to print errors out after the module but i'm not really sure i want that.
@@ -180,7 +180,7 @@ func (m *EndpointsModule) PrintEndpoints(outputFormat string, outputDirectory st
// return m.Errors[i] < m.Errors[j]
// })
// for _, e := range m.Errors {
// fmt.Printf("[%s] %s\n", cyan(m.output.CallingModule), e)
// fmt.Printf("[%s][%s] %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), e)
// }
}
@@ -284,12 +284,12 @@ func (m *EndpointsModule) writeLoot(outputDirectory string, verbosity int) {
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Feed this endpoints into nmap and something like gowitness/aquatone for screenshots."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Feed this endpoints into nmap and something like gowitness/aquatone for screenshots."))
fmt.Print(out)
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), f)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), f)
}
+5 -5
View File
@@ -68,15 +68,15 @@ func (m *EnvsModule) PrintEnvs(outputFormat string, outputDirectory string, verb
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "env-vars"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating environment variables in all regions for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Supported Services: App Runner, Elastic Container Service, Lambda, Lightsail Containers, Sagemaker \n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] Enumerating environment variables 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, Elastic Container Service, Lambda, Lightsail Containers, Sagemaker \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -138,10 +138,10 @@ func (m *EnvsModule) PrintEnvs(outputFormat string, outputDirectory string, verb
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
fmt.Printf("[%s] %s environment variables found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s environment variables found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No environment variables found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No environment variables found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
+8 -8
View File
@@ -59,7 +59,7 @@ func (m *FilesystemsModule) PrintFilesystems(outputFormat string, outputDirector
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "filesystems"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
@@ -70,8 +70,8 @@ func (m *FilesystemsModule) PrintFilesystems(outputFormat string, outputDirector
m.Regions[i].Region = region
}
fmt.Printf("[%s] Enumerating filesystems for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Supported Services: EFS, FSx \n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] Enumerating filesystems for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Supported Services: EFS, FSx \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -138,10 +138,10 @@ func (m *FilesystemsModule) PrintFilesystems(outputFormat string, outputDirector
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s filesystems found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s filesystems found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No filesystems found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No filesystems found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -211,12 +211,12 @@ func (m *FilesystemsModule) writeLoot(outputDirectory string, verbosity int) {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), f)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), f)
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Use the commands below to try and mount the identified filesystems."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Use the commands below to try and mount the identified filesystems."))
fmt.Print(out)
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
}
+49 -41
View File
@@ -61,22 +61,16 @@ var (
"apprunner:DescribeService",
"ec2:DescribeInstanceAttributeInput",
}
adminActionNames = []string{
"iam:PutUserPolicy",
"iam:AttachUserPolicy",
"iam:PutRolePolicy",
"iam:AttachRolePolicy",
"secretsmanager:GetSecretValue",
"ssm:GetDocument",
}
TxtLogger = utils.TxtLogger()
)
func (m *IamSimulatorModule) PrintIamSimulator(principal string, action string, resource string, outputFormat string, outputDirectory string, verbosity int) {
// These stuct values are used by the output module
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "iam-simulator"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
@@ -104,21 +98,21 @@ func (m *IamSimulatorModule) PrintIamSimulator(principal string, action string,
if principal != "" {
if action != "" {
// The user specified a specific --principal and a specific --action
fmt.Printf("[%s] Checking to see if %s can do %s.\n", cyan(m.output.CallingModule), principal, action)
fmt.Printf("[%s][%s] Checking to see if %s can do %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), principal, action)
m.output.FullFilename = filepath.Join(fmt.Sprintf("%s-custom-%s", m.output.CallingModule, strconv.FormatInt((time.Now().Unix()), 10)))
actionList = append(actionList, action)
m.getPolicySimulatorResult((&principal), actionList, resource, dataReceiver)
} else {
// The user specified a specific --principal, but --action was empty
fmt.Printf("[%s] Checking to see if %s can do any actions of interest.\n", cyan(m.output.CallingModule), principal)
fmt.Printf("[%s][%s] Checking to see if %s can do any actions of interest.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), principal)
m.output.FullFilename = filepath.Join(fmt.Sprintf("%s-custom-%s", m.output.CallingModule, strconv.FormatInt((time.Now().Unix()), 10)))
m.getPolicySimulatorResult((&principal), defaultActionNames, resource, dataReceiver)
}
} else {
if action != "" {
// The did not specify a specific --principal, but they did specify an --action
fmt.Printf("[%s] Checking to see if any principal can do %s.\n", cyan(m.output.CallingModule), action)
fmt.Printf("[%s][%s] Checking to see if any principal can do %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), action)
m.output.FullFilename = filepath.Join(fmt.Sprintf("%s-custom-%s", m.output.CallingModule, strconv.FormatInt((time.Now().Unix()), 10)))
actionList = append(actionList, action)
wg.Add(1)
@@ -129,7 +123,7 @@ func (m *IamSimulatorModule) PrintIamSimulator(principal string, action string,
pmapperCommands = append(pmapperCommands, fmt.Sprintf("pmapper --profile %s query \"who can do %s with %s\" | tee %s\n", m.AWSProfile, action, resource, pmapperOutFileName))
} else {
// Both --principal and --action are empty. Run in default mode!
fmt.Printf("[%s] Running multiple iam-simulator queries for account %s. (This command can be pretty slow, FYI)\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Running multiple iam-simulator queries for account %s. (This command can be pretty slow, FYI)\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
m.output.FullFilename = m.output.CallingModule
m.executeChecks(wg, resource, dataReceiver)
for _, action := range defaultActionNames {
@@ -177,15 +171,15 @@ func (m *IamSimulatorModule) PrintIamSimulator(principal string, action string,
if len(m.output.Body) > 0 {
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.FullFilename, m.output.CallingModule)
fmt.Printf("[%s] We suggest running the pmapper commands in the loot file to get the same information but taking privesc paths into account.\n", cyan(m.output.CallingModule))
// fmt.Printf("[%s]\t\tpmapper --profile %s graph create\n", cyan(m.output.CallingModule), m.AWSProfile)
fmt.Printf("[%s][%s] We suggest running the pmapper commands in the loot file to get the same information but taking privesc paths into account.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
// fmt.Printf("[%s]\t\tpmapper --profile %s graph create\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), m.AWSProfile)
// for _, line := range pmapperCommands {
// fmt.Printf("[%s]\t\t%s", cyan(m.output.CallingModule), line)
// fmt.Printf("[%s]\t\t%s", cyan(m.output.CallingModule), cyan(m.AWSProfile), line)
// }
m.writeLoot(m.output.FilePath, verbosity, pmapperCommands)
} else if principal != "" || action != "" {
fmt.Printf("[%s] No allowed permissions identified, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No allowed permissions identified, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -212,12 +206,12 @@ func (m *IamSimulatorModule) writeLoot(outputDirectory string, verbosity int, pm
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("We suggest running these pmapper commands in the loot file to get the same information but taking privesc paths into account."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("We suggest running these pmapper commands in the loot file to get the same information but taking privesc paths into account."))
fmt.Print(out)
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), outFile)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), outFile)
}
@@ -252,7 +246,6 @@ func (m *IamSimulatorModule) getIAMUsers(wg *sync.WaitGroup, actions []string, r
m.CommandCounter.Executing++
// "PaginationMarker" is a control variable used for output continuity, as AWS return the output in pages.
var PaginationControl *string
var adminCheckResult bool
for {
ListUsers, err := m.IAMClient.ListUsers(
@@ -270,8 +263,16 @@ func (m *IamSimulatorModule) getIAMUsers(wg *sync.WaitGroup, actions []string, r
for _, user := range ListUsers.Users {
//name := user.UserName
principal := user.Arn
adminCheckResult = m.policySimulatorAdminCheck(principal, adminActionNames, resource, dataReceiver)
if !adminCheckResult {
adminCheckResult := m.isPrincipalAnAdmin(principal)
if adminCheckResult {
query := fmt.Sprintf("Appears to be an administrator")
dataReceiver <- SimulatorResult{
AWSService: "IAM",
Principal: aws.ToString(principal),
Query: query,
Decision: "",
}
} else {
m.getPolicySimulatorResult(principal, actions, resource, dataReceiver)
}
@@ -299,7 +300,6 @@ func (m *IamSimulatorModule) getIAMRoles(wg *sync.WaitGroup, actions []string, r
m.CommandCounter.Executing++
// "PaginationMarker" is a control variable used for output continuity, as AWS return the output in pages.
var PaginationControl *string
var adminCheckResult bool
for {
ListRoles, err := m.IAMClient.ListRoles(
@@ -317,8 +317,16 @@ func (m *IamSimulatorModule) getIAMRoles(wg *sync.WaitGroup, actions []string, r
for _, role := range ListRoles.Roles {
//name := user.UserName
principal := role.Arn
adminCheckResult = m.policySimulatorAdminCheck(principal, adminActionNames, resource, dataReceiver)
if !adminCheckResult {
adminCheckResult := m.isPrincipalAnAdmin(principal)
if adminCheckResult {
query := fmt.Sprintf("Appears to be an administrator")
dataReceiver <- SimulatorResult{
AWSService: "IAM",
Principal: aws.ToString(principal),
Query: query,
Decision: "",
}
} else {
m.getPolicySimulatorResult(principal, actions, resource, dataReceiver)
}
@@ -386,25 +394,34 @@ func (m *IamSimulatorModule) getPolicySimulatorResult(principal *string, actionN
}
}
func (m *IamSimulatorModule) policySimulatorAdminCheck(principal *string, actionNames []string, resource string, dataReceiver chan SimulatorResult) bool {
func (m *IamSimulatorModule) isPrincipalAnAdmin(principal *string) bool {
var PaginationControl2 *string
var resourceArns []string
resourceArns = append(resourceArns, resource)
resourceArns = append(resourceArns, "*")
var adminActionNames = []string{
"iam:PutUserPolicy",
"iam:AttachUserPolicy",
"iam:PutRolePolicy",
"iam:AttachRolePolicy",
"secretsmanager:GetSecretValue",
"ssm:GetDocument",
}
for {
SimulatePrincipalPolicy, err := m.IAMClient.SimulatePrincipalPolicy(
context.TODO(),
&iam.SimulatePrincipalPolicyInput{
Marker: PaginationControl2,
ActionNames: actionNames,
ActionNames: adminActionNames,
PolicySourceArn: principal,
ResourceArns: resourceArns,
},
)
if err != nil {
m.modLog.Error(err.Error())
//m.modLog.Error(err.Error())
TxtLogger.Println(err.Error())
m.CommandCounter.Error++
m.modLog.Error(fmt.Sprintf("Failed admin check on %s\n\n", aws.ToString(principal)))
//m.modLog.Error(fmt.Sprintf("Failed admin check on %s\n\n", aws.ToString(principal)))
TxtLogger.Printf("Failed admin check on %s\n\n", aws.ToString(principal))
return false
}
@@ -428,14 +445,5 @@ func (m *IamSimulatorModule) policySimulatorAdminCheck(principal *string, action
break
}
}
query := fmt.Sprintf("Appears to be an administrator")
dataReceiver <- SimulatorResult{
AWSService: "IAM",
Principal: aws.ToString(principal),
Query: query,
Decision: "",
}
return true
}
+130 -39
View File
@@ -15,19 +15,23 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/iam"
iamTypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/sirupsen/logrus"
)
type InstancesModule struct {
// General configuration data
EC2Client *ec2.Client
Caller sts.GetCallerIdentityOutput
AWSRegions []string
OutputFormat string
Goroutines int
UserDataAttributesOnly bool
AWSProfile string
EC2Client *ec2.Client
IAMClient *iam.Client
Caller sts.GetCallerIdentityOutput
AWSRegions []string
OutputFormat string
Goroutines int
UserDataAttributesOnly bool
AWSProfile string
InstanceProfileToRolesMap map[string][]iamTypes.Role
// Module's Results
MappedInstances []MappedInstance
@@ -47,7 +51,9 @@ type MappedInstance struct {
ExternalIP string
PrivateIP string
Profile string
Role string
Region string
Admin string
}
func (m *InstancesModule) Instances(filter string, outputFormat string, outputDirectory string, verbosity int) {
@@ -55,22 +61,15 @@ func (m *InstancesModule) Instances(filter string, outputFormat string, outputDi
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "instances"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
// regions, errtemp := m.EC2Client.DescribeRegions(
// context.TODO(),
// &ec2.DescribeRegionsInput{})
// if errtemp != nil {
// m.modLog.Error(errtemp.Error())
// }
// for _, reg := range regions.Regions {
// fmt.Println(*reg.RegionName)
// }
// Populate the instance profile to roles map. You can't use getInstanceProfile by name, so the only way to do this is to
// list all of the profiles, save the data, and then do the lookup yourself.
// Parses the type of filter being used (file with instances or single instance id)
var instancesToSearch []string
@@ -81,7 +80,7 @@ func (m *InstancesModule) Instances(filter string, outputFormat string, outputDi
}
//Connects to EC2 service and maps instances
fmt.Printf("[%s] Enumerating EC2 instances in all regions for account %s\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating EC2 instances in all regions for account %s\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
wg := new(sync.WaitGroup)
@@ -96,7 +95,7 @@ func (m *InstancesModule) Instances(filter string, outputFormat string, outputDi
// Create a channel to signal to stop
receiverDone := make(chan bool)
go m.Receiver(dataReceiver, receiverDone)
m.getRolesFromInstanceProfiles()
for _, region := range m.AWSRegions {
wg.Add(1)
m.CommandCounter.Pending++
@@ -179,9 +178,9 @@ func (m *InstancesModule) printInstancesUserDataAttributesOnly(outputFormat stri
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), userDataFileName)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), userDataFileName)
} else {
fmt.Printf("[%s] No user data found, skipping the creation of an output file\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No user data found, skipping the creation of an output file\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -191,12 +190,14 @@ func (m *InstancesModule) printGeneralInstanceData(outputFormat string, outputDi
m.output.Headers = []string{
//"ID",
"Name",
"Arn",
//"Arn",
"ID",
"Zone",
"State",
"External IP",
"Internal IP",
"Profile",
"Role",
"isAdminRole?",
}
//Table rows
for _, instance := range m.MappedInstances {
@@ -206,12 +207,14 @@ func (m *InstancesModule) printGeneralInstanceData(outputFormat string, outputDi
[]string{
//instance.ID,
instance.Name,
instance.Arn,
//instance.Arn,
instance.ID,
instance.AvailabilityZone,
instance.State,
instance.ExternalIP,
instance.PrivateIP,
instance.Profile,
instance.Role,
instance.Admin,
},
)
}
@@ -221,10 +224,10 @@ func (m *InstancesModule) printGeneralInstanceData(outputFormat string, outputDi
utils.OutputSelector(m.output.Verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath)
fmt.Printf("[%s] %s instances found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s instances found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No instances found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No instances found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -261,8 +264,8 @@ func (m *InstancesModule) writeLoot(outputDirectory string) {
m.CommandCounter.Error++
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), privateIPsFilename)
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), publicIPsFilename)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), privateIPsFilename)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), publicIPsFilename)
}
@@ -352,6 +355,9 @@ func (m *InstancesModule) loadInstanceData(instance types.Instance, region strin
var profile string
var externalIP string
var name string = ""
var adminRole string = ""
localAdminMap := make(map[string]bool)
var roleArn string = ""
// The name is in a tag so we have to do this to grab the value from the right tag
for _, tag := range instance.Tags {
@@ -361,15 +367,7 @@ func (m *InstancesModule) loadInstanceData(instance types.Instance, region strin
}
arn := fmt.Sprintf("arn:aws:ec2:%s:%s:instance/%s", region, aws.ToString(accountId), aws.ToString(instance.InstanceId))
if instance.IamInstanceProfile == nil {
profile = "NoInstanceProfile"
} else {
// This returns only the role name without the preceding forward slash.
profileARN := aws.ToString(instance.IamInstanceProfile.Arn)
profile = strings.Split(profileARN, "/")[len(strings.Split(profileARN, "/"))-1]
}
//arn := fmt.Sprintf("arn:aws:ec2:%s:%s:instance/%s", region, aws.ToString(accountId), aws.ToString(instance.InstanceId))
if instance.PublicIpAddress == nil {
externalIP = "NoExternalIP"
@@ -377,16 +375,109 @@ func (m *InstancesModule) loadInstanceData(instance types.Instance, region strin
externalIP = aws.ToString(instance.PublicIpAddress)
}
if instance.IamInstanceProfile == nil {
profile = "NoInstanceProfile"
} else {
// This returns only the role name without the preceding forward slash.
profileARN := aws.ToString(instance.IamInstanceProfile.Arn)
profileID := aws.ToString(instance.IamInstanceProfile.Id)
profile = strings.Split(profileARN, "/")[len(strings.Split(profileARN, "/"))-1]
if roles, ok := m.InstanceProfileToRolesMap[profileID]; ok {
for _, role := range roles {
roleArn = aws.ToString(role.Arn)
if role.Arn != nil {
// If we've seen the function before, skip the isRoleAdmin function and just pull the value from the localAdminMap
roleArn := aws.ToString(role.Arn)
if val, ok := localAdminMap[roleArn]; ok {
if val {
// we've seen it before and it's an admin
adminRole = "YES"
} else {
// we've seen it before and it's NOT an admin
adminRole = "No"
}
} else {
isRoleAdmin := m.isRoleAdmin(role.Arn)
if isRoleAdmin {
adminRole = "YES"
localAdminMap[roleArn] = true
} else {
adminRole = "No"
localAdminMap[roleArn] = false
}
}
}
}
}
}
dataReceiver <- MappedInstance{
aws.ToString(instance.InstanceId),
aws.ToString(&name),
arn,
//arn,
aws.ToString(instance.InstanceId),
aws.ToString(instance.Placement.AvailabilityZone),
string(instance.State.Name),
externalIP,
aws.ToString(instance.PrivateIpAddress),
profile,
roleArn,
region,
adminRole,
}
}
func (m *InstancesModule) isRoleAdmin(principal *string) bool {
iamSimMod := IamSimulatorModule{
IAMClient: m.IAMClient,
Caller: m.Caller,
AWSProfile: m.AWSProfile,
Goroutines: m.Goroutines,
}
adminCheckResult := iamSimMod.isPrincipalAnAdmin(principal)
if adminCheckResult {
return true
} else {
return false
}
}
func (m *InstancesModule) getRolesFromInstanceProfiles() {
// The "PaginationControl" value is nil when there's no more data to return.
var PaginationMarker *string
PaginationControl := true
m.InstanceProfileToRolesMap = map[string][]iamTypes.Role{}
for PaginationControl {
ListInstanceProfiles, err := m.IAMClient.ListInstanceProfiles(
context.TODO(),
&(iam.ListInstanceProfilesInput{
Marker: PaginationMarker,
}),
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
for _, instanceProfile := range ListInstanceProfiles.InstanceProfiles {
m.InstanceProfileToRolesMap[aws.ToString(instanceProfile.InstanceProfileId)] = instanceProfile.Roles
}
if aws.ToString(ListInstanceProfiles.Marker) != "" {
PaginationMarker = ListInstanceProfiles.Marker
} else {
PaginationMarker = nil
break
}
}
// next step - debug and watch localAdminmap to see if it's working like it does on lambda
}
+7 -6
View File
@@ -101,7 +101,7 @@ func (m *Inventory2Module) PrintInventoryPerRegion(outputFormat string, outputDi
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "inventory"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": "inventory",
},
)
@@ -123,9 +123,10 @@ func (m *Inventory2Module) PrintInventoryPerRegion(outputFormat string, outputDi
}
}
fmt.Printf("[%s] Enumerating selected services in all regions for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Supported Services: ApiGateway, ApiGatewayv2, AppRunner, CloudFormation, Cloudfront, DynamoDB, EC2, ECS, EKS, \n", cyan(m.output.CallingModule))
fmt.Printf("[%s] \t\t\tELB, ELBv2, Glue, Grafana, IAM, Lambda, Lightsail, MQ, OpenSearch, RDS, S3, SecretsManager, SNS, SQS, SSM\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] Enumerating selected services 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: ApiGateway, ApiGatewayv2, AppRunner, CloudFormation, Cloudfront, DynamoDB, \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
fmt.Printf("[%s][%s] \t\t\tEC2, ECS, EKS, ELB, ELBv2, Glue, Grafana, IAM, Lambda, Lightsail, MQ, \n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
fmt.Printf("[%s][%s] \t\t\tOpenSearch, RDS, S3, SecretsManager, SNS, SQS, SSM\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -257,7 +258,7 @@ func (m *Inventory2Module) PrintInventoryPerRegion(outputFormat string, outputDi
m.PrintGlobalResources(outputFormat, outputDirectory, verbosity, dataReceiver)
m.PrintTotalResources(outputFormat)
} else {
fmt.Printf("[%s] No resources identified, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No resources identified, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
// Send a message to the data receiver goroutine to close the channel and stop
@@ -1750,5 +1751,5 @@ func (m *Inventory2Module) PrintTotalResources(outputFormat string) {
for i := range m.GlobalResourceCounts {
totalResources = totalResources + m.GlobalResourceCounts[i].count
}
fmt.Printf("[%s] %d resources found in the services we looked at. This is NOT the total number of resources in the account.\n", cyan(m.output.CallingModule), totalResources)
fmt.Printf("[%s][%s] %d resources found in the services we looked at. This is NOT the total number of resources in the account.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), totalResources)
}
+298
View File
@@ -0,0 +1,298 @@
package aws
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"sync"
"github.com/BishopFox/cloudfox/console"
"github.com/BishopFox/cloudfox/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"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/sts"
"github.com/sirupsen/logrus"
)
type LambdasModule struct {
// General configuration data
LambdaClient *lambda.Client
IAMClient *iam.Client
Caller sts.GetCallerIdentityOutput
AWSRegions []string
OutputFormat string
Goroutines int
AWSProfile string
// Main module data
Lambdas []Lambda
CommandCounter console.CommandCounter
// Used to store output data for pretty printing
output utils.OutputData2
modLog *logrus.Entry
}
type Lambda struct {
AWSService string
Region string
Type string
Name string
Role string
Admin string
Public string
}
func (m *LambdasModule) PrintLambdas(outputFormat string, outputDirectory string, verbosity int) {
// These stuct values are used by the output module
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "lambdas"
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s][%s] Enumerating lambdas for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), 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 console.SpinUntil(m.output.CallingModule, &m.CommandCounter, spinnerDone, "regions")
//create a channel to receive the objects
dataReceiver := make(chan Lambda)
// 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{
"Service",
"Region",
//"Type",
"Resource Arn",
"Role",
"isAdminRole?",
//"Public",
}
sort.Slice(m.Lambdas, func(i, j int) bool {
return m.Lambdas[i].AWSService < m.Lambdas[j].AWSService
})
// Table rows
for i := range m.Lambdas {
m.output.Body = append(
m.output.Body,
[]string{
m.Lambdas[i].AWSService,
m.Lambdas[i].Region,
//m.Lambdas[i].Type,
m.Lambdas[i].Name,
m.Lambdas[i].Role,
m.Lambdas[i].Admin,
//m.Lambdas[i].Public,
},
)
}
if len(m.output.Body) > 0 {
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s][%s] %s lambdas found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s][%s] No lambdas found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
func (m *LambdasModule) executeChecks(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Lambda) {
defer wg.Done()
m.CommandCounter.Total++
wg.Add(1)
m.getLambdasPerRegion(r, wg, semaphore, dataReceiver)
}
func (m *LambdasModule) Receiver(receiver chan Lambda, receiverDone chan bool) {
defer close(receiverDone)
for {
select {
case data := <-receiver:
m.Lambdas = append(m.Lambdas, data)
case <-receiverDone:
receiverDone <- true
return
}
}
}
func (m *LambdasModule) writeLoot(outputDirectory string, verbosity int) {
path := filepath.Join(outputDirectory, "loot")
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
pullFile := filepath.Join(path, "lambda-get-function-commands.txt")
var out string
out = out + fmt.Sprintln("#############################################")
out = out + fmt.Sprintln("# The profile you will use to perform these commands is most likely not the profile you used to run CloudFox")
out = out + fmt.Sprintln("# Set the $profile environment variable to the profile you are going to use to inspect the buckets.")
out = out + fmt.Sprintln("# E.g., export profile=dev-prod.")
out = out + fmt.Sprintln("#############################################")
out = out + fmt.Sprintln("")
for _, function := range m.Lambdas {
out = out + fmt.Sprintf("=============================================\n")
out = out + fmt.Sprintf("# Lambda Name: %s\n\n", function.Name)
out = out + "# Get function metadata including download location\n"
out = out + fmt.Sprintf("aws --profile $profile --region %s lambda get-function --function-name %s\n", function.Region, function.Name)
out = out + "# Download function code to to disk (requires jq and curl) \n"
out = out + fmt.Sprintf("mkdir -p ./lambdas/%s\n", function.Name)
out = out + fmt.Sprintf("url=`aws --profile $profile lambda get-function --region %s --function-name %s | jq .Code.Location | sed s/\"//g` && curl \"$url\" -o ./lambdas/%s.zip\n", function.Region, function.Name, function.Name)
}
err = os.WriteFile(pullFile, []byte(out), 0644)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
}
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s][%s] %s \n\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] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), pullFile)
}
func (m *LambdasModule) getLambdasPerRegion(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Lambda) {
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 adminRole string = ""
localAdminMap := make(map[string]bool)
for {
ListFunctions, err := m.LambdaClient.ListFunctions(
context.TODO(),
&lambda.ListFunctionsInput{
Marker: PaginationControl,
},
func(o *lambda.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
//var parsedArn types.Arn
for _, function := range ListFunctions.Functions {
//arn := aws.ToString(function.FunctionArn)
name := aws.ToString(function.FunctionName)
role := aws.ToString(function.Role)
if function.Role != nil {
// If we've seen the function before, skip the isRoleAdmin function and just pull the value from the localAdminMap
if val, ok := localAdminMap[role]; ok {
if val {
// we've seen it before and it's an admin
adminRole = "YES"
} else {
// we've seen it before and it's NOT an admin
adminRole = "No"
}
} else {
isRoleAdmin := m.isRoleAdmin(function.Role)
if isRoleAdmin {
adminRole = "YES"
localAdminMap[role] = true
} else {
adminRole = "No"
localAdminMap[role] = false
}
}
}
dataReceiver <- Lambda{
AWSService: "Lambda",
Name: name,
Region: r,
Type: "",
Role: role,
Admin: adminRole,
Public: "",
}
}
if aws.ToString(ListFunctions.NextMarker) != "" {
PaginationControl = ListFunctions.NextMarker
} else {
PaginationControl = nil
break
}
}
}
func (m *LambdasModule) isRoleAdmin(principal *string) bool {
iamSimMod := IamSimulatorModule{
IAMClient: m.IAMClient,
Caller: m.Caller,
AWSProfile: m.AWSProfile,
Goroutines: m.Goroutines,
}
adminCheckResult := iamSimMod.isPrincipalAnAdmin(principal)
if adminCheckResult {
return true
} else {
return false
}
}
+6 -6
View File
@@ -118,7 +118,7 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputFor
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "outbound-assumed-roles"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
@@ -126,8 +126,8 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputFor
}
m.Days = days
fmt.Printf("[%s] Enumerating outbound assumed role entries in cloudtrail for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Going back through %d days of cloudtrail events. (This command can be pretty slow, FYI)\n", cyan(m.output.CallingModule), days)
fmt.Printf("[%s][%s] Enumerating outbound assumed role entries in cloudtrail for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Going back through %d days of cloudtrail events. (This command can be pretty slow, FYI)\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), days)
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -192,11 +192,11 @@ func (m *OutboundAssumedRolesModule) PrintOutboundRoleTrusts(days int, outputFor
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
fmt.Printf("[%s] %s log entries found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s log entries found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
//m.writeLoot()
} else {
fmt.Printf("[%s] No matching log entries found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No matching log entries found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -216,7 +216,7 @@ func (m *OutboundAssumedRolesModule) Receiver(receiver chan OutboundAssumeRoleEn
func (m *OutboundAssumedRolesModule) executeChecks(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan OutboundAssumeRoleEntry) {
defer wg.Done()
wg.Add(1)
m.CommandCounter.Total++
m.getAssumeRoleLogEntriesPerRegion(r, wg, semaphore, dataReceiver)
+4 -4
View File
@@ -88,14 +88,14 @@ func (m *IamPermissionsModule) PrintIamPermissions(outputFormat string, outputDi
m.output.Directory = outputDirectory
m.output.CallingModule = "permissions"
m.output.FullFilename = m.output.CallingModule
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
fmt.Printf("[%s] Enumerating IAM permissions for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating IAM permissions for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
if principal != "" {
m.output.FullFilename = filepath.Join(fmt.Sprintf("%s-custom-%s", m.output.CallingModule, strconv.FormatInt((time.Now().Unix()), 10)))
@@ -140,10 +140,10 @@ func (m *IamPermissionsModule) PrintIamPermissions(outputFormat string, outputDi
//m.output.OutputSelector3(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.FullFilename, m.output.CallingModule)
fmt.Printf("[%s] %s unique permissions identified.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s unique permissions identified.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No IAM permissions found. skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No IAM permissions found. skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
+4 -4
View File
@@ -68,14 +68,14 @@ func (m *IamPrincipalsModule) PrintIamPrincipals(outputFormat string, outputDire
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "principals"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating IAM Users and Roles for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating IAM Users and Roles for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
// wg := new(sync.WaitGroup)
@@ -139,10 +139,10 @@ func (m *IamPrincipalsModule) PrintIamPrincipals(outputFormat string, outputDire
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
fmt.Printf("[%s] %s IAM principals found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s IAM principals found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No IAM principals found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No IAM principals found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
+90 -39
View File
@@ -11,6 +11,7 @@ import (
"github.com/BishopFox/cloudfox/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ram"
ramTypes "github.com/aws/aws-sdk-go-v2/service/ram/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/sirupsen/logrus"
)
@@ -38,6 +39,8 @@ type Resource struct {
Region string
Name string
Owner string
Type string
ShareType string
}
func (m *RAMModule) PrintRAM(outputFormat string, outputDirectory string, verbosity int) {
@@ -45,14 +48,14 @@ func (m *RAMModule) PrintRAM(outputFormat string, outputDirectory string, verbos
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "ram"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating shared resources for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating shared resources for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
wg := new(sync.WaitGroup)
@@ -87,8 +90,10 @@ func (m *RAMModule) PrintRAM(outputFormat string, outputDirectory string, verbos
m.output.Headers = []string{
"Service",
"Region",
"Name",
"Share Name",
"Type",
"Owner",
"Share Type",
}
// Table rows
@@ -99,7 +104,9 @@ func (m *RAMModule) PrintRAM(outputFormat string, outputDirectory string, verbos
m.Resources[i].AWSService,
m.Resources[i].Region,
m.Resources[i].Name,
m.Resources[i].Type,
m.Resources[i].Owner,
m.Resources[i].ShareType,
},
)
@@ -108,9 +115,9 @@ func (m *RAMModule) PrintRAM(outputFormat string, outputDirectory string, verbos
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
fmt.Printf("[%s] %s resources found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s resources found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No resources found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No resources found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -141,44 +148,88 @@ func (m *RAMModule) Receiver(receiver chan Resource, receiverDone chan bool) {
func (m *RAMModule) getRAMResourcesPerRegion(r string, dataReceiver chan Resource) {
// "PaginationMarker" is a control variable used for output continuity, as AWS return the output in pages.
var PaginationControl *string
var PaginationControl2 *string
var shareName string
var resourceType string
shareTypes := []ramTypes.ResourceOwner{"SELF", "OTHER-ACCOUNTS"}
for {
GetResourceShares, err := m.RAMClient.GetResourceShares(
context.TODO(),
&ram.GetResourceSharesInput{
NextToken: PaginationControl,
},
func(o *ram.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
for _, resource := range GetResourceShares.ResourceShares {
name := aws.ToString(resource.Name)
ownerID := aws.ToString(resource.OwningAccountId)
dataReceiver <- Resource{
AWSService: "RAM",
Name: name,
Region: r,
Owner: ownerID,
for _, shareType := range shareTypes {
for {
GetResourceShares, err := m.RAMClient.GetResourceShares(
context.TODO(),
&ram.GetResourceSharesInput{
NextToken: PaginationControl,
ResourceOwner: shareType,
},
func(o *ram.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
// }
break
}
for _, resourceShare := range GetResourceShares.ResourceShares {
var resourceShareArns []string
shareName = aws.ToString(resourceShare.Name)
resourceShareArns = append(resourceShareArns, aws.ToString(resourceShare.ResourceShareArn))
ownerID := aws.ToString(resourceShare.OwningAccountId)
// The "NextToken" value is nil when there's no more data to return.
if GetResourceShares.NextToken != nil {
PaginationControl = GetResourceShares.NextToken
} else {
PaginationControl = nil
break
for {
ListResources, err := m.RAMClient.ListResources(
context.TODO(),
&ram.ListResourcesInput{
NextToken: PaginationControl2,
ResourceOwner: shareType,
ResourceShareArns: resourceShareArns,
},
func(o *ram.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
for _, resource := range ListResources.Resources {
resourceType = aws.ToString(resource.Type)
var shareDirection string
if string(shareType) == "OTHER-ACCOUNTS" {
shareDirection = "Inbound share (Another account shared this with me)"
} else {
shareDirection = "Outbound share (I've shared this resource with others)"
}
dataReceiver <- Resource{
AWSService: "RAM",
Name: shareName,
Type: resourceType,
Region: r,
Owner: ownerID,
ShareType: shareDirection,
}
}
if ListResources.NextToken != nil {
PaginationControl2 = ListResources.NextToken
} else {
PaginationControl2 = nil
break
}
}
}
// The "NextToken" value is nil when there's no more data to return.
if GetResourceShares.NextToken != nil {
PaginationControl = GetResourceShares.NextToken
} else {
PaginationControl = nil
break
}
}
}
}
+6 -6
View File
@@ -40,13 +40,13 @@ func (m *RoleTrustsModule) PrintRoleTrusts(outputFormat string, outputDirectory
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "role-trusts"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating role trusts for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating role trusts for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
m.getAllRoleTrusts()
m.printPrincipalTrusts(outputFormat, outputDirectory)
@@ -79,10 +79,10 @@ func (m *RoleTrustsModule) printPrincipalTrusts(outputFormat string, outputDirec
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
////m.output.OutputSelector(outputFormat)
utils.OutputSelector(m.output.Verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.FullFilename, m.output.CallingModule)
fmt.Printf("[%s] %s role trusts found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s role trusts found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No role trusts found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No role trusts found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -113,10 +113,10 @@ func (m *RoleTrustsModule) printServiceTrusts(outputFormat string, outputDirecto
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(m.output.Verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.FullFilename, m.output.CallingModule)
fmt.Printf("[%s] %s role trusts found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s role trusts found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No role trusts found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No role trusts found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
+10 -10
View File
@@ -51,14 +51,14 @@ func (m *Route53Module) PrintRoute53(outputFormat string, outputDirectory string
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "route53"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating Route53 for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Enumerating Route53 for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
m.getRoute53Records()
@@ -90,10 +90,10 @@ func (m *Route53Module) PrintRoute53(outputFormat string, outputDirectory string
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s DNS records found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s DNS records found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No DNS records found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No DNS records found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -132,13 +132,13 @@ func (m *Route53Module) writeLoot(outputDirectory string, verbosity int) {
if verbosity > 2 {
if len(route53APublicRecords) > 0 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Feed these public zone A records into nmap and something like gowitness or aquatone."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Feed these public zone A records into nmap and something like gowitness or aquatone."))
fmt.Print(route53APublicRecords)
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), route53ARecordsPublicZonesFileName)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), route53ARecordsPublicZonesFileName)
err = os.WriteFile(route53ARecordsPrivateZonesFileName, []byte(route53APrivateRecords), 0644)
if err != nil {
@@ -150,13 +150,13 @@ func (m *Route53Module) writeLoot(outputDirectory string, verbosity int) {
if verbosity > 2 {
if len(route53APrivateRecords) > 0 {
fmt.Println()
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("Feed these private zone A records into nmap and something like gowitness or aquatone."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Feed these private zone A records into nmap and something like gowitness or aquatone."))
fmt.Print(route53APrivateRecords)
fmt.Printf("[%s] %s \n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), route53ARecordsPrivateZonesFileName)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), route53ARecordsPrivateZonesFileName)
}
+8 -8
View File
@@ -49,15 +49,15 @@ func (m *SecretsModule) PrintSecrets(outputFormat string, outputDirectory string
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "secrets"
m.modLog = utils.TxtLogger.WithFields(logrus.Fields{
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s] Enumerating secrets for account %s.\n", cyan(m.output.CallingModule), aws.ToString(m.Caller.Account))
fmt.Printf("[%s] Supported Services: SecretsManager, SSM Parameters\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] Enumerating secrets for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), aws.ToString(m.Caller.Account))
fmt.Printf("[%s][%s] Supported Services: SecretsManager, SSM Parameters\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
wg := new(sync.WaitGroup)
semaphore := make(chan struct{}, m.Goroutines)
@@ -116,10 +116,10 @@ func (m *SecretsModule) PrintSecrets(outputFormat string, outputDirectory string
//m.output.OutputSelector(outputFormat)
utils.OutputSelector(m.output.Verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s] %s secrets found.\n", cyan(m.output.CallingModule), strconv.Itoa(len(m.output.Body)))
fmt.Printf("[%s][%s] %s secrets found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
} else {
fmt.Printf("[%s] No secrets found, skipping the creation of an output file.\n", cyan(m.output.CallingModule))
fmt.Printf("[%s][%s] No secrets found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
@@ -183,13 +183,13 @@ func (m *SecretsModule) writeLoot(outputDirectory string, verbosity int) {
if verbosity > 2 {
fmt.Println()
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("Use the commands below to retrieve the secrets that look interesting"))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("Use the commands below to retrieve the secrets that look interesting"))
fmt.Print(out)
fmt.Printf("[%s] %s \n\n", cyan(m.output.CallingModule), green("End of loot file."))
fmt.Printf("[%s][%s] %s \n\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), green("End of loot file."))
}
fmt.Printf("[%s] Loot written to [%s]\n", cyan(m.output.CallingModule), pullFile)
fmt.Printf("[%s][%s] Loot written to [%s]\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), pullFile)
}
+270
View File
@@ -0,0 +1,270 @@
package aws
import (
"context"
"fmt"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/BishopFox/cloudfox/console"
"github.com/BishopFox/cloudfox/utils"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/sirupsen/logrus"
)
type TagsModule struct {
// General configuration data
ResourceGroupsTaggingApiClient *resourcegroupstaggingapi.Client
Caller sts.GetCallerIdentityOutput
AWSRegions []string
OutputFormat string
Goroutines int
AWSProfile string
// Main module data
Tags []Tag
CommandCounter console.CommandCounter
ResourceTypeCounts map[string]int
// Used to store output data for pretty printing
output utils.OutputData2
modLog *logrus.Entry
}
type Tag struct {
AWSService string
Region string
Arn string
Name string
Type string
Key string
Value string
}
func (m *TagsModule) PrintTags(outputFormat string, outputDirectory string, verbosity int) {
// These stuct values are used by the output module
m.output.Verbosity = verbosity
m.output.Directory = outputDirectory
m.output.CallingModule = "tags"
m.modLog = utils.TxtLog.WithFields(logrus.Fields{
"module": m.output.CallingModule,
})
if m.AWSProfile == "" {
m.AWSProfile = utils.BuildAWSPath(m.Caller)
}
fmt.Printf("[%s][%s] Enumerating tags for account %s.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), 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 console.SpinUntil(m.output.CallingModule, &m.CommandCounter, spinnerDone, "regions")
//create a channel to receive the objects
dataReceiver := make(chan Tag)
// 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{
"Service",
"Region",
"Type",
//"Name",
//"Resource Arn",
"Key",
"Value",
}
sort.Slice(m.Tags, func(i, j int) bool {
return m.Tags[i].AWSService < m.Tags[j].AWSService
})
// Table rows
for i := range m.Tags {
m.output.Body = append(
m.output.Body,
[]string{
m.Tags[i].AWSService,
m.Tags[i].Region,
m.Tags[i].Type,
//m.Tags[i].Arn,
//m.Tags[i].Name,
m.Tags[i].Key,
m.Tags[i].Value,
},
)
}
if len(m.output.Body) > 0 {
m.output.FilePath = filepath.Join(outputDirectory, "cloudfox-output", "aws", m.AWSProfile)
utils.OutputSelector(verbosity, outputFormat, m.output.Headers, m.output.Body, m.output.FilePath, m.output.CallingModule, m.output.CallingModule)
//m.writeLoot(m.output.FilePath, verbosity)
fmt.Printf("[%s][%s] %s tags found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), strconv.Itoa(len(m.output.Body)))
count := m.countUniqueResourcesWithTags()
fmt.Printf("[%s][%s] %d unique resources with tags found.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile), count)
} else {
fmt.Printf("[%s][%s] No tags found, skipping the creation of an output file.\n", cyan(m.output.CallingModule), cyan(m.AWSProfile))
}
}
func (m *TagsModule) countUniqueResourcesWithTags() int {
var uniqueResources []string
for i := range m.Tags {
if !utils.Contains(m.Tags[i].Name, uniqueResources) {
uniqueResources = append(uniqueResources, m.Tags[i].Name)
}
}
//
return len(uniqueResources)
}
// TODO: Make summary table
// func (m *TagsModule) createTagsSummary() {
// var serviceMap map[string]map[string]int
// // var services []string
// // var totalRegionCounts map[string]int
// var uniqueResources []string
// var uniqueServiceTypes []string
// for i := range m.Tags {
// if !utils.Contains(m.Tags[i].Name, uniqueResources) {
// uniqueResources = append(uniqueResources, m.serviceMap[m.Tags[i].Name][m.])
// }
// if !utils.Contains(fmt.Sprintf("%s %s", m.Tags[i].AWSService, m.Tags[i].Type), uniqueServiceTypes) {
// uniqueServiceTypes = append(uniqueServiceTypes, fmt.Sprintf("%s %s", m.Tags[i].AWSService, m.Tags[i].Type))
// }
// }
// for j, resource := range uniqueResources {
// for k, ServiceType := range uniqueServiceTypes {
// if fmt.Sprintf("%s %s", resource[j].AWSService, m.Tags[i].Type). == ServiceType[k]
// }
// }
// }
func (m *TagsModule) executeChecks(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Tag) {
defer wg.Done()
m.CommandCounter.Total++
wg.Add(1)
m.getTagsPerRegion(r, wg, semaphore, dataReceiver)
}
func (m *TagsModule) Receiver(receiver chan Tag, receiverDone chan bool) {
defer close(receiverDone)
for {
select {
case data := <-receiver:
m.Tags = append(m.Tags, data)
case <-receiverDone:
receiverDone <- true
return
}
}
}
func (m *TagsModule) getTagsPerRegion(r string, wg *sync.WaitGroup, semaphore chan struct{}, dataReceiver chan Tag) {
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
for {
GetResources, err := m.ResourceGroupsTaggingApiClient.GetResources(
context.TODO(),
&resourcegroupstaggingapi.GetResourcesInput{
PaginationToken: PaginationControl,
},
func(o *resourcegroupstaggingapi.Options) {
o.Region = r
},
)
if err != nil {
m.modLog.Error(err.Error())
m.CommandCounter.Error++
break
}
//var parsedArn types.Arn
for _, resource := range GetResources.ResourceTagMappingList {
var resourceType string
resourceArn := aws.ToString(resource.ResourceARN)
parsedArn, err := arn.Parse(resourceArn)
if parsedArn.Service != "s3" {
resourceType = strings.Split(parsedArn.Resource, ":")[0]
resourceType = strings.Split(resourceType, "/")[0]
} else {
resourceType = "bucket"
}
//resourceName := strings.Split(parsedArn.Resource, ":")[]
if err != nil {
break
}
for _, tag := range resource.Tags {
key := aws.ToString(tag.Key)
value := aws.ToString(tag.Value)
dataReceiver <- Tag{
AWSService: parsedArn.Service,
Arn: resourceArn,
Name: parsedArn.Resource,
Region: r,
Type: resourceType,
Key: key,
Value: value,
}
}
}
if aws.ToString(GetResources.PaginationToken) != "" {
PaginationControl = GetResources.PaginationToken
} else {
PaginationControl = nil
break
}
}
}
+488 -329
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -37,6 +37,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/ram v1.16.15
github.com/aws/aws-sdk-go-v2/service/rds v1.16.0
github.com/aws/aws-sdk-go-v2/service/redshift v1.25.0
github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.13.19
github.com/aws/aws-sdk-go-v2/service/route53 v1.20.5
github.com/aws/aws-sdk-go-v2/service/s3 v1.24.0
github.com/aws/aws-sdk-go-v2/service/sagemaker v1.32.1
+2
View File
@@ -162,6 +162,8 @@ github.com/aws/aws-sdk-go-v2/service/rds v1.16.0 h1:xYxIpmqlnc+U/miylJaNmEty34MC
github.com/aws/aws-sdk-go-v2/service/rds v1.16.0/go.mod h1:U1tzFmWLyt4AqSRLONL0RXcYsQg0huiInDdRmCecz1w=
github.com/aws/aws-sdk-go-v2/service/redshift v1.25.0 h1:sD7lJ9EchUyaZXjXyBtK0TwaGULzTmtV1xo+wrNT6hw=
github.com/aws/aws-sdk-go-v2/service/redshift v1.25.0/go.mod h1:7vdpNDFFcV8yDaDTPpwy5wv28w1815yVJxHaCX4hmmM=
github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.13.19 h1:1KQhU01IDvg4fohFIBGlITT4OM/Q99QY6FRj23M1MUg=
github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.13.19/go.mod h1:tTgBdzibiIxq4r4+ZopTWLk4rh9U5imMsdKPALItjH8=
github.com/aws/aws-sdk-go-v2/service/route53 v1.20.5 h1:Vex6D07/CmahT0LIaiRk+j9xyVAsvQxBa8iv38p3Ajc=
github.com/aws/aws-sdk-go-v2/service/route53 v1.20.5/go.mod h1:QZWV7sxHUg/qsPJcAtAI9JyLPKZ78weHmdILmYMCqEE=
github.com/aws/aws-sdk-go-v2/service/s3 v1.24.0 h1:REKac2iT0HYxUSzqOSuncnmsZnE3m4MlGfo1dOUN3vg=
+1 -1
View File
@@ -11,7 +11,7 @@ import (
var (
rootCmd = &cobra.Command{
Use: os.Args[0],
Version: "1.7.2",
Version: "1.8.0",
}
)
+8 -3
View File
@@ -5,7 +5,9 @@
"Action": [
"apigateway:GET",
"apprunner:DescribeService",
"apprunner:ListServices",
"apprunner:ListServices",
"cloudformation:DescribeStacks",
"cloudformation:GetTemplate",
"cloudformation:ListStacks",
"cloudtrail:LookupEvents",
"cloudfront:ListDistributions",
@@ -44,6 +46,8 @@
"mq:ListBrokers",
"es:DescribeDomain",
"es:ListDomainNames",
"ram:GetResourceShares",
"ram:ListResources",
"rds:DescribeDBInstances",
"redshift:DescribeClusters",
"route53:ListHostedZones",
@@ -62,12 +66,13 @@
"sagemaker:DescribeModel",
"secretsmanager:ListSecrets",
"sns:ListTopics",
"sqs:ListQueues"
"sqs:ListQueues",
"tag:GetResources"
],
"Resource": "*",
"Effect": "Allow",
"Sid": "AllowMoreReadForCloudFox171"
"Sid": "AllowMoreReadForCloudFox180"
}
]
}
+42 -34
View File
@@ -20,7 +20,7 @@ import (
var (
TxtLoggerName = "root"
TxtLogger = txtLogger()
TxtLog = TxtLogger()
UtilsFs = afero.NewOsFs()
)
@@ -32,13 +32,13 @@ func AWSConfigFileLoader(AWSProfile string, version string) aws.Config {
}))
if err != nil {
fmt.Println(err)
TxtLogger.Println(err)
TxtLog.Println(err)
}
_, err = cfg.Credentials.Retrieve(context.TODO())
if err != nil {
fmt.Printf("[%s] Error retrieving credentials from the [%s] profile, environment variables, or the instance metadata service.\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)), AWSProfile)
TxtLogger.Printf("Could not retrieve the specified profile name %s", err)
fmt.Printf("[%s][%s] Error retrieving credentials from environment variables, or the instance metadata service.\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)), cyan(AWSProfile))
TxtLog.Printf("Could not retrieve the specified profile name %s", err)
}
return cfg
@@ -50,8 +50,8 @@ func AWSWhoami(awsProfile string, version string) (*sts.GetCallerIdentityOutput,
STSService := sts.NewFromConfig(AWSConfigFileLoader(awsProfile, version))
CallerIdentity, err := STSService.GetCallerIdentity(context.TODO(), &sts.GetCallerIdentityInput{})
if err != nil {
fmt.Printf("[%s] Could not get caller's identity for the [%s] profile\n\nError: %s\n\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)), awsProfile, err)
TxtLogger.Printf("Could not get caller's identity: %s", err)
fmt.Printf("[%s][%s] Could not get caller's identity\n\nError: %s\n\n", cyan(emoji.Sprintf(":fox:cloudfox v%s :fox:", version)), cyan(awsProfile), err)
TxtLog.Printf("Could not get caller's identity: %s", err)
return CallerIdentity, err
}
@@ -93,7 +93,7 @@ func AWSWhoami(awsProfile string, version string) (*sts.GetCallerIdentityOutput,
// }
// txtLogger - Returns the txt logger
func txtLogger() *logrus.Logger {
func TxtLogger() *logrus.Logger {
txtLogger := logrus.New()
txtFile, err := os.OpenFile(fmt.Sprintf("%s/cloudfox-error.log", ptr.ToString(GetLogDirPath())), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
@@ -108,42 +108,46 @@ func txtLogger() *logrus.Logger {
func CheckErr(e error, msg string) {
if e != nil {
TxtLogger.Printf("[-] Error %s", msg)
TxtLog.Printf("[-] Error %s", msg)
}
}
func GetAllAWSProfiles(AWSConfirm bool) []string {
var AWSProfiles []string
credentialsFile, err := UtilsFs.Open(config.DefaultSharedCredentialsFilename())
CheckErr(err, "could not open default AWS credentials file")
defer credentialsFile.Close()
configFile, err := UtilsFs.Open(config.DefaultSharedConfigFilename())
CheckErr(err, "could not open default AWS credentials file")
defer configFile.Close()
var AWSProfiles []string
scanner := bufio.NewScanner(credentialsFile)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
text = strings.TrimPrefix(text, "[")
text = strings.TrimSuffix(text, "]")
if !Contains(text, AWSProfiles) {
AWSProfiles = append(AWSProfiles, text)
if err == nil {
defer credentialsFile.Close()
scanner := bufio.NewScanner(credentialsFile)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
text = strings.TrimPrefix(text, "[")
text = strings.TrimSuffix(text, "]")
if !Contains(text, AWSProfiles) {
AWSProfiles = append(AWSProfiles, text)
}
}
}
}
scanner2 := bufio.NewScanner(configFile)
scanner2.Split(bufio.ScanLines)
for scanner2.Scan() {
text := strings.TrimSpace(scanner2.Text())
if strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
text = strings.TrimPrefix(text, "[profile ")
text = strings.TrimPrefix(text, "[")
text = strings.TrimSuffix(text, "]")
if !Contains(text, AWSProfiles) {
AWSProfiles = append(AWSProfiles, text)
configFile, err := UtilsFs.Open(config.DefaultSharedConfigFilename())
CheckErr(err, "could not open default AWS credentials file")
if err == nil {
defer configFile.Close()
scanner2 := bufio.NewScanner(configFile)
scanner2.Split(bufio.ScanLines)
for scanner2.Scan() {
text := strings.TrimSpace(scanner2.Text())
if strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
text = strings.TrimPrefix(text, "[profile ")
text = strings.TrimPrefix(text, "[")
text = strings.TrimSuffix(text, "]")
if !Contains(text, AWSProfiles) {
AWSProfiles = append(AWSProfiles, text)
}
}
}
}
@@ -177,6 +181,10 @@ func ConfirmSelectedProfiles(AWSProfiles []string) bool {
func GetSelectedAWSProfiles(AWSProfilesListPath string) []string {
AWSProfilesListFile, err := UtilsFs.Open(AWSProfilesListPath)
CheckErr(err, fmt.Sprintf("could not open given file %s", AWSProfilesListPath))
if err != nil {
fmt.Printf("\nError loading profiles. Could not open file at location[%s]\n", AWSProfilesListPath)
os.Exit(1)
}
defer AWSProfilesListFile.Close()
var AWSProfiles []string
scanner := bufio.NewScanner(AWSProfilesListFile)