1/*
2 * Copyright (c) 2012, 2015, 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
26package sun.security.ssl;
27
28import java.util.Arrays;
29
30/**
31 * This class represents an SSL/TLS/DTLS message authentication token,
32 * which encapsulates a sequence number and ensures that attempts to
33 * delete or reorder messages can be detected.
34 *
35 * Each connection state contains a sequence number, which is maintained
36 * separately for read and write states.
37 *
38 * For SSL/TLS protocols, the sequence number MUST be set to zero
39 * whenever a connection state is made the active state.
40 *
41 * DTLS uses an explicit sequence number, rather than an implicit one.
42 * Sequence numbers are maintained separately for each epoch, with
43 * each sequence number initially being 0 for each epoch.  The sequence
44 * number used to compute the DTLS MAC is the 64-bit value formed by
45 * concatenating the epoch and the sequence number.
46 *
47 * Sequence numbers do not wrap.  If an implementation would need to wrap
48 * a sequence number, it must renegotiate instead.  A sequence number is
49 * incremented after each record: specifically, the first record transmitted
50 * under a particular connection state MUST use sequence number 0.
51 */
52class Authenticator {
53
54    // byte array containing the additional authentication information for
55    // each record
56    private final byte[] block;
57
58    // the block size of SSL v3.0:
59    // sequence number + record type + + record length
60    private static final int BLOCK_SIZE_SSL = 8 + 1 + 2;
61
62    // the block size of TLS v1.0 and later:
63    // sequence number + record type + protocol version + record length
64    private static final int BLOCK_SIZE_TLS = 8 + 1 + 2 + 2;
65
66    // the block size of DTLS v1.0 and later:
67    // epoch + sequence number + record type + protocol version + record length
68    private static final int BLOCK_SIZE_DTLS = 2 + 6 + 1 + 2 + 2;
69
70    private final boolean isDTLS;
71
72    /**
73     * Default construct, no message authentication token is initialized.
74     *
75     * Note that this construct can only be called for null MAC
76     */
77    protected Authenticator(boolean isDTLS) {
78        if (isDTLS) {
79            // For DTLS protocols, plaintexts use explicit epoch and
80            // sequence number in each record.  The first 8 byte of
81            // the block is initialized for null MAC so that the
82            // epoch and sequence number can be acquired to generate
83            // plaintext records.
84            block = new byte[8];
85        } else {
86            block = new byte[0];
87        }
88
89        this.isDTLS = isDTLS;
90    }
91
92    /**
93     * Constructs the message authentication token for the specified
94     * SSL/TLS protocol.
95     */
96    Authenticator(ProtocolVersion protocolVersion) {
97        if (protocolVersion.isDTLSProtocol()) {
98            block = new byte[BLOCK_SIZE_DTLS];
99            block[9] = protocolVersion.major;
100            block[10] = protocolVersion.minor;
101
102            this.isDTLS = true;
103        } else if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
104            block = new byte[BLOCK_SIZE_TLS];
105            block[9] = protocolVersion.major;
106            block[10] = protocolVersion.minor;
107
108            this.isDTLS = false;
109        } else {
110            block = new byte[BLOCK_SIZE_SSL];
111
112            this.isDTLS = false;
113        }
114    }
115
116    /**
117     * Checks whether the sequence number is close to wrap.
118     *
119     * Sequence numbers are of type uint64 and may not exceed 2^64-1.
120     * Sequence numbers do not wrap. When the sequence number is near
121     * to wrap, we need to close the connection immediately.
122     *
123     * @return true if the sequence number is close to wrap
124     */
125    final boolean seqNumOverflow() {
126        /*
127         * Conservatively, we don't allow more records to be generated
128         * when there are only 2^8 sequence numbers left.
129         */
130        if (isDTLS) {
131            return (block.length != 0 &&
132                // no epoch bytes, block[0] and block[1]
133                block[2] == (byte)0xFF && block[3] == (byte)0xFF &&
134                block[4] == (byte)0xFF && block[5] == (byte)0xFF &&
135                block[6] == (byte)0xFF);
136        } else {
137            return (block.length != 0 &&
138                block[0] == (byte)0xFF && block[1] == (byte)0xFF &&
139                block[2] == (byte)0xFF && block[3] == (byte)0xFF &&
140                block[4] == (byte)0xFF && block[5] == (byte)0xFF &&
141                block[6] == (byte)0xFF);
142        }
143    }
144
145    /**
146     * Checks whether the sequence number close to renew.
147     *
148     * Sequence numbers are of type uint64 and may not exceed 2^64-1.
149     * Sequence numbers do not wrap.  If a TLS
150     * implementation would need to wrap a sequence number, it must
151     * renegotiate instead.
152     *
153     * @return true if the sequence number is huge enough to renew
154     */
155    final boolean seqNumIsHuge() {
156        /*
157         * Conservatively, we should ask for renegotiation when there are
158         * only 2^32 sequence numbers left.
159         */
160        if (isDTLS) {
161            return (block.length != 0 &&
162                // no epoch bytes, block[0] and block[1]
163                block[2] == (byte)0xFF && block[3] == (byte)0xFF);
164        } else {
165            return (block.length != 0 &&
166                block[0] == (byte)0xFF && block[1] == (byte)0xFF &&
167                block[2] == (byte)0xFF && block[3] == (byte)0xFF);
168        }
169    }
170
171    /**
172     * Gets the current sequence number, including the epoch number for
173     * DTLS protocols.
174     *
175     * @return the byte array of the current sequence number
176     */
177    final byte[] sequenceNumber() {
178        return Arrays.copyOf(block, 8);
179    }
180
181    /**
182     * Sets the epoch number (only apply to DTLS protocols).
183     */
184    final void setEpochNumber(int epoch) {
185        if (!isDTLS) {
186            throw new RuntimeException(
187                "Epoch numbers apply to DTLS protocols only");
188        }
189
190        block[0] = (byte)((epoch >> 8) & 0xFF);
191        block[1] = (byte)(epoch & 0xFF);
192    }
193
194    /**
195     * Increase the sequence number.
196     */
197    final void increaseSequenceNumber() {
198        /*
199         * The sequence number in the block array is a 64-bit
200         * number stored in big-endian format.
201         */
202        int k = 7;
203        while ((k >= 0) && (++block[k] == 0)) {
204            k--;
205        }
206    }
207
208    /**
209     * Acquires the current message authentication information with the
210     * specified record type and fragment length, and then increases the
211     * sequence number.
212     *
213     * @param  type the record type
214     * @param  length the fragment of the record
215     * @param  sequence the explicit sequence number of the record
216     *
217     * @return the byte array of the current message authentication information
218     */
219    final byte[] acquireAuthenticationBytes(
220            byte type, int length, byte[] sequence) {
221
222        byte[] copy = block.clone();
223        if (sequence != null) {
224            if (sequence.length != 8) {
225                throw new RuntimeException(
226                        "Insufficient explicit sequence number bytes");
227            }
228
229            System.arraycopy(sequence, 0, copy, 0, sequence.length);
230        }   // Otherwise, use the implicit sequence number.
231
232        if (block.length != 0) {
233            copy[8] = type;
234
235            copy[copy.length - 2] = (byte)(length >> 8);
236            copy[copy.length - 1] = (byte)(length);
237
238            if (sequence == null || sequence.length != 0) {
239                // Increase the implicit sequence number in the block array.
240                increaseSequenceNumber();
241            }
242        }
243
244        return copy;
245    }
246
247    static final long toLong(byte[] recordEnS) {
248        if (recordEnS != null && recordEnS.length == 8) {
249            return ((recordEnS[0] & 0xFFL) << 56) |
250                   ((recordEnS[1] & 0xFFL) << 48) |
251                   ((recordEnS[2] & 0xFFL) << 40) |
252                   ((recordEnS[3] & 0xFFL) << 32) |
253                   ((recordEnS[4] & 0xFFL) << 24) |
254                   ((recordEnS[5] & 0xFFL) << 16) |
255                   ((recordEnS[6] & 0xFFL) <<  8) |
256                    (recordEnS[7] & 0xFFL);
257        }
258
259        return -1L;
260    }
261}
262