├── LICENSE-2.0.txt ├── README.md ├── snowflakepasswords-database-plugin └── main.go └── vault-snowflakepasswords-sample.go /LICENSE-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PLEASE NOTE: Hashicorp has released an official plugin, which you can find here: https://github.com/hashicorp/vault-plugin-database-snowflake 2 | 3 | # Vault database plugin for Snowflake 4 | 5 | > A _sample_ Hashicorp Vault database plugin designed to work with the Snowflake Data Platform. 6 | 7 | Copyright © 2020 Snowflake Inc. All rights reserved. 8 | 9 | ## Contents 10 | * [General usage](#general-usage) 11 | * [Requirements](#requirements) 12 | * [Setting up a minimalist system](#setting-up-a-minimalist-system) 13 | * [Using the plugin](#using-the-plugin) 14 | * [Known limitations](#known-limitations) 15 | * [Apache license](#apache-license) 16 | 17 | 18 | 19 | ## General Usage 20 | 21 | This _sample_ Hashicorp Vault database plugin works with the Snowflake Data Platform. If you are familiar with Vault built-in database plugins, this plugin provides the same features and works the same way. Otherwise, see Vault's [general concepts](https://www.vaultproject.io/docs/secrets/databases) and [detailed usage](https://www.vaultproject.io/api/secret/databases) documentation to get started. Known limitations are [noted below](#known-limitations). 22 | 23 | 24 | ## Requirements 25 | 26 | The `snowflakepasswords-database-plugin` requires: 27 | 28 | 1. **A working Vault install** with the database secrets backend active. 29 | 2. **A Go build environment** and the **[Snowflake Go Driver](https://docs.snowflake.com/en/user-guide/go-driver.html)**. Both are required to build a binary version of the plugin. 30 | 31 | ### Required Snowflake Setup 32 | 33 | 1. **A Snowflake user with _at least_ the USERADMIN role granted**. Required to create a plugin command or to run a command. See [Preparing Snowflake to work with the plugin](#preparing-snowflake-to-work-with-the-plugin) for steps to create the user. 34 | 2. **A Snowflake instance configured with a WAREHOUSE and ROLE for use with dynamically created users**. To run any SQL, dynamically-created Users based on Vault roles will need a warehouse and a role. 35 | 3. **A user owned by the USERADMIN role** that will be controlled by this plugin. 36 | 37 | 38 | 39 | ## Setting up a Minimalist System 40 | This section describes how to test this plugin in a development setting using a minimalist setup. This README file does not comment on adapting this SAMPLE for uses other than testing in a dev environment. 41 | 42 | ### Starting with Hashicorp Vault in Dev mode 43 | After you [install Vault](https://learn.hashicorp.com/vault/getting-started/install), you will [start it in "dev mode"](https://learn.hashicorp.com/vault/getting-started/dev-server). At this stage, you simply want to ensure it works as expected. Use the [simplest possible secret](https://learn.hashicorp.com/vault/getting-started/first-secret) to test this. 44 | 45 | Next, prepare the server to run the SAMPLE plugin. Start by [following the procedure for the mock plugin](https://learn.hashicorp.com/vault/developer/plugin-backends). If this works as expected, proceed with this SAMPLE. 46 | 47 | ### Building the Plugin 48 | If you followed the mock plugin procedure above, you should have a working golang environment on your system. To build the `snowflakepasswords-database-plugin` plugin binary, follow these steps: 49 | 50 | 1. cd to the root directory of the cloned repo, `sfguide-vault-snowflakepasswords` by default. 51 | 2. `go mod init github.com/sanderiam/vault-snowflakepasswords-sample` (depending on your go version, you may also need to run `go mod tidy` or equiv at this time) 52 | 3. `go build` 53 | 4. `go build snowflakepasswords-database-plugin/main.go` 54 | 5. `mv ./main /snowflakepasswords-database-plugin` 55 | 6. `sha256sum /snowflakepasswords-database-plugin | awk '{print $1}'` 56 | 7. Save the output of step #6 for a later step, which will be referred to as ``. 57 | 58 | ### Enabling the Plugin in Vault 59 | To enable the plugin (`snowflakepasswords-database-plugin`) with your dev Vault server, follow these steps: 60 | 61 | 1. Start the Vault server in dev mode and point to `` as used above, _e.g._ `vault server -dev -dev-root-token-id=root -dev-plugin-dir=./plugins` 62 | This step takes over that session and you will need a second one to continue. 63 | 2. Prepare your session to interact with the running Vault server by setting the `VAULT_ADDR`, _e.g._ `export VAULT_ADDR='http://127.0.0.1:8200'` 64 | 3. Log in to Vault, _e.g._ `vault login root` 65 | 5. Enable the built-in Vault Database Backend by running `vault secrets enable database` 66 | 6. Enable the snowflakepasswords-database-plugin by running `vault write sys/plugins/catalog/database/snowflakepasswords-database-plugin sha256= command="snowflakepasswords-database-plugin"` - where `` is the value saved from step #6 of [Building the snowflakepasswords-database-plugin](#building-the-snowflakepasswords-database-plugin)." 67 | 68 | Look for this indicator of success: `Success! Data written to: sys/plugins/catalog/database/snowflakepasswords-database-plugin`. 69 | 70 | 71 | ## Using the Plugin 72 | If the SAMPLE is running successfully, you're ready to use the plugin features. 73 | 74 | ### Preparing Snowflake to Work with the Plugin 75 | If you have not yet created the Snowflake user described in the [Required Snowflake Setup](#required-snowflake-setup) section, create the user now. You need the appropriate Snowflake rights to do this. In this example, the User name is `karnak`. For a full discussion on user creation in Snowflake, see the [CREATE USER topic](https://docs.snowflake.com/en/sql-reference/sql/create-user.html) in the Snowflake product documentation. 76 | 77 | To create the user: 78 | 79 | ``` 80 | create user karnak PASSWORD = '' DEFAULT_ROLE = USERADMIN; 81 | grant role USERADMIN to user karnak; 82 | ``` 83 | 84 | The `USERADMIN` role provides the minimum rights necessary to accomplish the examples documented in this README file. Additional rights may be required to have the plugin do things differently. For a full discussion of access control in Snowflake, see the [Access Control in Snowflake](https://docs.snowflake.com/en/user-guide/security-access-control.html) topic in the product documentation. To allow Vault to manage (rotate) the credentials for the `karnak` user, grant ownership of that user to the `USERADMIN` role: 85 | 86 | ``` 87 | grant ownership on user karnak to role USERADMIN; 88 | ``` 89 | 90 | Because users in Snowflake typically need to run SQL and need a role other than the `PUBLIC` role, create the assets and grant the `USERADMIN` role access to manage these so the `karnak` user in Vault can do what it needs to do: 91 | 92 | ``` 93 | CREATE WAREHOUSE VAULTTEST WITH WAREHOUSE_SIZE = 'XSMALL' WAREHOUSE_TYPE = 'STANDARD' AUTO_SUSPEND = 60 AUTO_RESUME = TRUE MIN_CLUSTER_COUNT = 1 94 | MAX_CLUSTER_COUNT = 2 SCALING_POLICY = 'STANDARD'; 95 | create role vaulttesting; 96 | grant ownership on role vaulttesting to role USERADMIN; 97 | grant ownership on warehouse VAULTTEST to role USERADMIN; 98 | ``` 99 | 100 | In this SAMPLE we only use one Snowflake role and warehouse. In a real world scenario, you would have a wide variety of Snowflake roles and warehouses that would be managed by a wide variety of Vault roles, all with different levels of rights and permissions. 101 | 102 | ### Connecting Vault to Snowflake 103 | This section requires the Snowflake user named `karnak` that we created in the previous section. Running the following command sets up one of your Snowflake accounts in Vault: 104 | 105 | > `vault write database/config/uncannyxmen plugin_name=snowflakepasswords-database-plugin allowed_roles="xvi" connection_url="{{username}}:{{password}}@uncannyxmen.us-east-1/" username="karnak" password=""` 106 | 107 | If we break down this command, the important pieces are: 108 | * `database/config/uncannyxmen` – This tells Vault to make a new configuration in the database backend for a Snowflake account it will know as `uncannyxmen`. This example uses the Snowflake Account's name as the name of the configuration entry, but it's not required that you do that. It can be named whatever you wish. 109 | * `plugin_name=snowflakepasswords-database-plugin` – This references the plugin enabled in the last section. 110 | * `allowed_roles="xvi` - Vault will always put things in the context of roles to authorize access to functions Vault offers. In this example walkthrough, I'm using a net new role I've created named `xvi`, but you can connect this to roles you already have. There is no special role required and it can be used with any roles you wish. 111 | * `connection_url="{{username}}:{{password}}@uncannyxmen.us-east-1/"` – This is the connection string the plugin uses to call out to Snowflake. This plugin is written in go/golang and uses the [Snowflake Go Driver](https://docs.snowflake.com/en/user-guide/go-driver.html). The format of this connection string is what is used in this driver. 112 | * `username="karnak" password=""` – This is the username and password for the Snowflake user with the USERADMIN privilege (from "Snowflake Configuration Requirements" item #1). These are the initial credentials for this user, and after this you can use this plugin to rotate and manage those credentials from that point on (which will be covered below). 113 | 114 | ### Rotating the Snowflake Plugin Vault Credentials 115 | Now that Vault is controlling credentials, the first natural thing is to ensure it also has control of its own credentials. This can be accomplished using the following command (or the equivalent API call), and can be automated in any way orchestration is convenient for you. 116 | 117 | ``` 118 | vault write -force database/rotate-root/uncannyxmen 119 | ``` 120 | 121 | If we break down this command, the important pieces are: 122 | * `-force` – this makes the command go through for sure (may not be needed). 123 | * `database/` – reference to being in the database backend again. 124 | * `rotate-root/uncannyxmen` – the instruction is to rotate the "root" credentials for the `uncannyxmen` Snowflake Account we connected at the start. 125 | 126 | ### Setting up an Ephemeral Snowflake User with Vault 127 | 128 | > `vault write database/roles/xvi db_name=uncannyxmen creation_statements="create user {{name}} LOGIN_NAME='{{name}}' FIRST_NAME = \"VAULT\" LAST_NAME = \"CREATED\"; alter user {{name}} set PASSWORD = '{{password}}'; alter user {{name}} set DEFAULT_ROLE = vaulttesting; grant role vaulttesting to user {{name}}; alter user {{name}} set default_warehouse = \"VAULTTEST\"; grant usage on warehouse VAULTTEST to role vaulttesting; alter user {{name}} set DAYS_TO_EXPIRY = {{expiration}}" default_ttl=1h max_ttl=2h` 129 | 130 | If we break down this command, the important pieces are: 131 | * `database/roles/xvi` – Names the role we are creating. Note that the `xvi` role was named when we created the `uncannyxmen` Snowflake Account definition. If the role was not allowed then, this write would fail because the role would not be authorized. If you want to name this role something else or need to authorize other roles in the future, run `vault write database/config/uncannyxmen allowed_roles="xvi,astonishing,mercs"` and write allowed roles as needed. 132 | 133 | * `creation_statements="create user {{name}} LOGIN_NAME='{{name}}'...` – Creates a Snowflake user every time it is called. To do that it needs instructions for creating a Snowflake user. This lets you define the SQL used in that process, which means you can alter the user creation process for each distinct role as needed. 134 | > _PLEASE NOTE:_ These steps recommend using the Snowflake `USERADMIN` role for authorization. If you add SQL that exceeds what the role can do, the operation will fail. All the SQL commands used here are listed below. 135 | 136 | * `default_ttl=1h max_ttl=2h` – Sets the default and max lease lifetimes for any user created using this role. 137 | 138 | For easier readability all the SQL is listed here: 139 | * `create user {{name}} LOGIN_NAME='{{name}}' FIRST_NAME = "VAULT" LAST_NAME = "CREATED";` – Everything that appears in `{{this}}` format is replaced by the runtime values in the code. 140 | * `alter user {{name}} set PASSWORD = '{{password}}';` 141 | * `alter user {{name}} set DEFAULT_ROLE = vaulttesting;` – The `DEFAULT_ROLE` will likely vary between different Vault roles you define. 142 | * `grant role vaulttesting to user {{name}};` 143 | * `alter user {{name}} set default_warehouse = "VAULTTEST";` – The `default_warehouse` will likely vary between different Vault roles you define. 144 | * `grant usage on warehouse VAULTTEST to role vaulttesting;` 145 | * `alter user {{name}} set DAYS_TO_EXPIRY = {{expiration}};` – Snowflake does not expire users in hours, so this is [calculated as days in the plugin code](https://github.com/sanderiam/vault-snowflakepasswords-sample/blob/f35d2a3b9cc2c356b8b26d12754d9fd12e870bbe/vault-snowflakepasswords-sample.go#L362) and can be set to a single day for every value of hours below 24. 146 | 147 | 148 | Once you have the role defined, read from it to generate a user. On the command line the command looks like this: 149 | 150 | ``` 151 | $ vault read database/creds/xvi 152 | Key Value 153 | --- ----- 154 | lease_id database/creds/xvi/Jk8qolr98MgcwFoPo9Kib5xn 155 | lease_duration 1h 156 | lease_renewable true 157 | password A1a-randomCHARsWz9z 158 | username v_token_xvi_hKg9wm9R7Bj98EWxGnXa_1589390049 159 | ``` 160 | For the next hour (until the lease expires) this user exists with that password. When the lease expires, the user is dropped by Vault. 161 | 162 | ### Auditing the Actions of Vault in Snowflake 163 | Now that Vault is running commands and creating users, you can see what it's up to in Snowflake. There are many ways to do this, and for a full discussion of that please see the [Account Usage docs](https://docs.snowflake.com/en/sql-reference/account-usage.html). A quick thing you can do to see what Vault is up to is show all users that it creates: 164 | 165 | ``` 166 | show users like '%token%'; 167 | ``` 168 | 169 | Or you can get a complete record of the queries it is running: 170 | 171 | ``` 172 | select QUERY_ID, QUERY_TEXT, USER_NAME, ERROR_CODE, ERROR_MESSAGE, START_TIME 173 | from table(snowflake.information_schema.query_history(dateadd('hours',-4,current_timestamp()),current_timestamp())) 174 | where USER_NAME like '%KAR%' order by start_time DESC; 175 | ``` 176 | 177 | This is looking for a user with a name like `KAR`, but if you used a different root user for Vault you should alter that part of the SQL. 178 | 179 | ### Using Vault to Rotate Existing Users' Credentials 180 | Along with creating dynamic users, the other common Vault pattern is to manage the passwords of existing Users. This is often applied to User leveraged as service accounts by orchestrated and programmatic tasks. 181 | 182 | To test this using this SAMPLE, first create a user to manage and grant ownership of that use to the USERADMIN role. 183 | 184 | ``` 185 | create user bob; 186 | grant OWNERSHIP on user bob to role USERADMIN; 187 | ``` 188 | 189 | The USERADMIN role must own the user, or have rights to manage the user in order for this to work. 190 | 191 | Because this extends the Vault configuration for our Snowflake account to a new role, that role must become an `allowed_role` in the configuration. We set that up like so: 192 | 193 | ``` 194 | vault write database/config/uncannyxmen allowed_roles="xvi,astonishing,teamdp" 195 | ``` 196 | 197 | This adds `astonishing` and `teamdp` to the roles that are allowed for `uncannyxmen`. It is the same command used to originally create the `uncannyxmen` configuration, but only writing the single attribute for `allowed_roles`. Note that you must also include the original `xvi` role or it will no longer be allowed. 198 | 199 | Next we configure Vault to manage the `bob` user we created. 200 | 201 | > `vault write /database/static-roles/teamdp username="bob" rotation_period="5m" db_name="uncannyxmen" rotation_statements="alter user {{name}} set password='{{password}}';"` 202 | 203 | If we break down this command, the important pieces are: 204 | * `write /database` - Writes a new configuration to the database backend. 205 | * `/static-roles/teamdp` - Like other constructs, Vault manages this as a role. The type of role is the "static-role". This is understood in comparison to the dynamic roles used in the last example of Vault role creation where a new credential (a new Snowflake User) was created each time the role was called. This time there is a static User and only the user's password is changed. The role is named `teamdp` in this example. 206 | * `username="bob"` - The User name for this static role. 207 | * `rotation_period="5m"` - This sets how often Vault will change this User's password. It can be measured in increments as small as minutes, but can also be set to hours or days. 208 | * `db_name="uncannyxmen"` - The database name that will hold this role's configuration. 209 | * `rotation_statements="alter user {{name}} set password='{{password}}';"` - This is the SQL that will be run each time Vault reaches the `rotation_period` and executes the configured commands. This example uses the absolute minimum SQL needed to accomplish the task of rotating the credential, but you could extend this to run any SQL needed. The only limitation is that the user running these commands has the rights to do so. 210 | 211 | Once you have the role defined, use it by reading from it to change the user's password. For example, on the command line: 212 | 213 | ``` 214 | $ vault read /database/static-creds/teamdp 215 | Key                    Value 216 | ---                    ----- 217 | last_vault_rotation    2020-05-16T09:32:24.46958155-04:00 218 | password               A1a-QXnOpEnOpEX4G0oc 219 | rotation_period        5m 220 | ttl                    4m52s 221 | username               bob 222 | ``` 223 | 224 | For five minutes this user exists with the specified password, and when the counter expires, Vault changes the user's password. The `ttl` is the countdown to the next time Vault will automatically change the value of the User's password. If you check again in a few moments, you will see that the countdown has diminished: 225 | 226 | ``` 227 | $ vault read /database/static-creds/teamdp 228 | Key                    Value 229 | ---                    ----- 230 | last_vault_rotation    2020-05-16T09:32:24.46958155-04:00 231 | password               A1a-QXnOpEnOpEX4G0oc 232 | rotation_period        5m 233 | ttl                    3m46s 234 | username               bob 235 | ``` 236 | 237 | You can also force the rotation to happen, which will also reset the `ttl`. 238 | 239 | ``` 240 | $ vault write -force /database/rotate-role/teamdp 241 | Success! Data written to: database/rotate-role/teamdp 242 | $ vault read /database/static-creds/teamdp 243 | Key                    Value 244 | ---                    ----- 245 | last_vault_rotation    2020-05-16T09:33:56.530157317-04:00 246 | password               A1a-XMnAdAnAdAsNWbK2 247 | rotation_period        5m 248 | ttl                    4m57s 249 | username               bob 250 | ``` 251 | 252 | 253 | ## Known Limitations 254 | 255 | * Most similar Vault database plugins will check for the user's existence before dropping the user. Since that sort of operation requires a warehouse to run SQL and rights the USERADMIN role would not normally have, we've skipped that check. There should be no harm in that, but it is a deviation from the normal pattern. 256 | * This plugin was developed using Go version 1.14.2 on Ubuntu 20.04 LTS. Compatibility with other versions and systems is unknown. 257 | 258 | 259 | 260 | ## Apache License 261 | 262 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 263 | You may obtain a copy of the License at 264 | 265 | http://www.apache.org/licenses/LICENSE-2.0 266 | 267 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 268 | 269 | 270 | 271 |





272 | -------------------------------------------------------------------------------- /snowflakepasswords-database-plugin/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Snowflake Inc. All rights reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the 5 | "License"); you may not use this file except in compliance 6 | with the License. You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, 11 | software distributed under the License is distributed on an 12 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | KIND, either express or implied. See the License for the 14 | specific language governing permissions and limitations 15 | under the License. 16 | */ 17 | package main 18 | 19 | import ( 20 | "log" 21 | "os" 22 | 23 | "github.com/hashicorp/vault/api" 24 | "github.com/sanderiam/vault-snowflakepasswords-sample" 25 | ) 26 | 27 | // this just encapsulates the rest of the program 28 | func main() { 29 | apiClientMeta := &api.PluginAPIClientMeta{} 30 | flags := apiClientMeta.FlagSet() 31 | flags.Parse(os.Args[1:]) 32 | 33 | err := snowpasssample.Run(apiClientMeta.GetTLSConfig()) 34 | if err != nil { 35 | log.Println(err) 36 | os.Exit(1) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /vault-snowflakepasswords-sample.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Snowflake Inc. All rights reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the 5 | "License"); you may not use this file except in compliance 6 | with the License. You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, 11 | software distributed under the License is distributed on an 12 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | KIND, either express or implied. See the License for the 14 | specific language governing permissions and limitations 15 | under the License. 16 | */ 17 | package snowpasssample 18 | 19 | import ( 20 | "context" 21 | "database/sql" 22 | "errors" 23 | "fmt" 24 | "math" 25 | "strconv" 26 | "strings" 27 | "time" 28 | 29 | "github.com/hashicorp/vault/api" 30 | "github.com/hashicorp/vault/sdk/database/dbplugin" 31 | "github.com/hashicorp/vault/sdk/database/helper/connutil" 32 | "github.com/hashicorp/vault/sdk/database/helper/credsutil" 33 | "github.com/hashicorp/vault/sdk/database/helper/dbutil" 34 | "github.com/hashicorp/vault/sdk/helper/dbtxn" 35 | "github.com/hashicorp/vault/sdk/helper/strutil" 36 | _ "github.com/snowflakedb/gosnowflake" 37 | ) 38 | 39 | const ( 40 | snowflakeSQLTypeName = "snowflake" 41 | defaultSnowflakeRenewSQL = ` 42 | alter user {{name}} set DAYS_TO_EXPIRY = {{expiration}}; 43 | ` 44 | defaultSnowflakeRotateRootCredentialsSQL = ` 45 | alter user {{name}} set PASSWORD = '{{password}}'; 46 | ` 47 | ) 48 | 49 | var ( 50 | _ dbplugin.Database = &SnowflakeSQL{} 51 | ) 52 | 53 | // New implements builtinplugins.BuiltinFactory 54 | func New() (interface{}, error) { 55 | db := new() 56 | // Wrap the plugin with middleware to sanitize errors 57 | dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.SecretValues) 58 | return dbType, nil 59 | } 60 | 61 | func new() *SnowflakeSQL { 62 | connProducer := &connutil.SQLConnectionProducer{} 63 | connProducer.Type = snowflakeSQLTypeName 64 | 65 | credsProducer := &credsutil.SQLCredentialsProducer{ 66 | DisplayNameLen: 8, 67 | RoleNameLen: 8, 68 | UsernameLen: 63, 69 | Separator: "_", 70 | } 71 | 72 | db := &SnowflakeSQL{ 73 | SQLConnectionProducer: connProducer, 74 | CredentialsProducer: credsProducer, 75 | } 76 | 77 | return db 78 | } 79 | 80 | // Run instantiates a SnowflakeSQL object, and runs the RPC server for the plugin 81 | func Run(apiTLSConfig *api.TLSConfig) error { 82 | dbType, err := New() 83 | if err != nil { 84 | return err 85 | } 86 | 87 | dbplugin.Serve(dbType.(dbplugin.Database), api.VaultPluginTLSProvider(apiTLSConfig)) 88 | 89 | return nil 90 | } 91 | 92 | type SnowflakeSQL struct { 93 | *connutil.SQLConnectionProducer 94 | credsutil.CredentialsProducer 95 | } 96 | 97 | func (s *SnowflakeSQL) Type() (string, error) { 98 | return snowflakeSQLTypeName, nil 99 | } 100 | 101 | func (s *SnowflakeSQL) getConnection(ctx context.Context) (*sql.DB, error) { 102 | db, err := s.Connection(ctx) 103 | if err != nil { 104 | return nil, err 105 | } 106 | 107 | return db.(*sql.DB), nil 108 | } 109 | 110 | // SetCredentials uses provided information to set/create a user in the 111 | // database. Used by /database/static-roles/:name call from vault. 112 | // Unlike CreateUser, this method requires a username be provided and 113 | // uses the name given, instead of generating a name. This is used for creating 114 | // and setting the password of static accounts, as well as rolling back 115 | // passwords in the database in the event an updated database fails to save in 116 | // Vault's storage. In Snowflake, the user must be owned by USERADMIN role (or 117 | // whatever role vault is using for it's authority) for this to work 118 | func (s *SnowflakeSQL) SetCredentials(ctx context.Context, statements dbplugin.Statements, staticUser dbplugin.StaticUserConfig) (username, password string, err error) { 119 | if len(statements.Rotation) == 0 { 120 | statements.Rotation = []string{defaultSnowflakeRotateRootCredentialsSQL} 121 | } 122 | 123 | username = staticUser.Username 124 | password = staticUser.Password 125 | if username == "" || password == "" { 126 | return "", "", errors.New("must provide both username and password") 127 | } 128 | 129 | // Get the connection 130 | db, err := s.getConnection(ctx) 131 | if err != nil { 132 | return "", "", err 133 | } 134 | 135 | // Vault requires the database user already exist, and that the credentials 136 | // used to execute the rotation statements has sufficient privileges. 137 | stmts := statements.Rotation 138 | 139 | // Execute each query 140 | for _, stmt := range stmts { 141 | for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { 142 | query = strings.TrimSpace(query) 143 | if len(query) == 0 { 144 | continue 145 | } 146 | 147 | m := map[string]string{ 148 | "name": staticUser.Username, 149 | "username": staticUser.Username, 150 | "password": password, 151 | } 152 | if err := dbtxn.ExecuteDBQuery(ctx, db, m, query); err != nil { 153 | return "", "", err 154 | } 155 | } 156 | } 157 | 158 | return username, password, nil 159 | } 160 | 161 | func (s *SnowflakeSQL) CreateUser(ctx context.Context, statements dbplugin.Statements, usernameConfig dbplugin.UsernameConfig, expiration time.Time) (username string, password string, err error) { 162 | statements = dbutil.StatementCompatibilityHelper(statements) 163 | 164 | if len(statements.Creation) == 0 { 165 | return "", "", dbutil.ErrEmptyCreationStatement 166 | } 167 | 168 | username, err = s.GenerateUsername(usernameConfig) 169 | if err != nil { 170 | return "", "", err 171 | } 172 | 173 | password, err = s.GeneratePassword() 174 | if err != nil { 175 | return "", "", err 176 | } 177 | 178 | expirationStr, err := calculateExpirationString(expiration) 179 | if err != nil { 180 | return "", "", err 181 | } 182 | 183 | // Get the connection 184 | db, err := s.getConnection(ctx) 185 | if err != nil { 186 | return "", "", err 187 | } 188 | 189 | // Execute each query 190 | for _, stmt := range statements.Creation { 191 | // it's fine to split the statements on the semicolon. 192 | for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { 193 | query = strings.TrimSpace(query) 194 | if len(query) == 0 { 195 | continue 196 | } 197 | 198 | m := map[string]string{ 199 | "name": username, 200 | "username": username, 201 | "password": password, 202 | "expiration": expirationStr, 203 | } 204 | if err := dbtxn.ExecuteDBQuery(ctx, db, m, query); err != nil { 205 | return "", "", err 206 | } 207 | } 208 | } 209 | 210 | return username, password, nil 211 | } 212 | 213 | func (s *SnowflakeSQL) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error { 214 | statements = dbutil.StatementCompatibilityHelper(statements) 215 | 216 | renewStmts := statements.Renewal 217 | if len(renewStmts) == 0 { 218 | renewStmts = []string{defaultSnowflakeRenewSQL} 219 | } 220 | 221 | db, err := s.getConnection(ctx) 222 | if err != nil { 223 | return err 224 | } 225 | 226 | expirationStr, err := calculateExpirationString(expiration) 227 | if err != nil { 228 | return err 229 | } 230 | 231 | for _, stmt := range renewStmts { 232 | for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { 233 | query = strings.TrimSpace(query) 234 | if len(query) == 0 { 235 | continue 236 | } 237 | 238 | m := map[string]string{ 239 | "name": username, 240 | "username": username, 241 | "expiration": expirationStr, 242 | } 243 | if err := dbtxn.ExecuteDBQuery(ctx, db, m, query); err != nil { 244 | return err 245 | } 246 | } 247 | } 248 | 249 | return err 250 | } 251 | 252 | func (s *SnowflakeSQL) RevokeUser(ctx context.Context, statements dbplugin.Statements, username string) error { 253 | statements = dbutil.StatementCompatibilityHelper(statements) 254 | 255 | if len(statements.Revocation) == 0 { 256 | return s.defaultRevokeUser(ctx, username) 257 | } 258 | 259 | return s.customRevokeUser(ctx, username, statements.Revocation) 260 | } 261 | 262 | func (s *SnowflakeSQL) customRevokeUser(ctx context.Context, username string, revocationStmts []string) error { 263 | db, err := s.getConnection(ctx) 264 | if err != nil { 265 | return err 266 | } 267 | 268 | for _, stmt := range revocationStmts { 269 | for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { 270 | query = strings.TrimSpace(query) 271 | if len(query) == 0 { 272 | continue 273 | } 274 | 275 | m := map[string]string{ 276 | "name": username, 277 | "username": username, 278 | } 279 | if err := dbtxn.ExecuteDBQuery(ctx, db, m, query); err != nil { 280 | return err 281 | } 282 | } 283 | } 284 | 285 | return err 286 | } 287 | 288 | func (s *SnowflakeSQL) defaultRevokeUser(ctx context.Context, username string) error { 289 | db, err := s.getConnection(ctx) 290 | if err != nil { 291 | return err 292 | } 293 | 294 | // Drop this user 295 | stmt, err := db.PrepareContext(ctx, fmt.Sprintf( 296 | `drop user %s;`, strings.ToUpper(username))) 297 | if err != nil { 298 | errString := err.Error() 299 | 300 | // the 002003 (02000) error means the user isn't there. something may 301 | // have already dropped it. that's fine. but this is a bit brittle as 302 | // the error may change at some point and this would need updating 303 | if !(strings.Contains(errString, "002003 (02000)")) { 304 | return err 305 | } 306 | } 307 | 308 | defer stmt.Close() 309 | if _, err := stmt.ExecContext(ctx); err != nil { 310 | return err 311 | } 312 | 313 | return nil 314 | } 315 | 316 | func (s *SnowflakeSQL) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) { 317 | if len(s.Username) == 0 || len(s.Password) == 0 { 318 | return nil, errors.New("username and password are required to rotate") 319 | } 320 | 321 | rotateStatements := statements 322 | if len(rotateStatements) == 0 { 323 | rotateStatements = []string{defaultSnowflakeRotateRootCredentialsSQL} 324 | } 325 | 326 | db, err := s.getConnection(ctx) 327 | if err != nil { 328 | return nil, err 329 | } 330 | 331 | password, err := s.GeneratePassword() 332 | if err != nil { 333 | return nil, err 334 | } 335 | 336 | for _, stmt := range rotateStatements { 337 | for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") { 338 | query = strings.TrimSpace(query) 339 | if len(query) == 0 { 340 | continue 341 | } 342 | m := map[string]string{ 343 | "name": s.Username, 344 | "username": s.Username, 345 | "password": password, 346 | } 347 | if err := dbtxn.ExecuteDBQuery(ctx, db, m, query); err != nil { 348 | return nil, err 349 | } 350 | } 351 | } 352 | 353 | // Close the database connection to ensure no new connections come in 354 | if err := db.Close(); err != nil { 355 | return nil, err 356 | } 357 | 358 | s.RawConfig["password"] = password 359 | return s.RawConfig, nil 360 | } 361 | 362 | func calculateExpirationString(expiration time.Time) (string, error) { 363 | // create time.Time object 364 | currentTime := time.Now() 365 | 366 | // get the diff 367 | expirationTime := expiration 368 | timeDiff := expirationTime.Sub(currentTime) 369 | 370 | // since it's going to be a string, just make it one 371 | diffStr := timeDiff.String() 372 | 373 | // split into pieces 374 | pieces := strings.SplitAfterN(diffStr, "h", 2) 375 | 376 | // extract the hours 377 | expirationStr := strings.ReplaceAll(pieces[0], "h", "") 378 | 379 | // translate the expiration into whole days from hours 380 | // SEEMS TO BE LAST THING FROM GETTING THIS WORKING 381 | // TAKING OUT FOR NOW TO SEE... 382 | // expirationStr = "1" // for now 383 | if expirationInt, err := strconv.Atoi(expirationStr); err == nil { 384 | // this number will be in hours 385 | if (expirationInt / 24) < 1 { 386 | // anything less than 24 hours becomes 1 day 387 | expirationStr = "1" 388 | } else { 389 | // anything more than 24 hours is rounded down to least possible days 390 | expirationStr = strconv.Itoa(int(math.Floor(float64(expirationInt / 24)))) 391 | } 392 | 393 | return expirationStr, nil 394 | } else { 395 | return "", err 396 | } 397 | } 398 | --------------------------------------------------------------------------------