├── .gitignore ├── .travis.yml ├── AUTHORS ├── LICENSE.txt ├── NOTICE ├── README.md ├── TODO.txt ├── checkstyle.xml ├── java.header ├── pom.xml └── src ├── main └── java │ └── com │ └── spotify │ └── crtauth │ ├── CrtAuthClient.java │ ├── CrtAuthServer.java │ ├── Fingerprint.java │ ├── exceptions │ ├── CrtAuthException.java │ ├── KeyNotFoundException.java │ ├── ProtocolVersionException.java │ └── TokenExpiredException.java │ ├── keyprovider │ ├── FileKeyProvider.java │ ├── InMemoryKeyProvider.java │ └── KeyProvider.java │ ├── protocol │ ├── Challenge.java │ ├── CrtAuthCodec.java │ ├── DeserializationException.java │ ├── MiniMessagePack.java │ ├── Response.java │ └── Token.java │ ├── signer │ ├── AgentSigner.java │ ├── Signer.java │ └── SingleKeySigner.java │ └── utils │ ├── ASCIICodec.java │ ├── RealTimeSupplier.java │ ├── SettableTimeSupplier.java │ ├── TimeIntervals.java │ ├── TimeSupplier.java │ └── TraditionalKeyParser.java └── test └── java └── com └── spotify └── crtauth ├── CrtAuthClientTest.java ├── CrtAuthServerTest.java ├── FingerprintTest.java ├── protocol ├── ChallengeTest.java ├── CrtAuthCodecTest.java ├── MiniMessagePackTest.java └── TokenTest.java ├── signer ├── AgentSignerTest.java ├── SignerTest.java └── SingleKeySignerTest.java └── utils ├── ASCIICodecTest.java └── TraditionalKeyParserTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea/ 3 | *.iml 4 | *.iws 5 | *.ipr 6 | *.DS_Store 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk7 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Noa Resare 2 | David Xia 3 | -------------------------------------------------------------------------------- /LICENSE.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 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | crtauth-java 2 | Copyright (c) 2015 Spotify AB 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crtauth-java 2 | 3 | 4 | [![Master Build Status](https://travis-ci.org/spotify/crtauth-java.svg?branch=master)][3] 5 | 6 | crtauth-java is a public key backed client/server authentication system written 7 | in Java. 8 | 9 | crtauth-java is the Java port of the original crtauth implementation that can be 10 | found [here][4]. The java implementation is 11 | fully wire compatible with the python version. 12 | 13 | crtauth itself is a system for authenticating a user to a centralized server. 14 | The initial use case is to create a convenient authentication for command line 15 | tools that interacts with a central server without resorting to authentication 16 | using a shared secret, such as a password. 17 | 18 | If you are looking at building a client in Java and would like to connect to a local 19 | ssh-agent, here's how: 20 | 21 | 22 | ```java 23 | final AgentSigner signer = new AgentSigner(); 24 | final byte[] signed = signer.sign(new byte[] {1, 2, 3, 4}, new Fingerprint(publicKey)); 25 | ``` 26 | 27 | ## License 28 | 29 | 30 | crtauth-java is free software, this code is released under the Apache Software 31 | License, version 2. The original code is written by Federico Piccinini with 32 | contributions from Noa Resare, John-John Tedro, Martin Parm and Nic Cope. 33 | 34 | All code is Copyright (c) 2015 Spotify AB 35 | 36 | [1]: https://github.com/jnr/jnr-unixsocket 37 | [2]: http://mvnrepository.com/artifact/commons-codec/commons-codec 38 | [3]: https://travis-ci.org/spotify/crtauth-java 39 | [4]: https://github.com/spotify/crtauth 40 | [5]: https://github.com/spotify/crtauth-java-agent-signer 41 | [6]: https://github.com/spotify/crtauth-java-agent-signer-apache 42 | [7]: https://mina.apache.org/downloads-sshd.html 43 | [8]: https://tomcat.apache.org/download-native.cgi 44 | 45 | -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | * write test case for FileKeyProvider 2 | * move InMemoryKeyProvider to test module 3 | 4 | 5 | * simplify Signer interface (we only need to sign arbitrary byte arrays) 6 | sign(byte[] data, PublicKeyFingerprint fingerprint)? 7 | * move agent signer into a separate package 8 | 9 | * Better naming for Digest algorithm (naming from HMAC standard perhaps?) 10 | * Make all internal classes nonpublic (less packages perhaps?) 11 | * Replace InvalidInputException (and friends) with IllegalArgumentException 12 | 13 | * write LDAP KeyProvider (reconnecting!) 14 | * sort out CrtAuthServer constructor argument confusion (DigestAlgorithm and secret amounts 15 | to the same thing) 16 | -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 | 34 | 35 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 65 | 66 | 67 | 68 | 69 | 71 | 74 | 75 | 76 | 77 | 78 | 79 | 81 | 82 | 83 | 84 | 85 | 86 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 96 | 97 | 98 | 99 | 100 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 132 | 133 | 134 | 135 | 136 | 138 | 139 | 140 | 141 | 142 | 144 | 145 | 146 | 147 | 148 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 164 | 165 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 184 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 213 | 215 | 216 | 217 | 218 | 219 | 220 | 225 | 226 | 227 | 232 | 233 | 234 | 235 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 248 | 250 | 251 | 252 | 253 | 255 | 257 | 259 | 261 | 262 | 263 | 264 | 267 | 268 | 269 | 270 | 271 | 274 | 276 | 277 | 278 | 279 | 280 | 281 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 293 | 294 | 295 | 296 | 297 | 298 | -------------------------------------------------------------------------------- /java.header: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.spotify 6 | crtauth 7 | 0.2.3-SNAPSHOT 8 | jar 9 | crtauth 10 | A public key backed client/server authentication system 11 | https://github.com/spotify/crtauth-java 12 | 13 | 14 | 15 | The Apache Software License, Version 2.0 16 | http://www.apache.org/licenses/LICENSE-2.0.txt 17 | repo 18 | 19 | 20 | 21 | 22 | scm:git:https://github.com/spotify/crtauth-java.git 23 | scm:git:git@github.com:spotify/crtauth-java.git 24 | https://github.com/spotify/crtauth-java 25 | HEAD 26 | 27 | 28 | 29 | UTF-8 30 | UTF-8 31 | true 32 | 33 | 34 | 35 | 36 | ossrh 37 | https://oss.sonatype.org/content/repositories/snapshots 38 | 39 | 40 | 41 | 42 | 43 | noa 44 | Noa Resare 45 | noa@spotify.com 46 | 47 | 48 | 49 | 50 | 51 | com.google.guava 52 | guava 53 | 17.0 54 | 55 | 56 | org.slf4j 57 | slf4j-api 58 | 1.7.7 59 | 60 | 61 | com.spotify 62 | ssh-agent-proxy 63 | 0.1.2 64 | 65 | 66 | 67 | 68 | junit 69 | junit 70 | 4.11 71 | test 72 | 73 | 74 | org.mockito 75 | mockito-all 76 | 1.9.5 77 | test 78 | 79 | 80 | 81 | 82 | 83 | sign-artifacts 84 | 85 | 86 | 87 | org.apache.maven.plugins 88 | maven-gpg-plugin 89 | 1.6 90 | 91 | 92 | sign-artifacts 93 | verify 94 | 95 | sign 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | org.apache.maven.plugins 109 | maven-source-plugin 110 | 2.4 111 | 112 | 113 | attach-sources 114 | 115 | jar 116 | 117 | 118 | 119 | 120 | 121 | org.apache.maven.plugins 122 | maven-javadoc-plugin 123 | 2.10.3 124 | 125 | 126 | attach-javadocs 127 | 128 | jar 129 | 130 | 131 | 132 | 133 | 134 | org.apache.maven.plugins 135 | maven-release-plugin 136 | 2.5.2 137 | 138 | @{project.version} 139 | 140 | 141 | 142 | org.apache.maven.scm 143 | maven-scm-provider-gitexe 144 | 1.9.4 145 | 146 | 147 | 148 | 149 | org.apache.maven.plugins 150 | maven-compiler-plugin 151 | 3.3 152 | 153 | 1.7 154 | 1.7 155 | 156 | 157 | 158 | org.apache.maven.plugins 159 | maven-project-info-reports-plugin 160 | 2.8.1 161 | 162 | 163 | org.apache.maven.plugins 164 | maven-checkstyle-plugin 165 | 2.16 166 | 167 | 168 | validate 169 | validate 170 | 171 | checkstyle.xml 172 | UTF-8 173 | true 174 | true 175 | 176 | 177 | check 178 | 179 | 180 | 181 | 182 | 183 | com.puppycrawl.tools 184 | checkstyle 185 | 6.1.1 186 | 187 | 188 | 189 | 190 | org.sonatype.plugins 191 | nexus-staging-maven-plugin 192 | 1.6.5 193 | true 194 | 195 | ossrh 196 | https://oss.sonatype.org/ 197 | ${autoReleaseAfterClose} 198 | 10 199 | 200 | 201 | 202 | org.apache.maven.plugins 203 | maven-enforcer-plugin 204 | 1.4.1 205 | 206 | 207 | enforce 208 | 209 | 210 | 211 | 212 | 213 | 214 | enforce 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/CrtAuthClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 21 | import com.spotify.crtauth.exceptions.ProtocolVersionException; 22 | import com.spotify.crtauth.protocol.Challenge; 23 | import com.spotify.crtauth.protocol.CrtAuthCodec; 24 | import com.spotify.crtauth.protocol.Response; 25 | import com.spotify.crtauth.signer.Signer; 26 | 27 | import static com.spotify.crtauth.utils.ASCIICodec.decode; 28 | import static com.spotify.crtauth.utils.ASCIICodec.encode; 29 | 30 | /** 31 | * This class creates a response String given a challenge from a server using the Signer instance 32 | * provided in the constructor. Additionally, this class verifies that the serverName embedded in 33 | * the challenge matches serverName, to prevent attacks when a client is tricked to sign a challenge 34 | * for an unrelated serverName by an attacker. 35 | */ 36 | public class CrtAuthClient { 37 | 38 | private final Signer signer; 39 | private final String serverName; 40 | 41 | /** 42 | * Construct an CrtAuthClient instance backed by the provided signer. 43 | * 44 | * @param signer a Signer instance to back the constructed instance. 45 | * @param serverName the name of the server this client gets requests from. 46 | */ 47 | public CrtAuthClient(Signer signer, String serverName) { 48 | this.signer = signer; 49 | this.serverName = serverName; 50 | } 51 | 52 | /** 53 | * Generate a response String using the Signer of this instance, additionally verifying that the 54 | * embedded serverName matches the serverName of this instance. 55 | * 56 | * @param challenge A challenge String obtained from a server. 57 | * @return The response String to be returned to the server. 58 | * @throws IllegalArgumentException if there is something wrong with the challenge. 59 | */ 60 | public String createResponse(String challenge) 61 | throws IllegalArgumentException, KeyNotFoundException, ProtocolVersionException { 62 | byte[] decodedChallenge = decode(challenge); 63 | Challenge deserializedChallenge = CrtAuthCodec.deserializeChallenge(decodedChallenge); 64 | if (!deserializedChallenge.getServerName().equals(serverName)) { 65 | throw new IllegalArgumentException( 66 | String.format("Server name mismatch (%s != %s). Possible MITM attack.", 67 | deserializedChallenge.getServerName(), serverName) 68 | ); 69 | } 70 | byte[] signature = signer.sign(decodedChallenge, deserializedChallenge.getFingerprint()); 71 | return encode(CrtAuthCodec.serialize(new Response(decodedChallenge, signature))); 72 | } 73 | 74 | /** 75 | * Create a request string from a username. Request is too trivial for it to make it into a class 76 | * of it's own a this stage. 77 | * 78 | * @param username the username to encode 79 | * @return an encoded request message 80 | */ 81 | public static String createRequest(String username) { 82 | return CrtAuthCodec.serializeEncodedRequest(username); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/CrtAuthServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.google.common.base.Charsets; 21 | import com.google.common.base.Optional; 22 | import com.google.common.collect.ImmutableList; 23 | import com.google.common.collect.Lists; 24 | import com.google.common.primitives.UnsignedInteger; 25 | 26 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 27 | import com.spotify.crtauth.exceptions.ProtocolVersionException; 28 | import com.spotify.crtauth.exceptions.TokenExpiredException; 29 | import com.spotify.crtauth.keyprovider.KeyProvider; 30 | import com.spotify.crtauth.protocol.Challenge; 31 | import com.spotify.crtauth.protocol.CrtAuthCodec; 32 | import com.spotify.crtauth.protocol.Response; 33 | import com.spotify.crtauth.protocol.Token; 34 | import com.spotify.crtauth.utils.RealTimeSupplier; 35 | import com.spotify.crtauth.utils.TimeSupplier; 36 | 37 | import org.slf4j.Logger; 38 | import org.slf4j.LoggerFactory; 39 | 40 | import java.security.PublicKey; 41 | import java.security.Signature; 42 | import java.security.interfaces.RSAPublicKey; 43 | import java.util.Arrays; 44 | import java.util.List; 45 | import java.util.Random; 46 | 47 | import static com.google.common.base.Preconditions.checkArgument; 48 | import static com.google.common.base.Preconditions.checkNotNull; 49 | import static com.spotify.crtauth.utils.ASCIICodec.decode; 50 | import static com.spotify.crtauth.utils.ASCIICodec.encode; 51 | 52 | /** 53 | * Instances of this class implements the server part of an crtauth authentication interaction. A 54 | * consumer of this class would typically provide a means for remote clients to call the 55 | * createChallenge() and createToken() methods using i.e. HTTPS. 56 | * 57 | * A client is expected to perform the following operations: 58 | *
    59 | *
  1. Request a challenge by obtaining the output from createChallenge(), 60 | * given the username of the user about to authenticate.
  2. 61 | *
  3. Turn the challenge string into a response string using a private key. One implementation 62 | * of response generation is provided in CrtAuthClient.crateResponse()
  4. 63 | *
  5. Return the response String to the server in exchange for a token string.
  6. 64 | *
  7. Use the provided token to make authenticated API calls on the server. The API endpoints 65 | * in turn use verifyToken() to check that the token provided is indeed valid.
  8. 66 | *
67 | * 68 | * The authentication mechanism is time sensitive, since it relies on a specified validity period 69 | * for tokens. A clock can be off at most CLOCK_FUGDE seconds before the server starts emitting too 70 | * new/too old messages. Also, after the server sends a challenge, the client is supposed to produce 71 | * a reply within RESP_TIMEOUT seconds. 72 | */ 73 | public class CrtAuthServer { 74 | 75 | private static final UnsignedInteger CLOCK_FUDGE = UnsignedInteger.fromIntBits(2); 76 | private static final UnsignedInteger RESPONSE_TIMEOUT = UnsignedInteger.fromIntBits(20); 77 | // The maximum token lifetime in seconds. 78 | private static final int MAX_VALIDITY = 600; 79 | private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; 80 | private final UnsignedInteger tokenLifetimeSeconds; 81 | private final String serverName; 82 | private final List keyProviders; 83 | private final TimeSupplier timeSupplier; 84 | private final Random random; 85 | private final byte[] secret; 86 | 87 | private static final Logger log = LoggerFactory.getLogger(CrtAuthServer.class); 88 | 89 | public static class Builder { 90 | 91 | private static final UnsignedInteger DEFAULT_TOKEN_LIFETIME_SECONDS = 92 | UnsignedInteger.fromIntBits(60); 93 | private static final TimeSupplier DEFAULT_TIME_SUPPLIER = new RealTimeSupplier(); 94 | private Optional tokenLifetimeSeconds = Optional.absent(); 95 | private String serverName; 96 | private List keyProviders = Lists.newArrayList(); 97 | private Optional timeSupplier = Optional.absent(); 98 | private Optional random = Optional.absent(); 99 | private byte[] secret; 100 | 101 | public Builder setTokenLifetimeSeconds(int tokenLifetimeSeconds) { 102 | this.tokenLifetimeSeconds = Optional.of(UnsignedInteger.fromIntBits(tokenLifetimeSeconds)); 103 | return this; 104 | } 105 | 106 | public Builder setServerName(String serverName) { 107 | this.serverName = serverName; 108 | return this; 109 | } 110 | 111 | public Builder addKeyProvider(KeyProvider keyProvider) { 112 | this.keyProviders.add(keyProvider); 113 | return this; 114 | } 115 | 116 | public Builder setKeyProvider(KeyProvider keyProvider) { 117 | this.keyProviders.clear(); 118 | this.keyProviders.add(keyProvider); 119 | return this; 120 | } 121 | 122 | public Builder setTimeSupplier(TimeSupplier timeSupplier) { 123 | this.timeSupplier = Optional.of(timeSupplier); 124 | return this; 125 | } 126 | 127 | public Builder setRandom(Random random) { 128 | this.random = Optional.of(random); 129 | return this; 130 | } 131 | 132 | public Builder setSecret(byte[] secret) { 133 | checkArgument(secret.length > 0); 134 | this.secret = Arrays.copyOf(secret, secret.length); 135 | return this; 136 | } 137 | 138 | public CrtAuthServer build() { 139 | checkNotNull(serverName); 140 | checkNotNull(keyProviders); 141 | checkNotNull(secret); 142 | 143 | if (keyProviders.isEmpty()) { 144 | throw new IllegalArgumentException("At least one key provider must be specified."); 145 | } 146 | 147 | final UnsignedInteger lifetime = tokenLifetimeSeconds.or(DEFAULT_TOKEN_LIFETIME_SECONDS); 148 | if (lifetime.intValue() > MAX_VALIDITY) { 149 | throw new IllegalArgumentException(String.format( 150 | "Overly long token lifetime. Max lifetime is %d.", MAX_VALIDITY)); 151 | } 152 | 153 | return new CrtAuthServer(lifetime, 154 | serverName, 155 | keyProviders, 156 | timeSupplier.or(DEFAULT_TIME_SUPPLIER), 157 | random.or(new Random()), 158 | secret 159 | ); 160 | } 161 | } 162 | 163 | private CrtAuthServer(UnsignedInteger tokenLifetimeSeconds, String serverName, 164 | List keyProviders, TimeSupplier timeSupplier, Random random, 165 | byte[] secret) { 166 | this.tokenLifetimeSeconds = tokenLifetimeSeconds; 167 | this.serverName = serverName; 168 | this.keyProviders = ImmutableList.copyOf(keyProviders); 169 | this.timeSupplier = timeSupplier; 170 | this.random = random; 171 | checkArgument(secret != null && secret.length > 0); 172 | this.secret = Arrays.copyOf(secret, secret.length); 173 | } 174 | 175 | /** 176 | * Create a challenge to authenticate a given user. The userName needs to be provided at this 177 | * stage to encode a fingerprint of the public key stored in the server encoded in the challenge. 178 | * This is required because a client can hold more than one private key and would need this 179 | * information to pick the right key to sign the response. If the keyProvider fails to retrieve 180 | * the public key, a fake Fingerprint is generated so that the presence of a challenge doesn't 181 | * reveal whether a user key is present on the server or not. 182 | * 183 | * @param request The request message which contains an encoded username 184 | * @return A challenge message. 185 | * @throws IllegalArgumentException if the request format is invalid 186 | */ 187 | public String createChallenge(String request) 188 | throws IllegalArgumentException, ProtocolVersionException { 189 | 190 | String userName; 191 | userName = CrtAuthCodec.deserializeRequest(request); 192 | 193 | Fingerprint fingerprint; 194 | try { 195 | fingerprint = new Fingerprint(getKeyForUser(userName)); 196 | } catch (KeyNotFoundException e) { 197 | log.info("No public key found for user {}, creating fake fingerprint", userName); 198 | fingerprint = createFakeFingerprint(userName); 199 | } 200 | 201 | byte[] uniqueData = new byte[Challenge.UNIQUE_DATA_LENGTH]; 202 | UnsignedInteger timeNow = timeSupplier.getTime(); 203 | random.nextBytes(uniqueData); 204 | Challenge challenge = Challenge.newBuilder() 205 | .setFingerprint(fingerprint) 206 | .setUniqueData(uniqueData) 207 | .setValidFromTimestamp(timeNow.minus(CLOCK_FUDGE)) 208 | .setValidToTimestamp(timeNow.plus(RESPONSE_TIMEOUT)) 209 | .setServerName(serverName) 210 | .setUserName(userName) 211 | .build(); 212 | 213 | return encode(CrtAuthCodec.serialize(challenge, secret)); 214 | } 215 | 216 | /** 217 | * Get the public key for a user by iterating through all key providers. The first 218 | * matching key will be returned. 219 | * 220 | * @param userName the username to get the key for 221 | * @return the first RSAPublicKey found for the user 222 | * @throws KeyNotFoundException 223 | */ 224 | private RSAPublicKey getKeyForUser(String userName) throws KeyNotFoundException { 225 | RSAPublicKey key = null; 226 | for (final KeyProvider keyProvider : keyProviders) { 227 | try { 228 | key = keyProvider.getKey(userName); 229 | break; 230 | } catch (KeyNotFoundException e) { 231 | // that's fine, try the next provider 232 | } 233 | } 234 | 235 | if (key == null) { 236 | throw new KeyNotFoundException(); 237 | } 238 | 239 | return key; 240 | } 241 | 242 | /** 243 | * Generate a fake real looking fingerprint for a non-existent user. 244 | * 245 | * @param userName the username to seed the transform with 246 | * @return a Fingerprint with bytes that are a function of username and secret 247 | */ 248 | private Fingerprint createFakeFingerprint(String userName) { 249 | byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode( 250 | this.secret, userName.getBytes(Charsets.UTF_8)); 251 | return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6)); 252 | } 253 | 254 | /** 255 | * Given the response to a previous challenge, produce a token used by the client to 256 | * authenticate. 257 | * 258 | * @param response The client's response to the initial challenge. 259 | * @return A token used to authenticate subsequent requests. 260 | * @throws IllegalArgumentException if there is an encoding error in the response message 261 | */ 262 | public String createToken(String response) 263 | throws IllegalArgumentException, ProtocolVersionException { 264 | final Response decodedResponse; 265 | final Challenge challenge; 266 | decodedResponse = CrtAuthCodec.deserializeResponse(decode(response)); 267 | challenge = CrtAuthCodec.deserializeChallengeAuthenticated( 268 | decodedResponse.getPayload(), secret); 269 | 270 | if (!challenge.getServerName().equals(serverName)) { 271 | throw new IllegalArgumentException("Got challenge with the wrong server_name encoded."); 272 | } 273 | PublicKey publicKey; 274 | try { 275 | publicKey = getKeyForUser(challenge.getUserName()); 276 | } catch (KeyNotFoundException e) { 277 | // If the user requesting authentication doesn't have a public key, we throw an 278 | // InvalidInputException. This normally shouldn't happen, since at this stage a challenge 279 | // should have already been sent, which in turn requires knowledge of the user's public key. 280 | throw new IllegalArgumentException(e); 281 | } 282 | boolean signatureVerified; 283 | try { 284 | Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 285 | signature.initVerify(publicKey); 286 | signature.update(decodedResponse.getPayload()); 287 | signatureVerified = signature.verify(decodedResponse.getSignature()); 288 | } catch (Exception e) { 289 | throw new RuntimeException(e); 290 | } 291 | if (challenge.isExpired(timeSupplier)) { 292 | throw new IllegalArgumentException("The challenge is out of its validity period"); 293 | } 294 | if (!signatureVerified) { 295 | throw new IllegalArgumentException("Client did not provide proof that it controls the " + 296 | "secret key."); 297 | } 298 | UnsignedInteger validFrom = timeSupplier.getTime().minus(CLOCK_FUDGE); 299 | UnsignedInteger validTo = timeSupplier.getTime().plus(tokenLifetimeSeconds); 300 | Token token = new Token(validFrom.intValue(), validTo.intValue(), challenge.getUserName()); 301 | return encode(CrtAuthCodec.serialize(token, secret)); 302 | } 303 | 304 | /** 305 | * Verify that a given token is valid, i.e. that it has been produced by the current authenticator 306 | * and that it hasn't expired. 307 | * 308 | * @param token the token to validate. 309 | * @return the username that this token belongs to. 310 | * @throws IllegalArgumentException If the token appears to have been tampered with. 311 | * @throws TokenExpiredException If the token has expired. 312 | */ 313 | public String validateToken(String token) 314 | throws IllegalArgumentException, TokenExpiredException, ProtocolVersionException { 315 | final Token deserializedToken = 316 | CrtAuthCodec.deserializeTokenAuthenticated(decode(token), secret); 317 | if (deserializedToken.isExpired(timeSupplier)) { 318 | throw new TokenExpiredException(); 319 | } 320 | if (deserializedToken.getValidTo() - deserializedToken.getValidFrom() > MAX_VALIDITY) { 321 | throw new TokenExpiredException("Overly long token lifetime."); 322 | } 323 | return deserializedToken.getUserName(); 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/Fingerprint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.google.common.hash.Hashing; 21 | 22 | import java.io.ByteArrayOutputStream; 23 | import java.io.DataOutput; 24 | import java.io.DataOutputStream; 25 | import java.io.IOException; 26 | import java.security.interfaces.RSAPublicKey; 27 | import java.util.Arrays; 28 | 29 | import static com.google.common.base.Preconditions.checkPositionIndex; 30 | 31 | /** 32 | * Instances of this class contains a compact representation of the information needed to identify a 33 | * specific public key used to to sign a payload using the Signer interface. This piece of 34 | * information then gets sent from the server to the client to ensure that the right key gets picked 35 | * if there are many signing keys available. 36 | * 37 | * The bytes consists of the 6 first bytes of a SHA-1 hash of the traditional binary representation 38 | * of an RSA key used by ssh-keygen, a simple length value encoding with a 4 byte big endian length 39 | * followed by the value as a binary number first the public exponent followed by the modulus. 40 | */ 41 | public class Fingerprint { 42 | 43 | private static final int FINGERPRINT_LENGTH = 6; 44 | // The size of a newly generated public part of a 4096 bit key 45 | private static final int TYPICAL_KEY_SIZE = 535; 46 | 47 | private final byte[] bytes; 48 | 49 | // TODO: Move CrtAuthCodec into the same package, and make this constructor package local 50 | public Fingerprint(byte[] fingerprint) { 51 | this.bytes = fingerprint; 52 | } 53 | 54 | /** 55 | * Calculate a bytes from the provided public key. 56 | * 57 | * @param publicKey the RSAPublicKey instance to make this fingerprint match 58 | */ 59 | public Fingerprint(RSAPublicKey publicKey) { 60 | byte[] digestBytes = Hashing.sha1().hashBytes(getDerEncoding(publicKey)).asBytes(); 61 | checkPositionIndex(FINGERPRINT_LENGTH, digestBytes.length); 62 | this.bytes = Arrays.copyOf(digestBytes, FINGERPRINT_LENGTH); 63 | } 64 | 65 | public byte[] getBytes() { 66 | return bytes; 67 | } 68 | 69 | /** 70 | * Returns true if this Fingerprint matches the public key other 71 | * 72 | * @param other the other RSAPublicKey to match 73 | * @return true if this Fingerprint matches other, else false 74 | */ 75 | public boolean matches(RSAPublicKey other) { 76 | return this.equals(new Fingerprint(other)); 77 | } 78 | 79 | private static byte[] getDerEncoding(RSAPublicKey key) { 80 | ByteArrayOutputStream buffer = new ByteArrayOutputStream(TYPICAL_KEY_SIZE); 81 | DataOutputStream dataOutput = new DataOutputStream(buffer); 82 | writeVariableLengthOpaque("ssh-rsa".getBytes(), dataOutput); 83 | writeVariableLengthOpaque(key.getPublicExponent().toByteArray(), dataOutput); 84 | writeVariableLengthOpaque(key.getModulus().toByteArray(), dataOutput); 85 | return buffer.toByteArray(); 86 | } 87 | 88 | private static void writeVariableLengthOpaque(byte[] opaque, DataOutput byteBuffer) { 89 | try { 90 | byteBuffer.writeInt(opaque.length); 91 | byteBuffer.write(opaque); 92 | } catch (IOException e) { 93 | throw new RuntimeException(e); 94 | } 95 | } 96 | 97 | @Override 98 | public boolean equals(Object o) { 99 | if (this == o) { 100 | return true; 101 | } 102 | if (o == null || getClass() != o.getClass()) { 103 | return false; 104 | } 105 | 106 | Fingerprint that = (Fingerprint) o; 107 | 108 | return Arrays.equals(bytes, that.bytes); 109 | } 110 | 111 | @Override 112 | public int hashCode() { 113 | return Arrays.hashCode(bytes); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/exceptions/CrtAuthException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.exceptions; 19 | 20 | public class CrtAuthException extends Exception { 21 | 22 | public CrtAuthException() { 23 | super(); 24 | } 25 | 26 | public CrtAuthException(String message) { 27 | super(message); 28 | } 29 | 30 | public CrtAuthException(Throwable throwable) { 31 | super(throwable); 32 | } 33 | 34 | public CrtAuthException(String message, Throwable cause) { 35 | super(message, cause); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/exceptions/KeyNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.exceptions; 19 | 20 | public class KeyNotFoundException extends CrtAuthException { 21 | 22 | public KeyNotFoundException() { 23 | super(); 24 | } 25 | 26 | public KeyNotFoundException(String message) { 27 | super(message); 28 | } 29 | 30 | public KeyNotFoundException(Throwable throwable) { 31 | super(throwable); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/exceptions/ProtocolVersionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.exceptions; 19 | 20 | /** 21 | * This Exception is thrown when processing an incoming message that generated with a version of the 22 | * crtauth protocol that is unsupported by this library. 23 | */ 24 | public class ProtocolVersionException extends CrtAuthException { 25 | 26 | public ProtocolVersionException(String message) { 27 | super(message); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/exceptions/TokenExpiredException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.exceptions; 19 | 20 | public class TokenExpiredException extends CrtAuthException { 21 | 22 | public TokenExpiredException() { 23 | super(); 24 | } 25 | 26 | public TokenExpiredException(String message) { 27 | super(message); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/keyprovider/FileKeyProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.keyprovider; 19 | 20 | import com.google.common.base.Charsets; 21 | import com.google.common.io.Files; 22 | 23 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 24 | import com.spotify.crtauth.utils.TraditionalKeyParser; 25 | 26 | import java.io.File; 27 | import java.security.KeyFactory; 28 | import java.security.NoSuchAlgorithmException; 29 | import java.security.interfaces.RSAPublicKey; 30 | import java.security.spec.RSAPublicKeySpec; 31 | 32 | import static com.google.common.base.Preconditions.checkArgument; 33 | 34 | /** 35 | * This {@code KeyProvider} fetches keys from a local path. The file name of each public key file is 36 | * assumed to be in the format $username_id_rsa.pub, and keys are assumed to be stored in PKCS1, PEM 37 | * format, as generated by default by ssh-keygen. 38 | */ 39 | public class FileKeyProvider implements KeyProvider { 40 | 41 | private static final String KEYFILE_PATTERN = "%s_id_rsa.pub"; 42 | private static final String KEY_ALGORITHM = "RSA"; 43 | private final File keyRootDir; 44 | 45 | /** 46 | * Construct a key provider that fetches keys from a local path. 47 | * 48 | * @param keyRootDir Path to directory where all keys are located. 49 | */ 50 | public FileKeyProvider(File keyRootDir) { 51 | checkArgument(keyRootDir.exists(), "The root directory for ssh keys doesn't exist."); 52 | checkArgument(keyRootDir.isDirectory(), "The root directory for ssh keys is actually not a " + 53 | "directory."); 54 | this.keyRootDir = keyRootDir; 55 | } 56 | 57 | @Override 58 | public RSAPublicKey getKey(String username) throws KeyNotFoundException { 59 | String filename = String.format(KEYFILE_PATTERN, username); 60 | KeyFactory keyFactory; 61 | try { 62 | keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 63 | } catch (NoSuchAlgorithmException e) { 64 | throw new RuntimeException(e); 65 | } 66 | File keyFile = new File(keyRootDir, filename); 67 | try { 68 | byte[] keyBytes = Files.toByteArray(keyFile); 69 | String keyString = new String(keyBytes, Charsets.US_ASCII); 70 | RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(keyString); 71 | return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); 72 | } catch (Exception e) { 73 | throw new KeyNotFoundException(e); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/keyprovider/InMemoryKeyProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.keyprovider; 19 | 20 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 21 | 22 | import java.security.interfaces.RSAPublicKey; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | public class InMemoryKeyProvider implements KeyProvider { 27 | 28 | private final Map keys = new HashMap(); 29 | 30 | public void putKey(String username, RSAPublicKey key) { 31 | keys.put(username, key); 32 | } 33 | 34 | @Override 35 | public RSAPublicKey getKey(String username) throws KeyNotFoundException { 36 | RSAPublicKey key = keys.get(username); 37 | if (key == null) { 38 | throw new KeyNotFoundException(); 39 | } 40 | return key; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/keyprovider/KeyProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.keyprovider; 19 | 20 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 21 | 22 | import java.security.interfaces.RSAPublicKey; 23 | 24 | /** 25 | * This interface exposes a single method to obtain a key for a given user. 26 | */ 27 | public interface KeyProvider { 28 | 29 | /** 30 | * Return a public key for the given username. 31 | * 32 | * @param username A username as a string. 33 | * @return The user's public key. 34 | * @throws KeyNotFoundException when the key is not available. This might happen both because the 35 | * key for a given user is not available or because a key for the 36 | * given user is available but it cannot be recognized as a valid 37 | * public key. 38 | */ 39 | RSAPublicKey getKey(String username) throws KeyNotFoundException; 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/Challenge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | 22 | import com.spotify.crtauth.Fingerprint; 23 | import com.spotify.crtauth.utils.TimeIntervals; 24 | import com.spotify.crtauth.utils.TimeSupplier; 25 | 26 | import java.util.Arrays; 27 | 28 | import static com.google.common.base.Preconditions.checkArgument; 29 | 30 | public class Challenge { 31 | 32 | public static final int UNIQUE_DATA_LENGTH = 20; 33 | 34 | private final byte[] uniqueData; 35 | private final int validFromTimestamp; 36 | private final int validToTimestamp; 37 | private final Fingerprint fingerprint; 38 | private final String serverName; 39 | private final String userName; 40 | 41 | public static class Builder { 42 | 43 | private byte[] uniqueData; 44 | private int validFromTimestamp; 45 | private int validToTimestamp; 46 | private Fingerprint fingerprint; 47 | private String serverName; 48 | private String userName; 49 | 50 | public Builder setUniqueData(byte[] uniqueData) { 51 | checkArgument(uniqueData.length == UNIQUE_DATA_LENGTH); 52 | this.uniqueData = Arrays.copyOf(uniqueData, uniqueData.length); 53 | return this; 54 | } 55 | 56 | public Builder setValidFromTimestamp(UnsignedInteger timestamp) { 57 | this.validFromTimestamp = timestamp.intValue(); 58 | return this; 59 | } 60 | 61 | public Builder setValidFromTimestamp(int timestamp) { 62 | this.validFromTimestamp = timestamp; 63 | return this; 64 | } 65 | 66 | public Builder setValidToTimestamp(UnsignedInteger timestamp) { 67 | this.validToTimestamp = timestamp.intValue(); 68 | return this; 69 | } 70 | 71 | public Builder setValidToTimestamp(int timestamp) { 72 | this.validToTimestamp = timestamp; 73 | return this; 74 | } 75 | 76 | public Builder setFingerprint(Fingerprint fingerprint) { 77 | this.fingerprint = fingerprint; 78 | return this; 79 | } 80 | 81 | public Builder setServerName(String serverName) { 82 | this.serverName = serverName; 83 | return this; 84 | } 85 | 86 | public Builder setUserName(String userName) { 87 | this.userName = userName; 88 | return this; 89 | } 90 | 91 | public Challenge build() { 92 | return new Challenge(uniqueData, validFromTimestamp, validToTimestamp, 93 | fingerprint, serverName, userName); 94 | } 95 | } 96 | 97 | public Challenge(byte[] uniqueData, int validFromTimestamp, 98 | int validToTimestamp, Fingerprint fingerprint, String serverName, 99 | String userName) { 100 | if (uniqueData == null) { 101 | throw new IllegalArgumentException("'uniqueData' must be set"); 102 | } 103 | 104 | if (fingerprint == null) { 105 | throw new IllegalArgumentException("'fingerprint' must be set"); 106 | } 107 | 108 | if (!(validFromTimestamp < validToTimestamp)) { 109 | throw new IllegalArgumentException( 110 | "validity timestamps are invalid, 'validFromTimestamp' " 111 | + "must be smaller than 'validToTimestamp'"); 112 | } 113 | 114 | if (serverName == null || serverName.isEmpty()) { 115 | throw new IllegalArgumentException("'serverName' must be set and non-empty"); 116 | } 117 | 118 | if (userName == null || userName.isEmpty()) { 119 | throw new IllegalArgumentException("'userName' must be set and non-empty"); 120 | } 121 | 122 | this.uniqueData = uniqueData; 123 | this.validFromTimestamp = validFromTimestamp; 124 | this.validToTimestamp = validToTimestamp; 125 | this.fingerprint = fingerprint; 126 | this.serverName = serverName; 127 | this.userName = userName; 128 | } 129 | 130 | public static Builder newBuilder() { 131 | return new Builder(); 132 | } 133 | 134 | public byte[] getUniqueData() { 135 | return Arrays.copyOf(uniqueData, uniqueData.length); 136 | } 137 | 138 | public int getValidFromTimestamp() { 139 | return validFromTimestamp; 140 | } 141 | 142 | public int getValidToTimestamp() { 143 | return validToTimestamp; 144 | } 145 | 146 | public Fingerprint getFingerprint() { 147 | return fingerprint; 148 | } 149 | 150 | public String getServerName() { 151 | return serverName; 152 | } 153 | 154 | public String getUserName() { 155 | return userName; 156 | } 157 | 158 | public boolean isExpired(TimeSupplier timeSupplier) { 159 | return TimeIntervals.isExpired(validFromTimestamp, validToTimestamp, timeSupplier); 160 | } 161 | 162 | public boolean equals(Object o) { 163 | if (this == o) { 164 | return true; 165 | } 166 | if (o == null || getClass() != o.getClass()) { 167 | return false; 168 | } 169 | 170 | Challenge challenge = (Challenge) o; 171 | 172 | return Arrays.equals(uniqueData, challenge.uniqueData) 173 | && validFromTimestamp == challenge.validFromTimestamp 174 | && validToTimestamp == challenge.validToTimestamp 175 | && fingerprint.equals(challenge.fingerprint) 176 | && serverName.equals(challenge.serverName) 177 | && userName.equals(challenge.userName); 178 | } 179 | 180 | @Override 181 | public int hashCode() { 182 | int result = Arrays.hashCode(uniqueData); 183 | result = 31 * result + validFromTimestamp; 184 | result = 31 * result + validToTimestamp; 185 | result = 31 * result + fingerprint.hashCode(); 186 | result = 31 * result + serverName.hashCode(); 187 | result = 31 * result + userName.hashCode(); 188 | return result; 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/CrtAuthCodec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.spotify.crtauth.Fingerprint; 21 | import com.spotify.crtauth.exceptions.ProtocolVersionException; 22 | import com.spotify.crtauth.utils.ASCIICodec; 23 | 24 | import javax.crypto.Mac; 25 | import javax.crypto.SecretKey; 26 | import javax.crypto.spec.SecretKeySpec; 27 | 28 | /** 29 | * This class is used to encode and decode the different messages of the crtauth protocol between 30 | * binary and object representation. 31 | */ 32 | public class CrtAuthCodec { 33 | 34 | private static final byte VERSION = 1; 35 | private static final byte CHALLENGE_MAGIC = 'c'; 36 | private static final byte RESPONSE_MAGIC = 'r'; 37 | private static final byte TOKEN_MAGIC = 't'; 38 | private static final byte REQUEST_MAGIC = 'q'; 39 | 40 | 41 | private static final String MAC_ALGORITHM = "HmacSHA256"; 42 | 43 | /** 44 | * Serialize a challenge into it's binary representation 45 | * 46 | * @param challenge the challenge to serialize 47 | * @param hmacSecret the secret used to generate the HMAC field 48 | * @return an array of bytes representing the provided Challenge 49 | */ 50 | public static byte[] serialize(Challenge challenge, byte[] hmacSecret) { 51 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 52 | packer.pack(VERSION); 53 | packer.pack(CHALLENGE_MAGIC); 54 | packer.pack(challenge.getUniqueData()); 55 | packer.pack(challenge.getValidFromTimestamp()); 56 | packer.pack(challenge.getValidToTimestamp()); 57 | packer.pack(challenge.getFingerprint().getBytes()); 58 | packer.pack(challenge.getServerName()); 59 | packer.pack(challenge.getUserName()); 60 | byte[] bytes = packer.getBytes(); 61 | byte[] mac = getAuthenticationCode(hmacSecret, bytes); 62 | packer.pack(mac); 63 | return packer.getBytes(); 64 | } 65 | 66 | public static Challenge deserializeChallenge(byte[] data) 67 | throws IllegalArgumentException, ProtocolVersionException { 68 | return doDeserializeChallenge(new MiniMessagePack.Unpacker(data)); 69 | } 70 | 71 | public static Challenge deserializeChallengeAuthenticated(byte[] data, byte[] hmacSecret) 72 | throws IllegalArgumentException, ProtocolVersionException { 73 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(data); 74 | Challenge c = doDeserializeChallenge(unpacker); 75 | byte[] digest = getAuthenticationCode(hmacSecret, data, unpacker.getBytesRead()); 76 | try { 77 | if (!constantTimeEquals(digest, unpacker.unpackBin())) { 78 | throw new IllegalArgumentException("HMAC validation failed"); 79 | } 80 | } catch (DeserializationException e) { 81 | throw new IllegalArgumentException(e.getMessage()); 82 | } 83 | return c; 84 | } 85 | 86 | /** 87 | * Serialize a Response into binary representation 88 | * 89 | * @param response the Response to serialize. 90 | * @return an array of bytes representing the provided Response 91 | */ 92 | public static byte[] serialize(Response response) { 93 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 94 | packer.pack(VERSION); 95 | packer.pack(RESPONSE_MAGIC); 96 | packer.pack(response.getPayload()); 97 | packer.pack(response.getSignature()); 98 | return packer.getBytes(); 99 | } 100 | 101 | public static Response deserializeResponse(byte[] data) 102 | throws IllegalArgumentException, ProtocolVersionException { 103 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(data); 104 | try { 105 | parseVersionMagic(RESPONSE_MAGIC, unpacker); 106 | return new Response( 107 | unpacker.unpackBin(), // challenge 108 | unpacker.unpackBin() // signature 109 | ); 110 | } catch (DeserializationException e) { 111 | throw new IllegalArgumentException(e.getMessage()); 112 | } 113 | } 114 | 115 | public static Token deserializeTokenAuthenticated(byte[] data, byte[] hmacSecret) 116 | throws IllegalArgumentException, ProtocolVersionException { 117 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(data); 118 | try { 119 | Token token = doDeserializeToken(unpacker); 120 | byte[] digest = getAuthenticationCode(hmacSecret, data, unpacker.getBytesRead()); 121 | if (!constantTimeEquals(digest, unpacker.unpackBin())) { 122 | throw new IllegalArgumentException("HMAC validation failed"); 123 | } 124 | return token; 125 | } catch (DeserializationException e) { 126 | throw new IllegalArgumentException(e.getMessage()); 127 | } 128 | 129 | } 130 | 131 | public static byte[] serialize(Token token, byte[] hmacSecret) { 132 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 133 | packer.pack((byte) 0x01); 134 | packer.pack(TOKEN_MAGIC); 135 | packer.pack(token.getValidFrom()); 136 | packer.pack(token.getValidTo()); 137 | packer.pack(token.getUserName()); 138 | packer.pack(getAuthenticationCode(hmacSecret, packer.getBytes())); 139 | return packer.getBytes(); 140 | } 141 | 142 | 143 | private static Challenge doDeserializeChallenge(MiniMessagePack.Unpacker unpacker) 144 | throws IllegalArgumentException, ProtocolVersionException { 145 | try { 146 | parseVersionMagic(CHALLENGE_MAGIC, unpacker); 147 | return new Challenge( 148 | unpacker.unpackBin(), // unique data 149 | unpacker.unpackInt(), // validFromTimestamp 150 | unpacker.unpackInt(), // validToTimestamp 151 | new Fingerprint(unpacker.unpackBin()), // fingerprint 152 | unpacker.unpackString(), // serverName 153 | unpacker.unpackString() // username 154 | ); 155 | } catch (DeserializationException e) { 156 | throw new IllegalArgumentException(e); 157 | } 158 | } 159 | 160 | private static Token doDeserializeToken(MiniMessagePack.Unpacker unpacker) 161 | throws IllegalArgumentException, ProtocolVersionException { 162 | try { 163 | parseVersionMagic(TOKEN_MAGIC, unpacker); 164 | return new Token( 165 | unpacker.unpackInt(), // validFrom 166 | unpacker.unpackInt(), // validTo 167 | unpacker.unpackString() // userName 168 | ); 169 | } catch (DeserializationException e) { 170 | throw new IllegalArgumentException(e); 171 | } 172 | } 173 | 174 | /** 175 | * Calculate and return a keyed hash message authentication code, HMAC, as specified in RFC2104 176 | * using SHA256 as hash function. 177 | * 178 | * @param secret the secret used to authenticate 179 | * @param data the data to authenticate 180 | * @param length the number of bytes from data to use when calculating the HMAC 181 | * @return an HMAC code for the specified data and secret 182 | */ 183 | private static byte[] getAuthenticationCode(byte[] secret, byte[] data, int length) { 184 | try { 185 | SecretKey secretKey = new SecretKeySpec(secret, MAC_ALGORITHM); 186 | Mac mac = Mac.getInstance(MAC_ALGORITHM); 187 | mac.init(secretKey); 188 | mac.update(data, 0, length); 189 | return mac.doFinal(); 190 | } catch (Exception e) { 191 | throw new RuntimeException(e); 192 | } 193 | } 194 | 195 | public static byte[] getAuthenticationCode(byte[] secret, byte[] data) { 196 | return getAuthenticationCode(secret, data, data.length); 197 | } 198 | 199 | /** 200 | * Create a request string from a username. Request is too trivial for it to make it into a class 201 | * of it's own a this stage. 202 | * 203 | * @param username the username to encode 204 | * @return an encoded request message 205 | */ 206 | public static String serializeEncodedRequest(String username) { 207 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 208 | packer.pack(1); 209 | packer.pack('q'); 210 | packer.pack(username); 211 | return ASCIICodec.encode(packer.getBytes()); 212 | } 213 | 214 | /** 215 | * Deserialize an ASCII encoded request messages and return the username string it encodes. Also 216 | * verifies that the type magic value matches and that the version equals 1. 217 | * 218 | * @param request the ASCII encoded request String 219 | * @return the username encoded in the String 220 | */ 221 | public static String deserializeRequest(String request) 222 | throws IllegalArgumentException, ProtocolVersionException { 223 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(ASCIICodec.decode(request)); 224 | try { 225 | parseVersionMagic(REQUEST_MAGIC, unpacker); 226 | return unpacker.unpackString(); 227 | } catch (DeserializationException e) { 228 | throw new IllegalArgumentException(e.getMessage()); 229 | } 230 | 231 | } 232 | 233 | private static void parseVersionMagic(byte magic, MiniMessagePack.Unpacker unpacker) 234 | throws ProtocolVersionException, DeserializationException { 235 | 236 | byte version = unpacker.unpackByte(); 237 | if (version != (byte) 0x01) { 238 | // version 0 protocol begins with ascii 'v' or ascii 'r' 239 | if (version == 0x76 || version == 0x72) { 240 | throw new ProtocolVersionException( 241 | "Received message using version 0 of the protocol. Only version 1 is supported"); 242 | } 243 | throw new ProtocolVersionException( 244 | "Received a message with too new version of the protocol. " + 245 | "Only version 1 is supported, received version %d" + version 246 | ); 247 | } 248 | byte readMagic = unpacker.unpackByte(); 249 | if (readMagic != magic) { 250 | throw new DeserializationException(String.format( 251 | "invalid magic byte, expected %d but got %d", readMagic, magic)); 252 | } 253 | } 254 | 255 | /** 256 | * Checks if byte arrays a and be are equal in an algorithm that runs in 257 | * constant time provided that their lengths are equal. 258 | * 259 | * @param a the first byte array 260 | * @param b the second byte array 261 | * @return true if a and be are equal, else false 262 | */ 263 | private static boolean constantTimeEquals(byte[] a, byte[] b) { 264 | if (a.length != b.length) { 265 | return false; 266 | } 267 | 268 | int result = 0; 269 | for (int i = 0; i < a.length; i++) { 270 | result |= a[i] ^ b[i]; 271 | } 272 | return result == 0; 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/DeserializationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | /** 21 | * An internal exception thrown when deserialization fails. 22 | */ 23 | class DeserializationException extends Exception { 24 | 25 | public DeserializationException(String message) { 26 | super(message); 27 | } 28 | 29 | public DeserializationException(Throwable throwable) { 30 | super(throwable); 31 | } 32 | 33 | public DeserializationException(String message, Throwable cause) { 34 | super(message, cause); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/MiniMessagePack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.base.Charsets; 21 | import com.google.common.io.ByteStreams; 22 | 23 | import java.io.ByteArrayInputStream; 24 | import java.io.ByteArrayOutputStream; 25 | import java.io.DataInputStream; 26 | import java.io.DataOutputStream; 27 | import java.io.IOException; 28 | import java.io.InputStream; 29 | 30 | import static com.google.common.base.Preconditions.checkArgument; 31 | import static com.google.common.base.Preconditions.checkNotNull; 32 | 33 | /** 34 | * This class implements the needed subset of the draft msgpack specification as available at 35 | * https://github.com/msgpack/msgpack/blob/7498cf31d1110170e4901d47951fe880d169f327/spec.md 36 | * 37 | * When a stable implementation of this specification exists, please consider switching an 38 | * externally maintained version. 39 | */ 40 | class MiniMessagePack { 41 | 42 | public static class Packer { 43 | 44 | private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 45 | private final DataOutputStream dataOutput = new DataOutputStream(byteArrayOutputStream); 46 | 47 | /** 48 | * Pack an integer in msgpack format. Negative values are not supported at the moment. 49 | * 50 | * @param integer a positive integer 51 | */ 52 | public void pack(int integer) { 53 | checkArgument(integer >= 0, "Negative integers not supported at the moment"); 54 | try { 55 | if (integer < 1 << 7) { 56 | dataOutput.writeByte(integer); 57 | } else if (integer < 1 << 8) { 58 | dataOutput.writeByte((byte) 0xcc); 59 | dataOutput.writeByte(integer); 60 | } else if (integer < 1 << 16) { 61 | dataOutput.writeByte((byte) 0xcd); 62 | dataOutput.writeShort(integer); 63 | } else { 64 | dataOutput.writeByte((byte) 0xce); 65 | dataOutput.writeInt(integer); 66 | } 67 | } catch (IOException e) { 68 | throw new RuntimeException("Filed to write to buffer. Should not happen", e); 69 | } 70 | } 71 | 72 | /** 73 | * Pack an array of bytes in msgpack format. 74 | * 75 | * @param data an array of bytes to pack. 76 | */ 77 | public void pack(byte[] data) { 78 | checkNotNull(data); 79 | try { 80 | if (data.length < 1 << 8) { 81 | dataOutput.write(0xc4); 82 | dataOutput.writeByte(data.length); 83 | } else if (data.length < 1 << 16) { 84 | dataOutput.write(0xc5); 85 | dataOutput.writeShort(data.length); 86 | } else { 87 | dataOutput.write(0xc6); 88 | dataOutput.writeInt(data.length); 89 | } 90 | dataOutput.write(data); 91 | } catch (IOException e) { 92 | throw new RuntimeException("Filed to write to buffer. Should not happen", e); 93 | } 94 | } 95 | 96 | /** 97 | * Pack a String in msgpack format. 98 | * 99 | * @param data a String to pack. 100 | */ 101 | public void pack(String data) { 102 | checkNotNull(data); 103 | byte[] encoded = data.getBytes(Charsets.UTF_8); 104 | try { 105 | if (encoded.length < 1 << 5) { 106 | dataOutput.write(0xa0 | encoded.length); 107 | } else if (data.length() < 1 << 8) { 108 | dataOutput.write(0xd9); 109 | dataOutput.writeByte(encoded.length); 110 | } else if (data.length() < 1 << 16) { 111 | dataOutput.write(0xda); 112 | dataOutput.writeShort(encoded.length); 113 | } else { 114 | dataOutput.write(0xdb); 115 | dataOutput.writeInt(encoded.length); 116 | } 117 | dataOutput.write(encoded); 118 | } catch (IOException e) { 119 | throw new RuntimeException("Filed to write to buffer. Should not happen", e); 120 | } 121 | } 122 | 123 | 124 | /** 125 | * Gets the bytes of everything packed in this Packer so far. 126 | * 127 | * @return an array of bytes 128 | */ 129 | public byte[] getBytes() { 130 | return byteArrayOutputStream.toByteArray(); 131 | } 132 | } 133 | 134 | public static class Unpacker { 135 | 136 | private final DataInputStream dataInputStream; 137 | private final ByteArrayInputStream byteArrayInputStream; 138 | final int dataSize; 139 | 140 | public Unpacker(byte[] data) { 141 | byteArrayInputStream = new ByteArrayInputStream(data); 142 | dataInputStream = new DataInputStream(byteArrayInputStream); 143 | dataSize = data.length; 144 | } 145 | 146 | /** 147 | * Unpacks and returns an int from this Unpacker. Negative integers are not yet supported. 148 | * 149 | * @return the int we read. 150 | */ 151 | public int unpackInt() throws DeserializationException { 152 | try { 153 | int firstByte = readByte(dataInputStream); 154 | if (firstByte < 0x80) { 155 | return firstByte; 156 | } else if (firstByte == 0xcc) { 157 | return readByte(dataInputStream); 158 | } else if (firstByte == 0xcd) { 159 | // readShort() reads a signed short, which won't do in this case 160 | return readByte(dataInputStream) << 8 | readByte(dataInputStream); 161 | } else if (firstByte == 0xce) { 162 | int ret = dataInputStream.readInt(); 163 | if (ret < 0) { 164 | throw new DeserializationException( 165 | "Attempting to deserialize an integer larger than Integer.MAX_VALUE" 166 | ); 167 | } 168 | return ret; 169 | } else { 170 | throw new DeserializationException(String.format( 171 | "Attempted to read int but initial byte (0x%02x) indicates non-integer", 172 | firstByte 173 | )); 174 | } 175 | } catch (IOException e) { 176 | throw new DeserializationException("Attempted to read past end of buffer"); 177 | } 178 | } 179 | 180 | /** 181 | * Unpacks and returns a byte array from this Unpacker instance. 182 | * 183 | * @return a byte array with binary data 184 | * @throws DeserializationException if an attempt to read past the end of the internal buffer or 185 | * if the data read is not marked as in the bin family 186 | */ 187 | public byte[] unpackBin() throws DeserializationException { 188 | try { 189 | int firstByte = readByte(dataInputStream); 190 | int len; 191 | if (firstByte == 0xc4) { 192 | len = readByte(dataInputStream); 193 | } else if (firstByte == 0xc5) { 194 | len = readByte(dataInputStream) << 8 | readByte(dataInputStream); 195 | } else if (firstByte == 0xc6) { 196 | len = dataInputStream.readInt(); 197 | if (len < 0) { 198 | throw new DeserializationException( 199 | "Attempting to deserialize an bin longer than Integer.MAX_VALUE" 200 | ); 201 | } 202 | } else { 203 | throw new DeserializationException(String.format( 204 | "Attempted to read int initial byte (0x%02x) indicates non-bin type", 205 | firstByte 206 | )); 207 | } 208 | byte[] data = new byte[len]; 209 | ByteStreams.readFully(dataInputStream, data); 210 | return data; 211 | } catch (IOException e) { 212 | throw new DeserializationException("Attempted to read past end of buffer"); 213 | } 214 | } 215 | 216 | /** 217 | * Unpacks and returns a String read from this unpacker. 218 | * 219 | * @return returns a String 220 | * @throws DeserializationException if the read data is not possible to decode as UTF-8, or if 221 | * the buffer is too small, or if the data decoded is not 222 | * described as String 223 | */ 224 | public String unpackString() throws DeserializationException { 225 | try { 226 | final int firstByte = readByte(dataInputStream); 227 | final int len; 228 | if (firstByte > 0x9f && firstByte < 0xc0) { 229 | len = firstByte & 0x1f; 230 | } else if (firstByte == 0xd9) { 231 | len = readByte(dataInputStream); 232 | } else if (firstByte == 0xda) { 233 | len = readByte(dataInputStream) << 8 | readByte(dataInputStream); 234 | } else if (firstByte == 0xdb) { 235 | len = dataInputStream.readInt(); 236 | if (len < 0) { 237 | throw new DeserializationException( 238 | "Attempting to deserialize an str longer than Integer.MAX_VALUE" 239 | ); 240 | } 241 | } else { 242 | throw new DeserializationException(String.format( 243 | "Attempted to read int initial byte (0x%02x) indicates non-str type", 244 | firstByte 245 | )); 246 | } 247 | byte[] encodedString = new byte[len]; 248 | ByteStreams.readFully(dataInputStream, encodedString); 249 | return new String(encodedString, Charsets.UTF_8); 250 | } catch (IOException e) { 251 | throw new DeserializationException("Attempted to read past end of buffer"); 252 | } 253 | } 254 | 255 | /** 256 | * Unpack an int and return it cast to a java byte (which is signed), throwing an exception if 257 | * the integer unpacked is too large to fit. 258 | * 259 | * @return an unpacked byte 260 | * @throws DeserializationException if the read int is too big. 261 | */ 262 | public byte unpackByte() throws DeserializationException { 263 | int i = unpackInt(); 264 | if (i > 0xff) { 265 | throw new DeserializationException("Expected unsigned int < 0xff"); 266 | } 267 | return (byte) i; 268 | } 269 | 270 | 271 | /** 272 | * Wraps InputStream.read() and throws Deserialization exception when EOF is reached 273 | * 274 | * @param inputStream the InputStream to read from 275 | * @return an unsigned byte, stored in an int 276 | * @throws IOException if the read fails 277 | * @throws DeserializationException if end of file is reached 278 | */ 279 | private static int readByte(InputStream inputStream) 280 | throws IOException, DeserializationException { 281 | final int i = inputStream.read(); 282 | if (i == -1) { 283 | throw new DeserializationException("Attempted to read past end of buffer"); 284 | } 285 | return i; 286 | } 287 | 288 | /** 289 | * Indicates whether end of stream has been reached or not. Used for testing 290 | * 291 | * @return true if end of stream is reached, else false 292 | */ 293 | boolean bytesLeft() { 294 | return byteArrayInputStream.available() > 0; 295 | } 296 | 297 | public int getBytesRead() { 298 | return dataSize - byteArrayInputStream.available(); 299 | } 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.base.Preconditions; 21 | 22 | import java.util.Arrays; 23 | 24 | public class Response { 25 | 26 | private final byte[] payload; 27 | private final byte[] signature; 28 | 29 | public Response(byte[] payload, byte[] signature) { 30 | Preconditions.checkNotNull(payload); 31 | Preconditions.checkNotNull(signature); 32 | this.payload = payload; 33 | this.signature = signature; 34 | } 35 | 36 | public byte[] getPayload() { 37 | return payload; 38 | } 39 | 40 | public byte[] getSignature() { 41 | return Arrays.copyOf(signature, signature.length); 42 | } 43 | 44 | 45 | @Override 46 | public boolean equals(Object o) { 47 | if (this == o) { 48 | return true; 49 | } 50 | if (o == null || getClass() != o.getClass()) { 51 | return false; 52 | } 53 | 54 | Response response = (Response) o; 55 | return Arrays.equals(signature, response.signature) 56 | && Arrays.equals(payload, response.payload); 57 | } 58 | 59 | @Override 60 | public int hashCode() { 61 | int result = Arrays.hashCode(signature); 62 | result = 31 * result + Arrays.hashCode(payload); 63 | return result; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/protocol/Token.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.base.Preconditions; 21 | 22 | import com.spotify.crtauth.utils.TimeIntervals; 23 | import com.spotify.crtauth.utils.TimeSupplier; 24 | 25 | public class Token { 26 | 27 | private static final byte MAGIC = 't'; 28 | 29 | private final int validFrom; 30 | private final int validTo; 31 | private final String userName; 32 | 33 | public Token(int validFrom, int validTo, String userName) { 34 | Preconditions.checkArgument(validFrom < validTo, "negative lifespan of Token"); 35 | Preconditions.checkNotNull(userName); 36 | Preconditions.checkArgument(!userName.isEmpty(), "Field 'userName' can not be empty"); 37 | this.validFrom = validFrom; 38 | this.validTo = validTo; 39 | this.userName = userName; 40 | } 41 | 42 | public boolean isExpired(TimeSupplier timeSupplier) { 43 | return TimeIntervals.isExpired(validFrom, validTo, timeSupplier); 44 | } 45 | 46 | public int getValidFrom() { 47 | return validFrom; 48 | } 49 | 50 | public int getValidTo() { 51 | return validTo; 52 | } 53 | 54 | public String getUserName() { 55 | return this.userName; 56 | } 57 | 58 | 59 | @Override 60 | public boolean equals(Object o) { 61 | if (this == o) { 62 | return true; 63 | } 64 | if (o == null || getClass() != o.getClass()) { 65 | return false; 66 | } 67 | 68 | Token token = (Token) o; 69 | 70 | if (validFrom != token.validFrom) { 71 | return false; 72 | } 73 | if (validTo != token.validTo) { 74 | return false; 75 | } 76 | return userName.equals(token.userName); 77 | 78 | } 79 | 80 | @Override 81 | public int hashCode() { 82 | int result = validFrom; 83 | result = 31 * result + validTo; 84 | result = 31 * result + userName.hashCode(); 85 | return result; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/signer/AgentSigner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import com.google.common.annotations.VisibleForTesting; 21 | import com.google.common.base.Objects; 22 | 23 | import com.spotify.crtauth.Fingerprint; 24 | import com.spotify.crtauth.exceptions.CrtAuthException; 25 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 26 | import com.spotify.sshagentproxy.AgentProxies; 27 | import com.spotify.sshagentproxy.AgentProxy; 28 | import com.spotify.sshagentproxy.Identity; 29 | 30 | import java.io.IOException; 31 | import java.security.interfaces.RSAPublicKey; 32 | import java.util.List; 33 | 34 | /** 35 | * AgentSigner is intended for command line tools where their invoker 36 | * also controls an ssh-agent process that can be contacted via a UNIX 37 | * referenced by the SSH_AUTH_SOCK environment variable. 38 | */ 39 | public class AgentSigner implements Signer, AutoCloseable { 40 | 41 | private final AgentProxy proxy; 42 | 43 | public AgentSigner() throws CrtAuthException { 44 | proxy = AgentProxies.newInstance(); 45 | } 46 | 47 | @VisibleForTesting 48 | AgentSigner(final AgentProxy proxy) { 49 | this.proxy = proxy; 50 | } 51 | 52 | @Override 53 | public byte[] sign(final byte[] data, final Fingerprint fingerprint) 54 | throws IllegalArgumentException, KeyNotFoundException { 55 | try { 56 | final List identities = proxy.list(); 57 | for (final Identity id : identities) { 58 | if (!id.getPublicKey().getAlgorithm().equals("RSA")) { 59 | // TODO (dxia) Support other types of keys. 60 | continue; 61 | } 62 | if (fingerprint.matches((RSAPublicKey) id.getPublicKey())) { 63 | return proxy.sign(id, data); 64 | } 65 | } 66 | 67 | throw new KeyNotFoundException(); 68 | } catch (IOException e) { 69 | throw new KeyNotFoundException(e); 70 | } 71 | } 72 | 73 | @Override 74 | public void close() throws Exception { 75 | proxy.close(); 76 | } 77 | 78 | @Override 79 | public String toString() { 80 | return Objects.toStringHelper(this) 81 | .toString(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/signer/Signer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import com.spotify.crtauth.Fingerprint; 21 | import com.spotify.crtauth.exceptions.KeyNotFoundException; 22 | 23 | /** 24 | * This interface wraps a single method to sign a challenge. It's the core component of the CrtAuth 25 | * client. 26 | */ 27 | public interface Signer { 28 | 29 | /** 30 | * Sign some binary data using the private key corresponding to the public key with the provided 31 | * fingerprint. 32 | * 33 | * @param data Some data to sign, typically a serialized challenge 34 | * @return A signature, as a byte array. 35 | */ 36 | byte[] sign(byte[] data, Fingerprint fingerprint) 37 | throws IllegalArgumentException, KeyNotFoundException; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/signer/SingleKeySigner.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import com.spotify.crtauth.Fingerprint; 21 | 22 | import java.security.PrivateKey; 23 | import java.security.Signature; 24 | 25 | public class SingleKeySigner implements Signer { 26 | 27 | private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; 28 | private final PrivateKey privateKey; 29 | 30 | public SingleKeySigner(PrivateKey privateKey) { 31 | this.privateKey = privateKey; 32 | } 33 | 34 | @Override 35 | public byte[] sign(byte[] data, Fingerprint fingerprint) { 36 | try { 37 | Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 38 | signature.initSign(privateKey); 39 | signature.update(data); 40 | return signature.sign(); 41 | } catch (Exception e) { 42 | throw new IllegalArgumentException(e); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/ASCIICodec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.io.BaseEncoding; 21 | 22 | /** 23 | * Utility class to encode and decode binary data in to URL compatible ASCII. 24 | */ 25 | public class ASCIICodec { 26 | 27 | private static final BaseEncoding ENCODING = BaseEncoding.base64Url(); 28 | 29 | public static String encode(byte[] data) { 30 | return ENCODING.encode(data).replaceAll("=", ""); 31 | } 32 | 33 | public static byte[] decode(String encoded) { 34 | try { 35 | return ENCODING.decode(encoded); 36 | } catch (IllegalArgumentException e) { 37 | Throwable t = e; 38 | if (e.getCause() instanceof BaseEncoding.DecodingException) { 39 | t = e.getCause(); 40 | } 41 | throw new IllegalArgumentException(String.format("Failed to decode String '%s'", encoded), t); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/RealTimeSupplier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | 22 | import java.util.concurrent.TimeUnit; 23 | 24 | public class RealTimeSupplier implements TimeSupplier { 25 | 26 | @Override 27 | public UnsignedInteger getTime() { 28 | long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); 29 | return UnsignedInteger.valueOf(currentTime); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/SettableTimeSupplier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | 22 | /** 23 | * A configurable time supplier, useful fot testing. 24 | */ 25 | public class SettableTimeSupplier implements TimeSupplier { 26 | 27 | private int time; 28 | 29 | public void setTime(int time) { 30 | this.time = time; 31 | } 32 | 33 | @Override 34 | public UnsignedInteger getTime() { 35 | return UnsignedInteger.valueOf(time); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/TimeIntervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | 22 | public class TimeIntervals { 23 | 24 | public static boolean isExpired(int validFrom, int validTo, TimeSupplier timeSupplier) { 25 | UnsignedInteger currentUTime = timeSupplier.getTime(); 26 | UnsignedInteger validUFrom = UnsignedInteger.fromIntBits(validFrom); 27 | UnsignedInteger validUTo = UnsignedInteger.fromIntBits(validTo); 28 | return validUFrom.compareTo(currentUTime) > 0 || 29 | validUTo.compareTo(currentUTime) < 0; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/TimeSupplier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | 22 | /** 23 | * This interface wraps a single method that provides a plug-in source of time. 24 | */ 25 | public interface TimeSupplier { 26 | 27 | /** 28 | * Return the time, as the number of seconds elapsed from the Epoch. 29 | * 30 | * @return the number of seconds from the Epoch, as an unsigned integer. 31 | */ 32 | UnsignedInteger getTime(); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/spotify/crtauth/utils/TraditionalKeyParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.base.Charsets; 21 | import com.google.common.io.BaseEncoding; 22 | import com.google.common.primitives.UnsignedBytes; 23 | 24 | import java.math.BigInteger; 25 | import java.nio.ByteBuffer; 26 | import java.nio.ByteOrder; 27 | import java.security.InvalidKeyException; 28 | import java.security.spec.RSAPrivateKeySpec; 29 | import java.security.spec.RSAPublicKeySpec; 30 | import java.util.ArrayList; 31 | import java.util.Arrays; 32 | import java.util.List; 33 | import java.util.regex.Matcher; 34 | import java.util.regex.Pattern; 35 | 36 | /** 37 | * A set of utilities to parse private and public RSA PEM keys as produced by ssh-keygen. 38 | */ 39 | public class TraditionalKeyParser { 40 | 41 | private static final Pattern PUBLIC_KEY_PATTERN = Pattern.compile("^ssh-rsa (.+) .*$"); 42 | private static final Pattern PRIVATE_KEY_PATTERN = 43 | Pattern.compile("^-+BEGIN RSA PRIVATE KEY-+([^-]+)-+END RSA PRIVATE KEY-+$"); 44 | private static final int INTEGER_SIZE = Integer.SIZE; 45 | private static final String PUBLIC_KEY_TYPE = "ssh-rsa"; 46 | 47 | public static RSAPublicKeySpec parsePemPublicKey(String pemPublicKey) throws InvalidKeyException { 48 | Matcher matcher = PUBLIC_KEY_PATTERN.matcher(pemPublicKey); 49 | if (!matcher.matches()) { 50 | throw new InvalidKeyException(); 51 | } 52 | String pemKey = matcher.group(1); 53 | BaseEncoding encoding = BaseEncoding.base64(); 54 | byte[] derKey = encoding.decode(pemKey); 55 | ByteBuffer byteBuffer = ByteBuffer.wrap(derKey); 56 | byteBuffer.order(ByteOrder.BIG_ENDIAN); 57 | byte[] typeBytes = readVariableLengthOpaque(byteBuffer); 58 | byte[] expBytes = readVariableLengthOpaque(byteBuffer); 59 | byte[] modBytes = readVariableLengthOpaque(byteBuffer); 60 | if (typeBytes == null || expBytes == null || modBytes == null) { 61 | throw new InvalidKeyException(); 62 | } 63 | String type = new String(typeBytes, Charsets.US_ASCII); 64 | if (!type.equals(PUBLIC_KEY_TYPE)) { 65 | throw new InvalidKeyException(); 66 | } 67 | BigInteger exp = new BigInteger(expBytes); 68 | BigInteger mod = new BigInteger(modBytes); 69 | return new RSAPublicKeySpec(mod, exp); 70 | } 71 | 72 | public static RSAPrivateKeySpec parsePemPrivateKey(String pemPrivateKey) 73 | throws InvalidKeyException { 74 | pemPrivateKey = pemPrivateKey.replace("\n", ""); 75 | Matcher matcher = PRIVATE_KEY_PATTERN.matcher(pemPrivateKey); 76 | if (!matcher.matches()) { 77 | throw new InvalidKeyException(); 78 | } 79 | String pemKey = matcher.group(1); 80 | BaseEncoding encoding = BaseEncoding.base64(); 81 | byte[] derKey = encoding.decode(pemKey); 82 | List fields; 83 | try { 84 | fields = parsePrivateKeyASN1(ByteBuffer.wrap(derKey)); 85 | } catch (IllegalArgumentException e) { 86 | throw new InvalidKeyException(e); 87 | } 88 | BigInteger mod = new BigInteger(fields.get(1)); 89 | BigInteger exp = new BigInteger(fields.get(3)); 90 | return new RSAPrivateKeySpec(mod, exp); 91 | } 92 | 93 | /** 94 | * This is a simplistic ASN.1 parser that can only parse a collection of primitive types. 95 | * 96 | * @param byteBuffer the raw byte representation of a Pcks1 private key. 97 | * @return A list of bytes array that represent the content of the original ASN.1 collection. 98 | */ 99 | private static List parsePrivateKeyASN1(ByteBuffer byteBuffer) { 100 | final List collection = new ArrayList(); 101 | while (byteBuffer.hasRemaining()) { 102 | byte type = byteBuffer.get(); 103 | int length = UnsignedBytes.toInt(byteBuffer.get()); 104 | if ((length & 0x80) != 0) { 105 | int numberOfOctets = length ^ 0x80; 106 | length = 0; 107 | for (int i = 0; i < numberOfOctets; ++i) { 108 | int lengthChunk = UnsignedBytes.toInt(byteBuffer.get()); 109 | length += lengthChunk << (numberOfOctets - i - 1) * 8; 110 | } 111 | } 112 | if (length < 0) { 113 | throw new IllegalArgumentException(); 114 | } 115 | if (type == 0x30) { 116 | int position = byteBuffer.position(); 117 | byte[] data = Arrays.copyOfRange(byteBuffer.array(), position, position + length); 118 | return parsePrivateKeyASN1(ByteBuffer.wrap(data)); 119 | } 120 | if (type == 0x02) { 121 | byte[] segment = new byte[length]; 122 | byteBuffer.get(segment); 123 | collection.add(segment); 124 | } 125 | } 126 | return collection; 127 | } 128 | 129 | private static byte[] readVariableLengthOpaque(ByteBuffer byteBuffer) { 130 | if (byteBuffer.position() + INTEGER_SIZE > byteBuffer.limit()) { 131 | return null; 132 | } 133 | int length = byteBuffer.getInt(); 134 | if (byteBuffer.position() + length > byteBuffer.limit()) { 135 | return null; 136 | } 137 | byte[] bytes = new byte[length]; 138 | byteBuffer.get(bytes); 139 | return bytes; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/CrtAuthClientTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.spotify.crtauth.keyprovider.InMemoryKeyProvider; 21 | import com.spotify.crtauth.signer.Signer; 22 | import com.spotify.crtauth.signer.SingleKeySigner; 23 | import com.spotify.crtauth.utils.TraditionalKeyParser; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | 27 | import java.security.KeyFactory; 28 | import java.security.NoSuchAlgorithmException; 29 | import java.security.PrivateKey; 30 | import java.security.interfaces.RSAPublicKey; 31 | import java.security.spec.RSAPrivateKeySpec; 32 | import java.security.spec.RSAPublicKeySpec; 33 | 34 | import static org.junit.Assert.assertEquals; 35 | 36 | public class CrtAuthClientTest { 37 | private static final String SERVER_NAME = "server_name"; 38 | private static final String PUBLIC_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDK0wNhgGlFZfBo" + 39 | "RBS+M8wGoyOOVunYYjeaoRXKFKfhx288ZIo87WMfN6i5KnUTH3A/mYlVnK4bhchS6dUFisaXcURvFgY46pUSGuLTZ" + 40 | "xTe9anIIR/iT+V+8MRDHXffRGOCLEQUl0leYTht0dc7rxaW42d83yC7uuCISbgWqOANvMkZYqZjaejOOGVpkApxLG" + 41 | "G8K8RvNBBM8TYqE3DQHSyRVU6S9HWLbWF+i8W2h4CLX2Quodf0c1dcqlftClHjdIyed/zQKhAo+FDcJrN+2ZDJ0mk" + 42 | "YLVlJDZuLk/K/vSOwD3wXhby3cdHCsxnRfy2Ylnt31VF0aVtlhW4IJ+5mMzmz noa@date.office.spotify.net"; 43 | private static final String PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + 44 | "MIIEogIBAAKCAQEAytMDYYBpRWXwaEQUvjPMBqMjjlbp2GI3mqEVyhSn4cdvPGSK\n" + 45 | "PO1jHzeouSp1Ex9wP5mJVZyuG4XIUunVBYrGl3FEbxYGOOqVEhri02cU3vWpyCEf\n" + 46 | "4k/lfvDEQx1330RjgixEFJdJXmE4bdHXO68WluNnfN8gu7rgiEm4FqjgDbzJGWKm\n" + 47 | "Y2nozjhlaZAKcSxhvCvEbzQQTPE2KhNw0B0skVVOkvR1i21hfovFtoeAi19kLqHX\n" + 48 | "9HNXXKpX7QpR43SMnnf80CoQKPhQ3CazftmQydJpGC1ZSQ2bi5Pyv70jsA98F4W8\n" + 49 | "t3HRwrMZ0X8tmJZ7d9VRdGlbZYVuCCfuZjM5swIDAQABAoIBADtnoHbfQHYGDGrN\n" + 50 | "ffHTg+9xuslG5YjuA3EzuwkMEbvMSOU8YUzFDqInEDDjoZSvQZYvJw0/LbN79Jds\n" + 51 | "S2srIU1b7HpIzhu/gVfjLgpTB8bh1w95vDfxxLrwU9uAdwqaojaPNoV9ZgzRltB7\n" + 52 | "hHnDp28cPcRSKekyK+9fAB8K6Uy8N00hojBDwtwXM8C4PpQKod38Vd0Adp9dEdX6\n" + 53 | "Ro9suYb+d+qFalYbKIbjKWkll+ZiiGJjF1HSQCTwlzS2haPXUlbk57HnN+8ar+a3\n" + 54 | "ITTc2gbNuTqBRD1V/gCaD9F0npVI3mQ34eUADNVVGS0xw0pN4j++Da8KXP+pyn/G\n" + 55 | "DU/n8SECgYEA/KN4BTrg/LB7cGrzkMQmW26NA++htjiWHK3WTsQBKBDFyReJBn67\n" + 56 | "o9kMTHBP35352RfuJ3xEEJ0/ddqGEY/SzNk3HMTlxBbR5Xq8ye102dxfEO3eijJ/\n" + 57 | "F4VRSf9sFgdRoLvE62qLudytK4Ku9nnKoIqrMxFweTpwxzf2jjIKDbECgYEAzYXe\n" + 58 | "QxT1A/bfs5Qd6xoCVOAb4T/ALqFo95iJu4EtFt7nvt7avqL+Vsdxu5uBkTeEUHzh\n" + 59 | "1q47LFoFdGm+MesIIiPSSrbfZJ6ht9kw8EbF8Py85X4LBXey67JlzzUq+ewFEP91\n" + 60 | "do7uGQAY+BRwXtzzPqaVBVa94YOxdq/AGutrIqMCgYBr+cnQImwKU7tOPse+tbbX\n" + 61 | "GRa3+fEZmnG97CZOH8OGxjRiT+bGmd/ElX2GJfJdVn10ZZ/pzFii6TI4Qp9OXjPw\n" + 62 | "TV4as6Sn/EDVXXHWs+BfRKp059VXJ2HeQaKOh9ZAS/x9QANXwn/ZfhGdKQtyWHdb\n" + 63 | "yiiFeQyjI3EUFD0SZRya4QKBgA1QvQOvmeg12Gx0DjQrLTd+hY/kZ3kd8AUKlvHU\n" + 64 | "/qzaqD0PhzCOstfAeDflbVGRPTtRu/gCtca71lqidzYYuiAsHfXFP1fvhx64LZmD\n" + 65 | "nFNurHZZ4jDqfmcS2dHA6hXjGrjtNBkITZjFDtkTyev7eK74b/M2mXrA44CDBnk4\n" + 66 | "A2rtAoGAMv92fqI+B5taxlZhTLAIaGVFbzoASHTRl3eQJbc4zc38U3Zbiy4deMEH\n" + 67 | "3QTXq7nxWpE4YwHbgXAeJUGfUpE+nEZGMolj1Q0ueKuSstQg5p1nwhQIxej8EJW+\n" + 68 | "7siqmOTZDKzieik7KVzaJ/U02Q186smezKIuAOYtT8VCf9UksJ4=\n" + 69 | "-----END RSA PRIVATE KEY-----"; 70 | private CrtAuthServer crtAuthServer; 71 | private Signer signer; 72 | 73 | private static final KeyFactory keyFactory; 74 | 75 | static { 76 | try { 77 | keyFactory = KeyFactory.getInstance("RSA"); 78 | } catch (NoSuchAlgorithmException e) { 79 | throw new Error("RSA support not available", e); 80 | } 81 | } 82 | 83 | public static PrivateKey getPrivateKey() { 84 | try { 85 | RSAPrivateKeySpec privateKeySpec = TraditionalKeyParser.parsePemPrivateKey(PRIVATE_KEY); 86 | return keyFactory.generatePrivate(privateKeySpec); 87 | } catch (Exception e) { 88 | throw new RuntimeException(e); 89 | } 90 | } 91 | 92 | private static RSAPublicKey getPublicKey() { 93 | try { 94 | RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY); 95 | return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); 96 | } catch (Exception e) { 97 | throw new RuntimeException(e); 98 | } 99 | } 100 | 101 | @Before 102 | public void setup() throws Exception { 103 | InMemoryKeyProvider keyProvider = new InMemoryKeyProvider(); 104 | keyProvider.putKey("test", getPublicKey()); 105 | crtAuthServer = new CrtAuthServer.Builder() 106 | .setServerName(SERVER_NAME) 107 | .setSecret("server_secret".getBytes()) 108 | .setKeyProvider(keyProvider) 109 | .build(); 110 | signer = new SingleKeySigner(getPrivateKey()); 111 | } 112 | 113 | @Test 114 | public void testValidResponse() throws Exception { 115 | String challenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("test")); 116 | CrtAuthClient crtAuthClient = new CrtAuthClient(signer, SERVER_NAME); 117 | String response = crtAuthClient.createResponse(challenge); 118 | String verifiableToken = crtAuthServer.createToken(response); 119 | crtAuthServer.validateToken(verifiableToken); 120 | } 121 | 122 | @Test(expected = IllegalArgumentException.class) 123 | public void testMitm() throws Exception { 124 | String verifiableChallenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("test")); 125 | CrtAuthClient crtAuthClient = new CrtAuthClient(signer, "another_server"); 126 | crtAuthClient.createResponse(verifiableChallenge); 127 | } 128 | 129 | @Test 130 | public void testCreateRequest() throws Exception { 131 | assertEquals("AXGjbm9h", CrtAuthClient.createRequest("noa")); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/CrtAuthServerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.spotify.crtauth.exceptions.ProtocolVersionException; 21 | import com.spotify.crtauth.exceptions.TokenExpiredException; 22 | import com.spotify.crtauth.keyprovider.InMemoryKeyProvider; 23 | import com.spotify.crtauth.keyprovider.KeyProvider; 24 | import com.spotify.crtauth.protocol.CrtAuthCodec; 25 | import com.spotify.crtauth.protocol.Token; 26 | import com.spotify.crtauth.signer.Signer; 27 | import com.spotify.crtauth.signer.SingleKeySigner; 28 | import com.spotify.crtauth.utils.ASCIICodec; 29 | import com.spotify.crtauth.utils.TraditionalKeyParser; 30 | 31 | import org.junit.Assert; 32 | import org.junit.Before; 33 | import org.junit.Test; 34 | 35 | import java.security.KeyFactory; 36 | import java.security.PrivateKey; 37 | import java.security.interfaces.RSAPublicKey; 38 | import java.security.spec.RSAPrivateKeySpec; 39 | import java.security.spec.RSAPublicKeySpec; 40 | 41 | import static com.spotify.crtauth.utils.ASCIICodec.decode; 42 | import static com.spotify.crtauth.utils.ASCIICodec.encode; 43 | 44 | @SuppressWarnings("SpellCheckingInspection") 45 | public class CrtAuthServerTest { 46 | private static final String NOA_PUBLIC_KEY = 47 | "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEArt7xdaxlbzzGlgLhqpLuE5x9d+so0M" + 48 | "JiqQSmiUJojuK+v1cxnYCnQQPF0BkAhw2hiFiDvLLVogIu8m2wCV9XAGxrz38NLHVq" + 49 | "ke+EAduJAfiiD1iwvSLbFBOMVRYfzUoiuPIudwZqmLuCpln1RUE6O/ujmYNyoPS4fq" + 50 | "a1svaiZ4C77tLMi2ztMIX97SN2o0EntrhOonJ1nk+7JLYvkhsT8rX20bg6Mlu909iO" + 51 | "vtTbElnypKzmjFZyBvzZhocRo4yfrekP3s2QyKSIB5ARGenoSoQa43cD93tqbLGK4o" + 52 | "JSkkfxc9HFPo0t+deDorZmelNNFvEn5KeqP0HJvw/jm2U1PQ== noa@vader.local"; 53 | private static final String SERVER_NAME = "server_name"; 54 | private static final String PUBLIC_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDK0wNhgGlFZfBo" + 55 | "RBS+M8wGoyOOVunYYjeaoRXKFKfhx288ZIo87WMfN6i5KnUTH3A/mYlVnK4bhchS6dUFisaXcURvFgY46pUSGuLTZ" + 56 | "xTe9anIIR/iT+V+8MRDHXffRGOCLEQUl0leYTht0dc7rxaW42d83yC7uuCISbgWqOANvMkZYqZjaejOOGVpkApxLG" + 57 | "G8K8RvNBBM8TYqE3DQHSyRVU6S9HWLbWF+i8W2h4CLX2Quodf0c1dcqlftClHjdIyed/zQKhAo+FDcJrN+2ZDJ0mk" + 58 | "YLVlJDZuLk/K/vSOwD3wXhby3cdHCsxnRfy2Ylnt31VF0aVtlhW4IJ+5mMzmz noa@date.office.spotify.net"; 59 | private static final String PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + 60 | "MIIEogIBAAKCAQEAytMDYYBpRWXwaEQUvjPMBqMjjlbp2GI3mqEVyhSn4cdvPGSK\n" + 61 | "PO1jHzeouSp1Ex9wP5mJVZyuG4XIUunVBYrGl3FEbxYGOOqVEhri02cU3vWpyCEf\n" + 62 | "4k/lfvDEQx1330RjgixEFJdJXmE4bdHXO68WluNnfN8gu7rgiEm4FqjgDbzJGWKm\n" + 63 | "Y2nozjhlaZAKcSxhvCvEbzQQTPE2KhNw0B0skVVOkvR1i21hfovFtoeAi19kLqHX\n" + 64 | "9HNXXKpX7QpR43SMnnf80CoQKPhQ3CazftmQydJpGC1ZSQ2bi5Pyv70jsA98F4W8\n" + 65 | "t3HRwrMZ0X8tmJZ7d9VRdGlbZYVuCCfuZjM5swIDAQABAoIBADtnoHbfQHYGDGrN\n" + 66 | "ffHTg+9xuslG5YjuA3EzuwkMEbvMSOU8YUzFDqInEDDjoZSvQZYvJw0/LbN79Jds\n" + 67 | "S2srIU1b7HpIzhu/gVfjLgpTB8bh1w95vDfxxLrwU9uAdwqaojaPNoV9ZgzRltB7\n" + 68 | "hHnDp28cPcRSKekyK+9fAB8K6Uy8N00hojBDwtwXM8C4PpQKod38Vd0Adp9dEdX6\n" + 69 | "Ro9suYb+d+qFalYbKIbjKWkll+ZiiGJjF1HSQCTwlzS2haPXUlbk57HnN+8ar+a3\n" + 70 | "ITTc2gbNuTqBRD1V/gCaD9F0npVI3mQ34eUADNVVGS0xw0pN4j++Da8KXP+pyn/G\n" + 71 | "DU/n8SECgYEA/KN4BTrg/LB7cGrzkMQmW26NA++htjiWHK3WTsQBKBDFyReJBn67\n" + 72 | "o9kMTHBP35352RfuJ3xEEJ0/ddqGEY/SzNk3HMTlxBbR5Xq8ye102dxfEO3eijJ/\n" + 73 | "F4VRSf9sFgdRoLvE62qLudytK4Ku9nnKoIqrMxFweTpwxzf2jjIKDbECgYEAzYXe\n" + 74 | "QxT1A/bfs5Qd6xoCVOAb4T/ALqFo95iJu4EtFt7nvt7avqL+Vsdxu5uBkTeEUHzh\n" + 75 | "1q47LFoFdGm+MesIIiPSSrbfZJ6ht9kw8EbF8Py85X4LBXey67JlzzUq+ewFEP91\n" + 76 | "do7uGQAY+BRwXtzzPqaVBVa94YOxdq/AGutrIqMCgYBr+cnQImwKU7tOPse+tbbX\n" + 77 | "GRa3+fEZmnG97CZOH8OGxjRiT+bGmd/ElX2GJfJdVn10ZZ/pzFii6TI4Qp9OXjPw\n" + 78 | "TV4as6Sn/EDVXXHWs+BfRKp059VXJ2HeQaKOh9ZAS/x9QANXwn/ZfhGdKQtyWHdb\n" + 79 | "yiiFeQyjI3EUFD0SZRya4QKBgA1QvQOvmeg12Gx0DjQrLTd+hY/kZ3kd8AUKlvHU\n" + 80 | "/qzaqD0PhzCOstfAeDflbVGRPTtRu/gCtca71lqidzYYuiAsHfXFP1fvhx64LZmD\n" + 81 | "nFNurHZZ4jDqfmcS2dHA6hXjGrjtNBkITZjFDtkTyev7eK74b/M2mXrA44CDBnk4\n" + 82 | "A2rtAoGAMv92fqI+B5taxlZhTLAIaGVFbzoASHTRl3eQJbc4zc38U3Zbiy4deMEH\n" + 83 | "3QTXq7nxWpE4YwHbgXAeJUGfUpE+nEZGMolj1Q0ueKuSstQg5p1nwhQIxej8EJW+\n" + 84 | "7siqmOTZDKzieik7KVzaJ/U02Q186smezKIuAOYtT8VCf9UksJ4=\n" + 85 | "-----END RSA PRIVATE KEY-----"; 86 | private InMemoryKeyProvider keyProvider; 87 | private CrtAuthServer crtAuthServer; 88 | private CrtAuthClient crtAuthClient; 89 | 90 | @Before 91 | public void setup() throws Exception { 92 | keyProvider = new InMemoryKeyProvider(); 93 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 94 | RSAPublicKeySpec noaPublicKeySpec = TraditionalKeyParser.parsePemPublicKey(NOA_PUBLIC_KEY); 95 | RSAPublicKey noaPublicKey = (RSAPublicKey) keyFactory.generatePublic(noaPublicKeySpec); 96 | keyProvider.putKey("noa", noaPublicKey); 97 | RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY); 98 | RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); 99 | keyProvider.putKey("test", publicKey); 100 | crtAuthServer = new CrtAuthServer.Builder() 101 | .setServerName(SERVER_NAME) 102 | .setSecret("server_secret".getBytes()) 103 | .setKeyProvider(keyProvider) 104 | .build(); 105 | RSAPrivateKeySpec privateKeySpec = TraditionalKeyParser.parsePemPrivateKey(PRIVATE_KEY); 106 | PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); 107 | Signer signer = new SingleKeySigner(privateKey); 108 | crtAuthClient = new CrtAuthClient(signer, SERVER_NAME); 109 | } 110 | 111 | @Test 112 | public void testCreateChallenge() throws Exception { 113 | byte[] serverSecret = "spotify".getBytes(); 114 | CrtAuthServer crtAuthServer = new CrtAuthServer.Builder() 115 | .setServerName("server_name") 116 | .setSecret(serverSecret) 117 | .setKeyProvider(keyProvider) 118 | .build(); 119 | String challenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("noa")); 120 | Fingerprint expectedFingerprint = new Fingerprint(decode("-6Hqb9N5")); 121 | Assert.assertTrue(extractFingerprint(challenge).equals(expectedFingerprint)); 122 | } 123 | 124 | @Test 125 | public void testCreateChallengeUnknownUser() throws Exception { 126 | byte[] serverSecret = "spotify".getBytes(); 127 | CrtAuthServer crtAuthServer = new CrtAuthServer.Builder() 128 | .setServerName("server_name") 129 | .setSecret(serverSecret) 130 | .setKeyProvider(keyProvider) 131 | .build(); 132 | String encodedChallenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("another")); 133 | // just make sure that we have a parsable challenge 134 | CrtAuthCodec.deserializeChallenge(ASCIICodec.decode(encodedChallenge)); 135 | } 136 | 137 | @Test 138 | public void testCreateChallengeMultipleKeyProviders() throws Exception { 139 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 140 | 141 | InMemoryKeyProvider keyProvider1 = new InMemoryKeyProvider(); 142 | RSAPublicKeySpec publicKeySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_KEY); 143 | RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); 144 | keyProvider1.putKey("test", publicKey); 145 | 146 | InMemoryKeyProvider keyProvider2 = new InMemoryKeyProvider(); 147 | RSAPublicKeySpec noaPublicKeySpec = TraditionalKeyParser.parsePemPublicKey(NOA_PUBLIC_KEY); 148 | RSAPublicKey noaPublicKey = (RSAPublicKey) keyFactory.generatePublic(noaPublicKeySpec); 149 | keyProvider2.putKey("noa", noaPublicKey); 150 | 151 | byte[] serverSecret = "spotify".getBytes(); 152 | CrtAuthServer crtAuthServer = new CrtAuthServer.Builder() 153 | .setServerName("server_name") 154 | .setSecret(serverSecret) 155 | .addKeyProvider(keyProvider1) 156 | .addKeyProvider(keyProvider2) 157 | .build(); 158 | String challenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("noa")); 159 | Fingerprint expectedFingerprint = new Fingerprint(decode("-6Hqb9N5")); 160 | Assert.assertTrue(extractFingerprint(challenge).equals(expectedFingerprint)); 161 | } 162 | 163 | private Fingerprint extractFingerprint(String challenge) throws ProtocolVersionException { 164 | return CrtAuthCodec.deserializeChallenge(decode(challenge)).getFingerprint(); 165 | } 166 | 167 | @Test(expected = IllegalArgumentException.class) 168 | public void testMitm() throws Exception { 169 | CrtAuthServer otherOuthServer = new CrtAuthServer.Builder() 170 | .setServerName("another_server") 171 | .setSecret("server_secret".getBytes()) 172 | .setKeyProvider(keyProvider) 173 | .build(); 174 | String verifiableChallenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("test")); 175 | String response = crtAuthClient.createResponse(verifiableChallenge); 176 | otherOuthServer.createToken(response); 177 | } 178 | 179 | @Test(expected = IllegalArgumentException.class) 180 | public void testWrongSecret() throws Exception { 181 | CrtAuthServer otherServer = new CrtAuthServer.Builder() 182 | .setServerName("SERVER_NAME") 183 | .setSecret("another_secret".getBytes()) 184 | .setKeyProvider(keyProvider) 185 | .build(); 186 | String verifiableChallenge = crtAuthServer.createChallenge(CrtAuthClient.createRequest("test")); 187 | String response = crtAuthClient.createResponse(verifiableChallenge); 188 | otherServer.validateToken(crtAuthServer.createToken(response)); 189 | } 190 | 191 | @Test 192 | public void testGoodToken() throws Exception { 193 | int nowSeconds = (int) (System.currentTimeMillis() / 1000); 194 | Token t = new Token(nowSeconds, nowSeconds + 10, "test"); 195 | String ts = encode(CrtAuthCodec.serialize(t, "server_secret".getBytes())); 196 | crtAuthServer.validateToken(ts); 197 | } 198 | 199 | @Test(expected = TokenExpiredException.class) 200 | public void testExpiredToken() throws Exception { 201 | int nowSeconds = (int) (System.currentTimeMillis() / 1000); 202 | Token t = new Token(nowSeconds - 1000, nowSeconds - 950, "test"); 203 | String ts = encode(CrtAuthCodec.serialize(t, "server_secret".getBytes())); 204 | crtAuthServer.validateToken(ts); 205 | } 206 | 207 | @Test(expected = TokenExpiredException.class) 208 | public void testFutureToken() throws Exception { 209 | int nowSeconds = (int) (System.currentTimeMillis() / 1000); 210 | Token t = new Token(nowSeconds + 1000, nowSeconds + 1050, "test"); 211 | String ts = encode(CrtAuthCodec.serialize(t, "server_secret".getBytes())); 212 | crtAuthServer.validateToken(ts); 213 | } 214 | 215 | @Test(expected = TokenExpiredException.class) 216 | public void testOverlyLongTokenValidity() throws Exception { 217 | int nowSeconds = (int) (System.currentTimeMillis() / 1000); 218 | Token t = new Token(nowSeconds, nowSeconds + 10000, "test"); 219 | String ts = encode(CrtAuthCodec.serialize(t, "server_secret".getBytes())); 220 | crtAuthServer.validateToken(ts); 221 | } 222 | 223 | @Test(expected = IllegalArgumentException.class) 224 | public void testBuilderFailsOnOverlyLongTokenValidity() throws Exception { 225 | new CrtAuthServer.Builder() 226 | .setServerName(SERVER_NAME) 227 | .setSecret("server_secret".getBytes()) 228 | .setKeyProvider(keyProvider) 229 | .setTokenLifetimeSeconds(1000) 230 | .build(); 231 | } 232 | 233 | @Test(expected = IllegalArgumentException.class) 234 | public void testBuliderFailsOnNoKeyProviders() throws Exception { 235 | new CrtAuthServer.Builder() 236 | .setServerName(SERVER_NAME) 237 | .setSecret("server_secret".getBytes()) 238 | .build(); 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/FingerprintTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth; 19 | 20 | import com.google.common.io.BaseEncoding; 21 | import com.spotify.crtauth.utils.TraditionalKeyParser; 22 | import org.junit.Test; 23 | 24 | import java.security.KeyFactory; 25 | import java.security.interfaces.RSAPublicKey; 26 | import java.security.spec.RSAPublicKeySpec; 27 | 28 | import static org.junit.Assert.assertEquals; 29 | 30 | public class FingerprintTest { 31 | private static final String PUBLIC_PEM_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDjKPW24a0" + 32 | "Go7ETiMP/j8DsnG+E6bB2DvCuX5hJLbBKE/oBMsZ3eB8MyROXmv/h0b0OzugEx+llxIo0FpnsuJxMlF7xpEp7dHK" + 33 | "HTUdxWIclmGjI6tzurX+sDerUuJk9gNj3SK67lcZI5tsrXjDsy+ZpVQWcL/6trB9r69VDGm+GfnC8JIItLesAbJ1" + 34 | "IcSq4/oU3e0mRjiaf5X/bMy1lRejcqEOARWhTVTw3D+EdPqAWZPh1IzREPnoNVp5MeSVU4hRdoZmJPwP9qF4f2qb" + 35 | "hsw0cDDPNFigU/UDw2kW9CUlGscrPs+0sj9wim4ZwMC9hmiFS/yfzHOaoTylFkG6ia9W/ test@spotify.net"; 36 | 37 | @Test 38 | public void testFingerprint() throws Exception { 39 | final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 40 | final String expectedEncodedFingerprint = "c/XR6bib"; 41 | BaseEncoding encoding = BaseEncoding.base64(); 42 | 43 | RSAPublicKeySpec keySpec = TraditionalKeyParser.parsePemPublicKey(PUBLIC_PEM_KEY); 44 | RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec); 45 | Fingerprint actual = new Fingerprint(publicKey); 46 | Fingerprint expected = new Fingerprint(encoding.decode(expectedEncodedFingerprint)); 47 | assertEquals(actual, expected); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/protocol/ChallengeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | import com.spotify.crtauth.Fingerprint; 22 | import com.spotify.crtauth.utils.ASCIICodec; 23 | import org.junit.Test; 24 | 25 | public class ChallengeTest { 26 | 27 | @Test(expected=IllegalArgumentException.class) 28 | public void testNegativeValidity() { 29 | Challenge.newBuilder() 30 | .setUniqueData(ASCIICodec.decode("dVhGT9Lbf_59f5ORIHZoiUc2H8I=")) 31 | .setFingerprint(new Fingerprint(ASCIICodec.decode("TJoHEsse"))) 32 | .setValidFromTimestamp(UnsignedInteger.valueOf(1365084634).intValue()) 33 | .setValidToTimestamp(UnsignedInteger.valueOf(1365084334).intValue()) 34 | .setServerName("server.example.com") 35 | .setUserName("username") 36 | .build(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/protocol/CrtAuthCodecTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.google.common.primitives.UnsignedInteger; 21 | import com.spotify.crtauth.CrtAuthClientTest; 22 | import com.spotify.crtauth.Fingerprint; 23 | import com.spotify.crtauth.signer.Signer; 24 | import com.spotify.crtauth.signer.SingleKeySigner; 25 | import com.spotify.crtauth.utils.ASCIICodec; 26 | import org.junit.Assert; 27 | import org.junit.Test; 28 | 29 | import java.util.Arrays; 30 | 31 | import static org.junit.Assert.assertEquals; 32 | 33 | /** 34 | * Tests CrtAuthCodec 35 | */ 36 | public class CrtAuthCodecTest { 37 | 38 | // ENCODED_ data is encoded using the python implementation, to ensure binary compatibility 39 | private static final byte[] ENCODED_CHALLENGE = 40 | ASCIICodec.decode("AWPEFHVYRk_S23_-fX-TkSB2aIlHNh_CzlFdiK7OUV2J2sQGTJoHEssesnNlcnZlci5leG" + 41 | "FtcGxlLmNvbah1c2VybmFtZcQg9y3oyBv4xUfpPHC9ZcHoj-c1hjHtOj9TSn_jVvv8ELI="); 42 | 43 | private static final byte[] ENCODED_RESPONSE = ASCIICodec.decode( 44 | "AXLEaAFjxBR1WEZP0tt__n1_k5EgdmiJRzYfws5RXYiuzlFdidrEBkyaBxLLHrJzZXJ2ZXIuZXhhbXBsZS5jb22o" + 45 | "dXNlcm5hbWXEIPct6Mgb-MVH6TxwvWXB6I_nNYYx7To_U0p_41b7_BCyxQEAPymreRi3DDVCz5rUdCqLCdCP89pY" + 46 | "pnrBJ-p9yWColikZcoV6aY7xbEqRpY40fcgGcSmXVPZBCxCQ67YWAlFLuBs72YOBTd-lkABFe_-tnu_58k_Ll-Cd" + 47 | "S6UKU_NyzB0beKMQy3x4Bq4s35Jxtvsl1zjueyCOzUbS2Y-2evq9_cQBUHCbbbv-PmqU4fqvZ3KkTmQpQXHpE0rh" + 48 | "WFk_XdSiuNofT5lK38MPqbzfTcSwO0QKD-IJUhOrVo8nMcrbe-hNAIc9mM_qV1-qcUQMEMwVqRv7G4DIH71k0CEr" + 49 | "xfP_x024iQAf4fxRzGLBoq9ENWrMtLcieQ3AtoyoNDbWWSHVhg==" 50 | ); 51 | 52 | private static final byte[] ENCODED_TOKEN = ASCIICodec.decode( 53 | "AXTOUV2Irs5RXYnao25vYcQgKVlUyZneScS57Xwk2syvL0GTQhV0FF9ciWQZYluN4m8=" 54 | ); 55 | 56 | private static final Challenge CHALLENGE = Challenge.newBuilder() 57 | .setUniqueData(ASCIICodec.decode("dVhGT9Lbf_59f5ORIHZoiUc2H8I=")) 58 | .setFingerprint(new Fingerprint(ASCIICodec.decode("TJoHEsse"))) 59 | .setValidFromTimestamp(UnsignedInteger.valueOf(1365084334).intValue()) 60 | .setValidToTimestamp(UnsignedInteger.valueOf(1365084634).intValue()) 61 | .setServerName("server.example.com") 62 | .setUserName("username") 63 | .build(); 64 | 65 | 66 | static final Token TOKEN = new Token(1365084334, 1365084634, "noa"); 67 | 68 | @Test 69 | public void testSerializeChallenge() throws Exception { 70 | 71 | byte[] bytes = CrtAuthCodec.serialize(CHALLENGE, "secret".getBytes()); 72 | Assert.assertArrayEquals(ENCODED_CHALLENGE, bytes); 73 | } 74 | 75 | @Test 76 | public void testDeserializeChallenge() throws Exception { 77 | Challenge challenge = CrtAuthCodec.deserializeChallengeAuthenticated( 78 | ENCODED_CHALLENGE, "secret".getBytes()); 79 | 80 | assertEquals(CHALLENGE, challenge); 81 | } 82 | 83 | @Test 84 | public void testSerializeResponse() throws Exception { 85 | Signer signer = new SingleKeySigner(CrtAuthClientTest.getPrivateKey()); 86 | byte[] signature = signer.sign( 87 | CrtAuthCodecTest.ENCODED_CHALLENGE, 88 | CrtAuthCodec.deserializeChallenge(CrtAuthCodecTest.ENCODED_CHALLENGE).getFingerprint() 89 | ); 90 | Response resp = new Response(CrtAuthCodecTest.ENCODED_CHALLENGE, signature); 91 | Assert.assertArrayEquals(ENCODED_RESPONSE, CrtAuthCodec.serialize(resp)); 92 | } 93 | 94 | @Test 95 | public void testDeserializeResponse() throws Exception { 96 | Response r = CrtAuthCodec.deserializeResponse(CrtAuthCodecTest.ENCODED_RESPONSE); 97 | Challenge c = CrtAuthCodec.deserializeChallenge(r.getPayload()); 98 | 99 | Signer signer = new SingleKeySigner(CrtAuthClientTest.getPrivateKey()); 100 | byte[] signature = signer.sign(r.getPayload(), c.getFingerprint()); 101 | Assert.assertArrayEquals(signature, r.getSignature()); 102 | assertEquals(c, CHALLENGE); 103 | } 104 | 105 | @Test 106 | public void testSerializeToken() throws Exception { 107 | Assert.assertArrayEquals(CrtAuthCodec.serialize(TOKEN, "gurkburk".getBytes()), ENCODED_TOKEN); 108 | } 109 | 110 | @Test 111 | public void testDeserializeToken() throws Exception { 112 | Token token = CrtAuthCodec.deserializeTokenAuthenticated(ENCODED_TOKEN, "gurkburk".getBytes()); 113 | assertEquals(TOKEN, token); 114 | } 115 | 116 | @Test(expected = IllegalArgumentException.class) 117 | public void testDeserializeAuthenticatedTokenCorrupt() throws Exception { 118 | byte[] mine = Arrays.copyOf( 119 | CrtAuthCodecTest.ENCODED_TOKEN, CrtAuthCodecTest.ENCODED_TOKEN.length); 120 | mine[mine.length - 4] = 't'; 121 | CrtAuthCodec.deserializeTokenAuthenticated(mine, "gurkburk".getBytes()); 122 | } 123 | 124 | @Test(expected = IllegalArgumentException.class) 125 | public void testDeserializeAuthenticatedChallengeCorrupt() throws Exception { 126 | byte[] mine = Arrays.copyOf( 127 | CrtAuthCodecTest.ENCODED_CHALLENGE, CrtAuthCodecTest.ENCODED_CHALLENGE.length); 128 | mine[mine.length - 4] = 't'; 129 | CrtAuthCodec.deserializeChallengeAuthenticated(mine, "secret".getBytes()); 130 | } 131 | 132 | 133 | @Test 134 | public void testDeserializeRequest() throws Exception { 135 | assertEquals("noa", CrtAuthCodec.deserializeRequest("AXGjbm9h")); 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/protocol/MiniMessagePackTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import org.junit.Assert; 21 | import org.junit.Test; 22 | 23 | import java.util.Arrays; 24 | 25 | /** 26 | * Tests MiniMessagePack 27 | */ 28 | public class MiniMessagePackTest { 29 | 30 | @Test(expected = IllegalArgumentException.class) 31 | public void testPackNegativeInt() { 32 | new MiniMessagePack.Packer().pack(-1); 33 | } 34 | 35 | @Test 36 | public void testPackInt() { 37 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 38 | packer.pack(0x2a); 39 | compare(packer, false, 0x2a); 40 | 41 | packer = new MiniMessagePack.Packer(); 42 | packer.pack((1<<8) - 1); 43 | compare(packer, false, 0xcc, 0xff); 44 | 45 | packer = new MiniMessagePack.Packer(); 46 | packer.pack(1<<8); 47 | compare(packer, false, 0xcd, 0x01, 0x00); 48 | 49 | packer = new MiniMessagePack.Packer(); 50 | packer.pack((1<<16)-1); 51 | compare(packer, false, 0xcd, 0xff, 0xff); 52 | 53 | packer = new MiniMessagePack.Packer(); 54 | packer.pack(1<<16); 55 | compare(packer, false, 0xce, 0x00, 0x01, 0x00, 0x00); 56 | 57 | packer = new MiniMessagePack.Packer(); 58 | packer.pack(Integer.MAX_VALUE); 59 | compare(packer, false, 0xce, 0x7f, 0xff, 0xff, 0xff); 60 | } 61 | 62 | @Test 63 | public void testPackBin() { 64 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 65 | packer.pack(new byte[] {(byte)0xbe, (byte)0xef}); 66 | compare(packer, false, 0xc4, 0x02, 0xbe, 0xef); 67 | 68 | packer = new MiniMessagePack.Packer(); 69 | packer.pack(new byte[0x100]); 70 | Assert.assertEquals(0x100 + 3, packer.getBytes().length); 71 | compare(packer, true, 0xc5, 0x01, 0x00, 0x00); 72 | 73 | packer = new MiniMessagePack.Packer(); 74 | packer.pack(new byte[0x10000]); 75 | Assert.assertEquals(0x10000 + 5, packer.getBytes().length); 76 | compare(packer, true, 0xc6, 0x00, 0x01, 0x00, 0x00); 77 | } 78 | 79 | @Test 80 | public void testPackStr() { 81 | MiniMessagePack.Packer packer = new MiniMessagePack.Packer(); 82 | packer.pack("€"); 83 | compare(packer, false, 0xa3, 0xe2, 0x82, 0xac); 84 | 85 | packer = new MiniMessagePack.Packer(); 86 | packer.pack(makeString(31)); 87 | Assert.assertEquals(32, packer.getBytes().length); 88 | compare(packer, true, 0xbf, 0x61); 89 | 90 | packer = new MiniMessagePack.Packer(); 91 | packer.pack(makeString(32)); 92 | Assert.assertEquals(34, packer.getBytes().length); 93 | compare(packer, true, 0xd9, 0x20, 0x61); 94 | 95 | packer = new MiniMessagePack.Packer(); 96 | packer.pack(makeString(0x100)); 97 | Assert.assertEquals(0x103, packer.getBytes().length); 98 | compare(packer, true, 0xda, 0x01, 0x00, 0x61); 99 | 100 | packer = new MiniMessagePack.Packer(); 101 | packer.pack(makeString(0x10000)); 102 | Assert.assertEquals(0x10005, packer.getBytes().length); 103 | compare(packer, true, 0xdb, 0x00, 0x01, 0x00, 0x00, 0x61); 104 | } 105 | 106 | @Test 107 | public void testUnpackInt() throws Exception { 108 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(42)); 109 | Assert.assertEquals(42, unpacker.unpackInt()); 110 | Assert.assertFalse(unpacker.bytesLeft()); 111 | 112 | unpacker = new MiniMessagePack.Unpacker(byteArray(0x7f, 0x00)); 113 | Assert.assertEquals(0x7f, unpacker.unpackInt()); 114 | Assert.assertTrue(unpacker.bytesLeft()); 115 | Assert.assertEquals(0, unpacker.unpackInt()); 116 | Assert.assertFalse(unpacker.bytesLeft()); 117 | 118 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xcc, 0x80)); 119 | Assert.assertEquals(0x80, unpacker.unpackInt()); 120 | Assert.assertFalse(unpacker.bytesLeft()); 121 | 122 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xcc, 0xff)); 123 | Assert.assertEquals(0xff, unpacker.unpackInt()); 124 | Assert.assertFalse(unpacker.bytesLeft()); 125 | 126 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xcd, 0x01, 0x00)); 127 | Assert.assertEquals(0x100, unpacker.unpackInt()); 128 | Assert.assertFalse(unpacker.bytesLeft()); 129 | 130 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xcd, 0xff, 0xff)); 131 | Assert.assertEquals(0xffff, unpacker.unpackInt()); 132 | Assert.assertFalse(unpacker.bytesLeft()); 133 | 134 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xce, 0x00, 0x01, 0x00, 0x00)); 135 | Assert.assertEquals(0x10000, unpacker.unpackInt()); 136 | Assert.assertFalse(unpacker.bytesLeft()); 137 | 138 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xce, 0x00, 0x01, 0x00, 0x00)); 139 | Assert.assertEquals(0x10000, unpacker.unpackInt()); 140 | Assert.assertFalse(unpacker.bytesLeft()); 141 | } 142 | 143 | @Test(expected = DeserializationException.class) 144 | public void testReadStringAsInt() throws DeserializationException { 145 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0x0a1, 0x61)); 146 | unpacker.unpackInt(); 147 | } 148 | 149 | @Test(expected = DeserializationException.class) 150 | public void testReadAsIntPastEnd() throws DeserializationException { 151 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0x42)); 152 | unpacker.unpackInt(); 153 | unpacker.unpackInt(); 154 | } 155 | 156 | @Test(expected = DeserializationException.class) 157 | public void testShortReadFromFourByteInt() throws DeserializationException { 158 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xce, 0x00)); 159 | unpacker.unpackInt(); 160 | } 161 | 162 | @Test(expected = DeserializationException.class) 163 | public void testReadTooLargeUnsigned() throws DeserializationException { 164 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xce, 255, 0, 0, 0)); 165 | unpacker.unpackInt(); 166 | } 167 | 168 | @Test 169 | public void testReadBin() throws DeserializationException { 170 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xc4, 0x01, 0x00)); 171 | Assert.assertArrayEquals(byteArray(0x00), unpacker.unpackBin()); 172 | 173 | byte[] toUnpack = new byte[(1<<8) + 3]; 174 | toUnpack[0] = (byte)0xc5; 175 | toUnpack[1] = (byte)0x01; 176 | unpacker = new MiniMessagePack.Unpacker(toUnpack); 177 | Assert.assertArrayEquals(new byte[1<<8], unpacker.unpackBin()); 178 | 179 | toUnpack = new byte[(1<<16) + 5]; 180 | toUnpack[0] = (byte)0xc6; 181 | toUnpack[2] = (byte)0x01; 182 | unpacker = new MiniMessagePack.Unpacker(toUnpack); 183 | Assert.assertArrayEquals(new byte[1<<16], unpacker.unpackBin()); 184 | } 185 | 186 | @Test 187 | public void testReadStr() throws DeserializationException { 188 | byte[] data = byteArray(0xa3, 0xe2, 0x82, 0xac); 189 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(data); 190 | Assert.assertEquals("€", unpacker.unpackString()); 191 | 192 | data = new byte[32]; 193 | Arrays.fill(data, (byte)0x61); 194 | data[0] = (byte)0xbf; 195 | unpacker = new MiniMessagePack.Unpacker(data); 196 | Assert.assertEquals(makeString(31), unpacker.unpackString()); 197 | 198 | data = new byte[34]; 199 | Arrays.fill(data, (byte)0x61); 200 | data[0] = (byte)0xd9; 201 | data[1] = (byte)0x20; 202 | unpacker = new MiniMessagePack.Unpacker(data); 203 | Assert.assertEquals(makeString(32), unpacker.unpackString()); 204 | 205 | data = new byte[257]; 206 | Arrays.fill(data, (byte)0x61); 207 | data[0] = (byte)0xd9; 208 | data[1] = (byte)0xff; 209 | unpacker = new MiniMessagePack.Unpacker(data); 210 | Assert.assertEquals(makeString(255), unpacker.unpackString()); 211 | 212 | data = new byte[(1<<8) + 3]; 213 | Arrays.fill(data, (byte)0x61); 214 | data[0] = (byte)0xda; 215 | data[1] = (byte)0x01; 216 | data[2] = (byte)0x00; 217 | unpacker = new MiniMessagePack.Unpacker(data); 218 | Assert.assertEquals(makeString(256), unpacker.unpackString()); 219 | 220 | data = new byte[(1<<16) + 2]; 221 | Arrays.fill(data, (byte)0x61); 222 | data[0] = (byte)0xda; 223 | data[1] = (byte)0xff; 224 | data[2] = (byte)0xff; 225 | unpacker = new MiniMessagePack.Unpacker(data); 226 | Assert.assertEquals(makeString((1<<16)-1), unpacker.unpackString()); 227 | 228 | data = new byte[(1<<16) + 5]; 229 | Arrays.fill(data, (byte)0x61); 230 | data[0] = (byte)0xdb; 231 | data[1] = (byte)0x00; 232 | data[2] = (byte)0x01; 233 | data[3] = (byte)0x00; 234 | data[4] = (byte)0x00; 235 | unpacker = new MiniMessagePack.Unpacker(data); 236 | Assert.assertEquals(makeString(1<<16), unpacker.unpackString()); 237 | } 238 | 239 | 240 | @Test(expected = DeserializationException.class) 241 | public void testReadAsStringPastEnd() throws DeserializationException { 242 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0x42)); 243 | unpacker.unpackInt(); 244 | unpacker.unpackString(); 245 | } 246 | 247 | @Test(expected = DeserializationException.class) 248 | public void testShortReadFromFourByteIntString() throws DeserializationException { 249 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xdb, 0x00)); 250 | unpacker.unpackString(); 251 | } 252 | 253 | @Test(expected = DeserializationException.class) 254 | public void testReadTooLargeUnsignedStr() throws DeserializationException { 255 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xdb, 255, 0, 0, 0)); 256 | unpacker.unpackString(); 257 | } 258 | 259 | @Test(expected = DeserializationException.class) 260 | public void testReadIntAsString() throws DeserializationException { 261 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(42)); 262 | unpacker.unpackString(); 263 | } 264 | 265 | @Test(expected = DeserializationException.class) 266 | public void testReadIntAsBin() throws DeserializationException { 267 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(42)); 268 | unpacker.unpackBin(); 269 | } 270 | 271 | @Test(expected = DeserializationException.class) 272 | public void testReadTooLargeUnsignedBin() throws DeserializationException { 273 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xc6, 255, 0, 0, 0)); 274 | unpacker.unpackBin(); 275 | } 276 | 277 | @Test(expected = DeserializationException.class) 278 | public void testShortReadFromFourByteIntBin() throws DeserializationException { 279 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xc6, 0x00)); 280 | unpacker.unpackBin(); 281 | } 282 | 283 | @Test 284 | public void testGetBytesRead() throws DeserializationException { 285 | byte[] data = byteArray(0xa3, 0xe2, 0x82, 0xac, 42); 286 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(data); 287 | unpacker.unpackString(); 288 | Assert.assertEquals(4, unpacker.getBytesRead()); 289 | } 290 | 291 | @Test 292 | public void testUnpackByte() throws DeserializationException { 293 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(42)); 294 | Assert.assertEquals((byte)42, unpacker.unpackByte()); 295 | unpacker = new MiniMessagePack.Unpacker(byteArray(0xcc, 0xff)); 296 | Assert.assertEquals((byte)0xff, unpacker.unpackByte()); 297 | } 298 | 299 | @Test (expected=DeserializationException.class) 300 | public void testUnpackByteTooLarge() throws DeserializationException { 301 | MiniMessagePack.Unpacker unpacker = new MiniMessagePack.Unpacker(byteArray(0xcd, 0x01, 0)); 302 | unpacker.unpackByte(); 303 | 304 | } 305 | 306 | private static String makeString(int len) { 307 | byte[] data = new byte[len]; 308 | Arrays.fill(data, (byte)0x61); 309 | return new String(data); 310 | } 311 | 312 | private void compare(MiniMessagePack.Packer packer, boolean test_prefix, int... bytes) { 313 | byte[] packedData = packer.getBytes(); 314 | if (!test_prefix) { 315 | Assert.assertEquals("Wrong length of packed data", bytes.length, packedData.length); 316 | } 317 | for (int i = 0; i < bytes.length; i++) { 318 | Assert.assertEquals(String.format("Wrong byte at pos %d", i), bytes[i], pos(packedData[i])); 319 | } 320 | } 321 | 322 | private static int pos(byte b) { 323 | return b < 0 ? b + 0x100 : b; 324 | } 325 | 326 | private static byte[] byteArray(int ... bytes) { 327 | byte[] output = new byte[bytes.length]; 328 | for (int i = 0; i < bytes.length; i++) { 329 | output[i] = (byte)bytes[i]; 330 | } 331 | return output; 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/protocol/TokenTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.protocol; 19 | 20 | import com.spotify.crtauth.utils.SettableTimeSupplier; 21 | import org.junit.Test; 22 | 23 | import static org.junit.Assert.assertFalse; 24 | import static org.junit.Assert.assertTrue; 25 | 26 | public class TokenTest { 27 | private static final int DEFAULT_VALID_FROM = 1365084334; 28 | private static final int DEFAULT_VALID_TO = 1365084634; 29 | 30 | 31 | @Test 32 | public void testTokenIsNotExpired() { 33 | SettableTimeSupplier timeSupplier = new SettableTimeSupplier(); 34 | for (int time = DEFAULT_VALID_FROM; time <= DEFAULT_VALID_TO; ++time) { 35 | timeSupplier.setTime(DEFAULT_VALID_FROM); 36 | assertFalse(CrtAuthCodecTest.TOKEN.isExpired(timeSupplier)); 37 | } 38 | } 39 | 40 | @Test 41 | public void testTokenNotValid() { 42 | SettableTimeSupplier timeSupplier = new SettableTimeSupplier(); 43 | timeSupplier.setTime(DEFAULT_VALID_FROM - 1); 44 | assertTrue(CrtAuthCodecTest.TOKEN.isExpired(timeSupplier)); 45 | } 46 | 47 | @Test 48 | public void testTokenExpired() { 49 | SettableTimeSupplier timeSupplier = new SettableTimeSupplier(); 50 | timeSupplier.setTime(DEFAULT_VALID_TO + 1); 51 | assertTrue(CrtAuthCodecTest.TOKEN.isExpired(timeSupplier)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/signer/AgentSignerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import com.google.common.collect.ImmutableList; 21 | 22 | import com.spotify.sshagentproxy.AgentProxy; 23 | import com.spotify.sshagentproxy.Identity; 24 | 25 | import org.mockito.invocation.InvocationOnMock; 26 | import org.mockito.stubbing.Answer; 27 | 28 | import java.security.KeyPair; 29 | import java.security.PublicKey; 30 | import java.security.Signature; 31 | 32 | import static org.mockito.Matchers.any; 33 | import static org.mockito.Matchers.eq; 34 | import static org.mockito.Mockito.mock; 35 | import static org.mockito.Mockito.when; 36 | 37 | 38 | public class AgentSignerTest extends SignerTest { 39 | 40 | private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; 41 | 42 | private static final AgentProxy proxy = mock(AgentProxy.class); 43 | 44 | @Override 45 | protected AgentSigner getInstance(final KeyPair keyPair) throws Exception { 46 | final Identity id = new TestIdentity(keyPair); 47 | when(proxy.list()).thenReturn(ImmutableList.of(id)); 48 | when(proxy.sign(eq(id), any(byte[].class))).thenAnswer(new Answer() { 49 | @Override 50 | public byte[] answer(InvocationOnMock invocation) throws Throwable { 51 | final Object[] args = invocation.getArguments(); 52 | final byte[] data = (byte[]) args[1]; 53 | Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 54 | signature.initSign(keyPair.getPrivate()); 55 | signature.update(data); 56 | return signature.sign(); 57 | } 58 | }); 59 | return new AgentSigner(proxy); 60 | } 61 | 62 | private static class TestIdentity implements Identity { 63 | 64 | private final PublicKey publicKey; 65 | 66 | TestIdentity(final KeyPair keyPair) { 67 | this.publicKey = keyPair.getPublic(); 68 | } 69 | 70 | @Override 71 | public String getKeyFormat() { 72 | return publicKey.getFormat(); 73 | } 74 | 75 | @Override 76 | public PublicKey getPublicKey() { 77 | return publicKey; 78 | } 79 | 80 | @Override 81 | public String getComment() { 82 | return null; 83 | } 84 | 85 | @Override 86 | public byte[] getKeyBlob() { 87 | return publicKey.getEncoded(); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/signer/SignerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import com.google.common.io.BaseEncoding; 21 | import com.spotify.crtauth.Fingerprint; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | 25 | import java.security.KeyFactory; 26 | import java.security.KeyPair; 27 | import java.security.PrivateKey; 28 | import java.security.Signature; 29 | import java.security.interfaces.RSAPublicKey; 30 | import java.security.spec.KeySpec; 31 | import java.security.spec.PKCS8EncodedKeySpec; 32 | import java.security.spec.X509EncodedKeySpec; 33 | 34 | public abstract class SignerTest { 35 | private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; 36 | // RSA private key, PKCS#8, PEM 37 | private static final String PRIVATE_KEY_STRING = 38 | "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDjKPW24a0Go7ET" + 39 | "iMP/j8DsnG+E6bB2DvCuX5hJLbBKE/oBMsZ3eB8MyROXmv/h0b0OzugEx+llxIo0" + 40 | "FpnsuJxMlF7xpEp7dHKHTUdxWIclmGjI6tzurX+sDerUuJk9gNj3SK67lcZI5tsr" + 41 | "XjDsy+ZpVQWcL/6trB9r69VDGm+GfnC8JIItLesAbJ1IcSq4/oU3e0mRjiaf5X/b" + 42 | "My1lRejcqEOARWhTVTw3D+EdPqAWZPh1IzREPnoNVp5MeSVU4hRdoZmJPwP9qF4f" + 43 | "2qbhsw0cDDPNFigU/UDw2kW9CUlGscrPs+0sj9wim4ZwMC9hmiFS/yfzHOaoTylF" + 44 | "kG6ia9W/AgMBAAECggEBAN9HJmWw4uJwyR+7QXOUN/waM59AF7ujKb0rp0LejrXx" + 45 | "dr3wy5UoU9S8W+6bYsHy51KD2xi/6tCl43YZdQhx2OeIut3nL3KzXdNSCVQGwSgZ" + 46 | "63z5JVnQ3XofX9/g5nbGi/xby6wEJpcHmwvAlHRcYsjL0izYHAtW8LeiYceIV3Co" + 47 | "Qq99W98mgpXJ2zSeyPvBV+f/P0kUJSesRuukk9jD3Yj/iAKgaimL3YAqAnM6ZRWz" + 48 | "gwOL8apS3ki6qKwORCLAMI8/YrbcESXcT7063tUzA3dihKhN7h6wWKJBYcMxRDXb" + 49 | "hXiJiEjHnIPVR/bMVl2qe7ol+hhQrrKFxUQTtbw9pOkCgYEA/hJBNBoUMnVktZOx" + 50 | "yFVLeyu70+NLzsGaQ5GgSlupXPmkAsF8MZjQOSFwZqIKeh2LsPQQLNIAy9Lsj3eR" + 51 | "UNW1Xzvrpn02bgkpnw9ZiEl1nmYm4qMuE38tmbuBI1+hr5m3YJm0Me+/ZZ4iXClI" + 52 | "VMv5cy8WocLj9cEoseQviE5KYSMCgYEA5OJoUBp1gP/yhDho5sLEQqjfG7zIZZh6" + 53 | "ouMgle01r/rrrEu965MNeILghzSVnreKNi1GyHSinM2ms4IBh6Q3SxfEit9u2fXT" + 54 | "GSzYZACOkK7/LSevyhulMETZ4h8D3E0UgOsyxH/9Mb9uEwAU+aZqNaabHJFASP39" + 55 | "1wKJXGAsuLUCgYBXeamBaskxZkG6UpOPSe6nBbOxjDx5fybBxM3PTCfPnxPc7wj3" + 56 | "eomWYfD1JS0+RhXmYuF+zP8BLinMa3pYvnunwlWsCMhIslbmML6+sawRUVJqDYy7" + 57 | "obntiCU6LJ7aeq4sUD8+QjE/p2ZlHMGOkHveMIQ2RYd/AXYlaU8EOxBYyQKBgF+Y" + 58 | "YFD0fBdAzx2CIe4fcrEUrvp6wogMQ0w86KM1y7KQblYr3ErDxGCM6RIPWF5N8h/m" + 59 | "kSWv8Srkibd3mQP6Bk4Kwz/tSfMmxOBC5q39vY2YSWOmq7kSCtA6MXZL1eTxHJsr" + 60 | "oKyJeEqK1YKCCkCqzLlTuH0Z/Wt/CcH/gTdfw83xAoGAOiB9c+3WekYwYC3Wr5Uq" + 61 | "tUZxE4Wp2UV7KuBDPpk45hJsLjKWyQcoz3Lsh2Hem9nMquSMovh6cu8HmABaaQLv" + 62 | "Y2ftflaxHyHvPUaiObhKwPz2tR42LycbjxQppIisXOJNRlzYpnx7FJqCZMY3f9dI" + 63 | "2BegNGjTK+tfd5X4JH1S3RY="; 64 | // RSA public key, X.509, PEM 65 | private static final String PUBLIC_KEY_STRING = 66 | "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4yj1tuGtBqOxE4jD/4/A" + 67 | "7JxvhOmwdg7wrl+YSS2wShP6ATLGd3gfDMkTl5r/4dG9Ds7oBMfpZcSKNBaZ7Lic" + 68 | "TJRe8aRKe3Ryh01HcViHJZhoyOrc7q1/rA3q1LiZPYDY90iuu5XGSObbK14w7Mvm" + 69 | "aVUFnC/+rawfa+vVQxpvhn5wvCSCLS3rAGydSHEquP6FN3tJkY4mn+V/2zMtZUXo" + 70 | "3KhDgEVoU1U8Nw/hHT6gFmT4dSM0RD56DVaeTHklVOIUXaGZiT8D/aheH9qm4bMN" + 71 | "HAwzzRYoFP1A8NpFvQlJRrHKz7PtLI/cIpuGcDAvYZohUv8n8xzmqE8pRZBuomvV" + 72 | "vwIDAQAB"; 73 | private T instance; 74 | private RSAPublicKey publicKey; 75 | 76 | protected abstract T getInstance(KeyPair keyPair) throws Exception; 77 | 78 | @Before 79 | public void setup() throws Exception { 80 | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 81 | BaseEncoding encoding = BaseEncoding.base64(); 82 | byte[] privateKeyBytes = encoding.decode(PRIVATE_KEY_STRING); 83 | KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); 84 | PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); 85 | byte[] publicKeyBytes = encoding.decode(PUBLIC_KEY_STRING); 86 | KeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); 87 | publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); 88 | instance = getInstance(new KeyPair(publicKey, privateKey)); 89 | } 90 | 91 | @Test 92 | public void testSign() throws Exception { 93 | byte [] serialized = {0, 127, 64}; 94 | byte[] signature = instance.sign(serialized, new Fingerprint(publicKey)); 95 | Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM); 96 | signer.initVerify(publicKey); 97 | signer.verify(signature); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/signer/SingleKeySignerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.signer; 19 | 20 | import java.security.KeyPair; 21 | 22 | 23 | public class SingleKeySignerTest extends SignerTest { 24 | @Override 25 | protected SingleKeySigner getInstance(KeyPair keyPair) { 26 | return new SingleKeySigner(keyPair.getPrivate()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/utils/ASCIICodecTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import org.junit.Assert; 21 | import org.junit.Test; 22 | 23 | /** 24 | * Tests ASCIICodec 25 | */ 26 | public class ASCIICodecTest { 27 | @Test 28 | public void testEncode() { 29 | // yes, ugly, but 100% test coverage is nice :) 30 | new ASCIICodec(); 31 | Assert.assertEquals("3q0", ASCIICodec.encode(new byte[] {(byte)0xde, (byte)0xad})); 32 | } 33 | 34 | @Test 35 | public void testEncodeURLSensitive() { 36 | Assert.assertEquals("_-A", ASCIICodec.encode(new byte[] {(byte)0xff, (byte)0xe0})); 37 | } 38 | 39 | @Test 40 | public void testDecode() { 41 | Assert.assertArrayEquals(new byte[] {(byte)0xde, (byte)0xad}, ASCIICodec.decode("3q0")); 42 | } 43 | 44 | @Test(expected = IllegalArgumentException.class) 45 | public void testDecodeInvalidData() { 46 | ASCIICodec.decode("@"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/com/spotify/crtauth/utils/TraditionalKeyParserTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 Spotify AB. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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 | 18 | package com.spotify.crtauth.utils; 19 | 20 | import com.google.common.io.BaseEncoding; 21 | 22 | import org.junit.Test; 23 | 24 | import sun.security.rsa.RSAPrivateCrtKeyImpl; 25 | import sun.security.rsa.RSAPrivateKeyImpl; 26 | 27 | import java.security.KeyFactory; 28 | import java.security.PublicKey; 29 | import java.security.spec.KeySpec; 30 | import java.security.spec.PKCS8EncodedKeySpec; 31 | import java.security.spec.RSAPublicKeySpec; 32 | import java.security.spec.X509EncodedKeySpec; 33 | 34 | import static org.junit.Assert.assertEquals; 35 | 36 | @SuppressWarnings("restriction") 37 | public class TraditionalKeyParserTest { 38 | private static final String X509_PEM_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA" + 39 | "4yj1tuGtBqOxE4jD/4/A7JxvhOmwdg7wrl+YSS2wShP6ATLGd3gfDMkTl5r/4dG9Ds7oBMfpZcSKNBaZ7LicTJRe8a" + 40 | "RKe3Ryh01HcViHJZhoyOrc7q1/rA3q1LiZPYDY90iuu5XGSObbK14w7MvmaVUFnC/+rawfa+vVQxpvhn5wvCSCLS3r" + 41 | "AGydSHEquP6FN3tJkY4mn+V/2zMtZUXo3KhDgEVoU1U8Nw/hHT6gFmT4dSM0RD56DVaeTHklVOIUXaGZiT8D/aheH9" + 42 | "qm4bMNHAwzzRYoFP1A8NpFvQlJRrHKz7PtLI/cIpuGcDAvYZohUv8n8xzmqE8pRZBuomvVvwIDAQAB"; 43 | private static final String PKCS1_PEM_PUBLIC_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDjKPW" + 44 | "24a0Go7ETiMP/j8DsnG+E6bB2DvCuX5hJLbBKE/oBMsZ3eB8MyROXmv/h0b0OzugEx+llxIo0FpnsuJxMlF7xpEp7d" + 45 | "HKHTUdxWIclmGjI6tzurX+sDerUuJk9gNj3SK67lcZI5tsrXjDsy+ZpVQWcL/6trB9r69VDGm+GfnC8JIItLesAbJ1" + 46 | "IcSq4/oU3e0mRjiaf5X/bMy1lRejcqEOARWhTVTw3D+EdPqAWZPh1IzREPnoNVp5MeSVU4hRdoZmJPwP9qF4f2qbhs" + 47 | "w0cDDPNFigU/UDw2kW9CUlGscrPs+0sj9wim4ZwMC9hmiFS/yfzHOaoTylFkG6ia9W/ test@spotify.net"; 48 | private static final String PCKS1_PEM_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n" + 49 | "MIIEowIBAAKCAQEA4yj1tuGtBqOxE4jD/4/A7JxvhOmwdg7wrl+YSS2wShP6ATLG\n" + 50 | "d3gfDMkTl5r/4dG9Ds7oBMfpZcSKNBaZ7LicTJRe8aRKe3Ryh01HcViHJZhoyOrc\n" + 51 | "7q1/rA3q1LiZPYDY90iuu5XGSObbK14w7MvmaVUFnC/+rawfa+vVQxpvhn5wvCSC\n" + 52 | "LS3rAGydSHEquP6FN3tJkY4mn+V/2zMtZUXo3KhDgEVoU1U8Nw/hHT6gFmT4dSM0\n" + 53 | "RD56DVaeTHklVOIUXaGZiT8D/aheH9qm4bMNHAwzzRYoFP1A8NpFvQlJRrHKz7Pt\n" + 54 | "LI/cIpuGcDAvYZohUv8n8xzmqE8pRZBuomvVvwIDAQABAoIBAQDfRyZlsOLicMkf\n" + 55 | "u0FzlDf8GjOfQBe7oym9K6dC3o618Xa98MuVKFPUvFvum2LB8udSg9sYv+rQpeN2\n" + 56 | "GXUIcdjniLrd5y9ys13TUglUBsEoGet8+SVZ0N16H1/f4OZ2xov8W8usBCaXB5sL\n" + 57 | "wJR0XGLIy9Is2BwLVvC3omHHiFdwqEKvfVvfJoKVyds0nsj7wVfn/z9JFCUnrEbr\n" + 58 | "pJPYw92I/4gCoGopi92AKgJzOmUVs4MDi/GqUt5IuqisDkQiwDCPP2K23BEl3E+9\n" + 59 | "Ot7VMwN3YoSoTe4esFiiQWHDMUQ124V4iYhIx5yD1Uf2zFZdqnu6JfoYUK6yhcVE\n" + 60 | "E7W8PaTpAoGBAP4SQTQaFDJ1ZLWTschVS3sru9PjS87BmkORoEpbqVz5pALBfDGY\n" + 61 | "0DkhcGaiCnodi7D0ECzSAMvS7I93kVDVtV8766Z9Nm4JKZ8PWYhJdZ5mJuKjLhN/\n" + 62 | "LZm7gSNfoa+Zt2CZtDHvv2WeIlwpSFTL+XMvFqHC4/XBKLHkL4hOSmEjAoGBAOTi\n" + 63 | "aFAadYD/8oQ4aObCxEKo3xu8yGWYeqLjIJXtNa/666xLveuTDXiC4Ic0lZ63ijYt\n" + 64 | "Rsh0opzNprOCAYekN0sXxIrfbtn10xks2GQAjpCu/y0nr8obpTBE2eIfA9xNFIDr\n" + 65 | "MsR//TG/bhMAFPmmajWmmxyRQEj9/dcCiVxgLLi1AoGAV3mpgWrJMWZBulKTj0nu\n" + 66 | "pwWzsYw8eX8mwcTNz0wnz58T3O8I93qJlmHw9SUtPkYV5mLhfsz/AS4pzGt6WL57\n" + 67 | "p8JVrAjISLJW5jC+vrGsEVFSag2Mu6G57YglOiye2nquLFA/PkIxP6dmZRzBjpB7\n" + 68 | "3jCENkWHfwF2JWlPBDsQWMkCgYBfmGBQ9HwXQM8dgiHuH3KxFK76esKIDENMPOij\n" + 69 | "NcuykG5WK9xKw8RgjOkSD1heTfIf5pElr/Eq5Im3d5kD+gZOCsM/7UnzJsTgQuat\n" + 70 | "/b2NmEljpqu5EgrQOjF2S9Xk8RybK6CsiXhKitWCggpAqsy5U7h9Gf1rfwnB/4E3\n" + 71 | "X8PN8QKBgDogfXPt1npGMGAt1q+VKrVGcROFqdlFeyrgQz6ZOOYSbC4ylskHKM9y\n" + 72 | "7Idh3pvZzKrkjKL4enLvB5gAWmkC72Nn7X5WsR8h7z1Gojm4SsD89rUeNi8nG48U\n" + 73 | "KaSIrFziTUZc2KZ8exSagmTGN3/XSNgXoDRo0yvrX3eV+CR9Ut0W\n" + 74 | "-----END RSA PRIVATE KEY-----"; 75 | private static final String PCKS8_PEM_PRIVATE_KEY = 76 | "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDjKPW24a0Go7ET" + 77 | "iMP/j8DsnG+E6bB2DvCuX5hJLbBKE/oBMsZ3eB8MyROXmv/h0b0OzugEx+llxIo0" + 78 | "FpnsuJxMlF7xpEp7dHKHTUdxWIclmGjI6tzurX+sDerUuJk9gNj3SK67lcZI5tsr" + 79 | "XjDsy+ZpVQWcL/6trB9r69VDGm+GfnC8JIItLesAbJ1IcSq4/oU3e0mRjiaf5X/b" + 80 | "My1lRejcqEOARWhTVTw3D+EdPqAWZPh1IzREPnoNVp5MeSVU4hRdoZmJPwP9qF4f" + 81 | "2qbhsw0cDDPNFigU/UDw2kW9CUlGscrPs+0sj9wim4ZwMC9hmiFS/yfzHOaoTylF" + 82 | "kG6ia9W/AgMBAAECggEBAN9HJmWw4uJwyR+7QXOUN/waM59AF7ujKb0rp0LejrXx" + 83 | "dr3wy5UoU9S8W+6bYsHy51KD2xi/6tCl43YZdQhx2OeIut3nL3KzXdNSCVQGwSgZ" + 84 | "63z5JVnQ3XofX9/g5nbGi/xby6wEJpcHmwvAlHRcYsjL0izYHAtW8LeiYceIV3Co" + 85 | "Qq99W98mgpXJ2zSeyPvBV+f/P0kUJSesRuukk9jD3Yj/iAKgaimL3YAqAnM6ZRWz" + 86 | "gwOL8apS3ki6qKwORCLAMI8/YrbcESXcT7063tUzA3dihKhN7h6wWKJBYcMxRDXb" + 87 | "hXiJiEjHnIPVR/bMVl2qe7ol+hhQrrKFxUQTtbw9pOkCgYEA/hJBNBoUMnVktZOx" + 88 | "yFVLeyu70+NLzsGaQ5GgSlupXPmkAsF8MZjQOSFwZqIKeh2LsPQQLNIAy9Lsj3eR" + 89 | "UNW1Xzvrpn02bgkpnw9ZiEl1nmYm4qMuE38tmbuBI1+hr5m3YJm0Me+/ZZ4iXClI" + 90 | "VMv5cy8WocLj9cEoseQviE5KYSMCgYEA5OJoUBp1gP/yhDho5sLEQqjfG7zIZZh6" + 91 | "ouMgle01r/rrrEu965MNeILghzSVnreKNi1GyHSinM2ms4IBh6Q3SxfEit9u2fXT" + 92 | "GSzYZACOkK7/LSevyhulMETZ4h8D3E0UgOsyxH/9Mb9uEwAU+aZqNaabHJFASP39" + 93 | "1wKJXGAsuLUCgYBXeamBaskxZkG6UpOPSe6nBbOxjDx5fybBxM3PTCfPnxPc7wj3" + 94 | "eomWYfD1JS0+RhXmYuF+zP8BLinMa3pYvnunwlWsCMhIslbmML6+sawRUVJqDYy7" + 95 | "obntiCU6LJ7aeq4sUD8+QjE/p2ZlHMGOkHveMIQ2RYd/AXYlaU8EOxBYyQKBgF+Y" + 96 | "YFD0fBdAzx2CIe4fcrEUrvp6wogMQ0w86KM1y7KQblYr3ErDxGCM6RIPWF5N8h/m" + 97 | "kSWv8Srkibd3mQP6Bk4Kwz/tSfMmxOBC5q39vY2YSWOmq7kSCtA6MXZL1eTxHJsr" + 98 | "oKyJeEqK1YKCCkCqzLlTuH0Z/Wt/CcH/gTdfw83xAoGAOiB9c+3WekYwYC3Wr5Uq" + 99 | "tUZxE4Wp2UV7KuBDPpk45hJsLjKWyQcoz3Lsh2Hem9nMquSMovh6cu8HmABaaQLv" + 100 | "Y2ftflaxHyHvPUaiObhKwPz2tR42LycbjxQppIisXOJNRlzYpnx7FJqCZMY3f9dI" + 101 | "2BegNGjTK+tfd5X4JH1S3RY="; 102 | 103 | @Test 104 | public void testDecodePublicKey() throws Exception { 105 | final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 106 | BaseEncoding encoding = BaseEncoding.base64(); 107 | byte[] expectedKeyBytes = encoding.decode(X509_PEM_PUBLIC_KEY); 108 | KeySpec publicKeySpec = new X509EncodedKeySpec(expectedKeyBytes); 109 | PublicKey expected = keyFactory.generatePublic(publicKeySpec); 110 | RSAPublicKeySpec keySpec = TraditionalKeyParser.parsePemPublicKey(PKCS1_PEM_PUBLIC_KEY); 111 | PublicKey actual = keyFactory.generatePublic(keySpec); 112 | assertEquals(expected, actual); 113 | } 114 | 115 | @Test 116 | public void decodePrivateKey() throws Exception { 117 | final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 118 | BaseEncoding encoding = BaseEncoding.base64(); 119 | byte[] expectedKeyBytes = encoding.decode(PCKS8_PEM_PRIVATE_KEY); 120 | KeySpec expectedKeySpec = new PKCS8EncodedKeySpec(expectedKeyBytes); 121 | RSAPrivateCrtKeyImpl expected = (RSAPrivateCrtKeyImpl) 122 | keyFactory.generatePrivate(expectedKeySpec); 123 | KeySpec actualKeySpac = TraditionalKeyParser.parsePemPrivateKey(PCKS1_PEM_PRIVATE_KEY); 124 | RSAPrivateKeyImpl actual = (RSAPrivateKeyImpl) keyFactory.generatePrivate(actualKeySpac); 125 | assertEquals(actual.getModulus(), expected.getModulus()); 126 | assertEquals(actual.getPrivateExponent(), expected.getPrivateExponent()); 127 | } 128 | } 129 | --------------------------------------------------------------------------------