-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathClient.java
More file actions
363 lines (322 loc) · 13.7 KB
/
Client.java
File metadata and controls
363 lines (322 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package com.duosecurity;
import static com.duosecurity.Utils.createJwt;
import static com.duosecurity.Utils.createJwtForAuthUrl;
import static com.duosecurity.Utils.getAndValidateUrl;
import static com.duosecurity.Utils.transformDecodedJwtToToken;
import static com.duosecurity.Utils.validateCaCert;
import static com.duosecurity.Validator.validateClientParams;
import static com.duosecurity.Validator.validateState;
import static com.duosecurity.Validator.validateUsername;
import static java.lang.String.format;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.duosecurity.exception.DuoException;
import com.duosecurity.model.HealthCheckResponse;
import com.duosecurity.model.Token;
import com.duosecurity.model.TokenResponse;
import com.duosecurity.service.DuoConnector;
/**
* Client serves as the entry point for this library. Instantiating this class
* gives access to four public methods required for Duo's Universal Prompt 2FA.
*/
public class Client {
// **************************************************
// Constants
// **************************************************
private static final String OAUTH_V_1_HEALTH_CHECK_ENDPOINT = "/oauth/v1/health_check";
private static final String OAUTH_V_1_AUTHORIZE_ENDPOINT = "/oauth/v1/authorize";
private static final String OAUTH_V_1_TOKEN_ENDPOINT = "/oauth/v1/token";
private static final String CLIENT_ASSERTION_TYPE
= "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
private static final String USER_AGENT_LIB = "duo_universal_java";
private static final String USER_AGENT_VERSION = "1.1.4-SNAPSHOT";
// **************************************************
// Fields
// **************************************************
private String clientId;
private String clientSecret;
private String apiHost;
private String redirectUri;
private Boolean useDuoCodeAttribute;
protected DuoConnector duoConnector;
private String userAgent;
// **************************************************
// Constructors
// This class uses the "Builder" pattern and should not be directly instantiated.
// Use Client.Builder to generate the Client.
// **************************************************
private Client() {
}
/**
* Legacy simple constructor.
* @param clientId This value is the client id provided by Duo in the admin panel.
* @param clientSecret This value is the client secret provided by Duo in the admin panel.
* @param apiHost This value is the api host provided by Duo in the admin panel.
* @param redirectUri This value is the uri which Duo should redirect to after 2FA is completed.
*
* @throws DuoException For problems building the client
* @deprecated The constructors are deprecated.
* Prefer the {@link Client.Builder} for instantiating Clients
*/
@Deprecated
public Client(String clientId, String clientSecret, String apiHost, String redirectUri)
throws DuoException {
this(clientId, clientSecret, apiHost, redirectUri, null);
}
/**
* Legacy constructor which allows specifying custom CaCerts.
* @param clientId This value is the client id provided by Duo in the admin panel.
* @param clientSecret This value is the client secret provided by Duo in the admin panel.
* @param apiHost This value is the api host provided by Duo in the admin panel.
* @param redirectUri This value is the uri which Duo should redirect to after 2FA is completed.
* @param userCaCerts This value is a list of CA Certificates used to validate connections to Duo
*
* @throws DuoException For problems building the client
*
* @deprecated The constructors are deprecated.
* Prefer the {@link Client.Builder} for instantiating Clients
*/
@Deprecated
public Client(String clientId, String clientSecret, String apiHost,
String redirectUri, String[] userCaCerts) throws DuoException {
Client client = new Builder(clientId, clientSecret, apiHost, redirectUri)
.setCACerts(userCaCerts)
.build();
this.clientId = client.clientId;
this.clientSecret = client.clientSecret;
this.apiHost = client.apiHost;
this.redirectUri = client.redirectUri;
this.useDuoCodeAttribute = client.useDuoCodeAttribute;
this.duoConnector = client.duoConnector;
this.userAgent = client.userAgent;
}
public static class Builder {
private final String clientId;
private final String clientSecret;
private final String apiHost;
private final String redirectUri;
private Boolean useDuoCodeAttribute;
private String[] caCerts;
private String userAgent;
private static final String[] DEFAULT_CA_CERTS = {
//C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA
"sha256/I/Lt/z7ekCWanjD0Cvj5EqXls2lOaThEA0H2Bg4BT/o=",
//C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA
"sha256/r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E=",
//C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA
"sha256/WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=",
//C=US, O=SecureTrust Corporation, CN=SecureTrust CA
"sha256/dykHF2FLJfEpZOvbOLX4PKrcD2w2sHd/iA/G3uHTOcw=",
//C=US, O=SecureTrust Corporation, CN=Secure Global CA
"sha256/JZaQTcTWma4gws703OR/KFk313RkrDcHRvUt6na6DCg=",
//C=US, O=Amazon, CN=Amazon Root CA 1
"sha256/++MBgDH5WGvL9Bcn5Be30cRcL0f5O+NyoXuWtQdX1aI=",
//C=US, O=Amazon, CN=Amazon Root CA 2
"sha256/f0KW/FtqTjs108NpYj42SrGvOB2PpxIVM8nWxjPqJGE=",
//C=US, O=Amazon, CN=Amazon Root CA 3
"sha256/NqvDJlas/GRcYbcWE8S/IceH9cq77kg0jVhZeAPXq8k=",
//C=US, O=Amazon, CN=Amazon Root CA 4
"sha256/9+ze1cZgR9KO1kZrVDxA4HQ6voHRCSVNz4RdTCx4U8U=",
//C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2
"sha256/j9ESw8g3DxR9XM06fYZeuN1UB4O6xp/GAIjjdD/zM3g="
};
/**
* Builder.
*
* @param clientId This value is the client id provided by Duo in the admin panel.
* @param clientSecret This value is the client secret provided by Duo in the admin panel.
* @param apiHost This value is the api host provided by Duo in the admin panel.
* @param redirectUri This value is the uri which Duo should redirect to after 2FA is completed.
*/
public Builder(String clientId, String clientSecret, String apiHost,
String redirectUri) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.apiHost = apiHost;
this.redirectUri = redirectUri;
this.caCerts = DEFAULT_CA_CERTS;
this.useDuoCodeAttribute = true;
this.userAgent = computeUserAgent();
}
/**
* Build the client object.
*
* @return {@link Client}
*
* @throws DuoException For problems building the client
*/
public Client build() throws DuoException {
validateClientParams(clientId, clientSecret, apiHost, redirectUri);
Client client = new Client();
client.clientId = clientId;
client.clientSecret = clientSecret;
client.apiHost = apiHost;
client.redirectUri = redirectUri;
client.useDuoCodeAttribute = useDuoCodeAttribute;
client.userAgent = userAgent;
client.duoConnector = new DuoConnector(apiHost, caCerts);
return client;
}
/**
* Optionally use custom CA Certificates when validating connections to Duo.
*
* @param userCaCerts List of CA Certificates to use
*
* @return the Builder
*/
public Builder setCACerts(String[] userCaCerts) {
if (validateCaCert(userCaCerts)) {
this.caCerts = userCaCerts;
}
return this;
}
/**
* Optionally toggle the returned authorization parameter to use duo_code vs code.
* Defaults true to use duo_code.
*
* @param useDuoCodeAttribute true/false toggle
*
* @return the Builder
*/
public Builder setUseDuoCodeAttribute(boolean useDuoCodeAttribute) {
this.useDuoCodeAttribute = useDuoCodeAttribute;
return this;
}
/**
* Optionally appends string to userAgent.
*
* @param newUserAgent Additional info that will be added to the end of the user agent string
*
* @return the Builder
*/
public Builder appendUserAgentInfo(String newUserAgent) {
userAgent = format("%s %s", userAgent, newUserAgent);
return this;
}
private String computeUserAgent() {
String duoAgent = format("%s/%s", USER_AGENT_LIB, USER_AGENT_VERSION);
String javaAgent = format("%s/%s",
System.getProperty("java.vendor"),
System.getProperty("java.version"));
String osAgent = format("%s/%s/%s",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
return format("%s %s %s", duoAgent, javaAgent, osAgent);
}
}
// **************************************************
// Public methods
// **************************************************
/**
* Checks if Duo is healthy and available for 2FA.
*
* @return {@link HealthCheckResponse}
*
* @throws DuoException For health check errors
*/
public HealthCheckResponse healthCheck() throws DuoException {
String aud = getAndValidateUrl(apiHost, OAUTH_V_1_HEALTH_CHECK_ENDPOINT).toString();
HealthCheckResponse response = duoConnector.duoHealthcheck(clientId,
createJwt(clientId, clientSecret, aud));
if (!response.wasSuccess()) {
throw new DuoException(response.getMessage());
}
return response;
}
/**
* Constructs a string which can be used to redirect the client browser to Duo for 2FA.
*
* @param username The user to be authenticated by Duo.
* @param state A randomly generated String with at least 22 characters
* This value will be returned to the integration post 2FA
* and should be validated. {@link #generateState} exists as a utility function to
* generate this param.
* @return String
*
* @throws DuoException For problems creating the auth url
*/
public String createAuthUrl(String username, String state) throws DuoException {
validateUsername(username);
validateState(state);
String request = createJwtForAuthUrl(clientId, clientSecret, redirectUri,
state, username, useDuoCodeAttribute);
String query;
try {
query = format(
"?scope=openid&response_type=code&redirect_uri=%s&client_id=%s&request=%s",
URLEncoder.encode(redirectUri, StandardCharsets.UTF_8.toString()), clientId, request);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Could not find encoding: " + StandardCharsets.UTF_8.toString());
}
return getAndValidateUrl(apiHost, OAUTH_V_1_AUTHORIZE_ENDPOINT + query).toString();
}
/**
* Verifies the duoCode returned by Duo and exchanges it for a {@link Token} which contains
* information pertaining to the auth. Uses the default token validator defined in
* DuoIdTokenValidator.
* To use a custom validator, see exchangeAuthorizationCodeFor2FAResult(String, TokenValidator)
*
* @param duoCode This string is an identifier for the auth and should be exchanged with Duo for a
* token to determine if the auth was successful as well as obtain meta-data about
* about the auth.
*
* @param username The user to be authenticated by Duo
*
* @return {@link Token}
*
* @throws DuoException For errors exchanging duoCode for 2FA results
*/
public Token exchangeAuthorizationCodeFor2FAResult(String duoCode, String username)
throws DuoException {
TokenValidator validator = new DuoIdTokenValidator(clientSecret, username, clientId, apiHost);
return exchangeAuthorizationCodeFor2FAResult(duoCode, validator);
}
/**
* Verifies the duoCode returned by Duo and exchanges it for a {@link Token} which contains
* information pertaining to the auth. This version of the method allows the use of a
* custom JWT token validator.
* If you use a custom validator:
* You MUST confirm the integrity of the token by using the client secret to validate the
* SHA512 HMAC
* You MUST check the claims for
* Issuer
* Audience
* Issued at / Expiration
* Username (preferred_username)
*
* @param duoCode This string is an identifier for the auth and should be exchanged with Duo for a
* token to determine if the auth was successful as well as obtain meta-data about
* the auth.
*
* @param validator A TokenValidator that will validate and decode the JWT ID Token provided
* by Duo.
*
* @return {@link Token}
*
* @throws DuoException For errors exchanging duoCode for 2FA results
*
*/
public Token exchangeAuthorizationCodeFor2FAResult(String duoCode, TokenValidator validator)
throws DuoException {
String aud = getAndValidateUrl(apiHost, OAUTH_V_1_TOKEN_ENDPOINT).toString();
TokenResponse response = duoConnector.exchangeAuthorizationCodeFor2FAResult(userAgent,
"authorization_code", duoCode, redirectUri, CLIENT_ASSERTION_TYPE,
createJwt(clientId, clientSecret, aud));
String idToken = response.getId_token();
DecodedJWT decodedJwt = validator.validateAndDecode(idToken);
return transformDecodedJwtToToken(decodedJwt);
}
/**
* Generates a 36 character random identifier to be used as the state variable in the
* createAuthUrl method. This value should be stored in a variable and validated against
* the state returned by Duo.
*
* @return String
*/
public String generateState() {
return Utils.generateJwtId(36);
}
}