├── .gitignore ├── DELEGATED.md ├── LICENSE ├── README.md ├── backend.go ├── doc ├── adfs.png ├── delegated.png └── jwt.png ├── main.go ├── path_config.go ├── path_login.go ├── scripts └── mfa.sh ├── test ├── jwt-auth.bats └── test.hcl └── util.go /.gitignore: -------------------------------------------------------------------------------- 1 | **/.DS_Store 2 | **/releases 3 | **/*.crt 4 | **/*.pem 5 | **/test 6 | **/test/* 7 | **/config.sh 8 | **/build.sh 9 | -------------------------------------------------------------------------------- /DELEGATED.md: -------------------------------------------------------------------------------- 1 | A design for delegated authentication using Vault 2 | -------- 3 | 4 | I have built 2 Vault plugins - [the trustee plugin](https://github.com/immutability-io/trustee) and [the jwt-auth plugin](https://github.com/immutability-io/jwt-auth) - which when used together can provide a delegated authentication mechanism for web services. 5 | 6 | 7 | # Some Delegated Authentication Use Cases 8 | 9 | There are a handful of ways the Trustee plugin can be used effectively in conjunction with the JWT-Auth plugin. I will start with a very simple use case: 10 | 11 | ![Delegated Authentication](./doc/delegated.png?raw=true "Delegated Authentication Flow") 12 | 13 | It must be pointed out: **the Web Service above can use a completely separate Vault for the Trustee plugin than it uses for authentication (JWT-Auth plugin).** This is because the Trustee's address is all the JWT-Auth plugin needs to **trust** to validate the JWT. 14 | 15 | ## Governance by Proxy 16 | 17 | Imagine that you have an identity in Active Directory: You have a user ID and you are the member of a handful of Active Directory groups. One of these groups is `pay-master-group`. Your membership in this group means that you are allowed to cut checks from a bank account (`123412341234`) that holds millions of dollars. 18 | 19 | Accessing this bank account (`123412341234`) requires a credential - for simplicity's sake, let's call it a password - so, we want to use Vault to secure this password. We put the password in Vault at the following path: `secret/bank/123412341234` 20 | 21 | ### Protecting the Credential with RBAC Is Not Enough!!! 22 | 23 | A simple solution to securing this bank account password might be to use the JWT-Auth plugin as follows: 24 | 25 | 1. Create a policy that allows this path to be read: 26 | 27 | ```sh 28 | 29 | $ cat pay-master.hcl 30 | 31 | path "secret/bank/123412341234" { 32 | policy = "read" 33 | } 34 | 35 | $ vault policy write pay-master-policy pay-master.hcl 36 | ``` 37 | 38 | 2. Map this policy to the `pay-master` group: 39 | 40 | ```sh 41 | $ vault write auth/jwt-auth/map/claims/pay-master-group value=pay-master-policy 42 | ``` 43 | 44 | Now when you, the pay-master, authenticate to the `auth/jwt-auth/login` Vault endpoint you get a token you can use to read the password, and all is great: 45 | 46 | ```sh 47 | $ read -s PASSWORD; vault write -format=json auth/jwt-auth/login username=cypherhat password=$PASSWORD | jq ; unset PASSWORD 48 | { 49 | "request_id": "1bced3ff-acc7-14b0-99c8-f50c28e3b83c", 50 | "lease_id": "", 51 | "lease_duration": 0, 52 | "renewable": false, 53 | "data": null, 54 | "warnings": null, 55 | "auth": { 56 | "client_token": "5d72d7200-602f-3451-e19a-d9860fc05a63", 57 | "accessor": "953e1412-bb92-e81c-70bf-0aa6e7262238", 58 | "policies": [ 59 | "default", 60 | "pay-master-policy" 61 | ], 62 | "metadata": { 63 | "jwt": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJncm91cCI6WyJwYXktbWFzdGVyLWdyb3VwIl0sInN1YiI6ImN5cGhlcmhhdCJ9.kNrzfOxcALrGXQPbYkSnoBJ_LjiRfPmQXjCOv5l2uUeuM3H6GCdqnQY5kvnZtJuj4ztR3Us_uDI5cxhDJ45OQEHz4zRipYJX28rKHfO04rK1ieP95KNRxlQ1YCnufWmHHmPJgh3aK-a9zGdy2ZaXlmpVbDEOxNyUm7gNuJ1AFkYqN0S_LnNx_alU5zzoxTkKGMpTLVGzPqVKrhXRuEZwK1duKlAS4YIvq4BzYJm7lMyAafdxEkeqPb1VptQEvJzyIU2xkZMBBlhbxj6qZUEiiKloPzgAs6z1pLYDCpJL6SZ50ozyDM3tqocqY6Qqaxl3Rk0WARC17z7UFIuiOERMfUafvKC5v8aA7Wzr_3BoM91qNI3IyqFl-GEYToDZ4TD922hvNaVpdKciKIJMUUZjNXvXD9xhGWWUqwvHMPkYYJDnC5uRDdlgzgXVIGD0ABPk3a6ULLMw9PxF_RpjQzUkqVfywsUvaUOj0jPx1SVeS3CQdjFcPLwYQuub5H3HzjGUWSFLetktGrbdG_YnW6lFAz-wMzI_BYOSBtwiq9IhrxDL0x2E6PYnU1k5C0-DmYV3yDb_cMNul0KZLq4e0tC6i8YeteAlqCfoWOc3WgWPuqVulBsPGIkbmuRNYOWEpxlseWaX41On_BSskfL7NK02YHHFIZH91njGSDHo_Md0h6Y", 64 | "roles": "[pay-master-group]", 65 | "username": "tssbi08" 66 | }, 67 | "lease_duration": 3600, 68 | "renewable": true 69 | } 70 | } 71 | 72 | $ vault login 5d72d7200-602f-3451-e19a-d9860fc05a63 73 | 74 | Success! You are now authenticated. The token information displayed below 75 | is already stored in the token helper. You do NOT need to run "vault login" 76 | again. Future Vault requests will automatically use this token. 77 | 78 | Key Value 79 | --- ----- 80 | token d72d7200-602f-3451-e19a-d9860fc05a63 81 | token_accessor 953e1412-bb92-e81c-70bf-0aa6e7262238 82 | token_duration 30m 83 | token_renewable false 84 | token_policies [default pay-master-policy] 85 | 86 | $ vault read secret/bank/123412341234 87 | Key Value 88 | --- ----- 89 | refresh_interval 24h 90 | password pa49881word 91 | ``` 92 | 93 | ### Necessity and Sufficiency and Context 94 | 95 | Protecting the password to the bank account with an access control as described above is **necessary** to prevent unauthorized access to the password; however, it is not **sufficient** to prevent unauthorized access to the password. Most likely, this password should never be accessed by an end user's machine. Furthermore, there are typically many aspects of governance that are required to happen before this password can be used in a legitimate context. That governance is often manifested as a software process - trusted code that has to execute before and after accessing and using the password. Let's call this code a `service`. 96 | 97 | To make this use case realistic and interesting, let's say that this `service` also performs tasks that are less sensitive - in addition to debiting the bank account; it sends non-account information to the bank. 98 | 99 | Let's posit the following as a **sufficient** access control: 100 | 101 | 1. The actor that accesses the password must be in the `pay-master-group`; 102 | 2. The actor cannot access the password except within the context of the trusted code described above; 103 | 2. The password can **not** be accessed by the above service unless it is acting on behalf of the actor in #1. 104 | 105 | ### In Which Context is Everything 106 | 107 | Before we talk about the `service`, let's talk about the network context where the password is used. One might say: we could use IP constraints to add an additional authentication factor to the Vault JWT-Auth plugin. (This plugin **does** support IP constraints.) Though this is certainly possible; in our new world of containers as functions and micro-services, IP addresses are pretty hard to pin down with the kind of resolution that is necessary to make trust decisions. We rarely know the IP address ahead of time, so we are left with broad CIDR block ranges. 108 | 109 | Furthermore, IP addresses have always been problematic as an authentication factor: they only works well if you have "true" IP - the protocols used by proxies are insecure as X-Forwarded-For can be tampered with; and, it isn't realistic to expect a packet to be relayed without some form of network address translation. 110 | 111 | Wouldn't it be awesome if there was a functional equivalent of the IP address for the modern Internet? Well, as is evidenced by the Trustee Vault plugin, [we can extend the IP Metaphor with Ethereum Addreses](https://github.com/immutability-io/trustee#extending-the-ip-metaphor-with-ethereum-addreses). 112 | 113 | With the Trustee plugin, we can tighten up trust to effect what we describe as **sufficient** above. Follows is how we do that: 114 | 115 | #### Establish a Trustee 116 | 117 | A trustee is essentially a well-known Ethereum address - we trust that only the actor that possesses the private key associated with an Ethereum address can make valid claims on behalf of that Ethereum address. So, the first thing we have to do is establish a trustee. This doesn't have to be done using the Vault Trustee plugin, but since it **does** have to be done using a private key, Vault is a good choice for securing this key. 118 | 119 | To establish the `bank-account-service` trustee using the Vault Trustee plugin, we do the following (assuming the plugin has been successfully installed.): 120 | 121 | ```sh 122 | ## The Trustee plugin is mounted using: 123 | 124 | $ vault secrets enable -path=trust -plugin-name=trustee plugin 125 | $ vault write -f trust/trustees/bank-account-service 126 | Key Value 127 | --- ----- 128 | address 0x90f9321a3615fCFB4F0Fe8C1E45986D85251F5FE 129 | blacklist 130 | chain_id 1977 131 | whitelist 132 | 133 | ``` 134 | 135 | The above address is the Ethereum address. The critical element of the trust equation here is to give the **legitimate** `bank-account-service` write access to the path `trust/trustees/bank-account-service/claim`. This can be done in several ways using Vault; but, all of these amount to creating an authentication mechanism for the `bank-account-service` so that it has a policy that includes: 136 | 137 | ``` 138 | 139 | $ cat bank-account-service.hcl 140 | 141 | path "trust/trustees/bank-account-service/claim" { 142 | policy = "write" 143 | } 144 | 145 | ``` 146 | 147 | #### Trust the Trustee 148 | 149 | So, now we have a trustee, aka, an Ethereum address. Now, we have to trust it to authenticate as the `pay-master's` behalf. What this means is that we will add the trustee (address) to the jwt-auth mechanism described above. 150 | 151 | ```sh 152 | $ vault write auth/jwt-auth/config jwt_signer=@jwtRS256.key.pub trustee_list="0x90f9321a3615fCFB4F0Fe8C1E45986D85251F5FE" ttl=60m max_ttl=300m 153 | ``` 154 | 155 | Note: The file `jwtRS256.key.pub` is the public key that corresponds to the private key that Active Directory used to sign a JWT token. 156 | 157 | Now just to test, let's authenticate to Active Directory and get a JWT token. (I won't show this here.) If we capture this token in a file named `delegate.json` we can try to authenticate to Vault with the token: 158 | 159 | ```sh 160 | $ vault write -format=json auth/jwt-auth/login token=@delegate.json | jq . 161 | Error writing data to auth/test/jwt/login: Error making API request. 162 | 163 | URL: PUT https://vault.awesomesauce.com:8200/v1/auth/jwt-auth/login 164 | Code: 500. Errors: 165 | 166 | * we don't trust this issuer: http://fs.awesomesauce.com/adfs/services/trust 167 | ``` 168 | 169 | Authentication fails, as it should - we are not the `bank-account-service`! We are just the `pay-master` and we are trying to get secrets **out of the bounds of a legitimate context**. 170 | 171 | #### Delegated Authentication 172 | 173 | So, we have deployed our `bank-account-service` to a Kubernetes cluster. This service is used by a `bank-account-application` which we login to using an OAuth2 ceremony with ADFS. This application propagates our JWT token to our trustee - the `bank-account-service`. This JWT is a base64 encoded string that the `bank-account-service` adds to a JSON structure that constitutes the claims it wants to make. This JWT **must be** the `delegate` claim: 174 | 175 | ```sh 176 | 177 | $ cat claims.json 178 | { 179 | "service": "bank-account-service", 180 | "delegate": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJncm91cCI6WyJwYXktbWFzdGVyLWdyb3VwIl0sInN1YiI6ImN5cGhlcmhhdCJ9.kNrzfOxcALrGXQPbYkSnoBJ_LjiRfPmQXjCOv5l2uUeuM3H6GCdqnQY5kvnZtJuj4ztR3Us_uDI5cxhDJ45OQEHz4zRipYJX28rKHfO04rK1ieP95KNRxlQ1YCnufWmHHmPJgh3aK-a9zGdy2ZaXlmpVbDEOxNyUm7gNuJ1AFkYqN0S_LnNx_alU5zzoxTkKGMpTLVGzPqVKrhXRuEZwK1duKlAS4YIvq4BzYJm7lMyAafdxEkeqPb1VptQEvJzyIU2xkZMBBlhbxj6qZUEiiKloPzgAs6z1pLYDCpJL6SZ50ozyDM3tqocqY6Qqaxl3Rk0WARC17z7UFIuiOERMfUafvKC5v8aA7Wzr_3BoM91qNI3IyqFl-GEYToDZ4TD922hvNaVpdKciKIJMUUZjNXvXD9xhGWWUqwvHMPkYYJDnC5uRDdlgzgXVIGD0ABPk3a6ULLMw9PxF_RpjQzUkqVfywsUvaUOj0jPx1SVeS3CQdjFcPLwYQuub5H3HzjGUWSFLetktGrbdG_YnW6lFAz-wMzI_BYOSBtwiq9IhrxDL0x2E6PYnU1k5C0-DmYV3yDb_cMNul0KZLq4e0tC6i8YeteAlqCfoWOc3WgWPuqVulBsPGIkbmuRNYOWEpxlseWaX41On_BSskfL7NK02YHHFIZH91njGSDHo_Md0h6Y" 181 | } 182 | 183 | ``` 184 | 185 | First, we call the Vault Trustee plugin to create a `claim`. This `claim` takes the form of a JWT token that is signed with the private key used to generate the Trustee's Ethereum address: 186 | 187 | ```sh 188 | $ vault write -format=json trust/trustees/bank-account-service/claim claims=@claim.json 189 | { 190 | "request_id": "2aefacbf-152f-322b-3c32-468b98d6af37", 191 | "lease_id": "", 192 | "lease_duration": 0, 193 | "renewable": false, 194 | "data": { 195 | "delegate": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJncm91cCI6WyJwYXktbWFzdGVyLWdyb3VwIl0sInN1YiI6ImN5cGhlcmhhdCJ9.kNrzfOxcALrGXQPbYkSnoBJ_LjiRfPmQXjCOv5l2uUeuM3H6GCdqnQY5kvnZtJuj4ztR3Us_uDI5cxhDJ45OQEHz4zRipYJX28rKHfO04rK1ieP95KNRxlQ1YCnufWmHHmPJgh3aK-a9zGdy2ZaXlmpVbDEOxNyUm7gNuJ1AFkYqN0S_LnNx_alU5zzoxTkKGMpTLVGzPqVKrhXRuEZwK1duKlAS4YIvq4BzYJm7lMyAafdxEkeqPb1VptQEvJzyIU2xkZMBBlhbxj6qZUEiiKloPzgAs6z1pLYDCpJL6SZ50ozyDM3tqocqY6Qqaxl3Rk0WARC17z7UFIuiOERMfUafvKC5v8aA7Wzr_3BoM91qNI3IyqFl-GEYToDZ4TD922hvNaVpdKciKIJMUUZjNXvXD9xhGWWUqwvHMPkYYJDnC5uRDdlgzgXVIGD0ABPk3a6ULLMw9PxF_RpjQzUkqVfywsUvaUOj0jPx1SVeS3CQdjFcPLwYQuub5H3HzjGUWSFLetktGrbdG_YnW6lFAz-wMzI_BYOSBtwiq9IhrxDL0x2E6PYnU1k5C0-DmYV3yDb_cMNul0KZLq4e0tC6i8YeteAlqCfoWOc3WgWPuqVulBsPGIkbmuRNYOWEpxlseWaX41On_BSskfL7NK02YHHFIZH91njGSDHo_Md0h6Y", 196 | "eth": "0x0f2c5c77d6f0d7318653ceb68288d94463bee72265e9c38e0e12437bcbf10ef144596a5fbef9d4db833cdcdf9092031d30ea805939019cb9fc3ac33e718ece8601", 197 | "exp": "1528317525", 198 | "iss": "0x90f9321a3615fCFB4F0Fe8C1E45986D85251F5FE", 199 | "jti": "8bb409f3-2ccb-48f2-b3d6-d7beaea7f97b", 200 | "jwt": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZWxlZ2F0ZSI6ImV5SmhiR2NpT2lKU1V6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUpuY205MWNDSTZXeUp3WVhrdGJXRnpkR1Z5TFdkeWIzVndJbDBzSW5OMVlpSTZJbU41Y0dobGNtaGhkQ0o5LmtOcnpmT3hjQUxyR1hRUGJZa1Nub0JKX0xqaVJmUG1RWGpDT3Y1bDJ1VWV1TTNINkdDZHFuUVk1a3ZuWnRKdWo0enRSM1VzX3VESTVjeGhESjQ1T1FFSHo0elJpcFlKWDI4cktIZk8wNHJLMWllUDk1S05SeGxRMVlDbnVmV21ISG1QSmdoM2FLLWE5ekdkeTJaYVhsbXBWYkRFT3hOeVVtN2dOdUoxQUZrWXFOMFNfTG5OeF9hbFU1enpveFRrS0dNcFRMVkd6UHFWS3JoWFJ1RVp3SzFkdUtsQVM0WUl2cTRCellKbTdsTXlBYWZkeEVrZXFQYjFWcHRRRXZKenlJVTJ4a1pNQkJsaGJ4ajZxWlVFaWlLbG9QemdBczZ6MXBMWURDcEpMNlNaNTBvenlETTN0cW9jcVk2UXFheGwzUmswV0FSQzE3ejdVRkl1aU9FUk1mVWFmdktDNXY4YUE3V3pyXzNCb005MXFOSTNJeXFGbC1HRVlUb0RaNFREOTIyaHZOYVZwZEtjaUtJSk1VVVpqTlh2WEQ5eGhHV1dVcXd2SE1Qa1lZSkRuQzV1UkRkbGd6Z1hWSUdEMEFCUGszYTZVTExNdzlQeEZfUnBqUXpVa3FWZnl3c1V2YVVPajBqUHgxU1ZlUzNDUWRqRmNQTHdZUXV1YjVIM0h6akdVV1NGTGV0a3RHcmJkR19Zblc2bEZBei13TXpJX0JZT1NCdHdpcTlJaHJ4REwweDJFNlBZblUxazVDMC1EbVlWM3lEYl9jTU51bDBLWkxxNGUwdEM2aThZZXRlQWxxQ2ZvV09jM1dnV1B1cVZ1bEJzUEdJa2JtdVJOWU9XRXB4bHNlV2FYNDFPbl9CU3NrZkw3TkswMllISEZJWkg5MW5qR1NESG9fTWQwaDZZIiwiZXRoIjoiMHgwZjJjNWM3N2Q2ZjBkNzMxODY1M2NlYjY4Mjg4ZDk0NDYzYmVlNzIyNjVlOWMzOGUwZTEyNDM3YmNiZjEwZWYxNDQ1OTZhNWZiZWY5ZDRkYjgzM2NkY2RmOTA5MjAzMWQzMGVhODA1OTM5MDE5Y2I5ZmMzYWMzM2U3MThlY2U4NjAxIiwiZXhwIjoiMTUyODMxNzUyNSIsImlzcyI6IjB4OTBmOTMyMWEzNjE1ZkNGQjRGMEZlOEMxRTQ1OTg2RDg1MjUxRjVGRSIsImp0aSI6IjhiYjQwOWYzLTJjY2ItNDhmMi1iM2Q2LWQ3YmVhZWE3Zjk3YiIsIm5iZiI6IjE1MjgzMTM5MjUiLCJzZXJ2aWNlIjoiYmFuay1hY2NvdW50LXNlcnZpY2UiLCJzdWIiOiIweDkwZjkzMjFhMzYxNWZDRkI0RjBGZThDMUU0NTk4NkQ4NTI1MUY1RkUifQ.AwDFFg8V0bDQVJYpzqsucU6g2fIwiXlftHbx-7Yb3ymNo2OmgsqtbV-Qv5o0X0byma3yWhhMItvIdWMu3BgBZw", 201 | "nbf": "1528313925", 202 | "service": "bank-account-service", 203 | "sub": "0x90f9321a3615fCFB4F0Fe8C1E45986D85251F5FE" 204 | }, 205 | "warnings": null 206 | } 207 | ``` 208 | 209 | The JWT that is returned is captured in a file named `service.json` and then sent to the jwt-auth endpoint to perform delegated authentication. 210 | 211 | ```sh 212 | $ vault write -format=json auth/jwt-auth/login token=@service.json | jq . 213 | { 214 | "request_id": "532cc2cd-05e8-4704-b853-7fd5cd1dec5b", 215 | "lease_id": "", 216 | "lease_duration": 0, 217 | "renewable": false, 218 | "data": null, 219 | "warnings": null, 220 | "auth": { 221 | "client_token": "04302161-36af-6e96-54bf-319a8cf1aa73", 222 | "accessor": "92a422f4-ea74-6241-923f-00473345ba42", 223 | "policies": [ 224 | "default" 225 | ], 226 | "metadata": { 227 | "jwt": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJncm91cCI6WyJwYXktbWFzdGVyLWdyb3VwIl0sInN1YiI6ImN5cGhlcmhhdCJ9.kNrzfOxcALrGXQPbYkSnoBJ_LjiRfPmQXjCOv5l2uUeuM3H6GCdqnQY5kvnZtJuj4ztR3Us_uDI5cxhDJ45OQEHz4zRipYJX28rKHfO04rK1ieP95KNRxlQ1YCnufWmHHmPJgh3aK-a9zGdy2ZaXlmpVbDEOxNyUm7gNuJ1AFkYqN0S_LnNx_alU5zzoxTkKGMpTLVGzPqVKrhXRuEZwK1duKlAS4YIvq4BzYJm7lMyAafdxEkeqPb1VptQEvJzyIU2xkZMBBlhbxj6qZUEiiKloPzgAs6z1pLYDCpJL6SZ50ozyDM3tqocqY6Qqaxl3Rk0WARC17z7UFIuiOERMfUafvKC5v8aA7Wzr_3BoM91qNI3IyqFl-GEYToDZ4TD922hvNaVpdKciKIJMUUZjNXvXD9xhGWWUqwvHMPkYYJDnC5uRDdlgzgXVIGD0ABPk3a6ULLMw9PxF_RpjQzUkqVfywsUvaUOj0jPx1SVeS3CQdjFcPLwYQuub5H3HzjGUWSFLetktGrbdG_YnW6lFAz-wMzI_BYOSBtwiq9IhrxDL0x2E6PYnU1k5C0-DmYV3yDb_cMNul0KZLq4e0tC6i8YeteAlqCfoWOc3WgWPuqVulBsPGIkbmuRNYOWEpxlseWaX41On_BSskfL7NK02YHHFIZH91njGSDHo_Md0h6Y", 228 | "roles": "[pay-master-group]", 229 | "username": "cypherhat" 230 | }, 231 | "lease_duration": 3600, 232 | "renewable": true 233 | } 234 | } 235 | 236 | $ vault login 04302161-36af-6e96-54bf-319a8cf1aa73 237 | $ vault read secret/bank/123412341234 238 | Key Value 239 | --- ----- 240 | refresh_interval 24h 241 | password pa49881word 242 | 243 | ``` 244 | 245 | ### FIN -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | JWT-Auth: A generic, and simplistic, authentication plugin for Vault 2 | --------------- 3 | 4 | JWTs are all the rage. They provide a simple way of transmitting claims made by a trusted entity to another. So, if Vault trusts the signer of a JWT, why shouldn't Vault allow that signer to assert claims about an identity? JWTs are bearer tokens, so if the JWT gets compromised then an attacker could use it to gain access to Vault. While this attack vector is something to protect against, it is no different than the compromise of a GitHub personal access token or even a person's LDAP credentials. A nice aspect to JWTs is that they *usually* have short TTLs, so they are intrinsically safer than GitHub personal access tokens or LDAP credentials (which typically are long lived.) 5 | 6 | This plugin is just another tool in the chest for a Vaulter: if you wish to provide access to Vault based upon the bearer of a JWT, then here is your tool. Context is everything, and since Vault gives you choices about how to manage context, this plugin gives you another choice in how to navigate that context. 7 | 8 | ## Delegated Authentication 9 | 10 | This plugin can be used in concert with the [Trustee plugin](https://github.com/immutability-io/trustee) to effect [delegated authentication](./DELEGATED.md). 11 | 12 | ## Build/Install 13 | 14 | Building is typically golang: 15 | 16 | ```sh 17 | $ go get github.com/immutability-io/jwt-auth 18 | ``` 19 | 20 | This will drop the executable in your `$GOPATH/bin` directory. Alternatively, you can download the latest release from this GitHub repo. If you do this, you should verify the release like this (assuming your current directory is where the files `SHA256SUMS.sig` and `SHA256SUMS` reside.) 21 | 22 | ```sh 23 | $ keybase pgp verify -d ./SHA256SUMS.sig -i ./SHA256SUMS 24 | ``` 25 | 26 | ## Installation 27 | 28 | If you download the release, the zipfile contains a file called `SHA265SUM`. This is what I got for `shasum -a 256` on my build. You will need this value to install the plugin. You can export it into your environment: 29 | 30 | ```sh 31 | $ export SHA256=$(cat SHA265SUM) 32 | ``` 33 | 34 | Alternatively, if you built the plugin, and it is in the `$GOPATH/bin` directory do this: 35 | 36 | ```sh 37 | $ export SHA256=$(shasum -a 256 "$GOPATH/bin/jwt-auth" | cut -d' ' -f1) 38 | ``` 39 | 40 | I assume that you are using TLS to connect to Vault. I assume this because I respect you. Let's say that your Vault configuration resides in: `$HOME/etc/vault.d/` 41 | 42 | A very simple Vault configuration - a laptop special - might look like this: 43 | 44 | ``` 45 | "default_lease_ttl" = "24h" 46 | 47 | "ui" = "true" 48 | "max_lease_ttl" = "24h" 49 | "disable_mlock" = "true" 50 | "backend" "file" { 51 | "path" = "/Users/immutability/etc/vault.d/data" 52 | } 53 | 54 | "api_addr" = "https://localhost:8200" 55 | 56 | "listener" "tcp" { 57 | "address" = "localhost:8200" 58 | 59 | "tls_cert_file" = "/Users/immutability/etc/vault.d/vault.crt" 60 | "tls_client_ca_file" = "/Users/immutability/etc/vault.d/root.crt" 61 | "tls_key_file" = "/Users/immutability/etc/vault.d/vault.key" 62 | } 63 | 64 | "plugin_directory" = "/Users/immutability/etc/vault.d/vault_plugins" 65 | ``` 66 | 67 | Note: `"api_addr" = "https://localhost:8200"`. [This is important for plugins](https://www.vaultproject.io/docs/configuration/index.html#api_addr). 68 | 69 | Assuming this configuration - yours may be different, so the following commands may need to be tweaked -the following will install the plugin: 70 | 71 | ```sh 72 | $ mv $GOPATH/bin/jwt-auth $HOME/etc/vault.d/vault_plugins 73 | $ vault write sys/plugins/catalog/jwt-auth \ 74 | sha_256="${SHA256}" \ 75 | command="jwt-auth --ca-cert=$HOME/etc/vault.d/root.crt --client-cert=$HOME/etc/vault.d/vault.crt --client-key=$HOME/etc/vault.d/vault.key" 76 | $ vault auth enable -path=jwt-auth -plugin-name=jwt-auth -description="JWT authentication plugin" plugin 77 | ``` 78 | 79 | Assuming that worked, you should see something like this when you list your auth endpoints: 80 | 81 | ```sh 82 | $ vault auth list 83 | Path Type Description 84 | ---- ---- ----------- 85 | jwt-auth/ plugin JWT authentication plugin 86 | token/ token token based credentials 87 | ``` 88 | 89 | ## Configuration 90 | 91 | There are 4 main configuration *options* with this plugin: 92 | 93 | 1. Configure the trust - associate the signer key and algorithm with the authentication endpoint. 94 | 2. Configure the claims - choose which claims map to policies. 95 | 3. Configure the IP contraints: choose which IP ranges are allowed to authenticate. 96 | 4. Map policies to claims. 97 | 98 | The first 3 options are configured via the `config` endpoint. Assuming you used the path exemplified above (you can mount this plugin at a variety of paths - this is not a singleton) you configure as follows: 99 | 100 | ### Trust 101 | 102 | ```sh 103 | $ vault write auth/jwt-auth/config jwt_signer=@jwtRS256.key.pub ttl=60m max_ttl=300m 104 | ``` 105 | 106 | This will establish trust with whatever entity has the private key corresponding to the `jwtRS256.key.pub` public key. 107 | 108 | ### Claims 109 | 110 | The above will use the default claims `groups` and `sub` for claim and subject mapping. Since you are probably confused, and example JWT is probably useful now. Consider the following JWT: 111 | 112 | ![Very silly JWT](/doc/jwt.png?raw=true "Silly JWT") 113 | 114 | This JWT has 2 claims: `groups` and `sub`. The `sub` claim identifies the subject of the JWT - about whom the claims are made. The `groups` is an statement about attributes of the subject: `goober` belongs to the `test` group. 115 | 116 | If this is not your JWT schema, then you can change the names of the claims that you want to use to map policies. For example, consider an ADFS JWT: 117 | 118 | ![ADFS JWT](/doc/adfs.png?raw=true "ADFS JWT") 119 | 120 | In this case, you would want to point to different claims - probably `groupsid` and `upn`. You would do this thusly: 121 | 122 | ```sh 123 | $ vault write auth/jwt-auth/config jwt_signer=@adfs.key.pub role_claim=groupsid subject_claim=upn ttl=60m max_ttl=300m 124 | ``` 125 | 126 | ### Configure IP Constraints 127 | 128 | Suppose you only want certain machines to authenticate using this JWT. In that case, you can restrict authentication to a set of CIDR blocks. For example: 129 | 130 | ```sh 131 | $ vault write auth/jwt-auth/config jwt_signer=@adfs.key.pub role_claim=groupsid subject_claim=upn bound_cidr_list="10.23.14.0/22,10.45.12.0/22" ttl=60m max_ttl=300m 132 | ``` 133 | 134 | Now, when anything tries to authenticate - with a valid JWT token - from an IP address outside of that range it will fail. 135 | 136 | **Note: IP restrictions are helpful - to some extent - but not really awesome in a containerized world. Stay tuned - I will be merging ideas from my Ethereum plugin with this plugin in the near future. This will address that limitation.** 137 | 138 | ### Map policies to claims 139 | 140 | Suppose you have 2 policies in Vault: 141 | 142 | 1. A user policy called `developer`; and, 143 | 2. A policy called `admin` that requires some entitlement (aka, claim in a JWT) 144 | 145 | To map the `developer` policy to a user named `goober` do the following. (Note: the name `goober` is identified in the JWT by the subject claim. See #2 above): 146 | 147 | ```sh 148 | $ vault write auth/jwt-auth/map/users/goober value=developer 149 | ``` 150 | 151 | To map the `admin` policy to all users that are part of the `admin` group do the following. (Note: the name `admin` is identified in the JWT by the role claim. See #2 above): 152 | 153 | ```sh 154 | $ vault write auth/jwt-auth/map/claims/admin value=admin 155 | ``` 156 | 157 | ## Usage 158 | 159 | Once configured, authentication proceeds as follows: 160 | 161 | ```sh 162 | $ vault write -format=json auth/jwt-auth/login token=@jwt.json 163 | { 164 | "request_id": "13d0f04e-882f-f83c-7b5a-71807a948feb", 165 | "lease_id": "", 166 | "lease_duration": 0, 167 | "renewable": false, 168 | "data": null, 169 | "warnings": null, 170 | "auth": { 171 | "client_token": "782b473e-b79a-10bc-50a3-61a44b3937f3", 172 | "accessor": "ce6611a0-5055-fdc9-8ee4-3e324050d4ec", 173 | "policies": [ 174 | "default", 175 | "goober", 176 | "admin" 177 | ], 178 | "metadata": { 179 | "claims": "[test]", 180 | "username": "goober" 181 | }, 182 | "lease_duration": 3600, 183 | "renewable": true 184 | } 185 | } 186 | ``` 187 | 188 | ## Have fun 189 | 190 | And let me know what you like or hate... but be kind, I am very sensitive. :) Note: much of this code was based on the Vault GitHub plugin. I used the same code that I contributed to that plugin for MFA here. 191 | 192 | Also, I will be delivering a secrets plugin that allows the creation of JWTs in the near future. This will include some capabilities that should be fun. 193 | 194 | Cheers! 195 | -------------------------------------------------------------------------------- /backend.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2018 Immutability, LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "context" 19 | 20 | "github.com/hashicorp/vault/helper/mfa" 21 | "github.com/hashicorp/vault/logical" 22 | "github.com/hashicorp/vault/logical/framework" 23 | ) 24 | 25 | // Factory creates the Backend 26 | func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { 27 | b := Backend() 28 | if err := b.Setup(ctx, conf); err != nil { 29 | return nil, err 30 | } 31 | return b, nil 32 | } 33 | 34 | // FactoryType returns the Factory 35 | func FactoryType(backendType logical.BackendType) logical.Factory { 36 | return func(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { 37 | b := Backend() 38 | b.BackendType = backendType 39 | if err := b.Setup(ctx, conf); err != nil { 40 | return nil, err 41 | } 42 | return b, nil 43 | } 44 | } 45 | 46 | // Backend is the implementation of the JWT Auth backend 47 | func Backend() *backend { 48 | var b backend 49 | b.RoleMap = &framework.PolicyMap{ 50 | PathMap: framework.PathMap{ 51 | Name: "claims", 52 | }, 53 | DefaultKey: "default", 54 | } 55 | 56 | b.UserMap = &framework.PolicyMap{ 57 | PathMap: framework.PathMap{ 58 | Name: "users", 59 | }, 60 | DefaultKey: "default", 61 | } 62 | 63 | b.Backend = &framework.Backend{ 64 | Help: backendHelp, 65 | 66 | PathsSpecial: &logical.Paths{ 67 | Root: mfa.MFARootPaths(), 68 | Unauthenticated: []string{ 69 | "login", 70 | }, 71 | }, 72 | 73 | Paths: framework.PathAppend( 74 | pathConfig(&b), 75 | b.RoleMap.Paths(), 76 | b.UserMap.Paths(), 77 | mfa.MFAPaths(b.Backend, pathLogin(&b)[0]), 78 | ), 79 | AuthRenew: b.pathLoginRenew, 80 | BackendType: logical.TypeCredential, 81 | } 82 | 83 | return &b 84 | } 85 | 86 | type backend struct { 87 | *framework.Backend 88 | 89 | RoleMap *framework.PolicyMap 90 | UserMap *framework.PolicyMap 91 | } 92 | 93 | const backendHelp = ` 94 | The JWT Auth credential provider allows authentication via JWT. 95 | 96 | The JWT Auth backend is configured by mapping claims in the JWT 97 | to the policies that should be allowed for those claims. The name of 98 | claim to use is configurable via the config path. 99 | ` 100 | -------------------------------------------------------------------------------- /doc/adfs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutability-io/jwt-auth/56a06505d25275101ca583e18977a539256c6535/doc/adfs.png -------------------------------------------------------------------------------- /doc/delegated.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutability-io/jwt-auth/56a06505d25275101ca583e18977a539256c6535/doc/delegated.png -------------------------------------------------------------------------------- /doc/jwt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/immutability-io/jwt-auth/56a06505d25275101ca583e18977a539256c6535/doc/jwt.png -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2018 Immutability, LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "log" 19 | "os" 20 | 21 | "github.com/hashicorp/vault/helper/pluginutil" 22 | "github.com/hashicorp/vault/logical" 23 | "github.com/hashicorp/vault/logical/plugin" 24 | ) 25 | 26 | func main() { 27 | apiClientMeta := &pluginutil.APIClientMeta{} 28 | flags := apiClientMeta.FlagSet() 29 | flags.Parse(os.Args[1:]) // Ignore command, strictly parse flags 30 | 31 | tlsConfig := apiClientMeta.GetTLSConfig() 32 | tlsProviderFunc := pluginutil.VaultPluginTLSProvider(tlsConfig) 33 | 34 | factoryFunc := FactoryType(logical.TypeCredential) 35 | err := plugin.Serve(&plugin.ServeOpts{ 36 | BackendFactoryFunc: factoryFunc, 37 | TLSProviderFunc: tlsProviderFunc, 38 | }) 39 | if err != nil { 40 | log.Println(err) 41 | os.Exit(1) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /path_config.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2018 Immutability, LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "context" 19 | "fmt" 20 | "time" 21 | 22 | "github.com/hashicorp/vault/logical" 23 | "github.com/hashicorp/vault/logical/framework" 24 | ) 25 | 26 | func pathConfig(b *backend) []*framework.Path { 27 | return []*framework.Path{ 28 | &framework.Path{ 29 | Pattern: "config", 30 | Fields: map[string]*framework.FieldSchema{ 31 | "role_claim": &framework.FieldSchema{ 32 | Default: "group", 33 | Type: framework.TypeString, 34 | Description: `Name of the claim (key) which will be used to map roles to policies.`, 35 | }, 36 | "subject_claim": &framework.FieldSchema{ 37 | Default: "sub", 38 | Type: framework.TypeString, 39 | Description: `Name of the claim (key) which will be used to map the user's identity.`, 40 | }, 41 | "jwt_signer": &framework.FieldSchema{ 42 | Type: framework.TypeString, 43 | Description: `The public key used to validate the JWT signature.`, 44 | }, 45 | "jwt_algorithm": &framework.FieldSchema{ 46 | Type: framework.TypeString, 47 | Default: "RS256", 48 | Description: `The algorithm used to generate the signer's private key.`, 49 | }, 50 | "oauth_resource": &framework.FieldSchema{ 51 | Type: framework.TypeString, 52 | Description: `The resource that is the audience of this JWT. Only used when authenticating with user/pass.`, 53 | }, 54 | "oauth_endpoint": &framework.FieldSchema{ 55 | Type: framework.TypeString, 56 | Description: `The URL to authenticate to retrieve a JWT. Only used when authenticating with user/pass.`, 57 | }, 58 | "oauth_cacert": &framework.FieldSchema{ 59 | Type: framework.TypeString, 60 | Description: `The CA Certificate used to sign the OAuth endpoint certificate.`, 61 | }, 62 | "oauth_client_id": &framework.FieldSchema{ 63 | Type: framework.TypeString, 64 | Description: `The client ID to retrieve a JWT. Only used when authenticating with user/pass.`, 65 | }, 66 | "oauth_client_secret": &framework.FieldSchema{ 67 | Type: framework.TypeString, 68 | Description: `The shared secret to retrieve a JWT. Only used when authenticating with user/pass.`, 69 | }, 70 | "ad_domain": &framework.FieldSchema{ 71 | Type: framework.TypeString, 72 | Description: `The AD domain for the user.`, 73 | }, 74 | "ttl": &framework.FieldSchema{ 75 | Type: framework.TypeString, 76 | Description: `Duration after which authentication will be expired`, 77 | }, 78 | "max_ttl": &framework.FieldSchema{ 79 | Type: framework.TypeString, 80 | Description: `Maximum duration after which authentication will be expired`, 81 | }, 82 | "bound_cidr_list": &framework.FieldSchema{ 83 | Type: framework.TypeCommaStringSlice, 84 | Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of 85 | IP addresses which can perform the login operation.`, 86 | }, 87 | "trustee_list": &framework.FieldSchema{ 88 | Type: framework.TypeCommaStringSlice, 89 | Description: `Comma separated string or list of trustee addresses. If set, specifies that only delegated 90 | authentication by one of these trustees is allowed.`, 91 | }, 92 | }, 93 | Callbacks: map[logical.Operation]framework.OperationFunc{ 94 | logical.CreateOperation: b.pathConfigWrite, 95 | logical.UpdateOperation: b.pathConfigWrite, 96 | logical.ReadOperation: b.pathConfigRead, 97 | }, 98 | }, 99 | } 100 | } 101 | 102 | func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { 103 | roleClaim := data.Get("role_claim").(string) 104 | subjectClaim := data.Get("subject_claim").(string) 105 | jwtSigner := data.Get("jwt_signer").(string) 106 | jwtAlgorithm := data.Get("jwt_algorithm").(string) 107 | oauthResource := data.Get("oauth_resource").(string) 108 | oauthEndpoint := data.Get("oauth_endpoint").(string) 109 | oauthCACert := data.Get("oauth_cacert").(string) 110 | oauthClientID := data.Get("oauth_client_id").(string) 111 | oauthClientSecret := data.Get("oauth_client_secret").(string) 112 | adDomain := data.Get("ad_domain").(string) 113 | 114 | var ttl time.Duration 115 | var err error 116 | ttlRaw, ok := data.GetOk("ttl") 117 | if !ok || len(ttlRaw.(string)) == 0 { 118 | ttl = 0 119 | } else { 120 | ttl, err = time.ParseDuration(ttlRaw.(string)) 121 | if err != nil { 122 | return logical.ErrorResponse(fmt.Sprintf("Invalid 'ttl':%s", err)), nil 123 | } 124 | } 125 | 126 | var maxTTL time.Duration 127 | maxTTLRaw, ok := data.GetOk("max_ttl") 128 | if !ok || len(maxTTLRaw.(string)) == 0 { 129 | maxTTL = 0 130 | } else { 131 | maxTTL, err = time.ParseDuration(maxTTLRaw.(string)) 132 | if err != nil { 133 | return logical.ErrorResponse(fmt.Sprintf("Invalid 'max_ttl':%s", err)), nil 134 | } 135 | } 136 | var boundCIDRList []string 137 | if boundCIDRListRaw, ok := data.GetOk("bound_cidr_list"); ok { 138 | boundCIDRList = boundCIDRListRaw.([]string) 139 | } 140 | 141 | var trusteeList []string 142 | if trusteeListRaw, ok := data.GetOk("trustee_list"); ok { 143 | trusteeList = trusteeListRaw.([]string) 144 | } 145 | configBundle := config{ 146 | RoleClaim: roleClaim, 147 | SubjectClaim: subjectClaim, 148 | JWTSigner: jwtSigner, 149 | JWTAlgorithm: jwtAlgorithm, 150 | OauthResource: oauthResource, 151 | OauthEndpoint: oauthEndpoint, 152 | OauthCACert: oauthCACert, 153 | OauthClientID: oauthClientID, 154 | OauthClientSecret: oauthClientSecret, 155 | ADDomain: adDomain, 156 | TTL: ttl, 157 | MaxTTL: maxTTL, 158 | BoundCIDRList: boundCIDRList, 159 | TrusteeList: trusteeList, 160 | } 161 | entry, err := logical.StorageEntryJSON("config", configBundle) 162 | 163 | if err != nil { 164 | return nil, err 165 | } 166 | 167 | if err := req.Storage.Put(ctx, entry); err != nil { 168 | return nil, err 169 | } 170 | 171 | return nil, nil 172 | } 173 | 174 | func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { 175 | config, err := b.Config(ctx, req.Storage) 176 | if err != nil { 177 | return nil, err 178 | } 179 | 180 | if config == nil { 181 | return nil, fmt.Errorf("configuration object not found") 182 | } 183 | 184 | config.TTL /= time.Second 185 | config.MaxTTL /= time.Second 186 | 187 | resp := &logical.Response{ 188 | Data: map[string]interface{}{ 189 | "role_claim": config.RoleClaim, 190 | "subject_claim": config.SubjectClaim, 191 | "jwt_signer": config.JWTSigner, 192 | "jwt_algorithm": config.JWTAlgorithm, 193 | "oauth_resource": config.OauthResource, 194 | "oauth_endpoint": config.OauthEndpoint, 195 | "oauth_cacert": config.OauthCACert, 196 | "oauth_client_id": config.OauthClientID, 197 | "oauth_client_secret": config.OauthClientSecret, 198 | "oauth_ad_domain": config.ADDomain, 199 | "ttl": config.TTL, 200 | "max_ttl": config.MaxTTL, 201 | "bound_cidr_list": config.BoundCIDRList, 202 | "trustee_list": config.TrusteeList, 203 | }, 204 | } 205 | return resp, nil 206 | } 207 | 208 | // Config returns the configuration for this backend. 209 | func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error) { 210 | entry, err := s.Get(ctx, "config") 211 | if err != nil { 212 | return nil, err 213 | } 214 | 215 | var result config 216 | if entry != nil { 217 | if err := entry.DecodeJSON(&result); err != nil { 218 | return nil, fmt.Errorf("error reading configuration: %s", err) 219 | } 220 | } 221 | 222 | return &result, nil 223 | } 224 | 225 | type config struct { 226 | RoleClaim string `json:"role_claim" structs:"role_claim" mapstructure:"role_claim"` 227 | SubjectClaim string `json:"subject_claim" structs:"subject_claim" mapstructure:"subject_claim"` 228 | JWTSigner string `json:"jwt_signer" structs:"jwt_signer" mapstructure:"jwt_signer"` 229 | JWTAlgorithm string `json:"jwt_algorithm" structs:"jwt_algorithm" mapstructure:"jwt_algorithm"` 230 | OauthResource string `json:"oauth_resource" structs:"oauth_resource" mapstructure:"oauth_resource"` 231 | OauthEndpoint string `json:"oauth_endpoint" structs:"oauth_endpoint" mapstructure:"oauth_endpoint"` 232 | OauthCACert string `json:"oauth_cacert" structs:"oauth_cacert" mapstructure:"oauth_cacert"` 233 | OauthClientID string `json:"oauth_client_id" structs:"oauth_client_id" mapstructure:"oauth_client_id"` 234 | OauthClientSecret string `json:"oauth_client_secret" structs:"oauth_client_secret" mapstructure:"oauth_client_secret"` 235 | ADDomain string `json:"ad_domain" structs:"ad_domain" mapstructure:"ad_domain"` 236 | TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl"` 237 | MaxTTL time.Duration `json:"max_ttl" structs:"max_ttl" mapstructure:"max_ttl"` 238 | BoundCIDRList []string `json:"bound_cidr_list_list" structs:"bound_cidr_list" mapstructure:"bound_cidr_list"` 239 | TrusteeList []string `json:"trustee_list" structs:"trustee_list" mapstructure:"trustee_list"` 240 | } 241 | -------------------------------------------------------------------------------- /path_login.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2018 Immutability, LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "bytes" 19 | "context" 20 | "crypto/tls" 21 | "crypto/x509" 22 | "encoding/json" 23 | "fmt" 24 | "io/ioutil" 25 | "net/http" 26 | "net/url" 27 | "regexp" 28 | "strings" 29 | 30 | jwt "github.com/dgrijalva/jwt-go" 31 | "github.com/ethereum/go-ethereum/common/hexutil" 32 | "github.com/ethereum/go-ethereum/crypto" 33 | "github.com/hashicorp/vault/logical" 34 | "github.com/hashicorp/vault/logical/framework" 35 | 36 | "github.com/hashicorp/errwrap" 37 | "github.com/hashicorp/vault/helper/cidrutil" 38 | "github.com/hashicorp/vault/helper/policyutil" 39 | "github.com/sethgrid/pester" 40 | ) 41 | 42 | // JWTMappings is returned after successful authentication. This 43 | // struct contains the list of policies to which this identity is entitled 44 | // and the claims in the JWT as well. 45 | type JWTMappings struct { 46 | Claims jwt.MapClaims 47 | Policies []string 48 | } 49 | 50 | // TokenResponse is the response from the OAuth server 51 | type TokenResponse struct { 52 | AccessToken string `json:"access_token" structs:"access_token" mapstructure:"access_token"` 53 | TokenType string `json:"token_type" structs:"token_type" mapstructure:"token_type"` 54 | ExpiresIn int `json:"expires_in" structs:"expires_in" mapstructure:"expires_in"` 55 | Resource string `json:"resource" structs:"resource" mapstructure:"resource"` 56 | RefreshToken string `json:"refresh_token" structs:"refresh_token" mapstructure:"refresh_token"` 57 | RefreshTokenExpiresIn int `json:"refresh_token_expires_in" structs:"refresh_token_expires_in" mapstructure:"refresh_token_expires_in"` 58 | IDToken string `json:"id_token" structs:"id_token" mapstructure:"id_token"` 59 | } 60 | 61 | // ClaimsList returns this list of claims as strings 62 | func (jwt *JWTMappings) ClaimsList(name string) []string { 63 | var claimsList []string 64 | listSlice, ok := jwt.Claims[name].([]interface{}) 65 | if ok { 66 | for _, v := range listSlice { 67 | item, ok := v.(string) 68 | if ok { 69 | claimsList = append(claimsList, strings.ToLower(item)) 70 | } 71 | } 72 | } else { 73 | stringBean, ok := jwt.Claims[name].(string) 74 | if ok { 75 | claimsList = append(claimsList, strings.ToLower(stringBean)) 76 | } 77 | } 78 | return claimsList 79 | } 80 | 81 | func pathLogin(b *backend) []*framework.Path { 82 | return []*framework.Path{ 83 | &framework.Path{ 84 | Pattern: "login", 85 | Fields: map[string]*framework.FieldSchema{ 86 | "token": &framework.FieldSchema{ 87 | Type: framework.TypeString, 88 | Description: "This is the JWT token in base64 encoded form.", 89 | }, 90 | "username": &framework.FieldSchema{ 91 | Type: framework.TypeString, 92 | Description: "User name for authenticating to an endpoint to retrieve a JWT - overrides token auth.", 93 | }, 94 | "password": &framework.FieldSchema{ 95 | Type: framework.TypeString, 96 | Description: "The password for the username above.", 97 | }, 98 | }, 99 | 100 | Callbacks: map[logical.Operation]framework.OperationFunc{ 101 | logical.UpdateOperation: b.pathLogin, 102 | logical.CreateOperation: b.pathLogin, 103 | logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, 104 | }, 105 | }, 106 | } 107 | } 108 | 109 | func (b *backend) makeOauthRequest(ctx context.Context, req *logical.Request, data url.Values) (*TokenResponse, error) { 110 | config, err := b.Config(ctx, req.Storage) 111 | if err != nil { 112 | return nil, err 113 | } 114 | if config.OauthEndpoint == "" || config.OauthClientID == "" || config.OauthResource == "" || config.OauthClientSecret == "" || config.OauthCACert == "" { 115 | return nil, fmt.Errorf("missing configuration elements") 116 | } 117 | 118 | caCert, err := ioutil.ReadFile(config.OauthCACert) 119 | if err != nil { 120 | return nil, err 121 | } 122 | caCertPool := x509.NewCertPool() 123 | caCertPool.AppendCertsFromPEM(caCert) 124 | httpClient := pester.New() 125 | 126 | httpClient.Transport = &http.Transport{ 127 | TLSClientConfig: &tls.Config{ 128 | RootCAs: caCertPool, 129 | }, 130 | } 131 | 132 | data.Add("client_id", config.OauthClientID) 133 | data.Add("client_secret", config.OauthClientSecret) 134 | if config.OauthResource != "" { 135 | data.Add("resource", config.OauthResource) 136 | } 137 | encoded := []byte(data.Encode()) 138 | 139 | request, err := http.NewRequest("POST", config.OauthEndpoint, bytes.NewBuffer(encoded)) 140 | if err != nil { 141 | return nil, err 142 | } 143 | request.Header.Add("Content-Type", "x-www-form-urlencoded") 144 | 145 | resp, err := httpClient.Do(request) 146 | if err != nil { 147 | return nil, err 148 | } 149 | if resp == nil { 150 | return nil, fmt.Errorf("OAuth endpoint failed to return a response") 151 | } 152 | var htmlData []byte 153 | htmlData, err = ioutil.ReadAll(resp.Body) 154 | if err != nil { 155 | return nil, err 156 | } 157 | var payload TokenResponse 158 | err = json.Unmarshal(htmlData, &payload) 159 | if err != nil { 160 | return nil, err 161 | } 162 | 163 | return &payload, nil 164 | 165 | } 166 | 167 | func (b *backend) getJWTFromOauthPasswordGrant(ctx context.Context, req *logical.Request, username, password string) (*TokenResponse, error) { 168 | config, err := b.Config(ctx, req.Storage) 169 | if err != nil { 170 | return nil, err 171 | } 172 | 173 | data := url.Values{} 174 | data.Add("grant_type", "password") 175 | if config.ADDomain != "" { 176 | data.Add("username", fmt.Sprintf("%s\\%s", config.ADDomain, username)) 177 | } else { 178 | data.Add("username", username) 179 | } 180 | data.Add("password", password) 181 | return b.makeOauthRequest(ctx, req, data) 182 | } 183 | 184 | func (b *backend) getJWTFromOauthRefresh(ctx context.Context, req *logical.Request, refreshToken string) (*TokenResponse, error) { 185 | data := url.Values{} 186 | data.Add("grant_type", "refresh_token") 187 | data.Add("refresh_token", refreshToken) 188 | return b.makeOauthRequest(ctx, req, data) 189 | } 190 | 191 | func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { 192 | config, err := b.Config(ctx, req.Storage) 193 | if err != nil { 194 | return nil, err 195 | } 196 | token := data.Get("token").(string) 197 | if validConnection, err := b.validIPConstraints(ctx, req); !validConnection { 198 | return nil, err 199 | } 200 | 201 | var jwtMappings *JWTMappings 202 | if jwtMappingsResp, resp, err := b.validateJWT(ctx, req, token); err != nil { 203 | return nil, err 204 | } else if resp != nil { 205 | return resp, nil 206 | } else { 207 | jwtMappings = jwtMappingsResp 208 | } 209 | if jwtMappings == nil { 210 | return nil, fmt.Errorf("unable to map claims") 211 | } 212 | subject, ok := jwtMappings.Claims[config.SubjectClaim] 213 | if !ok { 214 | return nil, fmt.Errorf("unable to find subject") 215 | } 216 | 217 | return &logical.Response{ 218 | Auth: &logical.Auth{ 219 | Alias: &logical.Alias{ 220 | Name: subject.(string), 221 | }, 222 | }, 223 | }, nil 224 | } 225 | 226 | func (b *backend) isDelegatedAuth(ctx context.Context, req *logical.Request) (bool, error) { 227 | config, err := b.Config(ctx, req.Storage) 228 | if err != nil { 229 | return false, err 230 | } 231 | return (config.TrusteeList != nil && len(config.TrusteeList) > 0), nil 232 | } 233 | 234 | func (b *backend) isTrustee(ctx context.Context, req *logical.Request) (bool, error) { 235 | return false, nil 236 | } 237 | 238 | func (b *backend) delegatedLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { 239 | token := data.Get("token").(string) 240 | config, err := b.Config(ctx, req.Storage) 241 | if err != nil { 242 | return nil, err 243 | } 244 | 245 | claims, err := b.verifyTrustee(ctx, token, config.TrusteeList) 246 | if err != nil { 247 | return nil, err 248 | } 249 | trustee := claims["iss"].(string) 250 | if !containsIgnoreCase(config.TrusteeList, trustee) { 251 | return nil, fmt.Errorf("this %s address is not trusted", trustee) 252 | } 253 | delegateJWT, ok := claims["delegate"].(string) 254 | if !ok { 255 | return nil, fmt.Errorf("delegated login attempted without delegate") 256 | } 257 | return b.loginWithJWT(ctx, req, delegateJWT, "") 258 | } 259 | 260 | func (b *backend) loginWithJWT(ctx context.Context, req *logical.Request, token, refreshToken string) (*logical.Response, error) { 261 | var jwtMappings *JWTMappings 262 | if jwtMappingsResp, resp, err := b.validateJWT(ctx, req, token); err != nil { 263 | return nil, err 264 | } else if resp != nil { 265 | return resp, nil 266 | } else { 267 | jwtMappings = jwtMappingsResp 268 | } 269 | 270 | config, err := b.Config(ctx, req.Storage) 271 | if err != nil { 272 | return nil, err 273 | } 274 | if jwtMappings == nil { 275 | return nil, fmt.Errorf("unable to map claims") 276 | } 277 | subject, ok := jwtMappings.Claims[config.SubjectClaim] 278 | if !ok { 279 | return nil, fmt.Errorf("unable to find subject") 280 | } 281 | 282 | claims, ok := jwtMappings.Claims[config.RoleClaim] 283 | if !ok { 284 | return nil, fmt.Errorf("unable to find roles") 285 | } 286 | resp := &logical.Response{ 287 | Auth: &logical.Auth{ 288 | InternalData: map[string]interface{}{ 289 | "token": token, 290 | "refresh_token": refreshToken, 291 | }, 292 | DisplayName: subject.(string), 293 | Policies: jwtMappings.Policies, 294 | Metadata: map[string]string{ 295 | "username": subject.(string), 296 | "roles": fmt.Sprintf("%v", claims), 297 | }, 298 | LeaseOptions: logical.LeaseOptions{ 299 | TTL: config.TTL, 300 | Renewable: true, 301 | }, 302 | Alias: &logical.Alias{ 303 | Name: subject.(string), 304 | }, 305 | }, 306 | Data: map[string]interface{}{"jwt": token}, 307 | } 308 | listSlice := jwtMappings.ClaimsList(config.RoleClaim) 309 | for _, item := range listSlice { 310 | resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ 311 | Name: item, 312 | }) 313 | } 314 | 315 | return resp, nil 316 | } 317 | 318 | func (b *backend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { 319 | token := data.Get("token").(string) 320 | username := data.Get("username").(string) 321 | password := data.Get("password").(string) 322 | 323 | refreshToken := "" 324 | delegated, err := b.isDelegatedAuth(ctx, req) 325 | if err != nil { 326 | return nil, err 327 | } 328 | if delegated { 329 | return b.delegatedLogin(ctx, req, data) 330 | } 331 | if username != "" && password != "" { 332 | tokenResponse, err := b.getJWTFromOauthPasswordGrant(ctx, req, username, password) 333 | 334 | if err != nil { 335 | return nil, err 336 | } 337 | token = tokenResponse.AccessToken 338 | refreshToken = tokenResponse.RefreshToken 339 | } 340 | 341 | if validConnection, err := b.validIPConstraints(ctx, req); !validConnection { 342 | return nil, err 343 | } 344 | return b.loginWithJWT(ctx, req, token, refreshToken) 345 | 346 | } 347 | 348 | func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { 349 | if req.Auth == nil { 350 | return nil, fmt.Errorf("there is no authentication information in this request") 351 | } 352 | token := req.Auth.InternalData["token"].(string) 353 | refreshToken, ok := req.Auth.InternalData["refresh_token"] 354 | if ok && refreshToken != "" { 355 | tokenResponse, err := b.getJWTFromOauthRefresh(ctx, req, refreshToken.(string)) 356 | 357 | if err != nil { 358 | tokenRaw, ok := req.Auth.InternalData["token"] 359 | if !ok { 360 | return nil, fmt.Errorf("token created in previous version of Vault cannot be validated properly at renewal time") 361 | } 362 | token = tokenRaw.(string) 363 | } else { 364 | token = tokenResponse.AccessToken 365 | } 366 | } 367 | if validConnection, err := b.validIPConstraints(ctx, req); !validConnection { 368 | return nil, err 369 | } 370 | 371 | var jwtMappings *JWTMappings 372 | if jwtMappingsResp, validateResp, err := b.validateJWT(ctx, req, token); err != nil { 373 | return nil, err 374 | } else if validateResp != nil { 375 | return validateResp, nil 376 | } else { 377 | jwtMappings = jwtMappingsResp 378 | } 379 | if !policyutil.EquivalentPolicies(jwtMappings.Policies, req.Auth.Policies) { 380 | return nil, fmt.Errorf("policies are not equivalent") 381 | } 382 | 383 | config, err := b.Config(ctx, req.Storage) 384 | if err != nil { 385 | return nil, err 386 | } 387 | 388 | resp, err := framework.LeaseExtend(config.TTL, config.MaxTTL, b.System())(ctx, req, d) 389 | if err != nil { 390 | return nil, err 391 | } 392 | 393 | resp.Auth.GroupAliases = nil 394 | if jwtMappings == nil { 395 | return nil, fmt.Errorf("unable to map claims") 396 | } 397 | 398 | claims, ok := jwtMappings.Claims[config.RoleClaim].([]interface{}) 399 | if !ok { 400 | roleName, ok := jwtMappings.Claims[config.RoleClaim].(string) 401 | if !ok { 402 | return nil, fmt.Errorf("unable to find roles") 403 | } 404 | resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ 405 | Name: roleName, 406 | }) 407 | } else { 408 | for _, role := range claims { 409 | roleName := role.(string) 410 | resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ 411 | Name: roleName, 412 | }) 413 | } 414 | } 415 | 416 | return resp, nil 417 | } 418 | 419 | func (b *backend) parseJWT(ctx context.Context, token string, algorithm string, publicKey []byte) (jwt.MapClaims, error) { 420 | tokenWithoutWhitespace := regexp.MustCompile(`\s*$`).ReplaceAll([]byte(token), []byte{}) 421 | parsed, err := jwt.Parse(string(tokenWithoutWhitespace), func(t *jwt.Token) (interface{}, error) { 422 | if strings.HasPrefix(algorithm, "ES") { 423 | return jwt.ParseECPublicKeyFromPEM(publicKey) 424 | } else if strings.HasPrefix(algorithm, "RS") { 425 | return jwt.ParseRSAPublicKeyFromPEM(publicKey) 426 | } 427 | return publicKey, nil 428 | }) 429 | if err == nil { 430 | claims := parsed.Claims.(jwt.MapClaims) 431 | return claims, claims.Valid() 432 | } 433 | return nil, err 434 | } 435 | 436 | // PrettyPrint prints an indented JSON payload. This is used for development debugging. 437 | func PrettyPrint(v interface{}) string { 438 | jsonString, _ := json.Marshal(v) 439 | var out bytes.Buffer 440 | json.Indent(&out, jsonString, "", " ") 441 | return out.String() 442 | } 443 | 444 | func (b *backend) validateJWT(ctx context.Context, req *logical.Request, token string) (*JWTMappings, *logical.Response, error) { 445 | config, err := b.Config(ctx, req.Storage) 446 | if err != nil { 447 | return nil, nil, err 448 | } 449 | publicKey := []byte(config.JWTSigner) 450 | 451 | claims, err := b.parseJWT(ctx, token, config.JWTAlgorithm, publicKey) 452 | 453 | if err != nil { 454 | return nil, nil, err 455 | } 456 | if claims == nil { 457 | return nil, nil, fmt.Errorf("unable to parse claims - likely a time sync issue") 458 | } 459 | jwtMappings := &JWTMappings{ 460 | Claims: claims, 461 | } 462 | claimsList := jwtMappings.ClaimsList(config.RoleClaim) 463 | var claimPoliciesList []string 464 | if claimsList != nil { 465 | claimPoliciesList, err = b.RoleMap.Policies(ctx, req.Storage, claimsList...) 466 | } 467 | 468 | if err != nil { 469 | return nil, nil, err 470 | } 471 | 472 | claimsList = jwtMappings.ClaimsList(config.SubjectClaim) 473 | var userPoliciesList []string 474 | if claimsList != nil { 475 | userPoliciesList, err = b.UserMap.Policies(ctx, req.Storage, claimsList...) 476 | } 477 | 478 | if err != nil { 479 | return nil, nil, err 480 | } 481 | 482 | return &JWTMappings{ 483 | Claims: claims, 484 | Policies: append(claimPoliciesList, userPoliciesList...), 485 | }, nil, nil 486 | } 487 | 488 | func (b *backend) validIPConstraints(ctx context.Context, req *logical.Request) (bool, error) { 489 | config, err := b.Config(ctx, req.Storage) 490 | if err != nil { 491 | return false, err 492 | } 493 | if len(config.BoundCIDRList) != 0 { 494 | if req.Connection == nil || req.Connection.RemoteAddr == "" { 495 | return false, fmt.Errorf("failed to get connection information") 496 | } 497 | 498 | belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, config.BoundCIDRList) 499 | if err != nil { 500 | return false, errwrap.Wrapf("failed to verify the CIDR restrictions set on the role: {{err}}", err) 501 | } 502 | if !belongs { 503 | return false, fmt.Errorf("source address %q unauthorized through CIDR restrictions on the role", req.Connection.RemoteAddr) 504 | } 505 | } 506 | return true, nil 507 | } 508 | 509 | func (b *backend) verifyTrustee(ctx context.Context, rawToken string, trustees []string) (jwt.MapClaims, error) { 510 | tokenWithoutWhitespace := regexp.MustCompile(`\s*$`).ReplaceAll([]byte(rawToken), []byte{}) 511 | token := string(tokenWithoutWhitespace) 512 | 513 | jwtToken, _, err := new(jwt.Parser).ParseUnverified(token, jwt.MapClaims{}) 514 | if err != nil || jwtToken == nil { 515 | return nil, fmt.Errorf("cannot parse token") 516 | } 517 | unverifiedJwt := jwtToken.Claims.(jwt.MapClaims) 518 | if unverifiedJwt == nil { 519 | return nil, fmt.Errorf("cannot get claims") 520 | } 521 | ethereumAddress, ok := unverifiedJwt["iss"].(string) 522 | if !ok { 523 | return nil, fmt.Errorf("JWT has no issuer - iss") 524 | } 525 | if !containsIgnoreCase(trustees, ethereumAddress) { 526 | return nil, fmt.Errorf("we don't trust this issuer: %s", ethereumAddress) 527 | } 528 | jti, ok := unverifiedJwt["jti"].(string) 529 | if !ok { 530 | return nil, fmt.Errorf("JWT has no unique identifier - jti") 531 | } 532 | signatureRaw, ok := unverifiedJwt["eth"].(string) 533 | if !ok { 534 | return nil, fmt.Errorf("JWT has no unique Ethereum signature - eth") 535 | } 536 | hash := hashKeccak256(jti) 537 | signature, err := hexutil.Decode(signatureRaw) 538 | 539 | if err != nil { 540 | return nil, fmt.Errorf("failed to decode signature") 541 | } 542 | pubkey, err := crypto.SigToPub(hash, signature) 543 | 544 | if err != nil { 545 | return nil, fmt.Errorf("failed to derive public key from signature") 546 | } 547 | address := crypto.PubkeyToAddress(*pubkey) 548 | 549 | if strings.ToUpper(ethereumAddress) == strings.ToUpper(address.Hex()) { 550 | validateJwt, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { 551 | return pubkey, nil 552 | }) 553 | if err != nil { 554 | return nil, fmt.Errorf("signature not verified") 555 | } 556 | claims := validateJwt.Claims.(jwt.MapClaims) 557 | return claims, claims.Valid() 558 | } 559 | return nil, fmt.Errorf("Error verifying token") 560 | } 561 | -------------------------------------------------------------------------------- /scripts/mfa.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | function print_help { 3 | echo "Usage: bash mfa.sh ARGUMENTS" 4 | echo -e "\nARGUMENTS:" 5 | echo -e " [Duo API Hostname]" 6 | echo -e " [Duo Integration Key]" 7 | echo -e " [Duo Secret Key]" 8 | } 9 | 10 | if [ -z "$3" ]; then 11 | print_help 12 | exit 0 13 | else 14 | DUO_API_HOSTNAME=$1 15 | DUO_INTEGRATION_KEY=$2 16 | DUO_SECRET_KEY=$3 17 | fi 18 | 19 | vault write auth/jwt-auth/mfa_config type=duo 20 | vault write auth/jwt-auth/duo/access \ 21 | host=$DUO_API_HOSTNAME \ 22 | ikey=$DUO_INTEGRATION_KEY \ 23 | skey=$DUO_SECRET_KEY 24 | 25 | vault write auth/jwt-auth/duo/config \ 26 | user_agent="" \ 27 | username_format="%s-jwt-auth" 28 | -------------------------------------------------------------------------------- /test/jwt-auth.bats: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bats 2 | 3 | setup() { 4 | if [ ! -f jwtRS256.key ]; then 5 | ssh-keygen -t rsa -b 4096 -P "" -f jwtRS256.key 6 | openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub 7 | echo {\"sub\":\"goober\",\"group\": [\"test\"]} | jwt -key jwtRS256.key -alg RS256 -sign - > jwt.json 8 | fi 9 | } 10 | 11 | @test "test configure jwt-auth" { 12 | run vault write auth/test/jwt/config jwt_signer=@jwtRS256.key.pub trustee_list="0xF7353BEd87798F6fB95493D2b5D6025761a66f51" ttl=60m max_ttl=300m 13 | [ "$status" -eq 0 ] 14 | } 15 | 16 | @test "test map policies to role" { 17 | run vault policy write test test.hcl 18 | [ "$status" -eq 0 ] 19 | run vault write auth/test/jwt/map/claims/test value=test 20 | [ "$status" -eq 0 ] 21 | run vault write auth/test/jwt/map/users/goober value=goober 22 | [ "$status" -eq 0 ] 23 | } 24 | 25 | 26 | @test "test auth as goober" { 27 | results=$(vault write -format=json auth/test/jwt/login token=@jwt.json | jq .auth) 28 | username=$(echo $results | jq .metadata.username | tr -d '"') 29 | [ "$username" == "goober" ] 30 | } 31 | -------------------------------------------------------------------------------- /test/test.hcl: -------------------------------------------------------------------------------- 1 | path "secret*" { 2 | policy = "write" 3 | } 4 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/ethereum/go-ethereum/crypto" 8 | ) 9 | 10 | func hashKeccak256(data string) []byte { 11 | input := []byte(data) 12 | msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(input), input) 13 | hash := crypto.Keccak256([]byte(msg)) 14 | return hash 15 | } 16 | 17 | func containsIgnoreCase(stringSlice []string, searchString string) bool { 18 | for _, value := range stringSlice { 19 | if strings.ToUpper(value) == strings.ToUpper(searchString) { 20 | return true 21 | } 22 | } 23 | return false 24 | } 25 | --------------------------------------------------------------------------------