History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/sun/security/ssl/InputRecord.java (1 of 18352 files). Show all

Unified · Split

java/pkg/sun/security/ssl/InputRecord.java+703−0
@@ -0,0 +1,703 @@
1+/*
2+ * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
3+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+ *
5+ * This code is free software; you can redistribute it and/or modify it
6+ * under the terms of the GNU General Public License version 2 only, as
7+ * published by the Free Software Foundation. Oracle designates this
8+ * particular file as subject to the "Classpath" exception as provided
9+ * by Oracle in the LICENSE file that accompanied this code.
10+ *
11+ * This code is distributed in the hope that it will be useful, but WITHOUT
12+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+ * version 2 for more details (a copy is included in the LICENSE file that
15+ * accompanied this code).
16+ *
17+ * You should have received a copy of the GNU General Public License version
18+ * 2 along with this work; if not, write to the Free Software Foundation,
19+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+ *
21+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+ * or visit www.oracle.com if you need additional information or have any
23+ * questions.
24+ */
25+
26+
27+package sun.security.ssl;
28+
29+import java.io.*;
30+import java.nio.*;
31+import java.net.SocketException;
32+import java.net.SocketTimeoutException;
33+
34+import javax.crypto.BadPaddingException;
35+
36+import javax.net.ssl.*;
37+
38+import sun.misc.HexDumpEncoder;
39+
40+
41+/**
42+ * SSL 3.0 records, as pulled off a TCP stream. Input records are
43+ * basically buffers tied to a particular input stream ... a layer
44+ * above this must map these records into the model of a continuous
45+ * stream of data.
46+ *
47+ * Since this returns SSL 3.0 records, it's the layer that needs to
48+ * map SSL 2.0 style handshake records into SSL 3.0 ones for those
49+ * "old" clients that interop with both V2 and V3 servers. Not as
50+ * pretty as might be desired.
51+ *
52+ * NOTE: During handshaking, each message must be hashed to support
53+ * verification that the handshake process wasn't compromised.
54+ *
55+ * @author David Brownell
56+ */
57+class InputRecord extends ByteArrayInputStream implements Record {
58+
59+ private HandshakeHash handshakeHash;
60+ private int lastHashed;
61+ boolean formatVerified = true; // SSLv2 ruled out?
62+ private boolean isClosed;
63+ private boolean appDataValid;
64+
65+ // The ClientHello version to accept. If set to ProtocolVersion.SSL20Hello
66+ // and the first message we read is a ClientHello in V2 format, we convert
67+ // it to V3. Otherwise we throw an exception when encountering a V2 hello.
68+ private ProtocolVersion helloVersion;
69+
70+ /* Class and subclass dynamic debugging support */
71+ static final Debug debug = Debug.getInstance("ssl");
72+
73+ /* The existing record length */
74+ private int exlen;
75+
76+ /* V2 handshake message */
77+ private byte v2Buf[];
78+
79+ /*
80+ * Construct the record to hold the maximum sized input record.
81+ * Data will be filled in separately.
82+ */
83+ InputRecord() {
84+ super(new byte[maxRecordSize]);
85+ setHelloVersion(ProtocolVersion.DEFAULT_HELLO);
86+ pos = headerSize;
87+ count = headerSize;
88+ lastHashed = count;
89+ exlen = 0;
90+ v2Buf = null;
91+ }
92+
93+ void setHelloVersion(ProtocolVersion helloVersion) {
94+ this.helloVersion = helloVersion;
95+ }
96+
97+ ProtocolVersion getHelloVersion() {
98+ return helloVersion;
99+ }
100+
101+ /*
102+ * Enable format checks if initial handshaking hasn't completed
103+ */
104+ void enableFormatChecks() {
105+ formatVerified = false;
106+ }
107+
108+ // return whether the data in this record is valid, decrypted data
109+ boolean isAppDataValid() {
110+ return appDataValid;
111+ }
112+
113+ void setAppDataValid(boolean value) {
114+ appDataValid = value;
115+ }
116+
117+ /*
118+ * Return the content type of the record.
119+ */
120+ byte contentType() {
121+ return buf[0];
122+ }
123+
124+ /*
125+ * For handshaking, we need to be able to hash every byte above the
126+ * record marking layer. This is where we're guaranteed to see those
127+ * bytes, so this is where we can hash them ... especially in the
128+ * case of hashing the initial V2 message!
129+ */
130+ void setHandshakeHash(HandshakeHash handshakeHash) {
131+ this.handshakeHash = handshakeHash;
132+ }
133+
134+ HandshakeHash getHandshakeHash() {
135+ return handshakeHash;
136+ }
137+
138+ /*
139+ * Verify and remove the MAC ... used for all records.
140+ */
141+ boolean checkMAC(MAC signer) {
142+ int len = signer.MAClen();
143+ if (len == 0) { // no mac
144+ return true;
145+ }
146+
147+ int offset = count - len;
148+
149+ if (offset < headerSize) {
150+ // data length would be negative, something is wrong
151+ return false;
152+ }
153+
154+ byte[] mac = signer.compute(contentType(), buf,
155+ headerSize, offset - headerSize);
156+
157+ if (len != mac.length) {
158+ throw new RuntimeException("Internal MAC error");
159+ }
160+
161+ for (int i = 0; i < len; i++) {
162+ if (buf[offset + i] != mac[i]) {
163+ return false;
164+ }
165+ }
166+ count -= len;
167+ return true;
168+ }
169+
170+ void decrypt(CipherBox box) throws BadPaddingException {
171+ int len = count - headerSize;
172+ count = headerSize + box.decrypt(buf, headerSize, len);
173+ }
174+
175+
176+ /*
177+ * Well ... hello_request messages are _never_ hashed since we can't
178+ * know when they'd appear in the sequence.
179+ */
180+ void ignore(int bytes) {
181+ if (bytes > 0) {
182+ pos += bytes;
183+ lastHashed = pos;
184+ }
185+ }
186+
187+ /*
188+ * We hash the (plaintext) we've processed, but only on demand.
189+ *
190+ * There is one place where we want to access the hash in the middle
191+ * of a record: client cert message gets hashed, and part of the
192+ * same record is the client cert verify message which uses that hash.
193+ * So we track how much we've read and hashed.
194+ */
195+ void doHashes() {
196+ int len = pos - lastHashed;
197+
198+ if (len > 0) {
199+ hashInternal(buf, lastHashed, len);
200+ lastHashed = pos;
201+ }
202+ }
203+
204+ /*
205+ * Need a helper function so we can hash the V2 hello correctly
206+ */
207+ private void hashInternal(byte databuf [], int offset, int len) {
208+ if (debug != null && Debug.isOn("data")) {
209+ try {
210+ HexDumpEncoder hd = new HexDumpEncoder();
211+
212+ System.out.println("[read] MD5 and SHA1 hashes: len = "
213+ + len);
214+ hd.encodeBuffer(new ByteArrayInputStream(databuf, offset, len),
215+ System.out);
216+ } catch (IOException e) { }
217+ }
218+ handshakeHash.update(databuf, offset, len);
219+ }
220+
221+
222+ /*
223+ * Handshake messages may cross record boundaries. We "queue"
224+ * these in big buffers if we need to cope with this problem.
225+ * This is not anticipated to be a common case; if this turns
226+ * out to be wrong, this can readily be sped up.
227+ */
228+ void queueHandshake(InputRecord r) throws IOException {
229+ int len;
230+
231+ /*
232+ * Hash any data that's read but unhashed.
233+ */
234+ doHashes();
235+
236+ /*
237+ * Move any unread data to the front of the buffer,
238+ * flagging it all as unhashed.
239+ */
240+ if (pos > headerSize) {
241+ len = count - pos;
242+ if (len != 0) {
243+ System.arraycopy(buf, pos, buf, headerSize, len);
244+ }
245+ pos = headerSize;
246+ lastHashed = pos;
247+ count = headerSize + len;
248+ }
249+
250+ /*
251+ * Grow "buf" if needed
252+ */
253+ len = r.available() + count;
254+ if (buf.length < len) {
255+ byte newbuf [];
256+
257+ newbuf = new byte [len];
258+ System.arraycopy(buf, 0, newbuf, 0, count);
259+ buf = newbuf;
260+ }
261+
262+ /*
263+ * Append the new buffer to this one.
264+ */
265+ System.arraycopy(r.buf, r.pos, buf, count, len - count);
266+ count = len;
267+
268+ /*
269+ * Adjust lastHashed; important for now with clients which
270+ * send SSL V2 client hellos. This will go away eventually,
271+ * by buffer code cleanup.
272+ */
273+ len = r.lastHashed - r.pos;
274+ if (pos == headerSize) {
275+ lastHashed += len;
276+ } else {
277+ throw new SSLProtocolException("?? confused buffer hashing ??");
278+ }
279+ // we've read the record, advance the pointers
280+ r.pos = r.count;
281+ }
282+
283+
284+ /**
285+ * Prevent any more data from being read into this record,
286+ * and flag the record as holding no data.
287+ */
288+ public void close() {
289+ appDataValid = false;
290+ isClosed = true;
291+ mark = 0;
292+ pos = 0;
293+ count = 0;
294+ }
295+
296+
297+ /*
298+ * We may need to send this SSL v2 "No Cipher" message back, if we
299+ * are faced with an SSLv2 "hello" that's not saying "I talk v3".
300+ * It's the only one documented in the V2 spec as a fatal error.
301+ */
302+ private static final byte[] v2NoCipher = {
303+ (byte)0x80, (byte)0x03, // unpadded 3 byte record
304+ (byte)0x00, // ... error message
305+ (byte)0x00, (byte)0x01 // ... NO_CIPHER error
306+ };
307+
308+ private int readFully(InputStream s, byte b[], int off, int len)
309+ throws IOException {
310+ int n = 0;
311+ while (n < len) {
312+ int readLen = s.read(b, off + n, len - n);
313+ if (readLen < 0) {
314+ return readLen;
315+ }
316+
317+ if (debug != null && Debug.isOn("packet")) {
318+ try {
319+ HexDumpEncoder hd = new HexDumpEncoder();
320+ ByteBuffer bb = ByteBuffer.wrap(b, off + n, readLen);
321+
322+ System.out.println("[Raw read]: length = " +
323+ bb.remaining());
324+ hd.encodeBuffer(bb, System.out);
325+ } catch (IOException e) { }
326+ }
327+
328+ n += readLen;
329+ exlen += readLen;
330+ }
331+
332+ return n;
333+ }
334+
335+ /*
336+ * Read the SSL V3 record ... first time around, check to see if it
337+ * really IS a V3 record. Handle SSL V2 clients which can talk V3.0,
338+ * as well as real V3 record format; otherwise report an error.
339+ */
340+ void read(InputStream s, OutputStream o) throws IOException {
341+ if (isClosed) {
342+ return;
343+ }
344+
345+ /*
346+ * For SSL it really _is_ an error if the other end went away
347+ * so ungracefully as to not shut down cleanly.
348+ */
349+ if(exlen < headerSize) {
350+ int really = readFully(s, buf, exlen, headerSize - exlen);
351+ if (really < 0) {
352+ throw new EOFException("SSL peer shut down incorrectly");
353+ }
354+
355+ pos = headerSize;
356+ count = headerSize;
357+ lastHashed = pos;
358+ }
359+
360+ /*
361+ * The first record might use some other record marking convention,
362+ * typically SSL v2 header. (PCT could also be detected here.)
363+ * This case is currently common -- Navigator 3.0 usually works
364+ * this way, as do IE 3.0 and other products.
365+ */
366+ if (!formatVerified) {
367+ formatVerified = true;
368+ /*
369+ * The first record must either be a handshake record or an
370+ * alert message. If it's not, it is either invalid or an
371+ * SSLv2 message.
372+ */
373+ if (buf[0] != ct_handshake && buf[0] != ct_alert) {
374+ handleUnknownRecord(s, o);
375+ } else {
376+ readV3Record(s, o);
377+ }
378+ } else { // formatVerified == true
379+ readV3Record(s, o);
380+ }
381+ }
382+
383+ /**
384+ * Read a SSL/TLS record. Throw an IOException if the format is invalid.
385+ */
386+ private void readV3Record(InputStream s, OutputStream o)
387+ throws IOException {
388+ ProtocolVersion recordVersion = ProtocolVersion.valueOf(buf[1], buf[2]);
389+ // Check if too old (currently not possible)
390+ // or if the major version does not match.
391+ // The actual version negotiation is in the handshaker classes
392+ if ((recordVersion.v < ProtocolVersion.MIN.v)
393+ || (recordVersion.major > ProtocolVersion.MAX.major)) {
394+ throw new SSLException(
395+ "Unsupported record version " + recordVersion);
396+ }
397+
398+ /*
399+ * Get and check length, then the data.
400+ */
401+ int contentLen = ((buf[3] & 0x0ff) << 8) + (buf[4] & 0xff);
402+
403+ /*
404+ * Check for upper bound.
405+ */
406+ if (contentLen < 0 || contentLen > maxLargeRecordSize - headerSize) {
407+ throw new SSLProtocolException("Bad InputRecord size"
408+ + ", count = " + contentLen
409+ + ", buf.length = " + buf.length);
410+ }
411+
412+ /*
413+ * Grow "buf" if needed. Since buf is maxRecordSize by default,
414+ * this only occurs when we receive records which violate the
415+ * SSL specification. This is a workaround for a Microsoft SSL bug.
416+ */
417+ if (contentLen > buf.length - headerSize) {
418+ byte[] newbuf = new byte[contentLen + headerSize];
419+ System.arraycopy(buf, 0, newbuf, 0, headerSize);
420+ buf = newbuf;
421+ }
422+
423+ if (exlen < contentLen + headerSize) {
424+ int really = readFully(
425+ s, buf, exlen, contentLen + headerSize - exlen);
426+ if (really < 0) {
427+ throw new SSLException("SSL peer shut down incorrectly");
428+ }
429+ }
430+
431+ // now we've got a complete record.
432+ count = contentLen + headerSize;
433+ exlen = 0;
434+
435+ if (debug != null && Debug.isOn("record")) {
436+ if (count < 0 || count > (maxRecordSize - headerSize)) {
437+ System.out.println(Thread.currentThread().getName()
438+ + ", Bad InputRecord size" + ", count = " + count);
439+ }
440+ System.out.println(Thread.currentThread().getName()
441+ + ", READ: " + recordVersion + " "
442+ + contentName(contentType()) + ", length = " + available());
443+ }
444+ /*
445+ * then caller decrypts, verifies, and uncompresses
446+ */
447+ }
448+
449+ /**
450+ * Deal with unknown records. Called if the first data we read on this
451+ * connection does not look like an SSL/TLS record. It could a SSLv2
452+ * message, or just garbage.
453+ */
454+ private void handleUnknownRecord(InputStream s, OutputStream o)
455+ throws IOException {
456+ /*
457+ * No? Oh well; does it look like a V2 "ClientHello"?
458+ * That'd be an unpadded handshake message; we don't
459+ * bother checking length just now.
460+ */
461+ if (((buf[0] & 0x080) != 0) && buf[2] == 1) {
462+ /*
463+ * if the user has disabled SSLv2Hello (using
464+ * setEnabledProtocol) then throw an
465+ * exception
466+ */
467+ if (helloVersion != ProtocolVersion.SSL20Hello) {
468+ throw new SSLHandshakeException("SSLv2Hello is disabled");
469+ }
470+
471+ ProtocolVersion recordVersion =
472+ ProtocolVersion.valueOf(buf[3], buf[4]);
473+
474+ if (recordVersion == ProtocolVersion.SSL20Hello) {
475+ /*
476+ * Looks like a V2 client hello, but not one saying
477+ * "let's talk SSLv3". So we send an SSLv2 error
478+ * message, one that's treated as fatal by clients.
479+ * (Otherwise we'll hang.)
480+ */
481+ try {
482+ writeBuffer(o, v2NoCipher, 0, v2NoCipher.length);
483+ } catch (Exception e) {
484+ /* NOTHING */
485+ }
486+ throw new SSLException("Unsupported SSL v2.0 ClientHello");
487+ }
488+
489+ /*
490+ * If we can map this into a V3 ClientHello, read and
491+ * hash the rest of the V2 handshake, turn it into a
492+ * V3 ClientHello message, and pass it up.
493+ */
494+ int len = ((buf[0] & 0x7f) << 8) +
495+ (buf[1] & 0xff) - 3;
496+ if (v2Buf == null) {
497+ v2Buf = new byte[len];
498+ }
499+ if (exlen < len + headerSize) {
500+ int really = readFully(
501+ s, v2Buf, exlen - headerSize, len + headerSize - exlen);
502+ if (really < 0) {
503+ throw new EOFException("SSL peer shut down incorrectly");
504+ }
505+ }
506+
507+ // now we've got a complete record.
508+ exlen = 0;
509+
510+ hashInternal(buf, 2, 3);
511+ hashInternal(v2Buf, 0, len);
512+ V2toV3ClientHello(v2Buf);
513+ v2Buf = null;
514+ lastHashed = count;
515+
516+ if (debug != null && Debug.isOn("record")) {
517+ System.out.println(
518+ Thread.currentThread().getName()
519+ + ", READ: SSL v2, contentType = "
520+ + contentName(contentType())
521+ + ", translated length = " + available());
522+ }
523+ return;
524+
525+ } else {
526+ /*
527+ * Does it look like a V2 "ServerHello"?
528+ */
529+ if (((buf [0] & 0x080) != 0) && buf [2] == 4) {
530+ throw new SSLException(
531+ "SSL V2.0 servers are not supported.");
532+ }
533+
534+ /*
535+ * If this is a V2 NoCipher message then this means
536+ * the other server doesn't support V3. Otherwise, we just
537+ * don't understand what it's saying.
538+ */
539+ for (int i = 0; i < v2NoCipher.length; i++) {
540+ if (buf[i] != v2NoCipher[i]) {
541+ throw new SSLException(
542+ "Unrecognized SSL message, plaintext connection?");
543+ }
544+ }
545+
546+ throw new SSLException("SSL V2.0 servers are not supported.");
547+ }
548+ }
549+
550+ /*
551+ * Actually do the write here. For SSLEngine's HS data,
552+ * we'll override this method and let it take the appropriate
553+ * action.
554+ */
555+ void writeBuffer(OutputStream s, byte [] buf, int off, int len)
556+ throws IOException {
557+ s.write(buf, 0, len);
558+ s.flush();
559+ }
560+
561+ /*
562+ * Support "old" clients which are capable of SSL V3.0 protocol ... for
563+ * example, Navigator 3.0 clients. The V2 message is in the header and
564+ * the bytes passed as parameter. This routine translates the V2 message
565+ * into an equivalent V3 one.
566+ */
567+ private void V2toV3ClientHello(byte v2Msg []) throws SSLException
568+ {
569+ int i;
570+
571+ /*
572+ * Build the first part of the V3 record header from the V2 one
573+ * that's now buffered up. (Lengths are fixed up later).
574+ */
575+ buf [0] = ct_handshake;
576+ buf [1] = buf [3]; // V3.x
577+ buf[2] = buf[4];
578+ // header [3..4] for handshake message length
579+ // count = 5;
580+
581+ /*
582+ * Store the generic V3 handshake header: 4 bytes
583+ */
584+ buf [5] = 1; // HandshakeMessage.ht_client_hello
585+ // buf [6..8] for length of ClientHello (int24)
586+ // count += 4;
587+
588+ /*
589+ * ClientHello header starts with SSL version
590+ */
591+ buf [9] = buf [1];
592+ buf [10] = buf [2];
593+ // count += 2;
594+ count = 11;
595+
596+ /*
597+ * Start parsing the V2 message ...
598+ */
599+ int cipherSpecLen, sessionIdLen, nonceLen;
600+
601+ cipherSpecLen = ((v2Msg [0] & 0xff) << 8) + (v2Msg [1] & 0xff);
602+ sessionIdLen = ((v2Msg [2] & 0xff) << 8) + (v2Msg [3] & 0xff);
603+ nonceLen = ((v2Msg [4] & 0xff) << 8) + (v2Msg [5] & 0xff);
604+
605+ /*
606+ * Copy Random value/nonce ... if less than the 32 bytes of
607+ * a V3 "Random", right justify and zero pad to the left. Else
608+ * just take the last 32 bytes.
609+ */
610+ int offset = 6 + cipherSpecLen + sessionIdLen;
611+
612+ if (nonceLen < 32) {
613+ for (i = 0; i < (32 - nonceLen); i++)
614+ buf [count++] = 0;
615+ System.arraycopy(v2Msg, offset, buf, count, nonceLen);
616+ count += nonceLen;
617+ } else {
618+ System.arraycopy(v2Msg, offset + (nonceLen - 32),
619+ buf, count, 32);
620+ count += 32;
621+ }
622+
623+ /*
624+ * Copy Session ID (only one byte length!)
625+ */
626+ offset -= sessionIdLen;
627+ buf [count++] = (byte) sessionIdLen;
628+
629+ System.arraycopy(v2Msg, offset, buf, count, sessionIdLen);
630+ count += sessionIdLen;
631+
632+ /*
633+ * Copy and translate cipher suites ... V2 specs with first byte zero
634+ * are really V3 specs (in the last 2 bytes), just copy those and drop
635+ * the other ones. Preference order remains unchanged.
636+ *
637+ * Example: Netscape Navigator 3.0 (exportable) says:
638+ *
639+ * 0/3, SSL_RSA_EXPORT_WITH_RC4_40_MD5
640+ * 0/6, SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
641+ *
642+ * Microsoft Internet Explorer 3.0 (exportable) supports only
643+ *
644+ * 0/3, SSL_RSA_EXPORT_WITH_RC4_40_MD5
645+ */
646+ int j;
647+
648+ offset -= cipherSpecLen;
649+ j = count + 2;
650+
651+ for (i = 0; i < cipherSpecLen; i += 3) {
652+ if (v2Msg [offset + i] != 0)
653+ continue;
654+ buf [j++] = v2Msg [offset + i + 1];
655+ buf [j++] = v2Msg [offset + i + 2];
656+ }
657+
658+ j -= count + 2;
659+ buf [count++] = (byte) (j >>> 8);
660+ buf [count++] = (byte) j;
661+ count += j;
662+
663+ /*
664+ * Append compression methods (default/null only)
665+ */
666+ buf [count++] = 1;
667+ buf [count++] = 0; // Session.compression_null
668+
669+ /*
670+ * Fill in lengths of the messages we synthesized (nested:
671+ * V3 handshake message within V3 record) and then return
672+ */
673+ buf [3] = (byte) (count - headerSize);
674+ buf [4] = (byte) ((count - headerSize) >>> 8);
675+
676+ buf [headerSize + 1] = 0;
677+ buf [headerSize + 2] = (byte) (((count - headerSize) - 4) >>> 8);
678+ buf [headerSize + 3] = (byte) ((count - headerSize) - 4);
679+
680+ pos = headerSize;
681+ }
682+
683+ /**
684+ * Return a description for the given content type. This method should be
685+ * in Record, but since that is an interface this is not possible.
686+ * Called from InputRecord and OutputRecord.
687+ */
688+ static String contentName(int contentType) {
689+ switch (contentType) {
690+ case ct_change_cipher_spec:
691+ return "Change Cipher Spec";
692+ case ct_alert:
693+ return "Alert";
694+ case ct_handshake:
695+ return "Handshake";
696+ case ct_application_data:
697+ return "Application Data";
698+ default:
699+ return "contentType = " + contentType;
700+ }
701+ }
702+
703+}