aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/internal/net/ipsec/ike/message/IkeEncryptedPayloadBody.java
blob: 77cc9f4ea5bd0de7e1368b581805a2cd2e55fbf2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.net.ipsec.ike.message;

import android.net.ipsec.ike.exceptions.IkeProtocolException;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.net.ipsec.ike.crypto.IkeCipher;
import com.android.internal.net.ipsec.ike.crypto.IkeCombinedModeCipher;
import com.android.internal.net.ipsec.ike.crypto.IkeMacIntegrity;
import com.android.internal.net.ipsec.ike.crypto.IkeNormalModeCipher;

import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.AEADBadTagException;
import javax.crypto.IllegalBlockSizeException;

/**
 * IkeEncryptedPayloadBody is a package private class that represents an IKE payload substructure
 * that contains initialization vector, encrypted content, padding, pad length and integrity
 * checksum.
 *
 * <p>Both an Encrypted Payload (IkeSkPayload) and an EncryptedFragmentPayload (IkeSkfPayload)
 * consists of an IkeEncryptedPayloadBody instance.
 *
 * <p>When using normal cipher with separate integrity algorithm, data to authenticate includes
 * bytes from beginning of IKE header to the pad length, which are concatenation of IKE header,
 * current payload header, iv and encrypted and padded data.
 *
 * <p>When using AEAD, additional authentication data(also known as) associated data is required. It
 * MUST include bytes from beginning of IKE header to the last octet of the Payload Header of the
 * Encrypted Payload. Note fragment number and total fragments are also included if Encrypted
 * Payload is SKF.
 *
 * @see <a href="https://tools.ietf.org/html/rfc7296#page-105">RFC 7296, Internet Key Exchange
 *     Protocol Version 2 (IKEv2)</a>
 * @see <a href="https://tools.ietf.org/html/rfc7383#page-6">RFC 7383, Internet Key Exchange
 *     Protocol Version 2 (IKEv2) Message Fragmentation</a>
 */
final class IkeEncryptedPayloadBody {
    // Length of pad length field.
    private static final int PAD_LEN_LEN = 1;

    private final byte[] mUnencryptedData;
    private final byte[] mEncryptedAndPaddedData;
    private final byte[] mIv;
    private final byte[] mIntegrityChecksum;

    /**
     * Package private constructor for constructing an instance of IkeEncryptedPayloadBody from
     * decrypting an incoming packet.
     */
    IkeEncryptedPayloadBody(
            byte[] message,
            int encryptedBodyOffset,
            IkeMacIntegrity integrityMac,
            IkeCipher decryptCipher,
            byte[] integrityKey,
            byte[] decryptionKey)
            throws IkeProtocolException, GeneralSecurityException {
        ByteBuffer inputBuffer = ByteBuffer.wrap(message);

        // Skip IKE header and generic payload header (and SKF header)
        inputBuffer.get(new byte[encryptedBodyOffset]);

        // Extract bytes for authentication and decryption.
        int expectedIvLen = decryptCipher.getIvLen();
        mIv = new byte[expectedIvLen];

        int checksumLen = getChecksum(integrityMac, decryptCipher);
        int encryptedDataLen = message.length - (encryptedBodyOffset + expectedIvLen + checksumLen);
        // IkeMessage will catch exception if encryptedDataLen is negative.
        mEncryptedAndPaddedData = new byte[encryptedDataLen];

        mIntegrityChecksum = new byte[checksumLen];
        inputBuffer.get(mIv).get(mEncryptedAndPaddedData).get(mIntegrityChecksum);

        if (decryptCipher.isAead()) {
            byte[] dataToAuthenticate = Arrays.copyOfRange(message, 0, encryptedBodyOffset);
            mUnencryptedData =
                    combinedModeDecrypt(
                            (IkeCombinedModeCipher) decryptCipher,
                            mEncryptedAndPaddedData,
                            mIntegrityChecksum,
                            dataToAuthenticate,
                            decryptionKey,
                            mIv);
        } else {
            byte[] dataToAuthenticate =
                    Arrays.copyOfRange(message, 0, message.length - checksumLen);

            validateInboundChecksumOrThrow(
                    dataToAuthenticate, integrityMac, integrityKey, mIntegrityChecksum);
            mUnencryptedData =
                    normalModeDecrypt(
                            mEncryptedAndPaddedData,
                            (IkeNormalModeCipher) decryptCipher,
                            decryptionKey,
                            mIv);
        }
    }

    /**
     * Package private constructor for constructing an instance of IkeEncryptedPayloadBody for
     * building an outbound packet.
     */
    IkeEncryptedPayloadBody(
            IkeHeader ikeHeader,
            @IkePayload.PayloadType int firstPayloadType,
            byte[] skfHeaderBytes,
            byte[] unencryptedPayloads,
            IkeMacIntegrity integrityMac,
            IkeCipher encryptCipher,
            byte[] integrityKey,
            byte[] encryptionKey) {
        this(
                ikeHeader,
                firstPayloadType,
                skfHeaderBytes,
                unencryptedPayloads,
                integrityMac,
                encryptCipher,
                integrityKey,
                encryptionKey,
                encryptCipher.generateIv(),
                calculatePadding(unencryptedPayloads.length, encryptCipher.getBlockSize()));
    }

    /** Package private constructor only for testing. */
    @VisibleForTesting
    IkeEncryptedPayloadBody(
            IkeHeader ikeHeader,
            @IkePayload.PayloadType int firstPayloadType,
            byte[] skfHeaderBytes,
            byte[] unencryptedPayloads,
            IkeMacIntegrity integrityMac,
            IkeCipher encryptCipher,
            byte[] integrityKey,
            byte[] encryptionKey,
            byte[] iv,
            byte[] padding) {
        mUnencryptedData = unencryptedPayloads;

        mIv = iv;
        if (encryptCipher.isAead()) {
            byte[] paddedDataWithChecksum =
                    combinedModeEncrypt(
                            (IkeCombinedModeCipher) encryptCipher,
                            ikeHeader,
                            firstPayloadType,
                            skfHeaderBytes,
                            unencryptedPayloads,
                            encryptionKey,
                            iv,
                            padding);

            int checkSumLen = ((IkeCombinedModeCipher) encryptCipher).getChecksumLen();
            mIntegrityChecksum = new byte[checkSumLen];
            mEncryptedAndPaddedData = new byte[paddedDataWithChecksum.length - checkSumLen];

            ByteBuffer buffer = ByteBuffer.wrap(paddedDataWithChecksum);
            buffer.get(mEncryptedAndPaddedData);
            buffer.get(mIntegrityChecksum);
        } else {
            // Encrypt data
            mEncryptedAndPaddedData =
                    normalModeEncrypt(
                            unencryptedPayloads,
                            (IkeNormalModeCipher) encryptCipher,
                            encryptionKey,
                            iv,
                            padding);
            // Calculate checksum
            mIntegrityChecksum =
                    generateOutboundChecksum(
                            ikeHeader,
                            firstPayloadType,
                            skfHeaderBytes,
                            integrityMac,
                            iv,
                            mEncryptedAndPaddedData,
                            integrityKey);
        }
    }

    private int getChecksum(IkeMacIntegrity integrityMac, IkeCipher decryptCipher) {
        if (decryptCipher.isAead()) {
            return ((IkeCombinedModeCipher) decryptCipher).getChecksumLen();
        } else {
            return integrityMac.getChecksumLen();
        }
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] generateOutboundChecksum(
            IkeHeader ikeHeader,
            @IkePayload.PayloadType int firstPayloadType,
            byte[] skfHeaderBytes,
            IkeMacIntegrity integrityMac,
            byte[] iv,
            byte[] encryptedAndPaddedData,
            byte[] integrityKey) {
        // Length from encrypted payload header to the Pad Length field
        int encryptedPayloadHeaderToPadLen =
                IkePayload.GENERIC_HEADER_LENGTH
                        + skfHeaderBytes.length
                        + iv.length
                        + encryptedAndPaddedData.length;

        // Calculate length of authentication data and allocate ByteBuffer.
        int dataToAuthenticateLength = IkeHeader.IKE_HEADER_LENGTH + encryptedPayloadHeaderToPadLen;
        ByteBuffer authenticatedSectionBuffer = ByteBuffer.allocate(dataToAuthenticateLength);

        // Build data to authenticate.
        int encryptedPayloadLength = encryptedPayloadHeaderToPadLen + integrityMac.getChecksumLen();
        ikeHeader.encodeToByteBuffer(authenticatedSectionBuffer, encryptedPayloadLength);
        IkePayload.encodePayloadHeaderToByteBuffer(
                firstPayloadType, encryptedPayloadLength, authenticatedSectionBuffer);
        authenticatedSectionBuffer.put(skfHeaderBytes).put(iv).put(encryptedAndPaddedData);

        // Calculate checksum
        return integrityMac.generateChecksum(integrityKey, authenticatedSectionBuffer.array());
    }

    /** Package private for testing */
    @VisibleForTesting
    static void validateInboundChecksumOrThrow(
            byte[] dataToAuthenticate,
            IkeMacIntegrity integrityMac,
            byte[] integrityKey,
            byte[] integrityChecksum)
            throws GeneralSecurityException {
        // TODO: Make it package private and add test.
        int checkSumLen = integrityChecksum.length;
        byte[] calculatedChecksum = integrityMac.generateChecksum(integrityKey, dataToAuthenticate);

        if (!Arrays.equals(integrityChecksum, calculatedChecksum)) {
            throw new GeneralSecurityException("Message authentication failed.");
        }
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] normalModeEncrypt(
            byte[] dataToEncrypt,
            IkeNormalModeCipher encryptCipher,
            byte[] encryptionKey,
            byte[] iv,
            byte[] padding) {
        byte[] paddedData = getPaddedData(dataToEncrypt, padding);

        // Encrypt data.
        return encryptCipher.encrypt(paddedData, encryptionKey, iv);
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] normalModeDecrypt(
            byte[] encryptedData,
            IkeNormalModeCipher decryptCipher,
            byte[] decryptionKey,
            byte[] iv)
            throws IllegalBlockSizeException {
        byte[] paddedPlaintext = decryptCipher.decrypt(encryptedData, decryptionKey, iv);

        return stripPadding(paddedPlaintext);
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] combinedModeEncrypt(
            IkeCombinedModeCipher encryptCipher,
            IkeHeader ikeHeader,
            @IkePayload.PayloadType int firstPayloadType,
            byte[] skfHeaderBytes,
            byte[] dataToEncrypt,
            byte[] encryptionKey,
            byte[] iv,
            byte[] padding) {
        int dataToAuthenticateLength =
                IkeHeader.IKE_HEADER_LENGTH
                        + IkePayload.GENERIC_HEADER_LENGTH
                        + skfHeaderBytes.length;
        ByteBuffer authenticatedSectionBuffer = ByteBuffer.allocate(dataToAuthenticateLength);

        byte[] paddedData = getPaddedData(dataToEncrypt, padding);
        int encryptedPayloadLength =
                IkePayload.GENERIC_HEADER_LENGTH
                        + skfHeaderBytes.length
                        + iv.length
                        + paddedData.length
                        + encryptCipher.getChecksumLen();
        ikeHeader.encodeToByteBuffer(authenticatedSectionBuffer, encryptedPayloadLength);
        IkePayload.encodePayloadHeaderToByteBuffer(
                firstPayloadType, encryptedPayloadLength, authenticatedSectionBuffer);
        authenticatedSectionBuffer.put(skfHeaderBytes);

        return encryptCipher.encrypt(
                paddedData, authenticatedSectionBuffer.array(), encryptionKey, iv);
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] combinedModeDecrypt(
            IkeCombinedModeCipher decryptCipher,
            byte[] encryptedData,
            byte[] checksum,
            byte[] dataToAuthenticate,
            byte[] decryptionKey,
            byte[] iv)
            throws AEADBadTagException {
        ByteBuffer dataWithChecksumBuffer =
                ByteBuffer.allocate(encryptedData.length + checksum.length);
        dataWithChecksumBuffer.put(encryptedData);
        dataWithChecksumBuffer.put(checksum);
        dataWithChecksumBuffer.rewind();

        byte[] paddedPlaintext =
                decryptCipher.decrypt(
                        dataWithChecksumBuffer.array(), dataToAuthenticate, decryptionKey, iv);

        return stripPadding(paddedPlaintext);
    }

    /** Package private for testing */
    @VisibleForTesting
    static byte[] calculatePadding(int dataToEncryptLength, int blockSize) {
        // Sum of dataToEncryptLength, PAD_LEN_LEN and padLength should be aligned with block size.
        int unpaddedLen = dataToEncryptLength + PAD_LEN_LEN;
        int padLength = (unpaddedLen + blockSize - 1) / blockSize * blockSize - unpaddedLen;
        byte[] padding = new byte[padLength];

        // According to RFC 7296, "Padding MAY contain any value".
        new SecureRandom().nextBytes(padding);

        return padding;
    }

    private static byte[] getPaddedData(byte[] data, byte[] padding) {
        int padLength = padding.length;
        int paddedDataLength = data.length + padLength + PAD_LEN_LEN;
        ByteBuffer padBuffer = ByteBuffer.allocate(paddedDataLength);
        padBuffer.put(data).put(padding).put((byte) padLength);

        return padBuffer.array();
    }

    private static byte[] stripPadding(byte[] paddedPlaintext) {
        // Remove padding. Pad length value is the last byte of the padded unencrypted data.
        int padLength = Byte.toUnsignedInt(paddedPlaintext[paddedPlaintext.length - 1]);
        int decryptedDataLen = paddedPlaintext.length - padLength - PAD_LEN_LEN;

        return Arrays.copyOfRange(paddedPlaintext, 0, decryptedDataLen);
    }

    /** Package private */
    byte[] getUnencryptedData() {
        return mUnencryptedData;
    }

    /** Package private */
    int getLength() {
        return (mIv.length + mEncryptedAndPaddedData.length + mIntegrityChecksum.length);
    }

    /** Package private */
    byte[] encode() {
        ByteBuffer buffer = ByteBuffer.allocate(getLength());
        buffer.put(mIv).put(mEncryptedAndPaddedData).put(mIntegrityChecksum);
        return buffer.array();
    }
}