├── IAMAccount.template ├── LICENSE ├── ManagedAccount.template ├── README.md ├── go.mod ├── go.sum ├── mac.go ├── releases ├── mac └── mac.exe └── s3_public_acls_finder.py /IAMAccount.template: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Description": "Provisions the IAM Account with the groups, policies, and roles needed.", 4 | "Parameters" : { 5 | "IAMUser" : { 6 | "Type" : "String", 7 | "Default" : "IAMUser", 8 | "Description" : "Add one IAM user to admin group." 9 | }, 10 | "ManagedAccount" : { 11 | "Type" : "String", 12 | "Default" : "111111111111", 13 | "Description" : "Define One Managed Account number." 14 | }, 15 | "Prefix" : { 16 | "Type" : "String", 17 | "Default" : "mac", 18 | "Description" : "Enter the prefix for the service role." 19 | } 20 | }, 21 | "Resources": { 22 | "MacGroup": { 23 | "Type": "AWS::IAM::Group", 24 | "Properties": { 25 | "GroupName": { 26 | "Fn::Join": [ 27 | "-", [ 28 | { 29 | "Ref": "Prefix" 30 | }, 31 | "admins" 32 | ] 33 | ] 34 | }, 35 | "Path": "/", 36 | "Policies" : [ { 37 | "PolicyName": { 38 | "Fn::Join": [ 39 | "-", [ 40 | { 41 | "Ref": "Prefix" 42 | }, 43 | "assumerole" 44 | ] 45 | ] 46 | }, 47 | "PolicyDocument" : { 48 | "Version": "2012-10-17", 49 | "Statement": [ 50 | { 51 | "Sid": "VisualEditor0", 52 | "Effect": "Allow", 53 | "Action": "sts:AssumeRole", 54 | "Resource": [ 55 | "Fn::Join" : [ ":", [ "arn", "aws", "iam","", "Ref": "ManagedAccount","Fn::Join" : [ "/", [ "role", "Fn::Join" : [ "-", [ "Ref": "Prefix","service"] ]] ]] ] 56 | ] 57 | } 58 | ] } 59 | } ] 60 | } 61 | }, 62 | "addUserToGroup" : { 63 | "Type" : "AWS::IAM::UserToGroupAddition", 64 | "Properties" : { 65 | "GroupName" : { 66 | "Fn::Join": [ 67 | "", [ 68 | { 69 | "Ref": "Prefix" 70 | }, 71 | "-admins" 72 | ] 73 | ] 74 | }, 75 | "Users" : [ "Ref": "IAMUser" ] 76 | }, 77 | "DependsOn" : "MacGroup" 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /ManagedAccount.template: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Description": "Creates an IAM role with cross-account access for mac.", 4 | "Parameters" : { 5 | "IAMAccount" : { 6 | "Type" : "String", 7 | "Default" : "CHANGEME", 8 | "Description" : "Enter the Account number where your IAM users are defined." 9 | }, 10 | "Prefix" : { 11 | "Type" : "String", 12 | "Default" : "mac", 13 | "Description" : "Enter the prefix for the service role." 14 | } 15 | }, 16 | "Resources": { 17 | "CrossAccountRole": { 18 | "Type": "AWS::IAM::Role", 19 | "Properties": { 20 | "RoleName": { 21 | "Fn::Join": [ 22 | "-", [ 23 | { 24 | "Ref": "Prefix" 25 | }, 26 | "service" 27 | ] 28 | ] 29 | }, 30 | "AssumeRolePolicyDocument": { 31 | "Version": "2012-10-17", 32 | "Statement": [ 33 | { 34 | "Effect": "Allow", 35 | "Principal": { 36 | "AWS": [ 37 | "Fn::Join" : [ ":", [ "arn", "aws", "iam","", "Ref": "IAMAccount","root"] ] 38 | ] 39 | }, 40 | "Action": "sts:AssumeRole" 41 | } 42 | ] 43 | }, 44 | "Path": "/", 45 | "Policies": [ 46 | { 47 | "PolicyName": "AdministratorAccess", 48 | "PolicyDocument": { 49 | "Version": "2012-10-17", 50 | "Statement": [ 51 | { 52 | "Effect": "Allow", 53 | "Action": "*", 54 | "Resource": "*" 55 | } 56 | ] 57 | } 58 | } 59 | ] 60 | } 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mac 2 | **Multi Account Command** - runs any command in the context of the AWS Named Profile(s) specified. 3 | 4 | 5 | You want to quickly interact with one or many AWS accounts without the complications of swapping access keys, environment variables, or [aws-vault](https://github.com/99designs/aws-vault) in a for-loop. **mac** can help. 6 | 7 | ------------ 8 | How is this different from awscli's --profile option? 9 | ------------ 10 | * awscli's --profile allows passing a single profile at a time. 11 | * awscli's --profile only processes aws commands. 12 | * mac will loop through all the profiles you specify. e.g.: ````mac -p 'prod,dev' 'aws s3 ls'```` 13 | * mac will run any binary; aws, script. e.g.: ````mac -p 'prod,dev' 'python.exe .\s3_public_acls_finder.py'```` 14 | 15 | ------------ 16 | How it works 17 | ------------ 18 | Each account you manage has a mac-service role that can be assumed via STS. IAM users join the mac-admins group and inherit permissions to assume roles as defined in the mac-assumerole policy. When a new admin comes on board, you create them an IAM user with access keys, then add them to the mac-admins group. When a new managed account is created, you run the CloudFormation Template to install the service role. Also, update the stack on the IAM Account with the new Managed Account number. The admin prefixes any normal command, with the profile(s) of interest. The command will spawn parallel shells for each profile with the custom environment context, run the command, and return the results. 19 | 20 | ------------ 21 | Account Type Definitions 22 | ------------ 23 | The following Account types will be mentioned, here are the definitions. 24 | * **IAM Account:** This account is where all your IAM users exist. It's typically used in your central or security account. 25 | * **Managed Account:** This account is any account, including central/security that you want to be managed by the IAM Account users. 26 | 27 | ------------ 28 | EXAMPLES 29 | ------------ 30 | 31 | **Example 1: See all buckets in multiple accounts.** 32 | 33 | ```` 34 | $ mac -p 'bryanlabs,bryanlabsdev' 'aws s3 ls' 35 | Profile: bryanlabsdev 36 | 2018-08-15 21:36:32 cf-templates-aviic4ggd7jk-us-east-1 37 | Profile: bryanlabs 38 | 2017-12-16 17:34:50 bryanlabs 39 | ```` 40 | **Example 2: Wildcards.** 41 | 42 | ```` 43 | Example: 44 | $ mac -p 'bryan*' 'aws s3 ls' 45 | Profile: bryanlabsdev 46 | 2018-08-15 21:36:32 cf-templates-aviic4ggd7jk-us-east-1 47 | Profile: bryanlabs 48 | 2017-12-16 17:34:50 bryanlabs 49 | ```` 50 | 51 | **Example 3: Find Public Buckets.** 52 | ```` 53 | $ mac -p 'bryanlabs' 'python.exe .\s3_public_acls_finder.py' 54 | Profile: bryanlabs 55 | ('The following permission: *Read - Public Access: List Objects* has been granted on the bucket *bryanlabs-public*', True) 56 | ```` 57 | 58 | **Example 4: Run Script to find all InstanceIDs.** 59 | NOTE: redirection and pipes don't work yet, so sometimes a script is needed. 60 | 61 | ```` 62 | Example: 63 | $ cat < getEC2InstanceIDs.sh 64 | #!/bin/bash 65 | aws ec2 describe-instances | jq -r .[][].Instances[] | jq -r .InstanceId 66 | EOF 67 | mac -p 'bryanlabs' './getEC2InstanceIDs.sh' 68 | ```` 69 | 70 | ------------ 71 | SETUP 72 | ------------ 73 | **NOTE**: To my knowledge, CloudFormation only allows adding one user, with permission to assume role into one account. Others can be added by manually modifying the resources, or submitting a [Merge-Request](https://github.com/bryanlabs/mac/issues/1 "Merge-Request") with the necessary CloudFormation changes. 74 | 75 | **Managed Accounts:** Deploy the ManagedAccount.template in any accounts that you wish to administer including the IAM Account. Be sure to update the IAMAccount ParameterValue to your IAMAccount number. 76 | 77 | ```` 78 | aws cloudformation create-stack --stack-name managed-mac-stack --template-body file://ManagedAccount.template --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=IAMAccount,ParameterValue=601953533983 ParameterKey=Prefix,ParameterValue=mac 79 | ```` 80 | 81 | 82 | **IAM Account:** Deploy the IAMAccount.template in the Account where your IAM users are defined (typically your central or security account). Be sure to update the ManagedAccount ParameterValue to your ManagedAccount number. 83 | 84 | ```` 85 | aws cloudformation create-stack --stack-name iam-mac-stack --template-body file://IAMAccount.template --capabilities CAPABILITY_NAMED_IAM --parameters ParameterKey=IAMUser,ParameterValue=DanBryan ParameterKey=ManagedAccount,ParameterValue=331668981413 ParameterKey=Prefix,ParameterValue=mac 86 | ```` 87 | 88 | ------------ 89 | Administrator environment setup 90 | ------------ 91 | 92 | **Build or Download the App** 93 | 94 | **Build** 95 | ```` 96 | go get -u github.com/bryanlabs/mac 97 | ```` 98 | 99 | **Download** 100 | * Windows: https://github.com/bryanlabs/mac/blob/master/releases/mac.exe 101 | * Linux: https://github.com/bryanlabs/mac/blob/master/releases/mac 102 | 103 | Configure Credentials: (.aws/credentials) 104 | 105 | ```` 106 | [default] 107 | aws_access_key_id=AAAAABBBBBBCCCCCCDDDDDD 108 | aws_secret_access_key=aA/bbbb/cccccccccc/DdDdDD/eeeeeEEE/Ff 109 | ```` 110 | 111 | Configure Named Profiles (.aws/config) 112 | ```` 113 | [default] 114 | region=us-east-1 115 | 116 | [profile bryanlabs] 117 | region=us-east-1 118 | role_arn=arn:aws:iam::601953533983:role/mac-service 119 | source_profile=default 120 | 121 | [profile bryanlabsdev] 122 | region=us-east-1 123 | role_arn=arn:aws:iam::331668981413:role/mac-service 124 | source_profile=default 125 | ```` 126 | Test: 127 | ```` 128 | mac -a 'bryanlabs,bryanlabsdev' 'aws sts get-caller-identity' 129 | 130 | dan@devbox:mac$ ./mac -a 'bryanlabs,bryanlabsdev' 'aws sts get-caller-identity' 131 | Profile: bryanlabs 132 | { 133 | "Account": "bryanlabs", 134 | "UserId": "AROAJP7QAQIUQT6XY72VG:botocore-session-1534452856", 135 | "Arn": "arn:aws:sts::601953533983:assumed-role/mac-service/botocore-session-1534452856" 136 | } 137 | Profile: bryanlabsdev 138 | { 139 | "UserId": "AROAIWNRU4MMXGREHEURS:botocore-session-1534452839", 140 | "Arn": "arn:aws:sts::331668981413:assumed-role/mac-service/botocore-session-1534452839", 141 | "Account": "bryanlabsdev" 142 | } 143 | ```` 144 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/bryanlabs/mac 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc 7 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf 8 | github.com/ryanuber/go-glob v1.0.0 9 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 10 | gopkg.in/ini.v1 v1.51.0 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc h1:cAKDfWh5VpdgMhJosfJnn5/FoN2SRZ4p7fJNX58YPaU= 2 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 3 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY= 4 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 5 | github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= 6 | github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= 7 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc= 8 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 9 | gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= 10 | gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 11 | -------------------------------------------------------------------------------- /mac.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "log" 8 | "os" 9 | "os/exec" 10 | "runtime" 11 | "strings" 12 | "sync" 13 | 14 | "github.com/ryanuber/go-glob" 15 | "gopkg.in/alecthomas/kingpin.v2" 16 | ini "gopkg.in/ini.v1" 17 | ) 18 | 19 | var ( 20 | // Flag 'profiles' is a comma seperated list of aws named profiles. EG: mac -a 'prod,stage,dev'. This flag is required. 21 | profileinput = kingpin.Flag("profileinput", "String of profile names.").Required().Short('p').String() 22 | 23 | // Flag 'maxRunners' is a number of jobs to run in parallel. EG: mac -n '4'. This flag is optional, 4 is default. 24 | maxRunners = kingpin.Flag("maxRunners", "Max Number of Parallel runners.").Default("4").Short('n').Int() 25 | 26 | // Argument 'cmd' is the command to execute. EG: mac -a 'dev,prod' 'aws sts get-caller-identity' 27 | cmd = kingpin.Arg("cmd", "The Command to execute.").Required().String() 28 | 29 | // Create a waitgroup to handle go routines. 30 | wg sync.WaitGroup 31 | ) 32 | 33 | func main() { 34 | // Application version. 35 | kingpin.Version("2018.10.19") 36 | 37 | // Validate the commandline arguments and flags. 38 | kingpin.Parse() 39 | 40 | // Convert the profile input to a slice. 41 | profileinputslice := strings.Split(*profileinput, ",") 42 | 43 | // Create a channel to hold jobs for runners. 44 | c := make(chan int, *maxRunners) 45 | 46 | // getMatchedProfiles from aws config. 47 | matchedProfiles := getMatchedProfiles(profileinputslice) 48 | 49 | // Start a waitgroup based on the number of accounts provided. 50 | wg.Add(len(matchedProfiles)) 51 | 52 | // Run a job for each account in the slice. 53 | for _, matchedProfile := range matchedProfiles { 54 | go mac(matchedProfile, *cmd, c) 55 | } 56 | 57 | // wait for mac to finish processing all jobs before exiting. 58 | wg.Wait() 59 | 60 | } 61 | 62 | // mac will run a command under the specified profile. 63 | func mac(profile string, cmd string, c chan int) { 64 | // Fill the channel buffer with random data. 65 | c <- 1 66 | 67 | // Run command in the correct context. 68 | slice := strings.Split(cmd, " ") 69 | cmdName := slice[0] 70 | cmdArgs := slice[1:] 71 | macRun(profile, cmdName, cmdArgs) 72 | 73 | // Remove the job from the channel. 74 | <-c 75 | 76 | // Send Done when nothing remains on the channel. 77 | wg.Done() 78 | 79 | } 80 | 81 | // Run the command in the correct context. 82 | func macRun(profile string, cmdName string, cmdArgs []string) { 83 | // Setup the command details, binary, flags, environment variables... 84 | cmd := exec.Command(cmdName, cmdArgs...) 85 | cmd.Env = append(os.Environ(), "AWS_PROFILE="+profile, "AWS_SDK_LOAD_CONFIG=1") 86 | var errbuf bytes.Buffer 87 | // cmd.Stdout = &outbuf 88 | cmd.Stderr = &errbuf 89 | cmdReader, err := cmd.StdoutPipe() 90 | 91 | // Handle errors. 92 | if err != nil { 93 | fmt.Printf("Profile: %v, Error Creating Cmd: %v\n", profile, err) 94 | // os.Exit(1) 95 | } 96 | 97 | // scanner will display the cmd Stdoutput 98 | scanner := bufio.NewScanner(cmdReader) 99 | 100 | // format the output 101 | go func() { 102 | var outputslice []string 103 | var stdout string 104 | for scanner.Scan() { 105 | outputslice = append(outputslice, "\n", scanner.Text()) 106 | stdout = strings.Join(outputslice, "") 107 | } 108 | fmt.Printf("Profile: %s", profile) 109 | fmt.Printf("%s\n", stdout) 110 | }() 111 | 112 | // Handle errors. 113 | err = cmd.Start() 114 | if err != nil { 115 | fmt.Printf("Profile: %v, Error Starting Cmd: %v\n", profile, err) 116 | // os.Exit(1) 117 | } 118 | 119 | // Handle errors. 120 | err = cmd.Wait() 121 | if err != nil { 122 | // stdout := outbuf.String() 123 | stderr := errbuf.String() 124 | fmt.Printf("Profile: %v, Error waiting for Cmd. %v\n", profile, stderr) 125 | // os.Exit(1) 126 | } 127 | 128 | } 129 | 130 | // getAWSConfig will return the filename for the users awsconfig. 131 | func getAWSConfig() (awsconfig string) { 132 | switch flavor := runtime.GOOS; flavor { 133 | case "windows": 134 | return os.Getenv("userprofile") + "/.aws/config" 135 | case "linux": 136 | return os.Getenv("HOME") + "/.aws/config" 137 | default: 138 | log.Fatalf("Can't find aws config. %v is an Unsupported OS, please consider contributing to add this feature.", runtime.GOOS) 139 | } 140 | return 141 | } 142 | 143 | // getNamedProfile will find the named profile that matches the string provided. 144 | func getMatchedProfiles(profileinslice []string) (profileoutslice []string) { 145 | 146 | // find and load the awsconf file. 147 | awsconfig := getAWSConfig() 148 | cfg, err := ini.Load(awsconfig) 149 | 150 | // Handle errors. 151 | if err != nil { 152 | fmt.Fprintln(os.Stderr, "Error Loading awsConfig: ", err) 153 | os.Exit(1) 154 | } 155 | 156 | // Range over all the profiles in the slice. 157 | for _, profilein := range profileinslice { 158 | 159 | // Range over each item in the Named Profile 160 | for _, section := range cfg.Sections() { 161 | 162 | // Valid profiles must have a role_arn 163 | if section.HasKey("role_arn") { 164 | 165 | // If profilein matches the named profile. 166 | slice := strings.Split(section.Name(), " ") 167 | namedProfile := slice[1] 168 | if glob.Glob(profilein, namedProfile) { 169 | 170 | // Add Named Profile to output slice if it's not in the slice already. 171 | if stringInSlice(namedProfile, profileoutslice) != true { 172 | profileoutslice = append(profileoutslice, namedProfile) 173 | } 174 | } 175 | } 176 | } 177 | } 178 | 179 | return 180 | } 181 | 182 | // stringInSlice returns true of the string is in the slice. 183 | func stringInSlice(a string, list []string) bool { 184 | for _, b := range list { 185 | if b == a { 186 | return true 187 | } 188 | } 189 | return false 190 | } 191 | -------------------------------------------------------------------------------- /releases/mac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryanlabs/mac/141a8a3311ba7b247c86a227fdac7d06591541ef/releases/mac -------------------------------------------------------------------------------- /releases/mac.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryanlabs/mac/141a8a3311ba7b247c86a227fdac7d06591541ef/releases/mac.exe -------------------------------------------------------------------------------- /s3_public_acls_finder.py: -------------------------------------------------------------------------------- 1 | # Modified from https://github.com/mz1991/S3-public-ACLs-finder/blob/master/s3_public_acls_finder.py 2 | 3 | import boto3 4 | import requests 5 | import json 6 | 7 | s3_client_connection = boto3.resource( 8 | 's3' 9 | ) 10 | 11 | def check_bucket_grant(grant_permission, bucket_name): 12 | granted_warning = 'The following permission: *{}* has been granted on the bucket *{}*' 13 | if grant_permission == 'read': 14 | return granted_warning.format('Read - Public Access: List Objects', bucket_name), True 15 | elif grant_permission == 'write': 16 | return granted_warning.format('Write - Public Access: Write Objects', bucket_name), True 17 | elif grant_permission == 'read_acp': 18 | return granted_warning.format('Write - Public Access: Read Bucket Permissions', bucket_name), True 19 | elif grant_permission == 'write_acp': 20 | return granted_warning.format('Write - Public Access: Write Bucket Permissions', bucket_name), True 21 | elif grant_permission == 'full_control': 22 | return granted_warning.format('Public Access: Full Control', bucket_name), True 23 | return '' 24 | 25 | def check_S3_buckets_grants(): 26 | for bucket in s3_client_connection.buckets.all(): 27 | # print(bucket.name) 28 | acl = bucket.Acl() 29 | for grant in acl.grants: 30 | #http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html 31 | if grant['Grantee']['Type'].lower() == 'group' \ 32 | and grant['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers': 33 | 34 | text_to_post = check_bucket_grant(grant['Permission'].lower(), bucket.name) 35 | print(text_to_post) 36 | 37 | if __name__ == "__main__": 38 | check_S3_buckets_grants() --------------------------------------------------------------------------------