1 /*
   2  * Copyright (c) 2003, 2013, 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 
  32 /**
  33  * A OutputRecord class extension which uses external ByteBuffers
  34  * or the internal ByteArrayOutputStream for data manipulations.
  35  * <P>
  36  * Instead of rewriting this entire class
  37  * to use ByteBuffers, we leave things intact, so handshake, CCS,
  38  * and alerts will continue to use the internal buffers, but application
  39  * data will use external buffers.
  40  *
  41  * @author Brad Wetmore
  42  */
  43 final class EngineOutputRecord extends OutputRecord {
  44 
  45     private SSLEngineImpl engine;
  46     private EngineWriter writer;
  47 
  48     private boolean finishedMsg = false;
  49 
  50     /*
  51      * All handshake hashing is done by the superclass
  52      */
  53 
  54     /*
  55      * Default constructor makes a record supporting the maximum
  56      * SSL record size.  It allocates the header bytes directly.
  57      *
  58      * @param type the content type for the record
  59      */
  60     EngineOutputRecord(byte type, SSLEngineImpl engine) {
  61         super(type, recordSize(type));
  62         this.engine = engine;
  63         writer = engine.writer;
  64     }
  65 
  66     /**
  67      * Get the size of the buffer we need for records of the specified
  68      * type.
  69      * <P>
  70      * Application data buffers will provide their own byte buffers,
  71      * and will not use the internal byte caching.
  72      */
  73     private static int recordSize(byte type) {
  74         switch (type) {
  75 
  76         case ct_change_cipher_spec:
  77         case ct_alert:
  78             return maxAlertRecordSize;
  79 
  80         case ct_handshake:
  81             return maxRecordSize;
  82 
  83         case ct_application_data:
  84             return 0;
  85         }
  86 
  87         throw new RuntimeException("Unknown record type: " + type);
  88     }
  89 
  90     void setFinishedMsg() {
  91         finishedMsg = true;
  92     }
  93 
  94     @Override
  95     public void flush() throws IOException {
  96         finishedMsg = false;
  97     }
  98 
  99     boolean isFinishedMsg() {
 100         return finishedMsg;
 101     }
 102 
 103     /*
 104      * Override the actual write below.  We do things this way to be
 105      * consistent with InputRecord.  InputRecord may try to write out
 106      * data to the peer, and *then* throw an Exception.  This forces
 107      * data to be generated/output before the exception is ever
 108      * generated.
 109      */
 110     @Override
 111     void writeBuffer(OutputStream s, byte [] buf, int off, int len,
 112             int debugOffset) throws IOException {
 113         /*
 114          * Copy data out of buffer, it's ready to go.
 115          */
 116         ByteBuffer netBB = (ByteBuffer)
 117             ByteBuffer.allocate(len).put(buf, off, len).flip();
 118 
 119         writer.putOutboundData(netBB);
 120     }
 121 
 122     /*
 123      * Main method for writing non-application data.
 124      * We MAC/encrypt, then send down for processing.
 125      */
 126     void write(Authenticator authenticator, CipherBox writeCipher)
 127             throws IOException {
 128 
 129         /*
 130          * Sanity check.
 131          */
 132         switch (contentType()) {
 133             case ct_change_cipher_spec:
 134             case ct_alert:
 135             case ct_handshake:
 136                 break;
 137             default:
 138                 throw new RuntimeException("unexpected byte buffers");
 139         }
 140 
 141         /*
 142          * Don't bother to really write empty records.  We went this
 143          * far to drive the handshake machinery, for correctness; not
 144          * writing empty records improves performance by cutting CPU
 145          * time and network resource usage.  Also, some protocol
 146          * implementations are fragile and don't like to see empty
 147          * records, so this increases robustness.
 148          *
 149          * (Even change cipher spec messages have a byte of data!)
 150          */
 151         if (!isEmpty()) {
 152             // compress();              // eventually
 153             encrypt(authenticator, writeCipher);
 154 
 155             // send down for processing
 156             write((OutputStream)null, false, (ByteArrayOutputStream)null);
 157         }
 158         return;
 159     }
 160 
 161     /**
 162      * Main wrap/write driver.
 163      */
 164     void write(EngineArgs ea, Authenticator authenticator,
 165             CipherBox writeCipher) throws IOException {
 166         /*
 167          * sanity check to make sure someone didn't inadvertantly
 168          * send us an impossible combination we don't know how
 169          * to process.
 170          */
 171         assert(contentType() == ct_application_data);
 172 
 173         /*
 174          * Have we set the MAC's yet?  If not, we're not ready
 175          * to process application data yet.
 176          */
 177         if (authenticator == MAC.NULL) {
 178             return;
 179         }
 180 
 181         /*
 182          * Don't bother to really write empty records.  We went this
 183          * far to drive the handshake machinery, for correctness; not
 184          * writing empty records improves performance by cutting CPU
 185          * time and network resource usage.  Also, some protocol
 186          * implementations are fragile and don't like to see empty
 187          * records, so this increases robustness.
 188          */
 189         if (ea.getAppRemaining() == 0) {
 190             return;
 191         }
 192 
 193         /*
 194          * By default, we counter chosen plaintext issues on CBC mode
 195          * ciphersuites in SSLv3/TLS1.0 by sending one byte of application
 196          * data in the first record of every payload, and the rest in
 197          * subsequent record(s). Note that the issues have been solved in
 198          * TLS 1.1 or later.
 199          *
 200          * It is not necessary to split the very first application record of
 201          * a freshly negotiated TLS session, as there is no previous
 202          * application data to guess.  To improve compatibility, we will not
 203          * split such records.
 204          *
 205          * Because of the compatibility, we'd better produce no more than
 206          * SSLSession.getPacketBufferSize() net data for each wrap. As we
 207          * need a one-byte record at first, the 2nd record size should be
 208          * equal to or less than Record.maxDataSizeMinusOneByteRecord.
 209          *
 210          * This avoids issues in the outbound direction.  For a full fix,
 211          * the peer must have similar protections.
 212          */
 213         int length;
 214         if (engine.needToSplitPayload(writeCipher, protocolVersion)) {
 215             write(ea, authenticator, writeCipher, 0x01);
 216             ea.resetLim();      // reset application data buffer limit
 217             length = Math.min(ea.getAppRemaining(),
 218                         maxDataSizeMinusOneByteRecord);
 219         } else {
 220             length = Math.min(ea.getAppRemaining(), maxDataSize);
 221         }
 222 
 223         // Don't bother to really write empty records.
 224         if (length > 0) {
 225             write(ea, authenticator, writeCipher, length);
 226         }
 227 
 228         return;
 229     }
 230 
 231     void write(EngineArgs ea, Authenticator authenticator,
 232             CipherBox writeCipher, int length) throws IOException {
 233         /*
 234          * Copy out existing buffer values.
 235          */
 236         ByteBuffer dstBB = ea.netData;
 237         int dstPos = dstBB.position();
 238         int dstLim = dstBB.limit();
 239 
 240         /*
 241          * Where to put the data.  Jump over the header.
 242          *
 243          * Don't need to worry about SSLv2 rewrites, if we're here,
 244          * that's long since done.
 245          */
 246         int dstData = dstPos + headerSize + writeCipher.getExplicitNonceSize();
 247         dstBB.position(dstData);
 248 
 249         /*
 250          * transfer application data into the network data buffer
 251          */
 252         ea.gather(length);
 253         dstBB.limit(dstBB.position());
 254         dstBB.position(dstData);
 255 
 256         /*
 257          * "flip" but skip over header again, add MAC & encrypt
 258          */
 259         if (authenticator instanceof MAC) {
 260             MAC signer = (MAC)authenticator;
 261             if (signer.MAClen() != 0) {
 262                 byte[] hash = signer.compute(contentType(), dstBB, false);
 263 
 264                 /*
 265                  * position was advanced to limit in compute above.
 266                  *
 267                  * Mark next area as writable (above layers should have
 268                  * established that we have plenty of room), then write
 269                  * out the hash.
 270                  */
 271                 dstBB.limit(dstBB.limit() + hash.length);
 272                 dstBB.put(hash);
 273 
 274                 // reset the position and limit
 275                 dstBB.limit(dstBB.position());
 276                 dstBB.position(dstData);
 277             }
 278         }
 279 
 280         if (!writeCipher.isNullCipher()) {
 281             /*
 282              * Requires explicit IV/nonce for CBC/AEAD cipher suites for TLS 1.1
 283              * or later.
 284              */
 285             if (protocolVersion.v >= ProtocolVersion.TLS11.v &&
 286                     (writeCipher.isCBCMode() || writeCipher.isAEADMode())) {
 287                 byte[] nonce = writeCipher.createExplicitNonce(
 288                         authenticator, contentType(), dstBB.remaining());
 289                 dstBB.position(dstPos + headerSize);
 290                 dstBB.put(nonce);
 291                 if (!writeCipher.isAEADMode()) {
 292                     // The explicit IV in TLS 1.1 and later can be encrypted.
 293                     dstBB.position(dstPos + headerSize);
 294                 }   // Otherwise, DON'T encrypt the nonce_explicit for AEAD mode
 295             }
 296 
 297             /*
 298              * Encrypt may pad, so again the limit may have changed.
 299              */
 300             writeCipher.encrypt(dstBB, dstLim);
 301 
 302             if ((debug != null) && (Debug.isOn("record") ||
 303                     (Debug.isOn("handshake") &&
 304                         (contentType() == ct_change_cipher_spec)))) {
 305                 System.out.println(Thread.currentThread().getName()
 306                     // v3.0/v3.1 ...
 307                     + ", WRITE: " + protocolVersion
 308                     + " " + InputRecord.contentName(contentType())
 309                     + ", length = " + length);
 310             }
 311         } else {
 312             dstBB.position(dstBB.limit());
 313         }
 314 
 315         int packetLength = dstBB.limit() - dstPos - headerSize;
 316 
 317         /*
 318          * Finish out the record header.
 319          */
 320         dstBB.put(dstPos, contentType());
 321         dstBB.put(dstPos + 1, protocolVersion.major);
 322         dstBB.put(dstPos + 2, protocolVersion.minor);
 323         dstBB.put(dstPos + 3, (byte)(packetLength >> 8));
 324         dstBB.put(dstPos + 4, (byte)packetLength);
 325 
 326         /*
 327          * Position was already set by encrypt() above.
 328          */
 329         dstBB.limit(dstLim);
 330     }
 331 }