diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2234bf1 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,46 @@ +name: Release binaries + +on: + release: + types: [created] + +jobs: + amd64-releases-matrix: + name: Release Go Binary (amd64) + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, windows, darwin] + goarch: [amd64] + steps: + - uses: actions/checkout@v2 + - uses: wangyoucao577/go-release-action@v1.16 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + goversion: "https://dl.google.com/go/go1.17.5.linux-amd64.tar.gz" + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + project_path: "." + binary_name: "cleanup-aws-access-keys" + ldflags: "-s -w" + extra_files: LICENSE README.md + + arm64-releases-matrix: + name: Release Go Binary (arm64) + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, darwin] + goarch: [arm64] + steps: + - uses: actions/checkout@v2 + - uses: wangyoucao577/go-release-action@v1.16 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + goversion: "https://dl.google.com/go/go1.17.5.linux-amd64.tar.gz" + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + project_path: "." + binary_name: "cleanup-aws-access-keys" + ldflags: "-s -w" + extra_files: LICENSE README.md diff --git a/LICENSE b/LICENSE index 6651f0b..fab4486 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 Puru +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index cff2567..59818a7 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,111 @@ # cleanup-aws-access-keys -A cloud security tool to clean up AWS access keys. +A cloud security tool to search and clean up unused AWS access keys, written in Go. + +## Features: +* Find unused access keys (e.g: access keys unused for more than 90 days, access keys created both never used) +* Deactivate/activate access keys easily based on search criteria. +* Delete access keys based on search criteria. +* Auto-approve flag to run non-interactively (e.g: a cron job to deactivate access keys unused for more 90 days) + +## What is an AWS access keys? +* Access keys are long-term credentials for an IAM user or the AWS account root user. +* You can use access keys to make programmatic calls to AWS via AWS CLI, AWS SDKs, or direct AWS API calls. +* An IAM user is only allowed to have maximum of two access keys (active or inactive) at a time. +* Access keys consist of two parts: an access key ID (e.g: `AKIAIOSFODNN7EXAMPLE`) and a secret access key (e.g: `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`). Like a user name and password, you must use both the access key ID and secret access key together to authenticate your requests. Manage your access keys as securely as you do your user name and password. +* If you lose or forget your secret key, you cannot retrieve it. Instead, create a new access key and make the old key inactive and delete it. + + +> **Warning:** Never post your secret access key on public platforms, such as GitHub. This can compromise your account security. As a best practice, it's recommended to rotate your keys frequently. + +> __Best Practices:__ Use temporary security credentials (IAM roles) instead of access keys, and disable any AWS account root user access keys. For more information, see [Best Practices for Managing AWS Access Keys](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) in the Amazon Web Services General Reference. + +[Learn more about AWS access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html?icmpid=docs_iam_console) + +## Usage: +``` +$ ./cleanup-aws-access-keys +A cloud security tool to search and clean up unused AWS access keys (https://github.com/tuladhar/cleanup-aws-access-keys) + +Usage: + cleanup-aws-access-keys [command] + +Available Commands: + activate Activate access key(s) + completion Generate the autocompletion script for the specified shell + deactivate Deactivate access key(s) + delete Delete access key(s) + help Help about any command + search Search for access key(s) + +Flags: + -h, --help help for cleanup-aws-access-keys + -v, --version version for cleanup-aws-access-keys + +Use "cleanup-aws-access-keys [command] --help" for more information about a command. +``` + +## Examples: + +Search for active access keys unused for more than 90 days. +``` +./cleanup-aws-access-keys search --last-used 90 --status active +``` + +Search for access keys created but never used. +``` +./cleanup-aws-access-keys search --last-used -1 +``` + +Search for inactive access keys. +``` +./cleanup-aws-access-keys search --status inactive +``` + +Deactivate access keys unused for more than 90 days. +``` +./cleanup-aws-access-keys deactivate --last-used 90 +``` +> Hint: Use `--auto-approve` flag to skip interactive prompt. + +Deactivate access keys of specific username. +``` +./cleanup-aws-access-keys deactivate --username jeff.bezos +``` + +Delete access keys unused for more than 180 days. +``` +./cleanup-aws-access-keys delete --last-used 180 +``` + +Delete inactive access keys of specific username. +``` +./cleanup-aws-access-keys delete --status inactive --username jeff.bezos +``` + +## Installation +Binary is available for Linux, Windows and Mac OS (amd64 and arm64). Download the binary for your respective platform from the [releases page](https://github.com/tuladhar/cleanup-aws-access-keys/releases). + +### Linux: +``` +``` + +## Development +If you wish to contribute or compile from source code, you'll first need Go installed on your machine. Go version [Go v.1.9](https://go.dev/dl/)+ is required. + +- Clone the repository +``` +git clone https://github.com/tuladhar/cleanup-aws-access-keys +``` +- Add missing modules +``` +go mod tidy +``` +- Modify the code, and build the binary or run directly +``` +go run main.go +// or +go build +``` + +## Author +* Puru Tuladhar (https://github.com/tuladhar) \ No newline at end of file diff --git a/cmd/activate.go b/cmd/activate.go new file mode 100644 index 0000000..02fafce --- /dev/null +++ b/cmd/activate.go @@ -0,0 +1,81 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package cmd + +import ( + "fmt" + "context" + + "github.com/aws/aws-sdk-go-v2/service/iam" + "github.com/aws/aws-sdk-go-v2/service/iam/types" + + "github.com/spf13/cobra" +) + +func activateKeys() { + var n int + for _, d := range state.TableData { + _, err := client.UpdateAccessKey(context.TODO(), &iam.UpdateAccessKeyInput{ + UserName: &d[0], + AccessKeyId: &d[1], + Status: types.StatusTypeInactive, + }) + if err != nil { + fmt.Printf("Unable to activate access key %s for username %s: %s\n", d[1], d[0], err) + continue + } + n += 1 + } + fmt.Printf("\nSuccessfully activated %d access key(s).\n", n) +} + +// activateCmd represents the activate command +var activateCmd = &cobra.Command{ + Use: "activate", + Short: "Activate access key(s)", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + flags.Status = "inactive" + SearchKeys() + + if !flags.AutoApprove { + fmt.Println() + fmt.Printf("Are you sure you want to ACTIVATE %d access key(s)?\n", len(state.TableData)) + if AskApproval() { + activateKeys() + } + } else { + activateKeys() + } + }, +} + +func init() { + rootCmd.AddCommand(activateCmd) + + activateCmd.Flags().IntVarP(&flags.LastUsed, "last-used", "", 0, "access key was last used n days.") + activateCmd.Flags().StringVarP(&flags.Username, "username", "", "", "access key owned by username") + activateCmd.Flags().StringVarP(&flags.Status, "status", "", "", "access key status: active or inactive") + activateCmd.Flags().BoolVarP(&flags.AutoApprove, "auto-approve", "", false, "automatic yes to prompts and run non-interactively.") +} diff --git a/cmd/deactivate.go b/cmd/deactivate.go new file mode 100644 index 0000000..44dc9fb --- /dev/null +++ b/cmd/deactivate.go @@ -0,0 +1,82 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package cmd + +import ( + "fmt" + "context" + + "github.com/aws/aws-sdk-go-v2/service/iam" + "github.com/aws/aws-sdk-go-v2/service/iam/types" + + "github.com/spf13/cobra" +) + +func deactivateKeys() { + var n int + for _, d := range state.TableData { + _, err := client.UpdateAccessKey(context.TODO(), &iam.UpdateAccessKeyInput{ + UserName: &d[0], + AccessKeyId: &d[1], + Status: types.StatusTypeInactive, + }) + if err != nil { + fmt.Printf("Unable to deactivate access key %s for username %s: %s\n", d[1], d[0], err) + continue + } + n += 1 + } + fmt.Printf("\nSuccessfully deactivated %d access key(s).\n", n) +} + +// deactivateCmd represents the deactivate command +var deactivateCmd = &cobra.Command{ + Use: "deactivate", + Short: "Deactivate access key(s)", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + flags.Status = "active" + SearchKeys() + + if !flags.AutoApprove { + fmt.Println() + fmt.Printf("Are you sure you want to DEACTIVATE %d access key(s)?\n", len(state.TableData)) + fmt.Printf("WARNING: You can't use a disabled key to make AWS API calls but you can activate it again later.\n") + if AskApproval() { + deactivateKeys() + } + } else { + deactivateKeys() + } + }, +} + +func init() { + rootCmd.AddCommand(deactivateCmd) + + deactivateCmd.Flags().IntVarP(&flags.LastUsed, "last-used", "", 0, "access key was last used n days.") + deactivateCmd.Flags().StringVarP(&flags.Username, "username", "", "", "access key owned by username") + deactivateCmd.Flags().StringVarP(&flags.Status, "status", "", "", "access key status: active or inactive") + deactivateCmd.Flags().BoolVarP(&flags.AutoApprove, "auto-approve", "", false, "automatic yes to prompts and run non-interactively.") +} diff --git a/cmd/delete.go b/cmd/delete.go new file mode 100644 index 0000000..a279012 --- /dev/null +++ b/cmd/delete.go @@ -0,0 +1,80 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package cmd + +import ( + "fmt" + "context" + + "github.com/aws/aws-sdk-go-v2/service/iam" + + "github.com/spf13/cobra" +) + +func deleteKeys() { + var n int + for _, d := range state.TableData { + _, err := client.DeleteAccessKey(context.TODO(), &iam.DeleteAccessKeyInput{ + UserName: &d[0], + AccessKeyId: &d[1], + }) + if err != nil { + fmt.Printf("Unable to delete access key %s for username %s: %s\n", d[1], d[0], err) + continue + } + n += 1 + } + fmt.Printf("\nSuccessfully deleted %d access key(s).\n", n) +} + +// deleteCmd represents the delete command +var deleteCmd = &cobra.Command{ + Use: "delete", + Short: "Delete access key(s)", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + SearchKeys() + + if !flags.AutoApprove { + fmt.Println() + fmt.Printf("Are you sure you want to DELETE %d access key(s)?\n", len(state.TableData)) + fmt.Printf("NOTE: AWS recommends that you analyze the impact of deactivating the access key before permanently deleting it.\n") + fmt.Printf("WARNING: Any AWS API call made using this key will fail. You cannot recover an access key after you delete it.\n") + if AskApproval() { + deleteKeys() + } + } else { + deleteKeys() + } + }, +} + +func init() { + rootCmd.AddCommand(deleteCmd) + + deleteCmd.Flags().IntVarP(&flags.LastUsed, "last-used", "", 0, "access key was last used n days.") + deleteCmd.Flags().StringVarP(&flags.Username, "username", "", "", "access key owned by username") + deleteCmd.Flags().StringVarP(&flags.Status, "status", "", "", "access key status: active or inactive") + deleteCmd.Flags().BoolVarP(&flags.AutoApprove, "auto-approve", "", false, "automatic yes to prompts and run non-interactively.") +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..67b7ec8 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,96 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package cmd + +import ( + "os" + "fmt" + "context" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/iam" + "github.com/aws/aws-sdk-go-v2/config" + + "github.com/spf13/cobra" +) + +type Flags struct { + AutoApprove bool + Status string + LastUsed int + Username string +} + +const ( + GITHUB_URL = "https://github.com/tuladhar/cleanup-aws-access-keys" +) + +type State struct { + TableData [][]string +} + +var ( + flags = Flags{} + client *iam.Client + state = &State{} +) + +func AskApproval() bool { + var answer string + for { + fmt.Printf("Proceed? (yes/no): ") + fmt.Scanln(&answer) + switch answer { + case "no": + return false + case "yes": + return true + default: + fmt.Println("Please type 'yes' or 'no'.") + } + } +} + +func LoadConfigOrDie() (aws.Config) { + config, err := config.LoadDefaultConfig(context.TODO()) + if err != nil { + fmt.Println(err) + os.Exit(-1) + } + return config +} + +var rootCmd = &cobra.Command{ + Use: "cleanup-aws-access-keys", + Version: "1.0", + Short: fmt.Sprintf("A cloud security tool to search and clean up unused AWS access keys (%s)\n", GITHUB_URL), + Long: ``, +} + +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} diff --git a/cmd/search.go b/cmd/search.go new file mode 100644 index 0000000..47a0130 --- /dev/null +++ b/cmd/search.go @@ -0,0 +1,176 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package cmd + +import ( + "os" + "fmt" + "log" + "time" + "context" + "strings" + + "github.com/spf13/cobra" + + "github.com/aws/aws-sdk-go-v2/service/iam" + "github.com/aws/aws-sdk-go-v2/aws" + + "github.com/olekukonko/tablewriter" +) + +func SearchKeys() { + today := time.Now() + fmt.Printf("Starting %s v%s (%s) at %s\n", rootCmd.Use, rootCmd.Version, GITHUB_URL, today.Format(time.UnixDate)) + + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"UserName", "Access Key ID", "Last Used", "Last Service Used", "Region", "Status"}) + + // Load AWS config + config := LoadConfigOrDie() + + // Create an Amazon IAM service client + client = iam.NewFromConfig(config) + + // Use paginator in case there are more than 100 users + paginator := iam.NewListUsersPaginator(client, &iam.ListUsersInput{}) + + // Loop until paginator has no more data + for { + page, err := paginator.NextPage(context.TODO()) + if err != nil { + log.Fatal(err) + } + + usernameFound := false + for _, user := range page.Users { + // Skip if --username flag is set, and doesn't match the IAM user + if flags.Username != "" && *user.UserName != flags.Username { + continue + } + + // Fetch access keys filter by username + keys, err := client.ListAccessKeys(context.TODO(), &iam.ListAccessKeysInput{ + UserName: user.UserName, + }) + if err != nil { + log.Fatal(err) + } + + // Loop through each access keys + for _, m := range keys.AccessKeyMetadata { + status := strings.ToLower(fmt.Sprintf("%s", m.Status)) + + // Skip if --status flag is set, and doesn't match the key status + if flags.Status != "" && status != flags.Status { + continue + } + + // Request when was the last used date of access keys + lu, err := client.GetAccessKeyLastUsed(context.TODO(), &iam.GetAccessKeyLastUsedInput{ + AccessKeyId: m.AccessKeyId, + }) + if err != nil { + log.Print(err) + continue + } + + luDate := lu.AccessKeyLastUsed.LastUsedDate + luServiceName := aws.ToString(lu.AccessKeyLastUsed.ServiceName) + luRegion := aws.ToString(lu.AccessKeyLastUsed.Region) + luInDays := 0 + luDateHuman := "N/A" + + // Calculate how many days ago the access keys was last accessed relatively to today + if luDate != nil { + luInDays = int(today.Sub(*luDate).Hours() / 24) + if luInDays == 0 { + luDateHuman = fmt.Sprintf("today", ) + } else { + luDateHuman = fmt.Sprintf("%d days ago", luInDays) + } + } + + // Skip if --last-used N days is out of bound + if luInDays < flags.LastUsed { + continue + } + + // If --last-used flag is set to -1 then skip used access keys + if flags.LastUsed == -1 && luDate != nil { + continue + } + + // Populate the table to be later rendered as such: + // +---------------+----------------------+---------------+-------------------+-----------+----------+ + // | USERNAME | ACCESS KEY ID | LAST USED | LAST SERVICE USED | REGION | STATUS | + // +---------------+----------------------+---------------+-------------------+-----------+----------+ + // | devops | AKIAYD7BEQCFXIKIPU49 | N/A | N/A | N/A | inactive | + // | tuladhar.puru | AKIAYR7BEQCFXIKYPU40 | 180 days ago | sts | us-east-1 | active | + // | puru.tuladhar | AKIAK7UAUHHZ29ZNEEHQ | today | s3 | eu-west-1 | active | + // +---------------+----------------------+---------------+-------------------+-----------+----------+ + data := []string{aws.ToString(m.UserName), aws.ToString(m.AccessKeyId), luDateHuman, luServiceName, luRegion, status} + state.TableData = append(state.TableData, data) + table.Append(data) + } + + // Break out of loop if --username flag condition is met + if flags.Username != "" && *user.UserName == flags.Username { + usernameFound = true + break + } + } + // Break out of loop if --username flag condition is met + // or no more users left to paginate. + if usernameFound || !paginator.HasMorePages() { + break + } + } + + // Render the table if there's table data + fmt.Println() + if len(state.TableData) != 0 { + table.Render() + } else { + fmt.Printf("No access key(s) found.\n") + os.Exit(0) + } +} + +// searchCmd represents the search command +var searchCmd = &cobra.Command{ + Use: "search", + Short: "Search for access key(s)", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + SearchKeys() + }, +} + +func init() { + rootCmd.AddCommand(searchCmd) + + searchCmd.Flags().IntVarP(&flags.LastUsed, "last-used", "", 0, "access key was last used n days.") + searchCmd.Flags().StringVarP(&flags.Username, "username", "", "", "access key owned by username") + searchCmd.Flags().StringVarP(&flags.Status, "status", "", "", "access key status: active or inactive") +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c487310 --- /dev/null +++ b/go.mod @@ -0,0 +1,26 @@ +module github.com/tuladhar/cleanup-aws-access-keys + +go 1.19 + +require ( + github.com/aws/aws-sdk-go-v2 v1.16.11 + github.com/aws/aws-sdk-go-v2/config v1.17.1 + github.com/aws/aws-sdk-go-v2/service/iam v1.18.14 + github.com/olekukonko/tablewriter v0.0.5 + github.com/spf13/cobra v1.5.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/credentials v1.12.14 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.11.17 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.16.13 // indirect + github.com/aws/smithy-go v1.12.1 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/mattn/go-runewidth v0.0.9 // indirect + github.com/spf13/pflag v1.0.5 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..225cc7d --- /dev/null +++ b/go.sum @@ -0,0 +1,46 @@ +github.com/aws/aws-sdk-go-v2 v1.16.11 h1:xM1ZPSvty3xVmdxiGr7ay/wlqv+MWhH0rMlyLdbC0YQ= +github.com/aws/aws-sdk-go-v2 v1.16.11/go.mod h1:WTACcleLz6VZTp7fak4EO5b9Q4foxbn+8PIz3PmyKlo= +github.com/aws/aws-sdk-go-v2/config v1.17.1 h1:BWxTjokU/69BZ4DnLrZco6OvBDii6ToEdfBL/y5I1nA= +github.com/aws/aws-sdk-go-v2/config v1.17.1/go.mod h1:uOxDHjBemNTF2Zos+fgG0NNfE86wn1OAHDTGxjMEYi0= +github.com/aws/aws-sdk-go-v2/credentials v1.12.14 h1:AtVG/amkjbDBfnPr/tuW2IG18HGNznP6L12Dx0rLz+Q= +github.com/aws/aws-sdk-go-v2/credentials v1.12.14/go.mod h1:opAndTyq+YN7IpVG57z2CeNuXSQMqTYxGGlYH0m0RMY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12 h1:wgJBHO58Pc1V1QAnzdVM3JK3WbE/6eUF0JxCZ+/izz0= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.12/go.mod h1:aZ4vZnyUuxedC7eD4JyEHpGnCz+O2sHQEx3VvAwklSE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18 h1:OmiwoVyLKEqqD5GvB683dbSqxiOfvx4U2lDZhG2Esc4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.18/go.mod h1:348MLhzV1GSlZSMusdwQpXKbhD7X2gbI/TxwAPKkYZQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12 h1:5mvQDtNWtI6H56+E4LUnLWEmATMB7oEh+Z9RurtIuC0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.12/go.mod h1:ckaCVTEdGAxO6KwTGzgskxR1xM+iJW4lxMyDFVda2Fc= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19 h1:g5qq9sgtEzt2szMaDqQO6fqKe026T6dHTFJp5NsPzkQ= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.19/go.mod h1:cVHo8KTuHjShb9V8/VjH3S/8+xPu16qx8fdGwmotJhE= +github.com/aws/aws-sdk-go-v2/service/iam v1.18.14 h1:fpJ1z4MmjJKM3R3zTzRXGiGy4BZ5g+WDnI4AvYfxjrM= +github.com/aws/aws-sdk-go-v2/service/iam v1.18.14/go.mod h1:NbePPNB+2DP+zRdJZ2W+VkiVLElulc7rEKv23/D0mdA= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12 h1:7iPTTX4SAI2U2VOogD7/gmHlsgnYSgoNHt7MSQXtG2M= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.12/go.mod h1:1TODGhheLWjpQWSuhYuAUWYTCKwEjx2iblIFKDHjeTc= +github.com/aws/aws-sdk-go-v2/service/sso v1.11.17 h1:pXxu9u2z1UqSbjO9YA8kmFJBhFc1EVTDaf7A+S+Ivq8= +github.com/aws/aws-sdk-go-v2/service/sso v1.11.17/go.mod h1:mS5xqLZc/6kc06IpXn5vRxdLaED+jEuaSRv5BxtnsiY= +github.com/aws/aws-sdk-go-v2/service/sts v1.16.13 h1:dl8T0PJlN92rvEGOEUiD0+YPYdPEaCZK0TqHukvSfII= +github.com/aws/aws-sdk-go-v2/service/sts v1.16.13/go.mod h1:Ru3QVMLygVs/07UQ3YDur1AQZZp2tUNje8wfloFttC0= +github.com/aws/smithy-go v1.12.1 h1:yQRC55aXN/y1W10HgwHle01DRuV9Dpf31iGkotjt3Ag= +github.com/aws/smithy-go v1.12.1/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= +github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/main.go b/main.go new file mode 100644 index 0000000..c852617 --- /dev/null +++ b/main.go @@ -0,0 +1,30 @@ +/* +MIT License + +Copyright (c) 2022 Puru Tuladhar (ptuladhar3@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +package main + +import "github.com/tuladhar/cleanup-aws-access-keys/cmd" + +func main() { + cmd.Execute() +}