1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
6 * org.ibex.net.SSL - By Brian Alliet
7 * Copyright (C) 2004 Brian Alliet
9 * Based on TinySSL by Adam Megacz
10 * Copyright (C) 2003 Adam Megacz <adam@xwt.org> all rights reserved.
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 private String hostname;
33 private int negotiated;
35 private boolean tls = true;
38 private final DataInputStream rawIS;
39 private final DataOutputStream rawOS;
41 private final InputStream sslIS;
42 private final OutputStream sslOS;
44 private byte[] sessionID;
46 private Digest clientWriteMACDigest;
47 private Digest serverWriteMACDigest;
48 private byte[] masterSecret;
53 private long serverSequenceNumber;
54 private long clientSequenceNumber;
57 private boolean closed;
59 // These are only used during negotiation
60 private byte[] serverRandom;
61 private byte[] clientRandom;
62 private byte[] preMasterSecret;
67 private byte[] pending = new byte[16384];
68 private int pendingStart;
69 private int pendingLength;
71 private byte[] sendRecordBuf = new byte[16384];
73 private int handshakeDataStart;
74 private int handshakeDataLength;
75 private byte[] readRecordBuf = new byte[16384+20]; // 20 == sizeof(sha1 hash)
76 private byte[] readRecordScratch = new byte[16384+20];
78 private ByteArrayOutputStream handshakesBuffer;
83 private final static byte[] pad1 = new byte[48];
84 private final static byte[] pad2 = new byte[48];
85 private final static byte[] pad1_sha = new byte[40];
86 private final static byte[] pad2_sha = new byte[40];
89 for(int i=0; i<pad1.length; i++) pad1[i] = (byte)0x36;
90 for(int i=0; i<pad2.length; i++) pad2[i] = (byte)0x5C;
91 for(int i=0; i<pad1_sha.length; i++) pad1_sha[i] = (byte)0x36;
92 for(int i=0; i<pad2_sha.length; i++) pad2_sha[i] = (byte)0x5C;
95 private final static Hashtable caKeys = new Hashtable();
96 private static VerifyCallback verifyCallback;
101 public SSL(String host) throws IOException { this(host,443); }
102 public SSL(String host, int port) throws IOException { this(host,port,true); }
103 public SSL(String host, int port, boolean negotiate) throws IOException { this(host,port,negotiate,null); }
104 public SSL(String host, int port, State state) throws IOException { this(host,port,true,state); }
105 public SSL(String host, int port, boolean negotiate, State state) throws IOException {
108 rawIS = new DataInputStream(new BufferedInputStream(super.getInputStream()));
109 rawOS = new DataOutputStream(new BufferedOutputStream(super.getOutputStream()));
110 sslIS = new SSLInputStream();
111 sslOS = new SSLOutputStream();
112 if(negotiate) negotiate(state);
115 public synchronized void setTLS(boolean b) { if(negotiated!=0) throw new IllegalStateException("already negotiated"); tls = b; }
117 public void negotiate() throws IOException { negotiate(null); }
118 public synchronized void negotiate(State state) throws IOException {
119 if(negotiated != 0) throw new IllegalStateException("already negotiated");
121 handshakesBuffer = new ByteArrayOutputStream();
124 sendClientHello(state != null ? state.sessionID : null);
126 debug("sent ClientHello (" + (tls?"TLSv1.0":"SSLv3.0")+")");
128 receiveServerHello();
129 debug("got ServerHello (" + (tls?"TLSv1.0":"SSLv3.0")+")");
132 state != null && sessionID.length == state.sessionID.length &&
133 eq(state.sessionID,0,sessionID,0,sessionID.length);
136 negotiateResume(state);
140 // we're done with these now
141 clientRandom = serverRandom = preMasterSecret = null;
142 handshakesBuffer = null;
144 log("Negotiation with " + hostname + " complete (" + (tls?"TLSv1.0":"SSLv3.0")+")");
146 if((negotiated & 3) != 3) {
148 try { super.close(); } catch(IOException e) { /* ignore */ }
154 private void negotiateResume(State state) throws IOException {
155 masterSecret = state.masterSecret;
158 log("initializec crypto");
160 receiveChangeCipherSpec();
161 debug("Received ChangeCipherSpec");
164 debug("Received Finished");
166 sendChangeCipherSpec();
167 debug("Sent ChangeCipherSpec");
170 debug("Sent Finished");
173 private void negotiateNew() throws IOException {
174 X509.Certificate[] certs = receiveServerCertificates();
175 debug("got Certificate");
177 boolean gotCertificateRequest = false;
179 byte[] buf = readHandshake();
181 case 14: // ServerHelloDone
182 if(buf.length != 4) throw new Exn("ServerHelloDone contained trailing garbage");
183 debug("got ServerHelloDone");
185 case 13: // CertificateRequest
186 debug("Got a CertificateRequest message but we don't suport client certificates");
187 gotCertificateRequest = true;
190 throw new Exn("unknown handshake type " + buf[0]);
194 if(gotCertificateRequest)
195 sendHandshake((byte)11,new byte[3]); // send empty cert list
198 if(!hostname.equalsIgnoreCase(certs[0].getCN()))
199 throw new Exn("Certificate is for " + certs[0].getCN() + " not " + hostname);
202 if(verifyCallback == null) { /* throw e; */ } else
203 synchronized(SSL.class) {
204 if(!verifyCallback.checkCerts(certs,hostname,e)) throw e;
208 computeMasterSecret();
210 sendClientKeyExchange(certs[0]);
211 debug("sent ClientKeyExchange");
215 sendChangeCipherSpec();
216 debug("sent ChangeCipherSpec");
219 debug("sent Finished");
222 receiveChangeCipherSpec();
223 debug("got ChangeCipherSpec");
226 debug("got Finished");
229 public State getSessionState() {
230 if((negotiated&3)!=3 || !closed || warnings != 0) return null;
231 return new State(sessionID,masterSecret);
233 public boolean isActive() { return !closed; }
234 public boolean isNegotiated() { return (negotiated&3) == 3; }
236 private void sendClientHello(byte[] sessionID) throws IOException {
237 if(sessionID != null && sessionID.length > 256) throw new IllegalArgumentException("sessionID");
238 // 2 = version, 32 = randomvalue, 1 = sessionID size, 2 = cipher list size, 4 = the two ciphers,
239 // 2 = compression length/no compression
241 byte[] buf = new byte[2+32+1+(sessionID == null ? 0 : sessionID.length)+2+2+4];
242 buf[p++] = 0x03; // major version
243 buf[p++] = tls ? (byte)0x01 : (byte)0x00;
245 clientRandom = new byte[32];
246 int now = (int)(System.currentTimeMillis() / 1000L);
247 new Random().nextBytes(clientRandom);
248 clientRandom[0] = (byte)(now>>>24);
249 clientRandom[1] = (byte)(now>>>16);
250 clientRandom[2] = (byte)(now>>>8);
251 clientRandom[3] = (byte)(now>>>0);
252 System.arraycopy(clientRandom,0,buf,p,32);
255 buf[p++] = sessionID != null ? (byte)sessionID.length : 0;
256 if(sessionID != null && sessionID.length != 0) System.arraycopy(sessionID,0,buf,p,sessionID.length);
257 p += sessionID != null ? sessionID.length : 0;
258 buf[p++] = 0x00; // 4 bytes of ciphers
260 buf[p++] = 0x00; // SSL_RSA_WITH_RC4_128_SHA
262 buf[p++] = 0x00; // SSL_RSA_WITH_RC4_128_MD5
268 sendHandshake((byte)1,buf);
272 private void receiveServerHello() throws IOException {
274 byte[] buf = readHandshake();
275 if(buf[0] != 2) throw new Exn("expected a ServerHello message");
277 if(buf.length < 6 + 32 + 1) throw new Exn("ServerHello too small");
278 if(buf.length < 6 + 32 + 1 + buf[6+32] + 3) throw new Exn("ServerHello too small " + buf.length+" "+buf[6+32]);
280 if(buf[4] != 0x03 || !(buf[5]==0x00 || buf[5]==0x01)) throw new Exn("server wants to use version " + buf[4] + "." + buf[5]);
281 tls = buf[5] == 0x01;
283 serverRandom = new byte[32];
284 System.arraycopy(buf,p,serverRandom,0,32);
286 sessionID = new byte[buf[p++]&0xff];
287 if(sessionID.length != 0) System.arraycopy(buf,p,sessionID,0,sessionID.length);
288 p += sessionID.length;
289 int cipher = ((buf[p]&0xff)<<8) | (buf[p+1]&0xff);
292 case 0x0004: sha = false; debug("Using SSL_RSA_WITH_RC4_128_MD5"); break;
293 case 0x0005: sha = true; debug("Using SSL_RSA_WITH_RC4_128_SHA"); break;
294 default: throw new Exn("Unsupported cipher " + cipher);
296 mac = new byte[sha ? 20 : 16];
297 if(buf[p++] != 0x0) throw new Exn("unsupported compression " + buf[p-1]);
300 private X509.Certificate[] receiveServerCertificates() throws IOException {
301 byte[] buf = readHandshake();
302 if(buf[0] != 11) throw new Exn("expected a Certificate message");
303 if((((buf[4]&0xff)<<16)|((buf[5]&0xff)<<8)|((buf[6]&0xff)<<0)) != buf.length-7) throw new Exn("size mismatch in Certificate message");
307 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++;
308 if(count == 0) throw new Exn("server didn't provide any certificates");
309 X509.Certificate[] certs = new X509.Certificate[count];
311 while(p < buf.length) {
312 int len = ((buf[p+0]&0xff)<<16)|((buf[p+1]&0xff)<<8)|((buf[p+2]&0xff)<<0);
314 if(p + len > buf.length) throw new Exn("Certificate message cut short");
315 certs[count++] = new X509.Certificate(new ByteArrayInputStream(buf,p,len));
321 private void sendClientKeyExchange(X509.Certificate serverCert) throws IOException {
322 byte[] encryptedPreMasterSecret;
323 RSA.PublicKey pks = serverCert.getRSAPublicKey();
324 PKCS1 pkcs1 = new PKCS1(new RSA(pks.modulus,pks.exponent,false),random);
325 encryptedPreMasterSecret = pkcs1.encode(preMasterSecret);
328 buf = new byte[encryptedPreMasterSecret.length+2];
329 buf[0] = (byte) (encryptedPreMasterSecret.length>>>8);
330 buf[1] = (byte) (encryptedPreMasterSecret.length>>>0);
331 System.arraycopy(encryptedPreMasterSecret,0,buf,2,encryptedPreMasterSecret.length);
333 // ugh... netscape didn't send the length bytes and now every SSLv3 implementation
334 // must implement this bug
335 buf = encryptedPreMasterSecret;
337 sendHandshake((byte)16,buf);
340 private void sendChangeCipherSpec() throws IOException {
341 sendRecord((byte)20,new byte[] { 0x01 });
344 private void computeMasterSecret() {
345 preMasterSecret = new byte[48];
346 preMasterSecret[0] = 0x03; // version_high
347 preMasterSecret[1] = tls ? (byte) 0x01 : (byte) 0x00; // version_low
348 randomBytes(preMasterSecret,2,46);
351 masterSecret = tlsPRF(48,preMasterSecret,getBytes("master secret"),concat(clientRandom,serverRandom));
353 masterSecret = concat(new byte[][] {
354 md5(new byte[][] { preMasterSecret,
355 sha1(new byte[][] { new byte[] { 0x41 }, preMasterSecret, clientRandom, serverRandom })}),
356 md5(new byte[][] { preMasterSecret,
357 sha1(new byte[][] { new byte[] { 0x42, 0x42 }, preMasterSecret, clientRandom, serverRandom })}),
358 md5(new byte[][] { preMasterSecret,
359 sha1(new byte[][] { new byte[] { 0x43, 0x43, 0x43 }, preMasterSecret, clientRandom, serverRandom })})
364 public void initCrypto() {
368 keyMaterial = tlsPRF(
369 (mac.length + 16 + 0)*2, // MAC len + key len + iv len
371 getBytes("key expansion"),
372 concat(serverRandom,clientRandom)
375 keyMaterial = new byte[] { };
376 for(int i=0; keyMaterial.length < 72; i++) {
377 byte[] crap = new byte[i + 1];
378 for(int j=0; j<crap.length; j++) crap[j] = (byte)(((byte)0x41) + ((byte)i));
379 keyMaterial = concat(new byte[][] { keyMaterial,
380 md5(new byte[][] { masterSecret,
381 sha1(new byte[][] { crap, masterSecret, serverRandom, clientRandom }) }) });
385 byte[] clientWriteMACSecret = new byte[mac.length];
386 byte[] serverWriteMACSecret = new byte[mac.length];
387 byte[] clientWriteKey = new byte[16];
388 byte[] serverWriteKey = new byte[16];
391 System.arraycopy(keyMaterial, p, clientWriteMACSecret, 0, mac.length); p += mac.length;
392 System.arraycopy(keyMaterial, p, serverWriteMACSecret, 0, mac.length); p += mac.length;
393 System.arraycopy(keyMaterial, p, clientWriteKey, 0, 16); p += 16;
394 System.arraycopy(keyMaterial, p, serverWriteKey, 0, 16); p += 16;
398 writeRC4 = new RC4(clientWriteKey);
399 inner = sha ? (Digest)new SHA1() : (Digest)new MD5();
400 clientWriteMACDigest = tls ? (Digest) new HMAC(inner,clientWriteMACSecret) : (Digest)new SSLv3HMAC(inner,clientWriteMACSecret);
402 readRC4 = new RC4(serverWriteKey);
403 inner = sha ? (Digest)new SHA1() : (Digest)new MD5();
404 serverWriteMACDigest = tls ? (Digest)new HMAC(inner,serverWriteMACSecret) : (Digest)new SSLv3HMAC(inner,serverWriteMACSecret);
407 private void sendFinished() throws IOException {
408 byte[] handshakes = handshakesBuffer.toByteArray();
410 sendHandshake((byte)20, tlsPRF(
413 getBytes("client finished"),
414 concat(md5(handshakes),sha1(handshakes))));
417 sendHandshake((byte)20, concat(new byte[][] {
418 md5(new byte[][] { masterSecret, pad2,
419 md5(new byte[][] { handshakes, new byte[] { (byte)0x43, (byte)0x4C, (byte)0x4E, (byte)0x54 },
420 masterSecret, pad1 }) }),
421 sha1(new byte[][] { masterSecret, pad2_sha,
422 sha1(new byte[][] { handshakes, new byte[] { (byte)0x43, (byte)0x4C, (byte)0x4E, (byte)0x54 },
423 masterSecret, pad1_sha } ) })
428 private void receiveChangeCipherSpec() throws IOException {
429 int size = readRecord((byte)20);
430 if(size == -1) throw new Exn("got eof when expecting a ChangeCipherSpec message");
431 if(size != 1 || readRecordBuf[0] != 0x01) throw new Exn("Invalid ChangeCipherSpec message");
434 private void receieveFinished() throws IOException {
435 byte[] handshakes = handshakesBuffer.toByteArray();
436 byte[] buf = readHandshake();
437 if(buf[0] != 20) throw new Exn("expected a Finished message");
441 if(buf.length != 4 + 12) throw new Exn("Finished message too short");
444 getBytes("server finished"),
445 concat(md5(handshakes),sha1(handshakes)));
447 if(buf.length != 4 + 16 +20) throw new Exn("Finished message too short");
448 expected = concat(new byte[][] {
449 md5(new byte[][] { masterSecret, pad2,
450 md5(new byte[][] { handshakes, new byte[] { (byte)0x53, (byte)0x52, (byte)0x56, (byte)0x52 },
451 masterSecret, pad1 }) }),
452 sha1(new byte[][] { masterSecret, pad2_sha,
453 sha1(new byte[][] { handshakes, new byte[] { (byte)0x53, (byte)0x52, (byte)0x56, (byte)0x52 },
454 masterSecret, pad1_sha } ) } ) } );
456 if(!eq(expected,0,buf,4,expected.length)) throw new Exn("server finished message mismatch");
459 private void flush() throws IOException { rawOS.flush(); }
461 private void sendHandshake(byte type, byte[] payload) throws IOException {
462 if(payload.length > (1<<24)) throw new IllegalArgumentException("payload.length");
463 byte[] buf = new byte[4+payload.length];
465 buf[1] = (byte)(payload.length>>>16);
466 buf[2] = (byte)(payload.length>>>8);
467 buf[3] = (byte)(payload.length>>>0);
468 System.arraycopy(payload,0,buf,4,payload.length);
469 handshakesBuffer.write(buf);
470 sendRecord((byte)22,buf);
473 private void sendRecord(byte proto, byte[] buf) throws IOException { sendRecord(proto,buf,0,buf.length); }
474 private void sendRecord(byte proto, byte[] payload, int off, int totalLen) throws IOException {
475 int macLength = (negotiated & 1) != 0 ? mac.length : 0;
476 while(totalLen > 0) {
477 int len = min(totalLen,16384-macLength);
478 rawOS.writeByte(proto);
479 rawOS.writeShort(tls ? 0x0301 : 0x0300);
480 if((negotiated & 1) != 0) {
481 computeMAC(proto,payload,off,len,clientWriteMACDigest,clientSequenceNumber);
482 // FEATURE: Encode in place
483 writeRC4.process(payload,off,sendRecordBuf,0,len);
484 writeRC4.process(mac,0,sendRecordBuf,len,macLength);
485 rawOS.writeShort(len + macLength);
486 rawOS.write(sendRecordBuf,0, len +macLength);
487 clientSequenceNumber++;
489 rawOS.writeShort(len);
490 rawOS.write(payload,off,len);
497 private byte[] readHandshake() throws IOException {
498 if(handshakeDataLength == 0) {
499 handshakeDataStart = 0;
500 handshakeDataLength = readRecord((byte)22);
501 if(handshakeDataLength == -1) throw new Exn("got eof when expecting a handshake packet");
503 byte[] buf = readRecordBuf;
504 int len = ((buf[handshakeDataStart+1]&0xff)<<16)|((buf[handshakeDataStart+2]&0xff)<<8)|((buf[handshakeDataStart+3]&0xff)<<0);
505 // Handshake messages can theoretically span multiple records, but in practice this does not occur
506 if(len > handshakeDataLength) {
507 sendAlert(true,10); // 10 == unexpected message
508 throw new Exn("handshake message size too large " + len + " vs " + (handshakeDataLength-handshakeDataStart));
510 byte[] ret = new byte[4+len];
511 System.arraycopy(buf,handshakeDataStart,ret,0,ret.length);
512 handshakeDataLength -= ret.length;
513 handshakeDataStart += ret.length;
514 handshakesBuffer.write(ret);
518 private int readRecord(byte reqProto) throws IOException {
519 int macLength = (negotiated & 2) != 0 ? mac.length : 0;
525 proto = rawIS.readByte();
526 } catch(EOFException e) {
527 // this may or may not be an error. it is up to the application protocol
530 //throw new PrematureCloseExn();
534 version = rawIS.readShort();
535 if(version != 0x0300 && version != 0x0301) throw new Exn("invalid version ");
536 len = rawIS.readShort();
537 if(len <= 0 || len > 16384+((negotiated&2)!=0 ? macLength : 0)) throw new Exn("invalid length " + len);
538 rawIS.readFully((negotiated&2)!=0 ? readRecordScratch : readRecordBuf,0,len);
539 } catch(EOFException e) {
540 // an EOF here is always an error (we don't pass the EOF back on to the app
541 // because it isn't a "legitimate" eof)
542 throw new Exn("Hit EOF too early");
545 if((negotiated & 2) != 0) {
546 if(len < macLength) throw new Exn("packet size < macLength");
547 // FEATURE: Decode in place
548 readRC4.process(readRecordScratch,0,readRecordBuf,0,len);
549 computeMAC(proto,readRecordBuf,0,len-macLength,serverWriteMACDigest,serverSequenceNumber);
550 for(int i=0;i<macLength;i++)
551 if(mac[i] != readRecordBuf[len-macLength+i])
552 throw new Exn("mac mismatch");
554 serverSequenceNumber++;
557 if(proto == reqProto) return len;
561 if(len != 2) throw new Exn("invalid lengh for alert");
562 int level = readRecordBuf[0];
563 int desc = readRecordBuf[1];
565 if(desc == 0) { // CloseNotify
566 debug("Server requested connection closure");
569 } catch(SocketException e) { /* incomplete close, thats ok */ }
575 log("SSL ALERT WARNING: desc: " + desc);
577 } else if(level == 2) {
578 throw new Exn("SSL ALERT FATAL: desc: " +desc);
580 throw new Exn("invalid alert level");
584 case 22: { // Handshake
585 int type = readRecordBuf[0];
586 int hslen = ((readRecordBuf[1]&0xff)<<16)|((readRecordBuf[2]&0xff)<<8)|((readRecordBuf[3]&0xff)<<0);
587 if(hslen > len - 4) throw new Exn("Multiple sequential handshake messages received after negotiation");
588 if(type == 0) { // HellloRequest
589 if(tls) sendAlert(false,100); // politely refuse, 100 == NoRegnegotiation
591 throw new Exn("Unexpected Handshake type: " + type);
594 default: throw new Exn("Unexpected protocol: " + proto);
599 private static void longToBytes(long l, byte[] buf, int off) {
600 for(int i=0;i<8;i++) buf[off+i] = (byte)(l>>>(8*(7-i)));
602 private void computeMAC(byte proto, byte[] payload, int off, int len, Digest digest, long sequenceNumber) {
604 longToBytes(sequenceNumber,mac,0);
606 mac[9] = 0x03; // version
608 mac[11] = (byte)(len>>>8);
609 mac[12] = (byte)(len>>>0);
611 digest.update(mac,0,13);
612 digest.update(payload,off,len);
613 digest.doFinal(mac,0);
615 longToBytes(sequenceNumber, mac, 0);
617 mac[9] = (byte)(len>>>8);
618 mac[10] = (byte)(len>>>0);
620 digest.update(mac, 0, 11);
621 digest.update(payload, off, len);
622 digest.doFinal(mac, 0);
626 private void sendCloseNotify() throws IOException { sendRecord((byte)21, new byte[] { 0x01, 0x00 }); }
627 private void sendAlert(boolean fatal, int message) throws IOException {
628 byte[] buf = new byte[] { fatal ? (byte)2 :(byte)1, (byte)message };
629 sendRecord((byte)21,buf);
637 // Shared digest objects
638 private MD5 masterMD5 = new MD5();
639 private SHA1 masterSHA1 = new SHA1();
641 private byte[] md5(byte[] in) { return md5( new byte[][] { in }); }
642 private byte[] md5(byte[][] inputs) {
644 for(int i=0; i<inputs.length; i++) masterMD5.update(inputs[i], 0, inputs[i].length);
645 byte[] ret = new byte[masterMD5.getDigestSize()];
646 masterMD5.doFinal(ret, 0);
650 private byte[] sha1(byte[] in) { return sha1(new byte[][] { in }); }
651 private byte[] sha1(byte[][] inputs) {
653 for(int i=0; i<inputs.length; i++) masterSHA1.update(inputs[i], 0, inputs[i].length);
654 byte[] ret = new byte[masterSHA1.getDigestSize()];
655 masterSHA1.doFinal(ret, 0);
660 PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);
661 L_S = length in bytes of secret;
662 L_S1 = L_S2 = ceil(L_S / 2);
664 The secret is partitioned into two halves (with the possibility of
665 one shared byte) as described above, S1 taking the first L_S1 bytes
666 and S2 the last L_S2 bytes.
668 P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
669 HMAC_hash(secret, A(2) + seed) +
670 HMAC_hash(secret, A(3) + seed) + ...
673 A(i) = HMAC_hash(secret, A(i-1))
675 private byte[] tlsPRF(int size,byte[] secret, byte[] label, byte[] seed) {
676 if(size > 112) throw new IllegalArgumentException("size > 112");
677 seed = concat(label,seed);
679 int half_length = (secret.length + 1) / 2;
680 byte[] s1 = new byte[half_length];
681 System.arraycopy(secret,0,s1,0,half_length);
682 byte[] s2 = new byte[half_length];
683 System.arraycopy(secret,secret.length - half_length, s2, 0, half_length);
685 Digest hmac_md5 = new HMAC(new MD5(),s1);
686 Digest hmac_sha = new HMAC(new SHA1(),s2);
688 byte[] md5out = new byte[112];
689 byte[] shaout = new byte[120];
690 byte[] digest = new byte[20];
694 hmac_md5.update(seed,0,seed.length);
695 hmac_md5.doFinal(digest,0);
699 hmac_md5.update(digest,0,16);
700 hmac_md5.update(seed,0,seed.length);
701 hmac_md5.doFinal(md5out,n);
702 hmac_md5.update(digest,0,16);
703 hmac_md5.doFinal(digest,0);
708 hmac_sha.update(seed,0,seed.length);
709 hmac_sha.doFinal(digest,0);
712 hmac_sha.update(digest,0,20);
713 hmac_sha.update(seed,0,seed.length);
714 hmac_sha.doFinal(shaout,n);
715 hmac_sha.update(digest,0,20);
716 hmac_sha.doFinal(digest,0);
720 byte[] ret = new byte[size];
721 for(int i=0;i<size;i++) ret[i] = (byte)(md5out[i] ^ shaout[i]);
725 public static class SSLv3HMAC extends Digest {
726 private final Digest h;
727 private final byte[] digest;
728 private final byte[] key;
729 private final int padSize;
731 public int getDigestSize() { return h.getDigestSize(); }
733 public SSLv3HMAC(Digest h, byte[] key) {
736 switch(h.getDigestSize()) {
737 case 16: padSize = 48; break;
738 case 20: padSize = 40; break;
739 default: throw new IllegalArgumentException("unsupported digest size");
741 digest = new byte[h.getDigestSize()];
744 public void reset() {
746 h.update(key,0,key.length);
747 h.update(pad1,0,padSize);
749 public void update(byte[] b, int off, int len) { h.update(b,off,len); }
750 public void doFinal(byte[] out, int off){
752 h.update(key,0,key.length);
753 h.update(pad2,0,padSize);
754 h.update(digest,0,digest.length);
758 protected void processWord(byte[] in, int inOff) {}
759 protected void processLength(long bitLength) {}
760 protected void processBlock() {}
767 private static SecureRandom random = new SecureRandom();
768 public static synchronized void randomBytes(byte[] buf, int off, int len) {
769 byte[] bytes = new byte[len];
770 random.nextBytes(bytes);
771 System.arraycopy(bytes,0,buf,off,len);
774 public static byte[] concat(byte[] a, byte[] b) { return concat(new byte[][] { a, b }); }
775 public static byte[] concat(byte[] a, byte[] b, byte[] c) { return concat(new byte[][] { a, b, c }); }
776 public static byte[] concat(byte[][] inputs) {
778 for(int i=0; i<inputs.length; i++) total += inputs[i].length;
779 byte[] ret = new byte[total];
780 for(int i=0,pos=0; i<inputs.length;pos+=inputs[i].length,i++)
781 System.arraycopy(inputs[i], 0, ret, pos, inputs[i].length);
785 public static byte[] getBytes(String s) {
787 return s.getBytes("US-ASCII");
788 } catch (UnsupportedEncodingException e) {
789 return null; // will never happen
793 public static boolean eq(byte[] a, int aoff, byte[] b, int boff, int len){
794 for(int i=0;i<len;i++) if(a[aoff+i] != b[boff+i]) return false;
799 // InputStream/OutputStream/Socket interfaces
801 public OutputStream getOutputStream() { return sslOS; }
802 public InputStream getInputStream() { return sslIS; }
803 public synchronized void close() throws IOException {
805 if(negotiated != 0) {
808 // don't bother sending a close_notify back to the server
809 // this is an incomplete close which is allowed by the spec
816 private int read(byte[] buf, int off, int len) throws IOException {
817 if(pendingLength == 0) {
818 if(closed) return -1;
819 int readLen = readRecord((byte)23);
820 if(readLen == -1) return -1; // EOF
821 len = min(len,readLen);
822 System.arraycopy(readRecordBuf,0,buf,off,len);
823 if(readLen > len) System.arraycopy(readRecordBuf,len,pending,0,readLen-len);
825 pendingLength = readLen - len;
828 len = min(len,pendingLength);
829 System.arraycopy(pending,pendingStart,buf,off,len);
830 pendingLength -= len;
836 private void write(byte[] buf, int off, int len) throws IOException {
837 if(closed) throw new SocketException("Socket closed");
838 sendRecord((byte)23,buf,off,len);
842 private class SSLInputStream extends InputStream {
843 public int available() throws IOException {
844 synchronized(SSL.this) {
845 return negotiated != 0 ? pendingLength : rawIS.available();
848 public int read() throws IOException {
849 synchronized(SSL.this) {
850 if(negotiated==0) return rawIS.read();
851 if(pendingLength > 0) {
853 return pending[pendingStart++];
855 byte[] buf = new byte[1];
857 return n == -1 ? -1 : buf[0]&0xff;
861 public int read(byte[] buf, int off, int len) throws IOException {
862 synchronized(SSL.this) {
863 return negotiated!=0 ? SSL.this.read(buf,off,len) : rawIS.read(buf,off,len);
866 public long skip(long n) throws IOException {
867 synchronized(SSL.this) {
868 if(negotiated==0) return rawIS.skip(n);
869 if(pendingLength > 0) {
870 n = min((int)n,pendingLength);
875 return super.skip(n);
880 private class SSLOutputStream extends OutputStream {
881 public void flush() throws IOException { rawOS.flush(); }
882 public void write(int b) throws IOException { write(new byte[] { (byte)b }); }
883 public void write(byte[] buf, int off, int len) throws IOException {
884 synchronized(SSL.this) {
886 SSL.this.write(buf,off,len);
888 rawOS.write(buf,off,len);
893 public static class Exn extends IOException { public Exn(String s) { super(s); } }
894 public static class PrematureCloseExn extends Exn {
895 public PrematureCloseExn() { super("Connection was closed by the remote WITHOUT a close_noify"); }
898 public static boolean debugOn = false;
899 private static void debug(Object o) { if(debugOn) System.err.println("[BriSSL-Debug] " + o.toString()); }
900 private static void log(Object o) { System.err.println("[BriSSL] " + o.toString()); }
902 private static void verifyCerts(X509.Certificate[] certs) throws DER.Exception, Exn {
905 } catch(RuntimeException e) {
907 throw new Exn("Error while verifying certificates: " + e);
911 private static void verifyCerts_(X509.Certificate[] certs) throws DER.Exception, Exn {
912 boolean ignoreLast = false;
913 for(int i=0;i<certs.length;i++) {
914 debug("Cert " + i + ": " + certs[i].subject + " ok");
915 if(!certs[i].isValid())
916 throw new Exn("Certificate " + i + " in certificate chain is not valid (" + certs[i].startDate + " - " + certs[i].endDate + ")");
918 X509.Certificate.BC bc = certs[i].basicContraints;
920 if(i == certs.length - 1) {
924 throw new Exn("CA-cert lacks Basic Constraints");
926 if(!bc.isCA) throw new Exn("non-CA certificate used for signing");
927 if(bc.pathLenConstraint != null && bc.pathLenConstraint.longValue() < i-1) throw new Exn("CA cert can't be used this deep");
930 if(i != certs.length - 1) {
931 if(!certs[i].issuer.equals(certs[i+1].subject))
932 throw new Exn("Issuer for certificate " + i + " does not match next in chain");
933 if(!certs[i].isSignedBy(certs[i+1]))
934 throw new Exn("Certificate " + i + " in chain is not signed by the next certificate");
938 X509.Certificate cert = certs[ignoreLast ? certs.length - 2 : certs.length-1];
940 RSA.PublicKey pks = (RSA.PublicKey) caKeys.get(cert.issuer);
941 if(pks == null) throw new Exn("Certificate is signed by an unknown CA (" + cert.issuer + ")");
942 if(!cert.isSignedWith(pks)) throw new Exn("Certificate is not signed by its CA");
943 log("" + cert.subject + " is signed by " + cert.issuer);
946 public static void addCACert(byte[] b) throws IOException { addCACert(new ByteArrayInputStream(b)); }
947 public static void addCACert(InputStream is) throws IOException { addCACert(new X509.Certificate(is)); }
948 public static void addCACert(X509.Certificate cert) throws DER.Exception { addCAKey(cert.subject,cert.getRSAPublicKey()); }
949 public static void addCAKey(X509.Name subject, RSA.PublicKey pks) {
950 synchronized(caKeys) {
951 if(caKeys.get(subject) != null)
952 throw new IllegalArgumentException(subject.toString() + " already exists!");
953 caKeys.put(subject,pks);
959 // This will force a <clinit> which'll load the certs
960 Class.forName("org.ibex.net.ssl.RootCerts");
961 log("Loaded root keys from org.ibex.net.ssl.RootCerts");
962 } catch(ClassNotFoundException e) {
963 InputStream is = SSL.class.getClassLoader().getResourceAsStream("org.ibex/net/ssl/rootcerts.dat");
966 addCompactCAKeys(is);
967 log("Loaded root certs from rootcerts.dat");
968 } catch(IOException e2) {
969 log("Error loading certs from rootcerts.dat: " + e2.getMessage());
975 public static int addCompactCAKeys(InputStream is) throws IOException {
976 synchronized(caKeys) {
978 Vector seq = (Vector) new DER.InputStream(is).readObject();
979 for(Enumeration e = seq.elements(); e.hasMoreElements();) {
980 Vector seq2 = (Vector) e.nextElement();
981 X509.Name subject = new X509.Name(seq2.elementAt(0));
982 RSA.PublicKey pks = new RSA.PublicKey(seq2.elementAt(1));
983 addCAKey(subject,pks);
986 } catch(RuntimeException e) {
988 throw new IOException("error while reading stream: " + e);
993 public static synchronized void setVerifyCallback(VerifyCallback cb) { verifyCallback = cb; }
996 public static class State {
999 State(byte[] sessionID, byte[] masterSecret) {
1000 this.sessionID = sessionID;
1001 this.masterSecret = masterSecret;
1005 public interface VerifyCallback {
1006 public boolean checkCerts(X509.Certificate[] certs, String hostname, Exn exn);
1010 private static final int min(int a, int b) { return a < b ? a : b; }