2 * org.ibex.net.SSL - By Brian Alliet
3 * Copyright (C) 2004 Brian Alliet
5 * Based on TinySSL by Adam Megacz
6 * Copyright (C) 2003 Adam Megacz <adam@xwt.org> all rights reserved.
8 * You may modify, copy, and redistribute this code under the terms of
9 * the GNU Lesser General Public License version 2.1, with the exception
10 * of the portion of clause 6a after the semicolon (aka the "obnoxious
16 import org.ibex.crypto.*;
17 import java.security.SecureRandom;
19 import java.net.Socket;
20 import java.net.SocketException;
23 import java.util.Enumeration;
24 import java.util.Hashtable;
25 import java.util.Random;
26 import java.util.Vector;
28 // FEATURE: Server socket
30 public class SSL extends Socket {
31 public static final byte TLS_RSA_WITH_AES_256_CBC_SHA = 0x35;
32 public static final byte TLS_RSA_WITH_AES_128_CBC_SHA = 0x2f;
33 public static final byte SSL_RSA_WITH_RC4_128_SHA = 0x05;
34 public static final byte SSL_RSA_WITH_RC4_128_MD5 = 0x04;
36 private static final byte[] DEFAULT_CIPHER_PREFS = new byte[]{
37 TLS_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,
38 SSL_RSA_WITH_RC4_128_SHA,SSL_RSA_WITH_RC4_128_MD5
41 private String hostname;
43 private int negotiated;
45 private boolean tls = true;
49 private final DataInputStream rawIS;
50 private final DataOutputStream rawOS;
52 private final InputStream sslIS;
53 private final OutputStream sslOS;
55 private byte[] sessionID;
57 private Digest clientWriteMACDigest;
58 private Digest serverWriteMACDigest;
59 private byte[] masterSecret;
61 private Cipher writeCipher;
62 private Cipher readCipher;
64 private long serverSequenceNumber;
65 private long clientSequenceNumber;
68 private boolean closed;
70 // These are only used during negotiation
71 private byte[] serverRandom;
72 private byte[] clientRandom;
73 private byte[] preMasterSecret;
78 private byte[] pending = new byte[16384];
79 private int pendingStart;
80 private int pendingLength;
82 private byte[] sendRecordBuf = new byte[16384];
84 private int handshakeDataStart;
85 private int handshakeDataLength;
86 private byte[] readRecordBuf = new byte[16384+20]; // 20 == sizeof(sha1 hash)
87 private byte[] readRecordScratch = new byte[16384+20];
89 // These are only uses for CBCs
90 private int blockSize; // block size (0 for stream ciphers)
91 private byte[] padBuf;
92 private byte[] prevBlock;
94 private ByteArrayOutputStream handshakesBuffer;
99 private final static byte[] pad1 = new byte[48];
100 private final static byte[] pad2 = new byte[48];
101 private final static byte[] pad1_sha = new byte[40];
102 private final static byte[] pad2_sha = new byte[40];
105 for(int i=0; i<pad1.length; i++) pad1[i] = (byte)0x36;
106 for(int i=0; i<pad2.length; i++) pad2[i] = (byte)0x5C;
107 for(int i=0; i<pad1_sha.length; i++) pad1_sha[i] = (byte)0x36;
108 for(int i=0; i<pad2_sha.length; i++) pad2_sha[i] = (byte)0x5C;
111 private final static Hashtable caKeys = new Hashtable();
112 private static VerifyCallback verifyCallback;
117 public SSL(String host) throws IOException { this(host,443); }
118 public SSL(String host, int port) throws IOException { this(host,port,true); }
119 public SSL(String host, int port, boolean negotiate) throws IOException { this(host,port,negotiate,null); }
120 public SSL(String host, int port, State state) throws IOException { this(host,port,true,state); }
121 public SSL(String host, int port, boolean negotiate, State state) throws IOException {
124 rawIS = new DataInputStream(new BufferedInputStream(super.getInputStream()));
125 rawOS = new DataOutputStream(new BufferedOutputStream(super.getOutputStream()));
126 sslIS = new SSLInputStream();
127 sslOS = new SSLOutputStream();
128 if(negotiate) negotiate(state);
131 public synchronized void setTLS(boolean b) { if(negotiated!=0) throw new IllegalStateException("already negotiated"); tls = b; }
133 public void negotiate() throws IOException { negotiate(null,null); }
134 public void negotiate(State state) throws IOException { negotiate(state,null); }
135 public void negotiate(byte[] cipherPrefs) throws IOException { negotiate(null,cipherPrefs); }
136 private void negotiate(State state, byte[] cipherPrefs) throws IOException {
137 if(negotiated != 0) throw new IllegalStateException("already negotiated");
139 handshakesBuffer = new ByteArrayOutputStream();
142 sendClientHello(state != null ? state.sessionID : null, cipherPrefs);
144 debug("sent ClientHello (" + (tls?"TLSv1.0":"SSLv3.0")+")");
146 receiveServerHello();
147 debug("got ServerHello (" + (tls?"TLSv1.0":"SSLv3.0")+")");
150 state != null && sessionID.length == state.sessionID.length &&
151 eq(state.sessionID,0,sessionID,0,sessionID.length);
154 negotiateResume(state);
158 // we're done with these now
159 clientRandom = serverRandom = preMasterSecret = null;
160 handshakesBuffer = null;
162 log("Negotiation with " + hostname + " complete (" + (tls?"TLSv1.0":"SSLv3.0")+")");
164 if((negotiated & 3) != 3) {
166 try { super.close(); } catch(IOException e) { /* ignore */ }
172 private void negotiateResume(State state) throws IOException {
173 masterSecret = state.masterSecret;
176 log("initializec crypto");
178 receiveChangeCipherSpec();
179 debug("Received ChangeCipherSpec");
182 debug("Received Finished");
184 sendChangeCipherSpec();
185 debug("Sent ChangeCipherSpec");
188 debug("Sent Finished");
191 private void negotiateNew() throws IOException {
192 X509.Certificate[] certs = receiveServerCertificates();
193 debug("got Certificate");
195 boolean gotCertificateRequest = false;
197 byte[] buf = readHandshake();
199 case 14: // ServerHelloDone
200 if(buf.length != 4) throw new Exn("ServerHelloDone contained trailing garbage");
201 debug("got ServerHelloDone");
203 case 13: // CertificateRequest
204 debug("Got a CertificateRequest message but we don't suport client certificates");
205 gotCertificateRequest = true;
208 throw new Exn("unknown handshake type " + buf[0]);
212 if(gotCertificateRequest)
213 sendHandshake((byte)11,new byte[3]); // send empty cert list
216 if(!hostname.equalsIgnoreCase(certs[0].getCN()))
217 throw new Exn("Certificate is for " + certs[0].getCN() + " not " + hostname);
220 if(verifyCallback == null) throw e;
221 synchronized(SSL.class) {
222 if(!verifyCallback.checkCerts(certs,hostname,e)) throw e;
226 computeMasterSecret();
228 sendClientKeyExchange(certs[0]);
229 debug("sent ClientKeyExchange");
233 sendChangeCipherSpec();
234 debug("sent ChangeCipherSpec");
237 debug("sent Finished");
240 receiveChangeCipherSpec();
241 debug("got ChangeCipherSpec");
244 debug("got Finished");
247 public State getSessionState() {
248 if((negotiated&3)!=3 || !closed || warnings != 0) return null;
249 return new State(sessionID,masterSecret);
251 public boolean isActive() { return !closed; }
252 public boolean isNegotiated() { return (negotiated&3) == 3; }
254 private void sendClientHello(byte[] sessionID, byte[] cipherPrefs) throws IOException {
255 if(sessionID != null && sessionID.length > 256) throw new IllegalArgumentException("sessionID");
256 if(cipherPrefs == null) cipherPrefs = DEFAULT_CIPHER_PREFS;
257 else if(cipherPrefs.length > 4) throw new IllegalArgumentException("too many cipherPrefs");
258 // 2 = version, 32 = randomvalue, 1 = sessionID size, 2 = cipher list size, 8 = the four ciphers,
259 // 2 = compression length/no compression
261 byte[] buf = new byte[2+32+1+(sessionID == null ? 0 : sessionID.length)+2+(cipherPrefs.length * 2)+2];
262 buf[p++] = 0x03; // major version
263 buf[p++] = tls ? (byte)0x01 : (byte)0x00;
265 clientRandom = new byte[32];
266 int now = (int)(System.currentTimeMillis() / 1000L);
267 new Random().nextBytes(clientRandom);
268 clientRandom[0] = (byte)(now>>>24);
269 clientRandom[1] = (byte)(now>>>16);
270 clientRandom[2] = (byte)(now>>>8);
271 clientRandom[3] = (byte)(now>>>0);
272 System.arraycopy(clientRandom,0,buf,p,32);
275 buf[p++] = sessionID != null ? (byte)sessionID.length : 0;
276 if(sessionID != null && sessionID.length != 0) System.arraycopy(sessionID,0,buf,p,sessionID.length);
277 p += sessionID != null ? sessionID.length : 0;
279 buf[p++] = 0x00; // 8 bytes of ciphers
280 buf[p++] = (byte)(cipherPrefs.length * 2);
282 for(int i=0;i<cipherPrefs.length;i++) {
284 buf[p++] = cipherPrefs[i];
287 buf[p++] = 0x01; // compression length
288 buf[p++] = 0x00; // no compression
290 sendHandshake((byte)1,buf);
294 private void receiveServerHello() throws IOException {
296 byte[] buf = readHandshake();
297 if(buf[0] != 2) throw new Exn("expected a ServerHello message");
299 if(buf.length < 6 + 32 + 1) throw new Exn("ServerHello too small");
300 if(buf.length < 6 + 32 + 1 + buf[6+32] + 3) throw new Exn("ServerHello too small " + buf.length+" "+buf[6+32]);
302 if(buf[4] != 0x03 || !(buf[5]==0x00 || buf[5]==0x01)) throw new Exn("server wants to use version " + buf[4] + "." + buf[5]);
303 tls = buf[5] == 0x01;
305 serverRandom = new byte[32];
306 System.arraycopy(buf,p,serverRandom,0,32);
308 sessionID = new byte[buf[p++]&0xff];
309 if(sessionID.length != 0) System.arraycopy(buf,p,sessionID,0,sessionID.length);
310 p += sessionID.length;
311 int cipher = ((buf[p]&0xff)<<8) | (buf[p+1]&0xff);
313 if((cipher>>>8)!=0) throw new Exn("Unsupported cipher " + cipher);
314 switch(cipher&0xff) {
315 case SSL_RSA_WITH_RC4_128_MD5: sha = false; aes=0; debug("Using SSL_RSA_WITH_RC4_128_MD5"); break;
316 case SSL_RSA_WITH_RC4_128_SHA: sha = true; aes=0; debug("Using SSL_RSA_WITH_RC4_128_SHA"); break;
317 case TLS_RSA_WITH_AES_128_CBC_SHA: sha = true; aes = 128; debug("Using TLS_RSA_WITH_AES_128_CBC_SHA"); break;
318 case TLS_RSA_WITH_AES_256_CBC_SHA: sha = true; aes = 256; debug("Using TLS_RSA_WITH_AES_256_CBC_SHA"); break;
319 default: throw new Exn("Unsupported cipher " + cipher);
321 mac = new byte[sha ? 20 : 16];
322 if(buf[p++] != 0x0) throw new Exn("unsupported compression " + buf[p-1]);
325 private X509.Certificate[] receiveServerCertificates() throws IOException {
326 byte[] buf = readHandshake();
327 if(buf[0] != 11) throw new Exn("expected a Certificate message");
328 if((((buf[4]&0xff)<<16)|((buf[5]&0xff)<<8)|((buf[6]&0xff)<<0)) != buf.length-7) throw new Exn("size mismatch in Certificate message");
332 for(int i=p;i<buf.length-3;i+=((buf[p+0]&0xff)<<16)|((buf[p+1]&0xff)<<8)|((buf[p+2]&0xff)<<0)) count++;
333 if(count == 0) throw new Exn("server didn't provide any certificates");
334 X509.Certificate[] certs = new X509.Certificate[count];
336 while(p < buf.length) {
337 int len = ((buf[p+0]&0xff)<<16)|((buf[p+1]&0xff)<<8)|((buf[p+2]&0xff)<<0);
339 if(p + len > buf.length) throw new Exn("Certificate message cut short");
340 certs[count++] = new X509.Certificate(new ByteArrayInputStream(buf,p,len));
346 private void sendClientKeyExchange(X509.Certificate serverCert) throws IOException {
347 byte[] encryptedPreMasterSecret;
348 RSA.PublicKey pks = serverCert.getRSAPublicKey();
349 PKCS1 pkcs1 = new PKCS1(new RSA(pks.modulus,pks.exponent,false),random);
350 encryptedPreMasterSecret = pkcs1.encode(preMasterSecret);
353 buf = new byte[encryptedPreMasterSecret.length+2];
354 buf[0] = (byte) (encryptedPreMasterSecret.length>>>8);
355 buf[1] = (byte) (encryptedPreMasterSecret.length>>>0);
356 System.arraycopy(encryptedPreMasterSecret,0,buf,2,encryptedPreMasterSecret.length);
358 // ugh... netscape didn't send the length bytes and now every SSLv3 implementation
359 // must implement this bug
360 buf = encryptedPreMasterSecret;
362 sendHandshake((byte)16,buf);
365 private void sendChangeCipherSpec() throws IOException {
366 sendRecord((byte)20,new byte[] { 0x01 });
369 private void computeMasterSecret() {
370 preMasterSecret = new byte[48];
371 preMasterSecret[0] = 0x03; // version_high
372 preMasterSecret[1] = tls ? (byte) 0x01 : (byte) 0x00; // version_low
373 randomBytes(preMasterSecret,2,46);
376 masterSecret = tlsPRF(48,preMasterSecret,getBytes("master secret"),concat(clientRandom,serverRandom));
378 masterSecret = concat(new byte[][] {
379 md5(new byte[][] { preMasterSecret,
380 sha1(new byte[][] { new byte[] { 0x41 }, preMasterSecret, clientRandom, serverRandom })}),
381 md5(new byte[][] { preMasterSecret,
382 sha1(new byte[][] { new byte[] { 0x42, 0x42 }, preMasterSecret, clientRandom, serverRandom })}),
383 md5(new byte[][] { preMasterSecret,
384 sha1(new byte[][] { new byte[] { 0x43, 0x43, 0x43 }, preMasterSecret, clientRandom, serverRandom })})
389 public void initCrypto() {
394 keyMaterial = tlsPRF(
395 (mac.length + (aes==256 ? 32 : 16) + (aes==0 ? 0 : 16))*2, // MAC len + key len + iv len
397 getBytes("key expansion"),
398 concat(serverRandom,clientRandom)
401 keyMaterial = new byte[] { };
402 for(int i=0; keyMaterial.length < 72; i++) {
403 byte[] crap = new byte[i + 1];
404 for(int j=0; j<crap.length; j++) crap[j] = (byte)(((byte)0x41) + ((byte)i));
405 keyMaterial = concat(new byte[][] { keyMaterial,
406 md5(new byte[][] { masterSecret,
407 sha1(new byte[][] { crap, masterSecret, serverRandom, clientRandom }) }) });
409 if(aes != 0) throw new Error("should never happen");
412 byte[] clientWriteMACSecret = new byte[mac.length];
413 byte[] serverWriteMACSecret = new byte[mac.length];
414 byte[] clientWriteKey = new byte[aes==256 ? 32 : 16];
415 byte[] serverWriteKey = new byte[aes==256 ? 32 : 16];
416 byte[] clientWriteIV = aes == 0 ? null : new byte[16];
417 byte[] serverWriteIV = aes == 0 ? null : new byte[16];
420 System.arraycopy(keyMaterial, p, clientWriteMACSecret, 0, mac.length); p += mac.length;
421 System.arraycopy(keyMaterial, p, serverWriteMACSecret, 0, mac.length); p += mac.length;
422 System.arraycopy(keyMaterial, p, clientWriteKey, 0, clientWriteKey.length); p += clientWriteKey.length;
423 System.arraycopy(keyMaterial, p, serverWriteKey, 0, serverWriteKey.length); p += serverWriteKey.length;
424 if(clientWriteIV != null) System.arraycopy(keyMaterial,p,clientWriteIV,0,16); p += 16;
425 if(serverWriteIV != null) System.arraycopy(keyMaterial,p,serverWriteIV,0,16); p += 16;
429 writeCipher = aes==0 ? (Cipher)new RC4(clientWriteKey) : (Cipher)new CBC(new AES(clientWriteKey,false),16,clientWriteIV,false);
430 inner = sha ? (Digest)new SHA1() : (Digest)new MD5();
431 clientWriteMACDigest = tls ? (Digest) new HMAC(inner,clientWriteMACSecret) : (Digest)new SSLv3HMAC(inner,clientWriteMACSecret);
433 readCipher = aes==0 ? (Cipher)new RC4(serverWriteKey) : (Cipher)new CBC(new AES(serverWriteKey,true),16,serverWriteIV,true);
434 inner = sha ? (Digest)new SHA1() : (Digest)new MD5();
435 serverWriteMACDigest = tls ? (Digest)new HMAC(inner,serverWriteMACSecret) : (Digest)new SSLv3HMAC(inner,serverWriteMACSecret);
438 blockSize = 16; // aes block size == 16
439 padBuf = new byte[mac.length+blockSize]; // worse case, 15 bytes of data, mac, and padding byte
443 private void sendFinished() throws IOException {
444 byte[] handshakes = handshakesBuffer.toByteArray();
446 sendHandshake((byte)20, tlsPRF(
449 getBytes("client finished"),
450 concat(md5(handshakes),sha1(handshakes))));
453 sendHandshake((byte)20, concat(new byte[][] {
454 md5(new byte[][] { masterSecret, pad2,
455 md5(new byte[][] { handshakes, new byte[] { (byte)0x43, (byte)0x4C, (byte)0x4E, (byte)0x54 },
456 masterSecret, pad1 }) }),
457 sha1(new byte[][] { masterSecret, pad2_sha,
458 sha1(new byte[][] { handshakes, new byte[] { (byte)0x43, (byte)0x4C, (byte)0x4E, (byte)0x54 },
459 masterSecret, pad1_sha } ) })
464 private void receiveChangeCipherSpec() throws IOException {
465 int size = readRecord((byte)20);
466 if(size == -1) throw new Exn("got eof when expecting a ChangeCipherSpec message");
467 if(size != 1 || readRecordBuf[0] != 0x01) throw new Exn("Invalid ChangeCipherSpec message");
470 private void receieveFinished() throws IOException {
471 byte[] handshakes = handshakesBuffer.toByteArray();
472 byte[] buf = readHandshake();
473 if(buf[0] != 20) throw new Exn("expected a Finished message");
477 if(buf.length != 4 + 12) throw new Exn("Finished message too short");
480 getBytes("server finished"),
481 concat(md5(handshakes),sha1(handshakes)));
483 if(buf.length != 4 + 16 +20) throw new Exn("Finished message too short");
484 expected = concat(new byte[][] {
485 md5(new byte[][] { masterSecret, pad2,
486 md5(new byte[][] { handshakes, new byte[] { (byte)0x53, (byte)0x52, (byte)0x56, (byte)0x52 },
487 masterSecret, pad1 }) }),
488 sha1(new byte[][] { masterSecret, pad2_sha,
489 sha1(new byte[][] { handshakes, new byte[] { (byte)0x53, (byte)0x52, (byte)0x56, (byte)0x52 },
490 masterSecret, pad1_sha } ) } ) } );
492 if(!eq(expected,0,buf,4,expected.length)) throw new Exn("server finished message mismatch");
495 private void flush() throws IOException { rawOS.flush(); }
497 private void sendHandshake(byte type, byte[] payload) throws IOException {
498 if(payload.length > (1<<24)) throw new IllegalArgumentException("payload.length");
499 byte[] buf = new byte[4+payload.length];
501 buf[1] = (byte)(payload.length>>>16);
502 buf[2] = (byte)(payload.length>>>8);
503 buf[3] = (byte)(payload.length>>>0);
504 System.arraycopy(payload,0,buf,4,payload.length);
505 handshakesBuffer.write(buf);
506 sendRecord((byte)22,buf);
509 private void sendRecord(byte proto, byte[] buf) throws IOException { sendRecord(proto,buf,0,buf.length); }
510 private void sendRecord(byte proto, byte[] payload, int off, int totalLen) throws IOException {
511 int macLength = (negotiated & 1) != 0 ? mac.length : 0;
512 while(totalLen > 0) {
513 int len = min(totalLen,16384-macLength);
514 rawOS.writeByte(proto);
515 rawOS.writeShort(tls ? 0x0301 : 0x0300);
516 if((negotiated & 1) != 0) {
517 computeMAC(proto,payload,off,len,clientWriteMACDigest,clientSequenceNumber);
518 // FEATURE: Encode in place
520 int firstShot = len & ~(blockSize-1);
521 if(firstShot != 0) writeCipher.process(payload,off,sendRecordBuf,0,firstShot);
522 int _off = off + firstShot; // offset in sendRecordBuf
523 int _len = len - firstShot; // length of data in padBuf
524 if(_len != 0) System.arraycopy(payload,_off,padBuf,0,_len);
525 System.arraycopy(mac,0,padBuf,_len,macLength);
527 int extra = blockSize - (_len&~blockSize);
528 if(extra == 0) extra = 16;
529 for(int i=0;i<extra;i++) padBuf[_len+i] = (byte)(extra-1);
531 writeCipher.process(padBuf,0,sendRecordBuf,_off,_len);
532 rawOS.writeShort(firstShot+_len);
533 rawOS.write(sendRecordBuf,0,firstShot+_len);
535 writeCipher.process(payload,off,sendRecordBuf,0,len);
536 writeCipher.process(mac,0,sendRecordBuf,len,macLength);
537 rawOS.writeShort(len + macLength);
538 rawOS.write(sendRecordBuf,0, len +macLength);
540 clientSequenceNumber++;
542 rawOS.writeShort(len);
543 rawOS.write(payload,off,len);
550 private byte[] readHandshake() throws IOException {
551 if(handshakeDataLength == 0) {
552 handshakeDataStart = 0;
553 handshakeDataLength = readRecord((byte)22);
554 if(handshakeDataLength == -1) throw new Exn("got eof when expecting a handshake packet");
556 byte[] buf = readRecordBuf;
557 int len = ((buf[handshakeDataStart+1]&0xff)<<16)|((buf[handshakeDataStart+2]&0xff)<<8)|((buf[handshakeDataStart+3]&0xff)<<0);
558 // Handshake messages can theoretically span multiple records, but in practice this does not occur
559 if(len > handshakeDataLength) {
560 sendAlert(true,10); // 10 == unexpected message
561 throw new Exn("handshake message size too large " + len + " vs " + (handshakeDataLength-handshakeDataStart));
563 byte[] ret = new byte[4+len];
564 System.arraycopy(buf,handshakeDataStart,ret,0,ret.length);
565 handshakeDataLength -= ret.length;
566 handshakeDataStart += ret.length;
567 handshakesBuffer.write(ret);
571 private int readRecord(byte reqProto) throws IOException {
572 int macLength = (negotiated & 2) != 0 ? mac.length : 0;
578 proto = rawIS.readByte();
579 } catch(EOFException e) {
580 // this may or may not be an error. it is up to the application protocol
583 throw new PrematureCloseExn();
586 version = rawIS.readShort();
587 if(version != 0x0300 && version != 0x0301) throw new Exn("invalid version ");
588 len = rawIS.readShort();
589 if(len <= 0 || len > 16384+((negotiated&2)!=0 ? macLength : 0)) throw new Exn("invalid length " + len);
590 rawIS.readFully((negotiated&2)!=0 ? readRecordScratch : readRecordBuf,0,len);
591 } catch(EOFException e) {
592 // an EOF here is always an error (we don't pass the EOF back on to the app
593 // because it isn't a "legitimate" eof)
594 throw new Exn("Hit EOF too early");
597 if((negotiated & 2) != 0) {
598 // FEATURE: Decode in place
599 if(blockSize != 0 && (len % blockSize) != 0) throw new Exn("input not a multiple of the cipher's block size");
600 readCipher.process(readRecordScratch,0,readRecordBuf,0,len);
603 if(!tls) throw new Error("should never happen");
604 int padding = readRecordBuf[len-1]&0xff;
605 if(padding >= blockSize) throw new Exn("invalid padding length: " + padding);
606 for(int i=0;i<padding;i++) if(readRecordBuf[len-padding-1] != padding) throw new Exn("bad padding");
609 if(len < macLength) throw new Exn("packet size < macLength");
611 computeMAC(proto,readRecordBuf,0,len-macLength,serverWriteMACDigest,serverSequenceNumber);
612 for(int i=0;i<macLength;i++)
613 if(mac[i] != readRecordBuf[len-macLength+i])
614 throw new Exn("mac mismatch");
616 serverSequenceNumber++;
619 if(proto == reqProto) return len;
623 if(len != 2) throw new Exn("invalid lengh for alert");
624 int level = readRecordBuf[0];
625 int desc = readRecordBuf[1];
627 if(desc == 0) { // CloseNotify
628 debug("Server requested connection closure");
631 } catch(SocketException e) { /* incomplete close, thats ok */ }
637 log("SSL ALERT WARNING: desc: " + desc);
639 } else if(level == 2) {
640 throw new Exn("SSL ALERT FATAL: desc: " +desc);
642 throw new Exn("invalid alert level");
646 case 22: { // Handshake
647 int type = readRecordBuf[0];
648 int hslen = ((readRecordBuf[1]&0xff)<<16)|((readRecordBuf[2]&0xff)<<8)|((readRecordBuf[3]&0xff)<<0);
649 if(hslen > len - 4) throw new Exn("Multiple sequential handshake messages received after negotiation");
650 if(type == 0) { // HellloRequest
651 if(tls) sendAlert(false,100); // politely refuse, 100 == NoRegnegotiation
653 throw new Exn("Unexpected Handshake type: " + type);
656 default: throw new Exn("Unexpected protocol: " + proto);
661 private static void longToBytes(long l, byte[] buf, int off) {
662 for(int i=0;i<8;i++) buf[off+i] = (byte)(l>>>(8*(7-i)));
664 private void computeMAC(byte proto, byte[] payload, int off, int len, Digest digest, long sequenceNumber) {
666 longToBytes(sequenceNumber,mac,0);
668 mac[9] = 0x03; // version
670 mac[11] = (byte)(len>>>8);
671 mac[12] = (byte)(len>>>0);
673 digest.update(mac,0,13);
674 digest.update(payload,off,len);
675 digest.doFinal(mac,0);
677 longToBytes(sequenceNumber, mac, 0);
679 mac[9] = (byte)(len>>>8);
680 mac[10] = (byte)(len>>>0);
682 digest.update(mac, 0, 11);
683 digest.update(payload, off, len);
684 digest.doFinal(mac, 0);
688 private void sendCloseNotify() throws IOException { sendRecord((byte)21, new byte[] { 0x01, 0x00 }); }
689 private void sendAlert(boolean fatal, int message) throws IOException {
690 byte[] buf = new byte[] { fatal ? (byte)2 :(byte)1, (byte)message };
691 sendRecord((byte)21,buf);
699 // Shared digest objects
700 private MD5 masterMD5 = new MD5();
701 private SHA1 masterSHA1 = new SHA1();
703 private byte[] md5(byte[] in) { return md5( new byte[][] { in }); }
704 private byte[] md5(byte[][] inputs) {
706 for(int i=0; i<inputs.length; i++) masterMD5.update(inputs[i], 0, inputs[i].length);
707 byte[] ret = new byte[masterMD5.getDigestSize()];
708 masterMD5.doFinal(ret, 0);
712 private byte[] sha1(byte[] in) { return sha1(new byte[][] { in }); }
713 private byte[] sha1(byte[][] inputs) {
715 for(int i=0; i<inputs.length; i++) masterSHA1.update(inputs[i], 0, inputs[i].length);
716 byte[] ret = new byte[masterSHA1.getDigestSize()];
717 masterSHA1.doFinal(ret, 0);
722 PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);
723 L_S = length in bytes of secret;
724 L_S1 = L_S2 = ceil(L_S / 2);
726 The secret is partitioned into two halves (with the possibility of
727 one shared byte) as described above, S1 taking the first L_S1 bytes
728 and S2 the last L_S2 bytes.
730 P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
731 HMAC_hash(secret, A(2) + seed) +
732 HMAC_hash(secret, A(3) + seed) + ...
735 A(i) = HMAC_hash(secret, A(i-1))
737 private byte[] tlsPRF(int size,byte[] secret, byte[] label, byte[] seed) {
738 if(size > 140) throw new IllegalArgumentException("size > 140: " + size);
739 seed = concat(label,seed);
741 int half_length = (secret.length + 1) / 2;
742 byte[] s1 = new byte[half_length];
743 System.arraycopy(secret,0,s1,0,half_length);
744 byte[] s2 = new byte[half_length];
745 System.arraycopy(secret,secret.length - half_length, s2, 0, half_length);
747 Digest hmac_md5 = new HMAC(new MD5(),s1);
748 Digest hmac_sha = new HMAC(new SHA1(),s2);
750 byte[] md5out = new byte[144];
751 byte[] shaout = new byte[140];
752 byte[] digest = new byte[20];
756 hmac_md5.update(seed,0,seed.length);
757 hmac_md5.doFinal(digest,0);
761 hmac_md5.update(digest,0,16);
762 hmac_md5.update(seed,0,seed.length);
763 hmac_md5.doFinal(md5out,n);
764 hmac_md5.update(digest,0,16);
765 hmac_md5.doFinal(digest,0);
770 hmac_sha.update(seed,0,seed.length);
771 hmac_sha.doFinal(digest,0);
774 hmac_sha.update(digest,0,20);
775 hmac_sha.update(seed,0,seed.length);
776 hmac_sha.doFinal(shaout,n);
777 hmac_sha.update(digest,0,20);
778 hmac_sha.doFinal(digest,0);
782 byte[] ret = new byte[size];
783 for(int i=0;i<size;i++) ret[i] = (byte)(md5out[i] ^ shaout[i]);
787 public static class CBC implements Cipher {
788 private final Cipher c;
789 private final byte[] iv;
790 private final int blockSize;
791 private final boolean reverse;
792 public CBC(Cipher c, int blockSize, byte[] iv, boolean reverse) {
794 this.blockSize = blockSize;
796 this.reverse = reverse;
797 if(iv.length != blockSize) throw new IllegalArgumentException("iv.length != blockSize");
800 public void process(byte[] in, int inp, byte[] out, int outp, int len) {
801 if((len % blockSize) != 0) throw new IllegalArgumentException("buffer must be a multiple of block size");
804 for(int i=0;i<blockSize;i++) iv[i] ^= in[inp+i]; // mangle the cleartext
805 c.process(iv,0,out,outp,blockSize); // process it
806 System.arraycopy(out,outp,iv,0,blockSize); // copy the block to iv
808 c.process(in,inp,out,outp,blockSize); // process the ciphertext
809 for(int i=0;i<blockSize;i++) out[outp+i] ^= iv[i]; // mangle the cleartext
810 System.arraycopy(in,inp,iv,0,blockSize); // copy the ciphertext to iv
812 inp+=16; outp+=16; len-=16;
817 public static class SSLv3HMAC extends Digest {
818 private final Digest h;
819 private final byte[] digest;
820 private final byte[] key;
821 private final int padSize;
823 public int getDigestSize() { return h.getDigestSize(); }
825 public SSLv3HMAC(Digest h, byte[] key) {
828 switch(h.getDigestSize()) {
829 case 16: padSize = 48; break;
830 case 20: padSize = 40; break;
831 default: throw new IllegalArgumentException("unsupported digest size");
833 digest = new byte[h.getDigestSize()];
836 public void reset() {
838 h.update(key,0,key.length);
839 h.update(pad1,0,padSize);
841 public void update(byte[] b, int off, int len) { h.update(b,off,len); }
842 public void doFinal(byte[] out, int off){
844 h.update(key,0,key.length);
845 h.update(pad2,0,padSize);
846 h.update(digest,0,digest.length);
850 protected void processWord(byte[] in, int inOff) {}
851 protected void processLength(long bitLength) {}
852 protected void processBlock() {}
859 private static SecureRandom random = new SecureRandom();
860 public static synchronized void randomBytes(byte[] buf, int off, int len) {
861 byte[] bytes = new byte[len];
862 random.nextBytes(bytes);
863 System.arraycopy(bytes,0,buf,off,len);
866 public static byte[] concat(byte[] a, byte[] b) { return concat(new byte[][] { a, b }); }
867 public static byte[] concat(byte[] a, byte[] b, byte[] c) { return concat(new byte[][] { a, b, c }); }
868 public static byte[] concat(byte[][] inputs) {
870 for(int i=0; i<inputs.length; i++) total += inputs[i].length;
871 byte[] ret = new byte[total];
872 for(int i=0,pos=0; i<inputs.length;pos+=inputs[i].length,i++)
873 System.arraycopy(inputs[i], 0, ret, pos, inputs[i].length);
877 public static byte[] getBytes(String s) {
879 return s.getBytes("US-ASCII");
880 } catch (UnsupportedEncodingException e) {
881 return null; // will never happen
885 public static boolean eq(byte[] a, int aoff, byte[] b, int boff, int len){
886 for(int i=0;i<len;i++) if(a[aoff+i] != b[boff+i]) return false;
891 // InputStream/OutputStream/Socket interfaces
893 public OutputStream getOutputStream() { return sslOS; }
894 public InputStream getInputStream() { return sslIS; }
895 public synchronized void close() throws IOException {
897 if(negotiated != 0) {
900 // don't bother sending a close_notify back to the server
901 // this is an incomplete close which is allowed by the spec
908 private int read(byte[] buf, int off, int len) throws IOException {
909 if(pendingLength == 0) {
910 if(closed) return -1;
911 int readLen = readRecord((byte)23);
912 if(readLen == -1) return -1; // EOF
913 len = min(len,readLen);
914 System.arraycopy(readRecordBuf,0,buf,off,len);
915 if(readLen > len) System.arraycopy(readRecordBuf,len,pending,0,readLen-len);
917 pendingLength = readLen - len;
920 len = min(len,pendingLength);
921 System.arraycopy(pending,pendingStart,buf,off,len);
922 pendingLength -= len;
928 private void write(byte[] buf, int off, int len) throws IOException {
929 if(closed) throw new SocketException("Socket closed");
930 sendRecord((byte)23,buf,off,len);
934 private class SSLInputStream extends InputStream {
935 public int available() throws IOException {
936 synchronized(SSL.this) {
937 return negotiated != 0 ? pendingLength : rawIS.available();
940 public int read() throws IOException {
941 synchronized(SSL.this) {
942 if(negotiated==0) return rawIS.read();
943 if(pendingLength > 0) {
945 return pending[pendingStart++]&0xff;
947 byte[] buf = new byte[1];
949 return n == -1 ? -1 : buf[0]&0xff;
953 public int read(byte[] buf, int off, int len) throws IOException {
954 synchronized(SSL.this) {
955 return negotiated!=0 ? SSL.this.read(buf,off,len) : rawIS.read(buf,off,len);
958 public long skip(long n) throws IOException {
959 synchronized(SSL.this) {
960 if(negotiated==0) return rawIS.skip(n);
961 if(pendingLength > 0) {
962 n = min((int)n,pendingLength);
967 return super.skip(n);
972 private class SSLOutputStream extends OutputStream {
973 public void flush() throws IOException { rawOS.flush(); }
974 public void write(int b) throws IOException { write(new byte[] { (byte)b }); }
975 public void write(byte[] buf, int off, int len) throws IOException {
976 synchronized(SSL.this) {
978 SSL.this.write(buf,off,len);
980 rawOS.write(buf,off,len);
985 public static class Exn extends IOException { public Exn(String s) { super(s); } }
986 public static class PrematureCloseExn extends Exn {
987 public PrematureCloseExn() { super("Connection was closed by the remote WITHOUT a close_noify"); }
990 public static boolean debugOn = false;
991 private static void debug(Object o) { if(debugOn) System.err.println("[IbexSSL-Debug] " + o.toString()); }
992 private static void log(Object o) { System.err.println("[IbexSSL] " + o.toString()); }
994 public static void verifyCerts(X509.Certificate[] certs) throws DER.Exception, Exn {
997 } catch(RuntimeException e) {
999 throw new Exn("Error while verifying certificates: " + e);
1003 private static void verifyCerts_(X509.Certificate[] certs) throws DER.Exception, Exn {
1004 int last = certs.length-1;
1005 for(int i=0;i<certs.length;i++) {
1006 debug("Cert " + i + ": " + certs[i].subject + " ok");
1007 if(!certs[i].isValid())
1008 throw new Exn("Certificate " + i + " in certificate chain is not valid (" + certs[i].startDate + " - " + certs[i].endDate + ")");
1010 X509.Certificate.BC bc = certs[i].basicContraints;
1015 if(!bc.isCA) throw new Exn("non-CA certificate used for signing");
1016 if(bc.pathLenConstraint != null && bc.pathLenConstraint.longValue() < i-1) throw new Exn("CA cert can't be used this deep");
1019 if(i != certs.length - 1) {
1020 if(!certs[i].issuer.equals(certs[i+1].subject))
1021 throw new Exn("Issuer for certificate " + i + " does not match next in chain");
1022 if(!certs[i].isSignedBy(certs[i+1]))
1023 throw new Exn("Certificate " + i + " in chain is not signed by the next certificate");
1027 X509.Certificate cert = certs[last];
1029 RSA.PublicKey pks = (RSA.PublicKey) caKeys.get(cert.issuer);
1030 if(pks == null) throw new Exn("Certificate is signed by an unknown CA (" + cert.issuer + ")");
1031 if(!cert.isSignedWith(pks)) throw new Exn("Certificate is not signed by its CA");
1032 log("" + cert.subject + " is signed by " + cert.issuer);
1035 public static void addCACert(byte[] b) throws IOException { addCACert(new ByteArrayInputStream(b)); }
1036 public static void addCACert(InputStream is) throws IOException { addCACert(new X509.Certificate(is)); }
1037 public static void addCACert(X509.Certificate cert) throws DER.Exception { addCAKey(cert.subject,cert.getRSAPublicKey()); }
1038 public static void addCAKey(X509.Name subject, RSA.PublicKey pks) {
1039 synchronized(caKeys) {
1040 if(caKeys.get(subject) != null)
1041 throw new IllegalArgumentException(subject.toString() + " already exists!");
1042 caKeys.put(subject,pks);
1048 // This will force a <clinit> which'll load the certs
1049 Class.forName("org.ibex.net.ssl.RootCerts");
1050 log("Loaded root keys from org.ibex.net.ssl.RootCerts");
1051 } catch(ClassNotFoundException e) {
1052 InputStream is = SSL.class.getClassLoader().getResourceAsStream("org.ibex/net/ssl/rootcerts.dat");
1055 addCompactCAKeys(is);
1056 log("Loaded root certs from rootcerts.dat");
1057 } catch(IOException e2) {
1058 log("Error loading certs from rootcerts.dat: " + e2.getMessage());
1064 public static int addCompactCAKeys(InputStream is) throws IOException {
1065 synchronized(caKeys) {
1067 Vector seq = (Vector) new DER.InputStream(is).readObject();
1068 for(Enumeration e = seq.elements(); e.hasMoreElements();) {
1069 Vector seq2 = (Vector) e.nextElement();
1070 X509.Name subject = new X509.Name(seq2.elementAt(0));
1071 RSA.PublicKey pks = new RSA.PublicKey(seq2.elementAt(1));
1072 addCAKey(subject,pks);
1075 } catch(RuntimeException e) {
1076 e.printStackTrace();
1077 throw new IOException("error while reading stream: " + e);
1082 public static synchronized void setVerifyCallback(VerifyCallback cb) { verifyCallback = cb; }
1085 public static class State {
1087 byte[] masterSecret;
1088 State(byte[] sessionID, byte[] masterSecret) {
1089 this.sessionID = sessionID;
1090 this.masterSecret = masterSecret;
1094 public interface VerifyCallback {
1095 public boolean checkCerts(X509.Certificate[] certs, String hostname, Exn exn);
1099 private static final int min(int a, int b) { return a < b ? a : b; }