forked from eclipse-biscuit/biscuit-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnverifiedBiscuit.java
More file actions
402 lines (346 loc) · 12.5 KB
/
UnverifiedBiscuit.java
File metadata and controls
402 lines (346 loc) · 12.5 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
* Copyright (c) 2019 Geoffroy Couprie <contact@geoffroycouprie.com> and Contributors to the Eclipse Foundation.
* SPDX-License-Identifier: Apache-2.0
*/
package org.eclipse.biscuit.token;
import biscuit.format.schema.Schema.PublicKey.Algorithm;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.biscuit.crypto.BlockSignatureBuffer;
import org.eclipse.biscuit.crypto.KeyDelegate;
import org.eclipse.biscuit.crypto.KeyPair;
import org.eclipse.biscuit.crypto.PublicKey;
import org.eclipse.biscuit.datalog.Check;
import org.eclipse.biscuit.datalog.Pair;
import org.eclipse.biscuit.datalog.SymbolTable;
import org.eclipse.biscuit.error.Error;
import org.eclipse.biscuit.token.format.ExternalSignature;
import org.eclipse.biscuit.token.format.SerializedBiscuit;
import org.eclipse.biscuit.token.format.SignedBlock;
/**
* UnverifiedBiscuit auth token. UnverifiedBiscuit means it's deserialized without checking
* signatures.
*/
public class UnverifiedBiscuit {
protected final Block authority;
protected final List<Block> blocks;
protected final SymbolTable symbolTable;
protected final SerializedBiscuit serializedBiscuit;
UnverifiedBiscuit(
Block authority,
List<Block> blocks,
SymbolTable symbolTable,
SerializedBiscuit serializedBiscuit) {
this.authority = authority;
this.blocks = blocks;
this.symbolTable = symbolTable;
this.serializedBiscuit = serializedBiscuit;
}
/**
* Deserializes a Biscuit token from a base64 url (RFC4648_URLSAFE) string
*
* <p>This method uses the default symbol table
*
* <p>Note: This method accepts both padded and unpadded base64 strings
*
* @param data
* @return Biscuit
*/
public static UnverifiedBiscuit fromBase64Url(String data) throws Error {
return UnverifiedBiscuit.fromBytes(Base64.getUrlDecoder().decode(data));
}
/**
* Deserializes a Biscuit token from a byte array
*
* <p>This method uses the default symbol table
*
* @param data
* @return
*/
public static UnverifiedBiscuit fromBytes(byte[] data) throws Error {
return UnverifiedBiscuit.fromBytesWithSymbols(data, defaultSymbolTable());
}
/**
* Deserializes a UnverifiedBiscuit from a byte array
*
* @param data
* @return UnverifiedBiscuit
*/
public static UnverifiedBiscuit fromBytesWithSymbols(byte[] data, SymbolTable symbolTable)
throws Error {
SerializedBiscuit ser = SerializedBiscuit.deserializeUnsafe(data);
return UnverifiedBiscuit.fromSerializedBiscuit(ser, symbolTable);
}
/**
* Fills a UnverifiedBiscuit structure from a deserialized token
*
* @return UnverifiedBiscuit
*/
private static UnverifiedBiscuit fromSerializedBiscuit(
SerializedBiscuit ser, SymbolTable symbolTable) throws Error {
Pair<Block, ArrayList<Block>> t = ser.extractBlocks(symbolTable);
Block authority = t._1;
ArrayList<Block> blocks = t._2;
return new UnverifiedBiscuit(authority, blocks, symbolTable, ser);
}
/**
* Serializes a token to a byte array
*
* @return
*/
public byte[] serialize() throws Error.FormatError.SerializationError {
return this.serializedBiscuit.serialize();
}
/**
* Serializes a token to base 64 url String using RFC4648_URLSAFE
*
* @return String
* @throws Error.FormatError.SerializationError
*/
public String serializeBase64Url() throws Error.FormatError.SerializationError {
return Base64.getUrlEncoder().encodeToString(serialize());
}
/**
* Serializes a token to base 64 url String using RFC4648_URLSAFE without padding
*
* <p>This is useful for embedding tokens in URLs where padding characters (=) may cause issues
*
* @return String
* @throws Error.FormatError.SerializationError
*/
public String serializeBase64UrlNoPadding() throws Error.FormatError.SerializationError {
return Base64.getUrlEncoder().withoutPadding().encodeToString(serialize());
}
/**
* Creates a Block builder
*
* @return
*/
public org.eclipse.biscuit.token.builder.Block createBlock() {
return new org.eclipse.biscuit.token.builder.Block();
}
/**
* Generates a new token from an existing one and a new block
*
* @param block new block (should be generated from a Block builder)
* @param algorithm algorithm to use for the ephemeral key pair
* @return
*/
public UnverifiedBiscuit attenuate(
org.eclipse.biscuit.token.builder.Block block, Algorithm algorithm) throws Error {
SecureRandom rng = new SecureRandom();
KeyPair keypair = KeyPair.generate(algorithm, rng);
SymbolTable builderSymbols = new SymbolTable(this.symbolTable);
return attenuate(rng, keypair, block.build(builderSymbols));
}
public UnverifiedBiscuit attenuate(
final SecureRandom rng, final KeyPair keypair, org.eclipse.biscuit.token.builder.Block block)
throws Error {
SymbolTable builderSymbols = new SymbolTable(this.symbolTable);
return attenuate(rng, keypair, block.build(builderSymbols));
}
/**
* Generates a new token from an existing one and a new block
*
* @param rng random number generator
* @param keypair ephemeral key pair
* @param block new block (should be generated from a Block builder)
* @return
*/
private UnverifiedBiscuit attenuate(final SecureRandom rng, final KeyPair keypair, Block block)
throws Error {
UnverifiedBiscuit copiedBiscuit = this.copy();
if (!copiedBiscuit.symbolTable.disjoint(block.getSymbolTable())) {
throw new Error.SymbolTableOverlap();
}
var containerRes = copiedBiscuit.serializedBiscuit.append(keypair, block, Optional.empty());
if (containerRes.isErr()) {
throw containerRes.getErr();
}
SymbolTable symbols = new SymbolTable(copiedBiscuit.symbolTable);
for (String s : block.getSymbolTable().symbols()) {
symbols.add(s);
}
ArrayList<Block> blocks = new ArrayList<>();
for (Block b : copiedBiscuit.blocks) {
blocks.add(b);
}
blocks.add(block);
SerializedBiscuit container = containerRes.getOk();
return new UnverifiedBiscuit(copiedBiscuit.authority, blocks, symbols, container);
}
// FIXME: attenuate 3rd Party
public List<RevocationIdentifier> revocationIdentifiers() {
return this.serializedBiscuit.revocationIdentifiers().stream()
.map(RevocationIdentifier::fromBytes)
.collect(Collectors.toList());
}
public List<Optional<PublicKey>> externalPublicKeys() {
return Stream.<Optional<PublicKey>>concat(
Stream.of(Optional.empty()),
this.serializedBiscuit.getBlocks().stream()
.map(b -> b.getExternalSignature().map(ExternalSignature::getKey)))
.collect(Collectors.toList());
}
public List<List<Check>> getChecks() {
ArrayList<List<Check>> l = new ArrayList<>();
l.add(new ArrayList<>(this.authority.getChecks()));
for (Block b : this.blocks) {
l.add(new ArrayList<>(b.getChecks()));
}
return l;
}
public List<Optional<String>> getContext() {
ArrayList<Optional<String>> res = new ArrayList<>();
if (this.authority.getContext().isEmpty()) {
res.add(Optional.empty());
} else {
res.add(Optional.of(this.authority.getContext()));
}
for (Block b : this.blocks) {
if (b.getContext().isEmpty()) {
res.add(Optional.empty());
} else {
res.add(Optional.of(b.getContext()));
}
}
return res;
}
public Optional<Integer> getRootKeyId() {
return this.serializedBiscuit.getRootKeyId();
}
public SerializedBiscuit getContainer() {
return this.serializedBiscuit;
}
public int blockCount() {
return 1 + blocks.size();
}
public Optional<PublicKey> blockExternalKey(int index) {
if (index == 0) {
return authority.getExternalKey();
} else {
return blocks.get(index - 1).getExternalKey();
}
}
public List<PublicKey> blockPublicKeys(int index) {
if (index == 0) {
return authority.getPublicKeys();
} else {
return blocks.get(index - 1).getPublicKeys();
}
}
/** Generates a third party block request from a token */
public ThirdPartyBlockRequest thirdPartyRequest() {
byte[] previousSignature;
if (this.serializedBiscuit.getBlocks().isEmpty()) {
previousSignature = this.serializedBiscuit.getAuthority().getSignature();
} else {
previousSignature =
this.serializedBiscuit
.getBlocks()
.get(this.serializedBiscuit.getBlocks().size() - 1)
.getSignature();
}
return new ThirdPartyBlockRequest(previousSignature);
}
/** Generates a third party block request from a token */
public UnverifiedBiscuit appendThirdPartyBlock(
PublicKey externalKey, ThirdPartyBlockContents blockResponse)
throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, Error {
SignedBlock previousBlock;
if (this.serializedBiscuit.getBlocks().isEmpty()) {
previousBlock = this.serializedBiscuit.getAuthority();
} else {
previousBlock =
this.serializedBiscuit.getBlocks().get(this.serializedBiscuit.getBlocks().size() - 1);
}
KeyPair nextKeyPair = KeyPair.generate(previousBlock.getKey().getAlgorithm());
byte[] payload =
BlockSignatureBuffer.generateExternalBlockSignaturePayloadV1(
blockResponse.getPayload(),
previousBlock.getSignature(),
BlockSignatureBuffer.THIRD_PARTY_SIGNATURE_VERSION);
if (!externalKey.verify(payload, blockResponse.getSignature())) {
throw new Error.FormatError.Signature.InvalidSignature(
"signature error: Verification equation was not satisfied");
}
var res = Block.fromBytes(blockResponse.getPayload(), Optional.of(externalKey));
if (res.isErr()) {
throw res.getErr();
}
Block block = res.getOk();
ExternalSignature externalSignature =
new ExternalSignature(externalKey, blockResponse.getSignature());
UnverifiedBiscuit copiedBiscuit = this.copy();
var containerRes =
copiedBiscuit.serializedBiscuit.append(nextKeyPair, block, Optional.of(externalSignature));
if (containerRes.isErr()) {
throw containerRes.getErr();
}
SerializedBiscuit container = containerRes.getOk();
SymbolTable symbols = new SymbolTable(copiedBiscuit.symbolTable);
ArrayList<Block> blocks = new ArrayList<>();
for (Block b : copiedBiscuit.blocks) {
blocks.add(b);
}
blocks.add(block);
return new UnverifiedBiscuit(copiedBiscuit.authority, blocks, symbols, container);
}
/** Prints a token's content */
public String print() {
StringBuilder s = new StringBuilder();
s.append("UnverifiedBiscuit {\n\tsymbols: ");
s.append(this.symbolTable.getAllSymbols());
s.append("\n\tauthority: ");
s.append(this.authority.print(this.symbolTable));
s.append("\n\tblocks: [\n");
for (Block b : this.blocks) {
s.append("\t\t");
s.append(b.print(this.symbolTable));
s.append("\n");
}
s.append("\t]\n}");
return s.toString();
}
/** Default symbols list */
public static SymbolTable defaultSymbolTable() {
return new SymbolTable();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public UnverifiedBiscuit copy() throws Error {
return UnverifiedBiscuit.fromBytes(this.serialize());
}
public Biscuit verify(PublicKey publicKey)
throws Error, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
SerializedBiscuit serializedBiscuit = this.serializedBiscuit;
var result = serializedBiscuit.verify(publicKey);
if (result.isErr()) {
throw result.getErr();
}
return Biscuit.fromSerializedBiscuit(serializedBiscuit, this.symbolTable);
}
public Biscuit verify(KeyDelegate delegate)
throws Error, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
SerializedBiscuit serializedBiscuit = this.serializedBiscuit;
Optional<PublicKey> root = delegate.getRootKey(serializedBiscuit.getRootKeyId());
if (root.isEmpty()) {
throw new InvalidKeyException("unknown root key id");
}
var result = serializedBiscuit.verify(root.get());
if (result.isErr()) {
throw result.getErr();
}
return Biscuit.fromSerializedBiscuit(serializedBiscuit, this.symbolTable);
}
}