-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRsa.java
379 lines (340 loc) · 16 KB
/
Rsa.java
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.ballerinalang.stdlib.crypto.nativeimpl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.Hashing;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.ballerinalang.bre.Context;
import org.ballerinalang.bre.bvm.BlockingNativeCallableUnit;
import org.ballerinalang.model.types.TypeKind;
import org.ballerinalang.model.values.BString;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.natives.annotations.Argument;
import org.ballerinalang.natives.annotations.BallerinaFunction;
import org.ballerinalang.natives.annotations.ReturnType;
import org.ballerinalang.util.exceptions.BallerinaException;
import org.tomitribe.auth.signatures.MissingRequiredHeaderException;
import org.tomitribe.auth.signatures.PEM;
import org.tomitribe.auth.signatures.Signature;
import org.tomitribe.auth.signatures.Signer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;
/**
* Extern function ballerina.crypto:getRsa.
*
* @since 0.990.0
*/
/**
* This example creates a {@link RequestSigner}, then prints out the Authorization header
* that is inserted into the HttpGet object.
*
* <p>
* apiKey is the identifier for a key uploaded through the console.
* privateKeyFilename is the location of your private key (that matches the uploaded public key for apiKey).
* </p>
*
* The signed HttpGet request is not executed, since instanceId does not map to a real instance.
*/
@BallerinaFunction(
orgName = "ballerina", packageName = "crypto",
functionName = "rsa",
args = {
@Argument(name = "uriString", type = TypeKind.STRING),
@Argument(name = "privateKeyPath", type = TypeKind.STRING),
@Argument(name = "apiKey", type = TypeKind.STRING),
@Argument(name = "method", type = TypeKind.STRING),
@Argument(name = "keyEncoding", type = TypeKind.STRING),
@Argument(name = "algorithm", type = TypeKind.STRING),
},
returnType = {@ReturnType(type = TypeKind.STRING)},
isPublic = true
)
public class Rsa extends BlockingNativeCallableUnit {
@Override
public void execute(Context context) {
String uriString = context.getStringArgument(0);
String privateKeyPath = context.getStringArgument(1);
BString algorithm = context.getNullableRefArgument(0) != null ?
(BString) context.getNullableRefArgument(0) : new BString("");
BValue encodingBVal = context.getNullableRefArgument(1);
String encoding = encodingBVal != null ? encodingBVal.stringValue() : "UTF-8";
String apiKey = context.getStringArgument(2);
String method = context.getStringArgument(3);
String rsaAlgorithm;
//todo document the supported algorithm
switch (algorithm.stringValue()) {
case "SHA256":
rsaAlgorithm = "SHA256withRSA";
break;
default:
throw new BallerinaException("Unsupported algorithm " + algorithm + " for RSA calculation");
}
String result;
HttpRequestBase request;
String responseString;
switch (method) {
case "GET":
try {
PrivateKey privateKey = loadPrivateKey(privateKeyPath);
RequestSigner signer = new RequestSigner(apiKey, privateKey);
request = new HttpGet(uriString);
signer.signRequest(request);
@SuppressWarnings({ "deprecation", "resource" })
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
} catch (IllegalArgumentException | IOException e) {
throw new BallerinaException("Error while calculating RSA for " +
rsaAlgorithm + ": " + e.getMessage(), context);
}
break;
default:
throw new BallerinaException("Unsupported HTTP Request method " + method + " for RSA calculation");
}
context.setReturnValues(new BString(responseString));
}
/**
* Load a {@link PrivateKey} from a file.
*/
private static PrivateKey loadPrivateKey(String privateKeyFilename) {
try (InputStream privateKeyStream = Files.newInputStream(Paths.get(privateKeyFilename))) {
return PEM.readPrivateKey(privateKeyStream);
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Invalid format for private key");
} catch (IOException e) {
throw new RuntimeException("Failed to load private key");
}
}
/**
* A light wrapper around https://github.com/tomitribe/http-signatures-java
*/
public static class RequestSigner {
private static final SimpleDateFormat DATE_FORMAT;
private static final String SIGNATURE_ALGORITHM = "rsa-sha256";
private static final Map<String, List<String>> REQUIRED_HEADERS;
static {
DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
REQUIRED_HEADERS = ImmutableMap.<String, List<String>>builder()
.put("get", ImmutableList.of("date", "(request-target)", "host"))
.put("head", ImmutableList.of("date", "(request-target)", "host"))
.put("delete", ImmutableList.of("date", "(request-target)", "host"))
.put("put", ImmutableList.of("date", "(request-target)", "host", "content-length",
"content-type", "x-content-sha256"))
.put("post", ImmutableList.of("date", "(request-target)", "host", "content-length",
"content-type", "x-content-sha256"))
.build();
}
private final Map<Object, Object> signers;
/**
* @param apiKey The identifier for a key uploaded through the console.
* @param privateKey The private key that matches the uploaded public key for the given apiKey.
*/
public RequestSigner(String apiKey, Key privateKey) {
this.signers = REQUIRED_HEADERS
.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> buildSigner(apiKey, privateKey, entry.getKey())));
}
/**
* Create a {@link Signer} that expects the headers for a given method.
* @param apiKey The identifier for a key uploaded through the console.
* @param privateKey The private key that matches the uploaded public key for the given apiKey.
* @param method HTTP verb for this signer
* @return Signer
*/
protected Signer buildSigner(String apiKey, Key privateKey, String method) {
final Signature signature = new Signature(
apiKey, SIGNATURE_ALGORITHM, null, REQUIRED_HEADERS.get(method.toLowerCase(Locale.ENGLISH)));
return new Signer(privateKey, signature);
}
/**
* Sign a request, optionally including additional headers in the signature.
*
* <ol>
* <li>If missing, insert the Date header (RFC 2822).</li>
* <li>If PUT or POST, insert any missing content-type, content-length, x-content-sha256</li>
* <li>Verify that all headers to be signed are present.</li>
* <li>Set the request's Authorization header to the computed signature.</li>
* </ol>
*
* @param request The request to sign
*/
public void signRequest(HttpRequestBase request) {
final String method = request.getMethod().toLowerCase(Locale.ENGLISH);
// nothing to sign for options
if (method.equals("options")) {
return;
}
final String path = extractPath(request.getURI());
// supply date if missing
if (!request.containsHeader("date")) {
final SimpleDateFormat simpleDateFormat;
simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
request.addHeader("date", simpleDateFormat.format(new Date()));
}
// supply host if mossing
if (!request.containsHeader("host")) {
request.addHeader("host", request.getURI().getHost());
}
// supply content-type, content-length, and x-content-sha256 if missing (PUT and POST only)
if (method.equals("put") || method.equals("post")) {
if (!request.containsHeader("content-type")) {
request.addHeader("content-type", "application/json");
}
if (!request.containsHeader("content-length") || !request.containsHeader("x-content-sha256")) {
assert request instanceof HttpEntityEnclosingRequestBase : request.getClass();
byte[] body = getRequestBody((HttpEntityEnclosingRequestBase) request);
if (!request.containsHeader("content-length")) {
request.addHeader("content-length", Integer.toString(body.length));
}
if (!request.containsHeader("x-content-sha256")) {
request.addHeader("x-content-sha256", calculateSHA256(body));
}
}
}
final Map<String, String> headers = extractHeadersToSign(request);
final String signature = this.calculateSignature(method, path, headers);
request.setHeader("Authorization", signature);
}
/**
* Extract path and query string to build the (request-target) pseudo-header.
* For the URI "http://www.host.com/somePath?example=path" return "/somePath?example=path"
*/
private static String extractPath(URI uri) {
String path = uri.getRawPath();
String query = uri.getRawQuery();
if (query != null && !query.trim().isEmpty()) {
path = path + "?" + query;
}
return path;
}
/**
* Extract the headers required for signing from a {@link HttpRequestBase}, into a Map
* that can be passed to {@link RequestSigner#calculateSignature}.
*
* <p>
* Throws if a required header is missing, or if there are multiple values for a single header.
* </p>
*
* @param request The request to extract headers from.
*/
private static Map<String, String> extractHeadersToSign(HttpRequestBase request) {
List<String> headersToSign = REQUIRED_HEADERS.get(request.getMethod().toLowerCase(Locale.ENGLISH));
if (headersToSign == null) {
throw new RuntimeException("Don't know how to sign method " + request.getMethod());
}
return headersToSign.stream()
// (request-target) is a pseudo-header
.filter(header -> !header.toLowerCase(Locale.ENGLISH).equals("(request-target)"))
.collect(Collectors.toMap(
header -> header,
header -> {
if (!request.containsHeader(header)) {
throw new MissingRequiredHeaderException(header);
}
if (request.getHeaders(header).length > 1) {
throw new RuntimeException(
String.format("Expected one value for header %s", header));
}
return request.getFirstHeader(header).getValue();
}));
}
/**
* Wrapper around {@link Signer#sign}, returns the {@link Signature} as a String.
*
* @param method Request method (GET, POST, ...)
* @param path The path + query string for forming the (request-target) pseudo-header
* @param headers Headers to include in the signature.
*/
private String calculateSignature(String method, String path, Map<String, String> headers) {
Signer signer = (Signer) this.signers.get(method);
if (signer == null) {
throw new RuntimeException("Don't know how to sign method " + method);
}
try {
return signer.sign(method, path, headers).toString();
} catch (IOException e) {
throw new RuntimeException("Failed to generate signature", e);
}
}
/**
* Calculate the Base64-encoded string representing the SHA256 of a request body.
* @param body The request body to hash
*/
private String calculateSHA256(byte[] body) {
byte[] hash = Hashing.sha256().hashBytes(body).asBytes();
return Base64.getEncoder().encodeToString(hash);
}
/**
* Helper to safely extract a request body. Because an {@link HttpEntity} may not be repeatable,
* this function ensures the entity is reset after reading. Null entities are treated as an empty string.
*
* @param request A request with a (possibly null) {@link HttpEntity}
*/
private byte[] getRequestBody(HttpEntityEnclosingRequestBase request) {
HttpEntity entity = request.getEntity();
// null body is equivalent to an empty string
if (entity == null) {
return "".getBytes(StandardCharsets.UTF_8);
}
// May need to replace the request entity after consuming
boolean consumed = !entity.isRepeatable();
ByteArrayOutputStream content = new ByteArrayOutputStream();
try {
entity.writeTo(content);
} catch (IOException e) {
throw new RuntimeException("Failed to copy request body", e);
}
// Replace the now-consumed body with a copy of the content stream
byte[] body = content.toByteArray();
if (consumed) {
request.setEntity(new ByteArrayEntity(body));
}
return body;
}
}
}