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
|
/* Copyright (C) 2022 Dinglan Peng
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.tigervnc.rfb;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.JOptionPane;
import com.tigervnc.rdr.*;
import com.tigervnc.vncviewer.*;
public class CSecurityRSAAES extends CSecurity {
private static final int MinKeyLength = 1024;
private static final int MaxKeyLength = 8192;
private static final byte[] bigIntToBytes(BigInteger n, int bytes) {
int bits = n.bitCount();
byte[] arr = n.toByteArray();
//int len = bits % 8 == 0 ? arr.length - 1 : arr.length;
//System.out.printf("%d %d %d\n", bits, len, bytes);
//if (len > bytes)
// return null;
int len = arr.length < bytes ? arr.length : bytes;
byte[] res = new byte[bytes];
System.arraycopy(arr, arr.length - len, res, bytes - len, len);
return res;
}
public CSecurityRSAAES(int secType, int keySize, boolean isAllEncrypted) {
this.secType = secType;
this.keySize = keySize;
this.isAllEncrypted = isAllEncrypted;
}
public boolean processMsg(CConnection cc) {
readPubclicKey(cc);
verifyServer();
writePublicKey(cc);
writeRandom(cc);
readRandom(cc);
setCipher(cc);
writeHash(cc);
readHash();
readSubtype();
writeCredentials();
return true;
}
private void readPubclicKey(CConnection cc) {
InStream is = cc.getInStream();
serverKeyLength = is.readU32();
if (serverKeyLength < MinKeyLength)
throw new AuthFailureException("server key is too short");
if (serverKeyLength > MaxKeyLength)
throw new AuthFailureException("server key is too long");
int size = (serverKeyLength + 7) / 8;
serverKeyN = new byte[size];
serverKeyE = new byte[size];
is.readBytes(ByteBuffer.wrap(serverKeyN), size);
is.readBytes(ByteBuffer.wrap(serverKeyE), size);
BigInteger modulus = new BigInteger(1, serverKeyN);
BigInteger publicExponent = new BigInteger(1, serverKeyE);
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
try {
KeyFactory factory = KeyFactory.getInstance("RSA");
serverKey = factory.generatePublic(spec);
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("RSA algorithm is not supported");
} catch (InvalidKeySpecException e) {
throw new AuthFailureException("server key is invalid");
}
}
private void verifyServer() {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("SHA-1 algorithm is not supported");
}
byte[] length = new byte[4];
length[0] = (byte) ((serverKeyLength & 0xff000000) >> 24);
length[1] = (byte) ((serverKeyLength & 0xff0000) >> 16);
length[2] = (byte) ((serverKeyLength & 0xff00) >> 8);
length[3] = (byte) (serverKeyLength & 0xff);
digest.update(length);
digest.update(serverKeyN);
digest.update(serverKeyE);
byte[] f = digest.digest();
String title = "Server key fingerprint";
String text = String.format(
"The server has provided the following identifying information:\n" +
"Fingerprint: %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n" +
"Please verify that the information is correct and press \"Yes\". " +
"Otherwise press \"No\"", f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]);
if (!msg.showMsgBox(JOptionPane.YES_NO_OPTION, title, text))
throw new AuthFailureException("server key mismatch");
}
private void writePublicKey(CConnection cc) {
OutStream os = cc.getOutStream();
clientKeyLength = serverKeyLength;
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("RSA algorithm is not supported");
}
kpg.initialize(clientKeyLength);
KeyPair kp = kpg.generateKeyPair();
clientKey = kp.getPrivate();
clientPublicKey = kp.getPublic();
RSAPublicKey rsaKey = (RSAPublicKey) clientPublicKey;
BigInteger modulus = rsaKey.getModulus();
BigInteger publicExponent = rsaKey.getPublicExponent();
clientKeyN = bigIntToBytes(modulus, (clientKeyLength + 7) / 8);
clientKeyE = bigIntToBytes(publicExponent, (clientKeyLength + 7) / 8);
if (clientKeyN == null || clientKeyN == null) {
throw new AuthFailureException("failed to generate RSA keys");
}
os.writeU32(clientKeyLength);
os.writeBytes(clientKeyN, 0, clientKeyN.length);
os.writeBytes(clientKeyE, 0, clientKeyE.length);
os.flush();
}
private void writeRandom(CConnection cc) {
OutStream os = cc.getOutStream();
SecureRandom sr = new SecureRandom();
clientRandom = new byte[keySize / 8];
sr.nextBytes(clientRandom);
byte[] encrypted;
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, serverKey);
encrypted = cipher.doFinal(clientRandom);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new AuthFailureException("RSA algorithm is not supported");
} catch (InvalidKeyException | IllegalBlockSizeException |
BadPaddingException e) {
throw new AuthFailureException("failed to encrypt random");
}
os.writeU16(encrypted.length);
os.writeBytes(encrypted, 0, encrypted.length);
os.flush();
}
private void readRandom(CConnection cc) {
InStream is = cc.getInStream();
int size = is.readU16();
if (size != clientKeyN.length)
throw new AuthFailureException("client key length doesn't match");
byte[] buffer = new byte[size];
is.readBytes(ByteBuffer.wrap(buffer), size);
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, clientKey);
serverRandom = cipher.doFinal(buffer);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new AuthFailureException("RSA algorithm is not supported");
} catch (InvalidKeyException | IllegalBlockSizeException |
BadPaddingException e) {
System.out.println(e.getMessage());
throw new AuthFailureException("failed to decrypt server random");
}
if (serverRandom.length != keySize / 8)
throw new AuthFailureException("server random length doesn't match");
}
private void setCipher(CConnection cc) {
rawis = cc.getInStream();
rawos = cc.getOutStream();
MessageDigest digest;
try {
digest = MessageDigest.getInstance(keySize == 128 ? "SHA-1" : "SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("hash algorithm is not supported");
}
digest.update(clientRandom);
digest.update(serverRandom);
byte[] key = Arrays.copyOfRange(digest.digest(), 0, keySize / 8);
rais = new AESInStream(rawis, key);
digest.reset();
digest.update(serverRandom);
digest.update(clientRandom);
key = Arrays.copyOfRange(digest.digest(), 0, keySize / 8);
raos = new AESOutStream(rawos, key);
if (isAllEncrypted)
cc.setStreams(rais, raos);
}
private void writeHash(CConnection cc) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(keySize == 128 ? "SHA-1" : "SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("hash algorithm is not supported");
}
int len = serverKeyLength;
byte[] lenServerKey = new byte[] {
(byte) ((len & 0xff000000) >> 24),
(byte) ((len & 0xff0000) >> 16),
(byte) ((len & 0xff00) >> 8),
(byte) (len & 0xff)
};
len = clientKeyLength;
byte[] lenClientKey = new byte[] {
(byte) ((len & 0xff000000) >> 24),
(byte) ((len & 0xff0000) >> 16),
(byte) ((len & 0xff00) >> 8),
(byte) (len & 0xff)
};
digest.update(lenClientKey);
digest.update(clientKeyN);
digest.update(clientKeyE);
digest.update(lenServerKey);
digest.update(serverKeyN);
digest.update(serverKeyE);
byte[] hash = digest.digest();
raos.writeBytes(hash, 0, hash.length);
raos.flush();
}
void readHash() {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(keySize == 128 ? "SHA-1" : "SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AuthFailureException("hash algorithm is not supported");
}
int len = serverKeyLength;
byte[] lenServerKey = new byte[] {
(byte)((len & 0xff000000) >> 24),
(byte)((len & 0xff0000) >> 16),
(byte)((len & 0xff00) >> 8),
(byte)(len & 0xff)
};
len = clientKeyLength;
byte[] lenClientKey = new byte[] {
(byte)((len & 0xff000000) >> 24),
(byte)((len & 0xff0000) >> 16),
(byte)((len & 0xff00) >> 8),
(byte)(len & 0xff)
};
digest.update(lenServerKey);
digest.update(serverKeyN);
digest.update(serverKeyE);
digest.update(lenClientKey);
digest.update(clientKeyN);
digest.update(clientKeyE);
byte[] realHash = digest.digest();
ByteBuffer hash = ByteBuffer.allocate(realHash.length);
rais.readBytes(hash, realHash.length);
if (!Arrays.equals(hash.array(), realHash)) {
throw new AuthFailureException("hash doesn't match");
}
}
private void readSubtype() {
subtype = rais.readU8();
if (subtype != Security.secTypeRA2UserPass &&
subtype != Security.secTypeRA2Pass)
throw new AuthFailureException("unknown RSA-AES subtype");
}
private void writeCredentials() {
StringBuffer username = new StringBuffer();
StringBuffer password = new StringBuffer();
CSecurity.upg.getUserPasswd(secType == Security.secTypeRA256,
subtype == Security.secTypeRA2UserPass ?
username : null,
password);
if (username.length() > 255)
throw new AuthFailureException("username is too long");
byte[] usernameBytes;
try {
usernameBytes = username.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AuthFailureException("UTF-8 is not supported");
}
raos.writeU8(usernameBytes.length);
if (usernameBytes.length != 0)
raos.writeBytes(usernameBytes, 0, usernameBytes.length);
if (password.length() > 255)
throw new AuthFailureException("password is too long");
byte[] passwordBytes;
try {
passwordBytes = password.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AuthFailureException("UTF-8 is not supported");
}
raos.writeU8(passwordBytes.length);
if (passwordBytes.length != 0)
raos.writeBytes(passwordBytes, 0, passwordBytes.length);
raos.flush();
}
public int getType() {
return secType;
}
public String description() {
return "RSA-ASE security types";
}
private int secType;
private int subtype;
private int keySize;
private boolean isAllEncrypted;
private PrivateKey clientKey;
private PublicKey clientPublicKey;
private PublicKey serverKey;
private int serverKeyLength;
private byte[] serverKeyN;
private byte[] serverKeyE;
private int clientKeyLength;
private byte[] clientKeyN;
private byte[] clientKeyE;
private byte[] serverRandom;
private byte[] clientRandom;
private AESInStream rais;
private AESOutStream raos;
private InStream rawis;
private OutStream rawos;
}
|