-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNtsImpl.java
More file actions
314 lines (277 loc) · 10.8 KB
/
Copy pathNtsImpl.java
File metadata and controls
314 lines (277 loc) · 10.8 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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 nts;
import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.daead.AesSivKey;
import com.google.crypto.tink.daead.AesSivParameters;
import com.google.crypto.tink.daead.subtle.DeterministicAeads;
import com.google.crypto.tink.subtle.AesSiv;
import com.google.crypto.tink.util.SecretBytes;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
import nts.NTSExtensionFields.FieldType;
import nts.NTSExtensionFields.NTSExtensionField;
/**
* Implements {@link NtsPacket} to convert Java objects to and from the Network Time Protocol (NTP)
* data message header format described in RFC-1305.
*/
public class NtsImpl extends NtpV4Impl implements NtsPacket {
public int associatedDataLength;
public byte[] plaintext;
public NTSExtensionField authAndEncEF;
private DeterministicAeads aesSivDaead;
/** Creates a new instance of NtsImpl */
public NtsImpl(byte[] key) {
try {
// Create key
AesSivParameters AES_SIV_PARAMETERS =
AesSivParameters.builder()
.setKeySizeBytes(32)
.setVariant(AesSivParameters.Variant.NO_PREFIX)
.build();
SecretBytes keyBytes = SecretBytes.copyFrom(key, InsecureSecretKeyAccess.get());
AesSivKey aesSivkey =
AesSivKey.builder().setParameters(AES_SIV_PARAMETERS).setKeyBytes(keyBytes).build();
aesSivDaead = AesSiv.create(aesSivkey);
} catch (Exception e) {
throw new RuntimeException("Failed to create AES SIV KEY.", e);
}
}
/**
* Build an NTS packet
*
* @param cookie The NTS cookie to use in the packet
* @param num_cookies Number of cookies to request
*/
@Override
public void buildRequest(final byte[] cookie, final int num_cookies) {
super.buildRequest();
// Calculate a unique identifier and add the Extension Field
byte[] unique_identifier = new byte[32];
new SecureRandom().nextBytes(unique_identifier);
addUniqueIdentifierEF(unique_identifier);
// Use one of the negotiated cookies
addCookieEF(cookie);
// Replace used cookies (try to maintain a backlog of 8)
// The server will respond with one new cookie to replace
// the cookie in the extension field above plus one extra
// for each cookie placeholder, so we count from 0 to num_cookies-2
// below
for (int idx = 0; idx < num_cookies - 1; ++idx) {
addCookiePlaceholderEF(cookie);
}
/*
* Prepare the authentication and encryption Extension Field
* This is done here to avoid unnecessary delays in the time measurement the timestamping of the request packet.
*/
prepareAuthAndEncEF();
}
/**
* Resize the buffer to the new size if it is smaller than the current size.
*
* @param newSize The new size of the buffer.
*/
@Override
public void resize(int newSize) {
if (newSize < buf.length) {
buf = Arrays.copyOf(buf, newSize);
}
}
/**
* Adds a unique identifier extension field to the NTSv4 packet.
*
* @param unique_identifier_body the unique identifier byte array, must be at least 32 bytes long.
*/
@Override
public void addUniqueIdentifierEF(byte[] unique_identifier_body) {
if (unique_identifier_body == null || unique_identifier_body.length < 32) {
throw new IllegalArgumentException("unique_identifier_ef must be at least 32 bytes long");
}
addExtensionField(new NTSExtensionField(FieldType.UNIQUE_IDENTIFIER, unique_identifier_body));
}
/**
* Adds a cookie extension field to the NTSv4 packet.
*
* @param cookie_body a cookie received from the NTS KE process or from a server response.
*/
@Override
public void addCookieEF(byte[] cookie_body) {
addExtensionField(new NTSExtensionField(FieldType.NTS_COOKIE, cookie_body));
}
/**
* Adds a cookie placeholder extension filed to the NTSv4 packet
*
* @param existing_cookie The cookie to be replaced
*/
@Override
public void addCookiePlaceholderEF(byte[] existing_cookie) {
addExtensionField(
new NTSExtensionField(FieldType.NTS_COOKIE_PLACEHOLDER, new byte[existing_cookie.length]));
}
/**
* Prepare the authentication and encryption Extension Field body with the available information.
* Ideally we should get the nonce length and ciphertext length from a table depending on the
* negotiated protocol.
*
* @return the body of the AuthAndEnc EF as bytearray.
*/
private byte[] prepareAuthAndEncBody() {
int nonceLength = 16;
int ciphertextLength = 16;
byte[] authAndEncBody = new byte[4 + nonceLength + ciphertextLength];
authAndEncBody[0] = (byte) ((nonceLength >> 8) & 0xFF);
authAndEncBody[1] = (byte) (nonceLength & 0xFF);
authAndEncBody[2] = (byte) ((ciphertextLength >> 8) & 0xFF);
authAndEncBody[3] = (byte) (ciphertextLength & 0xFF);
return authAndEncBody;
}
/**
* Constructs all the possible variables that will be used for the authentication and encryption
* extension field. This is done here to avoid unnecessary delays in the time measurement after
* timestamping of the request packet. This should be called after all the Extension Fields and
* other parameters have been added to the packet.
*/
@Override
public void prepareAuthAndEncEF() {
// Construct the NTSv4 packet and store the associated data length
associatedDataLength = buf.length;
// Instantiate everything possible
plaintext = "".getBytes(StandardCharsets.UTF_8);
byte[] authAndEncBody = prepareAuthAndEncBody();
authAndEncEF = new NTSExtensionField(FieldType.NTS_AUTH_AND_ENC, authAndEncBody);
addExtensionField(authAndEncEF);
}
/**
* Creates the AuthAndEnc EF with the given keys and nonce. This is done after the NTP packet has
* been timestamped. Must be called after prepareAuthAndEncEF() has been called.
*
* @param nonce the nonce to be used for encryption
*/
@Override
public void createAuthAndEncEF(byte[] nonce) {
try {
// Change to _throws_ and control from caller
byte[] ciphertext =
aesSivDaead.encryptDeterministicallyWithAssociatedDatas(
plaintext, new byte[][] {Arrays.copyOf(buf, associatedDataLength), nonce});
authAndEncEF.replaceBody(nonce, 4);
authAndEncEF.replaceBody(ciphertext, 4 + nonce.length);
System.arraycopy(
authAndEncEF.toByteArray(), 0, buf, associatedDataLength, authAndEncEF.getFieldLength());
} catch (Exception e) {
throw new RuntimeException("Failed to encrypt NTS packet.", e);
}
}
/**
* Creates the AuthAndEnc EF with the given keys and a random nonce. This is done after the NTP
* packet has been timestamped. Must be called after prepareAuthAndEncEF() has been called.
*/
@Override
public void createAuthAndEncEF() {
byte[] nonce = new byte[16];
new SecureRandom().nextBytes(nonce);
createAuthAndEncEF(nonce);
}
/**
* @return 2 bytes as 16-bit int
*/
private int getShort(final byte[] buf, final int index) {
return ui(buf[index]) << 8 | ui(buf[index + 1]);
}
private void extractExtensionFieldsFrom(byte[] src, int idx) {
while (idx < src.length) {
NTSExtensionField ef = NTSExtensionField.fromBytes(src, idx);
if (ef.fieldType == FieldType.NTS_AUTH_AND_ENC) {
associatedDataLength = idx;
authAndEncEF = ef;
}
idx += ef.getFieldLength();
extensionFields.add(ef);
}
}
private void extractExtensionFields() {
int idx = 48;
associatedDataLength = -1;
authAndEncEF = null;
extractExtensionFieldsFrom(buf, idx);
}
public boolean validateUniqueIdentifier(NtsPacket req) throws IOException {
List<NTSExtensionField> unique_id_req = req.getExtensionFields(FieldType.UNIQUE_IDENTIFIER);
List<NTSExtensionField> unique_id_resp = getExtensionFields(FieldType.UNIQUE_IDENTIFIER);
if (unique_id_req.size() != 1 || unique_id_resp.size() != 1) {
throw new IOException(
"Expected exactly one UNIQUE_IDENTIFIER field, but found "
+ unique_id_req.size()
+ " in the request and "
+ unique_id_resp.size()
+ " in the response");
}
byte[] reqId = unique_id_req.get(0).body;
byte[] respId = unique_id_resp.get(0).body;
if (!Arrays.equals(reqId, respId)) {
throw new IOException("UNIQUE_IDENTIFIER field mismatch between request and response");
}
return true;
}
/** Decrypt and verify a received NTS packet */
@Override
public byte[] decryptAndVerify() throws AuthenticationFailureException {
if (associatedDataLength == -1 || authAndEncEF == null) {
extractExtensionFields();
if (associatedDataLength == -1 || authAndEncEF == null) {
throw new RuntimeException("No authentication information found");
}
}
int nonce_len = getShort(authAndEncEF.body, 0);
int ct_len = getShort(authAndEncEF.body, 2);
byte[] nonce = Arrays.copyOfRange(authAndEncEF.body, 4, 4 + nonce_len);
byte[] ct = Arrays.copyOfRange(authAndEncEF.body, 4 + nonce_len, 4 + nonce_len + ct_len);
byte[] ad = Arrays.copyOf(buf, associatedDataLength);
byte[] pt;
try {
pt = aesSivDaead.decryptDeterministicallyWithAssociatedDatas(ct, new byte[][] {ad, nonce});
} catch (final GeneralSecurityException e) {
throw new AuthenticationFailureException("Failed NTS Authentication", e);
} catch (final Exception e) {
throw new RuntimeException(e);
}
extractExtensionFieldsFrom(pt, 0);
return pt;
}
/**
* Validate a response packet given a request packet
*
* @param req - The request packet
* @throws IOException - On failure
*/
@Override
public void validate(NtsPacket req)
throws IOException, NtsNakException, AuthenticationFailureException {
if (getStratum() == 0 && getReferenceIdString().equals("NTSN")) {
throw new NtsNakException();
}
// NTPv3 validation
super.validate((NtpV3Packet) req);
// NTPv4 NTS validation
validateUniqueIdentifier(req);
decryptAndVerify();
}
}