index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/Nfold.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; import java.util.Arrays; /** * Based on RFC3961, with ref. MIT krb5 nfold.c */ /* * n-fold(k-bits): * l = lcm(n,k) * r = l/k * s = k-bits | k-bits rot 13 | k-bits rot 13*2 | ... | k-bits rot 13*(r-1) * compute the 1's complement sum: * n-fold = s[0..n-1]+s[n..2n-1]+s[2n..3n-1]+..+s[(k-1)*n..k*n-1] */ @SuppressWarnings("PMD") public class Nfold { /** * representation: msb first, assume n and k are multiples of 8, and * that {@code k>=16}. this is the case of all the cryptosystems which are * likely to be used. this function can be replaced if that * assumption ever fails. * @param inBytes The input bytes * @param size The size * @return The output byte */ public static byte[] nfold(byte[] inBytes, int size) { int inBytesNum = inBytes.length; // count inBytes byte int outBytesNum = size; // count inBytes byte int a = outBytesNum; int b = inBytesNum; while (b != 0) { int c = b; b = a % b; a = c; } int lcm = (outBytesNum * inBytesNum) / a; byte[] outBytes = new byte[outBytesNum]; Arrays.fill(outBytes, (byte) 0); int tmpByte = 0; for (int i = lcm - 1; i >= 0; i--) { // first, start with the msbit inBytes the first, unrotated byte int tmp = ((inBytesNum << 3) - 1); // then, for each byte, shift to the right for each repetition tmp += (((inBytesNum << 3) + 13) * (i / inBytesNum)); // last, pick outBytes the correct byte within that shifted repetition tmp += ((inBytesNum - (i % inBytesNum)) << 3); int msbit = tmp % (inBytesNum << 3); // pull outBytes the byte value itself tmp = ((((inBytes[((inBytesNum - 1) - (msbit >>> 3)) % inBytesNum] & 0xff) << 8) | (inBytes[((inBytesNum) - (msbit >>> 3)) % inBytesNum] & 0xff)) >>> ((msbit & 7) + 1)) & 0xff; tmpByte += tmp; tmp = (outBytes[i % outBytesNum] & 0xff); tmpByte += tmp; outBytes[i % outBytesNum] = (byte) (tmpByte & 0xff); tmpByte >>>= 8; } // if there's a carry bit left over, add it back inBytes if (tmpByte != 0) { for (int i = outBytesNum - 1; i >= 0; i--) { // do the addition tmpByte += (outBytes[i] & 0xff); outBytes[i] = (byte) (tmpByte & 0xff); tmpByte >>>= 8; } } return outBytes; } }
300
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/BytesUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; @SuppressWarnings("PMD") public class BytesUtil { public static short bytes2short(byte[] bytes, int offset, boolean bigEndian) { short val = 0; if (bigEndian) { val += (bytes[offset + 0] & 0xff) << 8; val += (bytes[offset + 1] & 0xff); } else { val += (bytes[offset + 1] & 0xff) << 8; val += (bytes[offset + 0] & 0xff); } return val; } public static short bytes2short(byte[] bytes, boolean bigEndian) { return bytes2short(bytes, 0, bigEndian); } public static byte[] short2bytes(int val, boolean bigEndian) { byte[] bytes = new byte[2]; short2bytes(val, bytes, 0, bigEndian); return bytes; } public static void short2bytes(int val, byte[] bytes, int offset, boolean bigEndian) { if (bigEndian) { bytes[offset + 0] = (byte) ((val >> 8) & 0xff); bytes[offset + 1] = (byte) ((val) & 0xff); } else { bytes[offset + 1] = (byte) ((val >> 8) & 0xff); bytes[offset + 0] = (byte) ((val) & 0xff); } } public static int bytes2int(byte[] bytes, boolean bigEndian) { return bytes2int(bytes, 0, bigEndian); } public static int bytes2int(byte[] bytes, int offset, boolean bigEndian) { int val = 0; if (bigEndian) { val += (bytes[offset + 0] & 0xff) << 24; val += (bytes[offset + 1] & 0xff) << 16; val += (bytes[offset + 2] & 0xff) << 8; val += (bytes[offset + 3] & 0xff); } else { val += (bytes[offset + 3] & 0xff) << 24; val += (bytes[offset + 2] & 0xff) << 16; val += (bytes[offset + 1] & 0xff) << 8; val += (bytes[offset + 0] & 0xff); } return val; } public static byte[] int2bytes(int val, boolean bigEndian) { byte[] bytes = new byte[4]; int2bytes(val, bytes, 0, bigEndian); return bytes; } public static void int2bytes(int val, byte[] bytes, int offset, boolean bigEndian) { if (bigEndian) { bytes[offset + 0] = (byte) ((val >> 24) & 0xff); bytes[offset + 1] = (byte) ((val >> 16) & 0xff); bytes[offset + 2] = (byte) ((val >> 8) & 0xff); bytes[offset + 3] = (byte) ((val) & 0xff); } else { bytes[offset + 3] = (byte) ((val >> 24) & 0xff); bytes[offset + 2] = (byte) ((val >> 16) & 0xff); bytes[offset + 1] = (byte) ((val >> 8) & 0xff); bytes[offset + 0] = (byte) ((val) & 0xff); } } public static byte[] long2bytes(long val, boolean bigEndian) { byte[] bytes = new byte[8]; long2bytes(val, bytes, 0, bigEndian); return bytes; } public static void long2bytes(long val, byte[] bytes, int offset, boolean bigEndian) { if (bigEndian) { for (int i = 0; i < 8; i++) { bytes[i + offset] = (byte) ((val >> ((7 - i) * 8)) & 0xffL); } } else { for (int i = 0; i < 8; i++) { bytes[i + offset] = (byte) ((val >> (i * 8)) & 0xffL); } } } public static long bytes2long(byte[] bytes, boolean bigEndian) { return bytes2long(bytes, 0, bigEndian); } public static long bytes2long(byte[] bytes, int offset, boolean bigEndian) { long val = 0; if (bigEndian) { for (int i = 0; i < 8; i++) { val |= (((long) bytes[i + offset]) & 0xffL) << ((7 - i) * 8); } } else { for (int i = 0; i < 8; i++) { val |= (((long) bytes[i + offset]) & 0xffL) << (i * 8); } } return val; } public static byte[] padding(byte[] data, int block) { int len = data.length; int paddingLen = len % block != 0 ? 8 - len % block : 0; if (paddingLen == 0) { return data; } byte[] result = new byte[len + paddingLen]; System.arraycopy(data, 0, result, 0, len); return result; } public static byte[] duplicate(byte[] bytes) { return duplicate(bytes, 0, bytes.length); } public static byte[] duplicate(byte[] bytes, int offset, int len) { byte[] dup = new byte[len]; System.arraycopy(bytes, offset, dup, 0, len); return dup; } public static void xor(byte[] input, int offset, byte[] output) { for (int i = 0; i < output.length / 4; ++i) { int a = BytesUtil.bytes2int(input, offset + i * 4, true); int b = BytesUtil.bytes2int(output, i * 4, true); b = a ^ b; BytesUtil.int2bytes(b, output, i * 4, true); } } public static void xor(byte[] a, byte[] b, byte[] output) { for (int i = 0; i < a.length / 4; ++i) { int av = BytesUtil.bytes2int(a, i * 4, true); int bv = BytesUtil.bytes2int(b, i * 4, true); int v = av ^ bv; BytesUtil.int2bytes(v, output, i * 4, true); } } }
301
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/Hmac.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.KrbException; import java.util.Arrays; /** * Ref. MIT krb5 hmac.c */ public class Hmac { public static byte[] hmac(HashProvider hashProvider, byte[] key, byte[] data, int outputSize) throws KrbException { return hmac(hashProvider, key, data, 0, data.length, outputSize); } public static byte[] hmac(HashProvider hashProvider, byte[] key, byte[] data, int start, int len, int outputSize) throws KrbException { byte[] hash = Hmac.hmac(hashProvider, key, data, start, len); byte[] output = new byte[outputSize]; System.arraycopy(hash, 0, output, 0, outputSize); return output; } public static byte[] hmac(HashProvider hashProvider, byte[] key, byte[] data) throws KrbException { return hmac(hashProvider, key, data, 0, data.length); } public static byte[] hmac(HashProvider hashProvider, byte[] key, byte[] data, int start, int len) throws KrbException { int blockLen = hashProvider.blockSize(); byte[] innerPaddedKey = new byte[blockLen]; byte[] outerPaddedKey = new byte[blockLen]; // Create the inner padded key Arrays.fill(innerPaddedKey, (byte) 0x36); for (int i = 0; i < key.length; i++) { innerPaddedKey[i] ^= key[i]; } // Create the outer padded key Arrays.fill(outerPaddedKey, (byte) 0x5c); for (int i = 0; i < key.length; i++) { outerPaddedKey[i] ^= key[i]; } hashProvider.hash(innerPaddedKey); hashProvider.hash(data, start, len); byte[] tmp = hashProvider.output(); hashProvider.hash(outerPaddedKey); hashProvider.hash(tmp); return hashProvider.output(); } }
302
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/Cmac.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; import java.util.Arrays; /** * Based on MIT krb5 cmac.c */ @SuppressWarnings("PMD") public class Cmac { private static byte[] constRb = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x87 }; public static byte[] cmac(EncryptProvider encProvider, byte[] key, byte[] data, int outputSize) throws KrbException { return cmac(encProvider, key, data, 0, data.length, outputSize); } public static byte[] cmac(EncryptProvider encProvider, byte[] key, byte[] data, int start, int len, int outputSize) throws KrbException { byte[] hash = Cmac.cmac(encProvider, key, data, start, len); if (hash.length > outputSize) { byte[] output = new byte[outputSize]; System.arraycopy(hash, 0, output, 0, outputSize); return output; } else { return hash; } } public static byte[] cmac(EncryptProvider encProvider, byte[] key, byte[] data) throws KrbException { return cmac(encProvider, key, data, 0, data.length); } public static byte[] cmac(EncryptProvider encProvider, byte[] key, byte[] data, int start, int len) throws KrbException { int blockSize = encProvider.blockSize(); byte[] y = new byte[blockSize]; byte[] mLast = new byte[blockSize]; byte[] padded = new byte[blockSize]; byte[] k1 = new byte[blockSize]; byte[] k2 = new byte[blockSize]; // step 1 makeSubkey(encProvider, key, k1, k2); // step 2 int n = (len + blockSize - 1) / blockSize; // step 3 boolean lastIsComplete; if (n == 0) { n = 1; lastIsComplete = false; } else { lastIsComplete = ((len % blockSize) == 0); } // Step 6 (all but last block) byte[] cipherState = new byte[blockSize]; byte[] cipher = new byte[blockSize]; for (int i = 0; i < n - 1; i++) { System.arraycopy(data, i * blockSize, cipher, 0, blockSize); encryptBlock(encProvider, key, cipherState, cipher); System.arraycopy(cipher, 0, cipherState, 0, blockSize); } // step 5 System.arraycopy(cipher, 0, y, 0, blockSize); // step 4 int lastPos = (n - 1) * blockSize; int lastLen = lastIsComplete ? blockSize : len % blockSize; byte[] lastBlock = new byte[lastLen]; System.arraycopy(data, lastPos, lastBlock, 0, lastLen); if (lastIsComplete) { BytesUtil.xor(lastBlock, k1, mLast); } else { padding(lastBlock, padded); BytesUtil.xor(padded, k2, mLast); } // Step 6 (last block) encryptBlock(encProvider, key, cipherState, mLast); return mLast; } // Generate subkeys K1 and K2 as described in RFC 4493 figure 2.2. private static void makeSubkey(EncryptProvider encProvider, byte[] key, byte[] k1, byte[] k2) throws KrbException { // L := encrypt(K, const_Zero) byte[] l = new byte[k1.length]; Arrays.fill(l, (byte) 0); encryptBlock(encProvider, key, null, l); // K1 := (MSB(L) == 0) ? L << 1 : (L << 1) XOR const_Rb if ((l[0] & 0x80) == 0) { leftShiftByOne(l, k1); } else { byte[] tmp = new byte[k1.length]; leftShiftByOne(l, tmp); BytesUtil.xor(tmp, constRb, k1); } // K2 := (MSB(K1) == 0) ? K1 << 1 : (K1 << 1) XOR const_Rb if ((k1[0] & 0x80) == 0) { leftShiftByOne(k1, k2); } else { byte[] tmp = new byte[k1.length]; leftShiftByOne(k1, tmp); BytesUtil.xor(tmp, constRb, k2); } } private static void encryptBlock(EncryptProvider encProvider, byte[] key, byte[] cipherState, byte[] block) throws KrbException { if (cipherState == null) { cipherState = new byte[encProvider.blockSize()]; } if (encProvider.supportCbcMac()) { encProvider.cbcMac(key, cipherState, block); } else { encProvider.encrypt(key, cipherState, block); } } private static void leftShiftByOne(byte[] input, byte[] output) { byte overflow = 0; for (int i = input.length - 1; i >= 0; i--) { output[i] = (byte) (input[i] << 1); output[i] |= overflow; overflow = (byte) ((input[i] & 0x80) != 0 ? 1 : 0); } } // Padding out data with a 1 bit followed by 0 bits, placing the result in pad private static void padding(byte[] data, byte[] padded) { int len = data.length; // original last block System.arraycopy(data, 0, padded, 0, len); padded[len] = (byte) 0x80; for (int i = len + 1; i < padded.length; i++) { padded[i] = 0x00; } } }
303
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/Crc32.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; /** * Reference: http://introcs.cs.princeton.edu/java/51data/CRC32.java */ public class Crc32 { private static long[] table = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; public static byte[] crc(byte[] data, int start, int size) { long c = crc(0, data, start, size); return BytesUtil.int2bytes((int) c, false); } public static long crc(long initial, byte[] data, int start, int len) { long c = initial; for (int i = 0; i < len; i++) { int idx = (int) ((data[start + i] ^ c) & 0xff); c = ((c & 0xffffffffL) >>> 8) ^ table[idx]; // why? } return c; } }
304
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/util/Camellia.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.util; /** * Camellia - based on RFC 3713, about half the size of CamelliaEngine. * * This is based on CamelliaEngine.java from bouncycastle library. */ @SuppressWarnings("PMD") public class Camellia { private static final int BLOCK_SIZE = 16; private int[] state = new int[4]; // for encryption and decryption private CamelliaKey camKey; public void setKey(boolean forEncryption, byte[] key) { camKey = new CamelliaKey(key, forEncryption); } private void process128Block(byte[] in, int inOff, byte[] out, int outOff) { for (int i = 0; i < 4; i++) { state[i] = BytesUtil.bytes2int(in, inOff + (i * 4), true); state[i] ^= camKey.kw[i]; } camKey.f2(state, camKey.subkey, 0); camKey.f2(state, camKey.subkey, 4); camKey.f2(state, camKey.subkey, 8); camKey.fls(state, camKey.ke, 0); camKey.f2(state, camKey.subkey, 12); camKey.f2(state, camKey.subkey, 16); camKey.f2(state, camKey.subkey, 20); camKey.fls(state, camKey.ke, 4); camKey.f2(state, camKey.subkey, 24); camKey.f2(state, camKey.subkey, 28); camKey.f2(state, camKey.subkey, 32); state[2] ^= camKey.kw[4]; state[3] ^= camKey.kw[5]; state[0] ^= camKey.kw[6]; state[1] ^= camKey.kw[7]; BytesUtil.int2bytes(state[2], out, outOff, true); BytesUtil.int2bytes(state[3], out, outOff + 4, true); BytesUtil.int2bytes(state[0], out, outOff + 8, true); BytesUtil.int2bytes(state[1], out, outOff + 12, true); } private void processBlockLargerBlock(byte[] in, int inOff, byte[] out, int outOff) { for (int i = 0; i < 4; i++) { state[i] = BytesUtil.bytes2int(in, inOff + (i * 4), true); state[i] ^= camKey.kw[i]; } camKey.f2(state, camKey.subkey, 0); camKey.f2(state, camKey.subkey, 4); camKey.f2(state, camKey.subkey, 8); camKey.fls(state, camKey.ke, 0); camKey.f2(state, camKey.subkey, 12); camKey.f2(state, camKey.subkey, 16); camKey.f2(state, camKey.subkey, 20); camKey.fls(state, camKey.ke, 4); camKey.f2(state, camKey.subkey, 24); camKey.f2(state, camKey.subkey, 28); camKey.f2(state, camKey.subkey, 32); camKey.fls(state, camKey.ke, 8); camKey.f2(state, camKey.subkey, 36); camKey.f2(state, camKey.subkey, 40); camKey.f2(state, camKey.subkey, 44); state[2] ^= camKey.kw[4]; state[3] ^= camKey.kw[5]; state[0] ^= camKey.kw[6]; state[1] ^= camKey.kw[7]; BytesUtil.int2bytes(state[2], out, outOff, true); BytesUtil.int2bytes(state[3], out, outOff + 4, true); BytesUtil.int2bytes(state[0], out, outOff + 8, true); BytesUtil.int2bytes(state[1], out, outOff + 12, true); } public void processBlock(byte[] in, int inOff) { byte[] out = new byte[BLOCK_SIZE]; if (camKey.is128()) { process128Block(in, inOff, out, 0); } else { processBlockLargerBlock(in, inOff, out, 0); } System.arraycopy(out, 0, in, inOff, BLOCK_SIZE); } public void encrypt(byte[] data, byte[] iv) { byte[] cipherState = new byte[BLOCK_SIZE]; int blocksNum = (data.length + BLOCK_SIZE - 1) / BLOCK_SIZE; int lastBlockLen = data.length - (blocksNum - 1) * BLOCK_SIZE; if (blocksNum == 1) { cbcEnc(data, 0, 1, cipherState); return; } if (iv != null) { System.arraycopy(iv, 0, cipherState, 0, BLOCK_SIZE); } int contBlocksNum, offset = 0; while (blocksNum > 2) { contBlocksNum = (data.length - offset) / BLOCK_SIZE; if (contBlocksNum > 0) { // Encrypt a series of contiguous blocks in place if we can, but // don't touch the last two blocks. contBlocksNum = (contBlocksNum > blocksNum - 2) ? blocksNum - 2 : contBlocksNum; cbcEnc(data, offset, contBlocksNum, cipherState); offset += contBlocksNum * BLOCK_SIZE; blocksNum -= contBlocksNum; } else { cbcEnc(data, offset, 1, cipherState); offset += BLOCK_SIZE; blocksNum--; } } // Encrypt the last two blocks and store the results in reverse order byte[] blockN2 = new byte[BLOCK_SIZE]; byte[] blockN1 = new byte[BLOCK_SIZE]; System.arraycopy(data, offset, blockN2, 0, BLOCK_SIZE); cbcEnc(blockN2, 0, 1, cipherState); System.arraycopy(data, offset + BLOCK_SIZE, blockN1, 0, lastBlockLen); cbcEnc(blockN1, 0, 1, cipherState); System.arraycopy(blockN1, 0, data, offset, BLOCK_SIZE); System.arraycopy(blockN2, 0, data, offset + BLOCK_SIZE, lastBlockLen); if (iv != null) { System.arraycopy(cipherState, 0, iv, 0, BLOCK_SIZE); } } public void decrypt(byte[] data, byte[] iv) { byte[] cipherState = new byte[BLOCK_SIZE]; int blocksNum = (data.length + BLOCK_SIZE - 1) / BLOCK_SIZE; int lastBlockLen = data.length - (blocksNum - 1) * BLOCK_SIZE; if (blocksNum == 1) { cbcDec(data, 0, 1, cipherState); return; } if (iv != null) { System.arraycopy(iv, 0, cipherState, 0, BLOCK_SIZE); } int contBlocksNum, offset = 0; while (blocksNum > 2) { contBlocksNum = (data.length - offset) / BLOCK_SIZE; if (contBlocksNum > 0) { // Decrypt a series of contiguous blocks in place if we can, but // don't touch the last two blocks. contBlocksNum = (contBlocksNum > blocksNum - 2) ? blocksNum - 2 : contBlocksNum; cbcDec(data, offset, contBlocksNum, cipherState); offset += contBlocksNum * BLOCK_SIZE; blocksNum -= contBlocksNum; } else { cbcDec(data, offset, 1, cipherState); offset += BLOCK_SIZE; blocksNum--; } } // Decrypt the last two blocks byte[] blockN2 = new byte[BLOCK_SIZE]; byte[] blockN1 = new byte[BLOCK_SIZE]; System.arraycopy(data, offset, blockN2, 0, BLOCK_SIZE); System.arraycopy(data, offset + BLOCK_SIZE, blockN1, 0, lastBlockLen); if (iv != null) { System.arraycopy(blockN2, 0, iv, 0, BLOCK_SIZE); } byte[] tmpCipherState = new byte[BLOCK_SIZE]; System.arraycopy(blockN1, 0, tmpCipherState, 0, BLOCK_SIZE); cbcDec(blockN2, 0, 1, tmpCipherState); System.arraycopy(blockN2, lastBlockLen, blockN1, lastBlockLen, BLOCK_SIZE - lastBlockLen); cbcDec(blockN1, 0, 1, cipherState); System.arraycopy(blockN1, 0, data, offset, BLOCK_SIZE); System.arraycopy(blockN2, 0, data, offset + BLOCK_SIZE, lastBlockLen); } /** * CBC encrypt nblocks blocks of data in place, using and updating iv. * @param data The data * @param offset The offset * @param blocksNum The block number * @param cipherState The cipher state */ public void cbcEnc(byte[] data, int offset, int blocksNum, byte[] cipherState) { byte[] cipher = new byte[BLOCK_SIZE]; for (int i = 0; i < blocksNum; ++i) { System.arraycopy(data, offset + i * BLOCK_SIZE, cipher, 0, BLOCK_SIZE); BytesUtil.xor(cipherState, 0, cipher); processBlock(cipher, 0); System.arraycopy(cipher, 0, data, offset + i * BLOCK_SIZE, BLOCK_SIZE); System.arraycopy(cipher, 0, cipherState, 0, BLOCK_SIZE); } } /** * CBC encrypt nblocks blocks of data in place, using and updating iv. * @param data The data * @param offset The offset * @param blocksNum The block number * @param cipherState The cipher state */ public void cbcDec(byte[] data, int offset, int blocksNum, byte[] cipherState) { byte[] lastBlock = new byte[BLOCK_SIZE]; byte[] cipher = new byte[BLOCK_SIZE]; System.arraycopy(data, offset + (blocksNum - 1) * BLOCK_SIZE, lastBlock, 0, BLOCK_SIZE); for (int i = blocksNum; i > 0; i--) { System.arraycopy(data, offset + (i - 1) * BLOCK_SIZE, cipher, 0, BLOCK_SIZE); processBlock(cipher, 0); if (i == 1) { BytesUtil.xor(cipherState, 0, cipher); } else { BytesUtil.xor(data, offset + (i - 2) * BLOCK_SIZE, cipher); } System.arraycopy(cipher, 0, data, offset + (i - 1) * BLOCK_SIZE, BLOCK_SIZE); } System.arraycopy(lastBlock, 0, cipherState, 0, BLOCK_SIZE); } }
305
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/fast/FastUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.fast; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import java.nio.charset.StandardCharsets; /** * Implementing FAST (RFC6113) armor key related algorithms. * Take two keys and two pepper strings as input and return a combined key. */ public class FastUtil { /** * Call the PRF function multiple times with the pepper prefixed with * a count byte to get enough bits of output. * @param key The encryption key * @param pepper The pepper * @param keyBytesLen The key bytes length * @return The output byte * @throws KrbException e */ public static byte[] prfPlus(EncryptionKey key, String pepper, int keyBytesLen) throws KrbException { byte[] prfInbuf = new byte[pepper.length() + 1]; byte[] tmpbuf = new byte[keyBytesLen]; int prfSize = EncryptionHandler.getEncHandler(key.getKeyType()).prfSize(); int iterations = keyBytesLen / prfSize; prfInbuf[0] = 1; System.arraycopy(pepper.getBytes(StandardCharsets.UTF_8), 0, prfInbuf, 1, pepper.length()); if (keyBytesLen % prfSize != 0) { iterations++; } byte[] buffer = new byte[prfSize * iterations]; for (int i = 0; i < iterations; i++) { System.arraycopy(EncryptionHandler.getEncHandler(key.getKeyType()) .prf(key.getKeyData(), prfInbuf), 0, buffer, i * prfSize, prfSize); prfInbuf[0]++; } System.arraycopy(buffer, 0, tmpbuf, 0, keyBytesLen); return tmpbuf; } public static EncryptionKey cf2(EncryptionKey key1, String pepper1, EncryptionKey key2, String pepper2) throws KrbException { int keyBites = EncryptionHandler.getEncHandler(key1.getKeyType()).encProvider().keyInputSize(); byte[] buf1 = prfPlus(key1, pepper1, keyBites); byte[] buf2 = prfPlus(key2, pepper2, keyBites); for (int i = 0; i < keyBites; i++) { buf1[i] ^= buf2[i]; } EncryptionKey outKey = EncryptionHandler.random2Key(key1.getKeyType(), buf1); return outKey; } /** * Make an encryption key for replying. * @param strengthenKey The strengthen key * @param existingKey The existing key * @return encryption key * @throws KrbException e */ public static EncryptionKey makeReplyKey(EncryptionKey strengthenKey, EncryptionKey existingKey) throws KrbException { return cf2(strengthenKey, "strengthenkey", existingKey, "replykey"); } /** * Make an encryption key for armoring. * @param subkey The sub key * @param ticketKey The ticket key * @return encryption key * @throws KrbException e */ public static EncryptionKey makeArmorKey(EncryptionKey subkey, EncryptionKey ticketKey) throws KrbException { return cf2(subkey, "subkeyarmor", ticketKey, "ticketarmor"); } }
306
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/RsaMd5CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.AbstractUnkeyedCheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class RsaMd5CheckSum extends AbstractUnkeyedCheckSumTypeHandler { public RsaMd5CheckSum() { super(new Md5Provider(), 16, 16); } public CheckSumType cksumType() { return CheckSumType.RSA_MD5; } }
307
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/AbstractKeyedCheckSumTypeHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.crypto.key.KeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractKeyedCheckSumTypeHandler extends AbstractCheckSumTypeHandler { private KeyMaker keyMaker; public AbstractKeyedCheckSumTypeHandler(EncryptProvider encProvider, HashProvider hashProvider, int computeSize, int outputSize) { super(encProvider, hashProvider, computeSize, outputSize); } protected void keyMaker(KeyMaker keyMaker) { this.keyMaker = keyMaker; } protected KeyMaker keyMaker() { return keyMaker; } @Override public byte[] checksumWithKey(byte[] data, byte[] key, int usage) throws KrbException { return checksumWithKey(data, 0, data.length, key, usage); } @Override public byte[] checksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { int outputSize = outputSize(); byte[] tmp = doChecksumWithKey(data, start, len, key, usage); if (outputSize < tmp.length) { byte[] output = new byte[outputSize]; System.arraycopy(tmp, 0, output, 0, outputSize); return output; } else { return tmp; } } protected byte[] doChecksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { return new byte[0]; } @Override public boolean verifyWithKey(byte[] data, byte[] key, int usage, byte[] checksum) throws KrbException { byte[] newCksum = checksumWithKey(data, key, usage); return checksumEqual(checksum, newCksum); } }
308
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HashProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.KrbException; /** * Ref. MIT Krb5: krb5_hash_provider */ /** * Hash provider that provides hash function * for implementing a checksum type defined by Kerberos RFC3961. */ public interface HashProvider { int hashSize(); int blockSize(); void hash(byte[] data, int start, int size) throws KrbException; void hash(byte[] data) throws KrbException; byte[] output(); }
309
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/AbstractCheckSumTypeHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.AbstractCryptoTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.CheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractCheckSumTypeHandler extends AbstractCryptoTypeHandler implements CheckSumTypeHandler { private int computeSize; private int outputSize; public AbstractCheckSumTypeHandler(EncryptProvider encProvider, HashProvider hashProvider, int computeSize, int outputSize) { super(encProvider, hashProvider); this.computeSize = computeSize; this.outputSize = outputSize; } @Override public String name() { return cksumType().getName(); } @Override public String displayName() { return cksumType().getDisplayName(); } @Override public int computeSize() { return computeSize; } @Override public int outputSize() { return outputSize; } public boolean isSafe() { return false; } public int cksumSize() { return 4; } public int keySize() { return 0; } public int confounderSize() { return 0; } @Override public byte[] checksum(byte[] data) throws KrbException { return checksum(data, 0, data.length); } @Override public byte[] checksum(byte[] data, int start, int size) throws KrbException { throw new UnsupportedOperationException(); } @Override public boolean verify(byte[] data, byte[] checksum) throws KrbException { return verify(data, 0, data.length, checksum); } @Override public boolean verify(byte[] data, int start, int size, byte[] checksum) throws KrbException { throw new UnsupportedOperationException(); } @Override public byte[] checksumWithKey(byte[] data, byte[] key, int usage) throws KrbException { return checksumWithKey(data, 0, data.length, key, usage); } @Override public byte[] checksumWithKey(byte[] data, int start, int size, byte[] key, int usage) throws KrbException { throw new UnsupportedOperationException(); } @Override public boolean verifyWithKey(byte[] data, byte[] key, int usage, byte[] checksum) throws KrbException { throw new UnsupportedOperationException(); } }
310
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/RsaMd4CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.AbstractUnkeyedCheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md4Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class RsaMd4CheckSum extends AbstractUnkeyedCheckSumTypeHandler { public RsaMd4CheckSum() { super(new Md4Provider(), 16, 16); } public CheckSumType cksumType() { return CheckSumType.RSA_MD4; } }
311
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/ConfounderedDesCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.Confounder; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.DesProvider; import org.apache.kerby.kerberos.kerb.KrbException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.spec.DESKeySpec; import java.security.InvalidKeyException; public abstract class ConfounderedDesCheckSum extends AbstractKeyedCheckSumTypeHandler { private static final Logger LOG = LoggerFactory .getLogger(ConfounderedDesCheckSum.class); public ConfounderedDesCheckSum(HashProvider hashProvider, int computeSize, int outputSize) { super(new DesProvider(), hashProvider, computeSize, outputSize); } @Override protected byte[] doChecksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { int computeSize = computeSize(); int blockSize = encProvider().blockSize(); int hashSize = hashProvider().hashSize(); byte[] workBuffer = new byte[computeSize]; // confounder byte[] conf = Confounder.makeBytes(blockSize); // confounder | data byte[] toHash = new byte[blockSize + len]; System.arraycopy(conf, 0, toHash, 0, blockSize); System.arraycopy(data, start, toHash, blockSize, len); HashProvider hashProvider = hashProvider(); hashProvider.hash(toHash); byte[] hash = hashProvider.output(); // confounder | hash System.arraycopy(conf, 0, workBuffer, 0, blockSize); System.arraycopy(hash, 0, workBuffer, blockSize, hashSize); // key byte[] newKey = deriveKey(key); encProvider().encrypt(newKey, workBuffer); return workBuffer; } protected byte[] deriveKey(byte[] key) { return fixKey(xorKey(key)); } protected byte[] xorKey(byte[] key) { byte[] xorKey = new byte[encProvider().keySize()]; System.arraycopy(key, 0, xorKey, 0, key.length); for (int i = 0; i < xorKey.length; i++) { xorKey[i] = (byte) (xorKey[i] ^ 0xf0); } return xorKey; } private byte[] fixKey(byte[] key) { boolean isWeak = true; try { isWeak = DESKeySpec.isWeak(key, 0); } catch (InvalidKeyException e) { LOG.error("Invalid key found. "); } if (isWeak) { key[7] = (byte) (key[7] ^ 0xF0); } return key; } @Override public boolean verifyWithKey(byte[] data, byte[] key, int usage, byte[] checksum) throws KrbException { // int computeSize = computeSize(); int blockSize = encProvider().blockSize(); int hashSize = hashProvider().hashSize(); // key byte[] newKey = deriveKey(key); encProvider().decrypt(newKey, checksum); byte[] decrypted = checksum; // confounder | hash // confounder | data byte[] toHash = new byte[blockSize + data.length]; System.arraycopy(decrypted, 0, toHash, 0, blockSize); System.arraycopy(data, 0, toHash, blockSize, data.length); HashProvider hashProvider = hashProvider(); hashProvider.hash(toHash); byte[] newHash = hashProvider.output(); return checksumEqual(newHash, decrypted, blockSize, hashSize); } }
312
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/CmacKcCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.Cmac; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class CmacKcCheckSum extends KcCheckSum { public CmacKcCheckSum(EncryptProvider encProvider, int computeSize, int outputSize) { super(encProvider, null, computeSize, outputSize); } protected byte[] mac(byte[] kc, byte[] data, int start, int len) throws KrbException { return Cmac.cmac(encProvider(), kc, data, start, len); } }
313
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/Sha1CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.AbstractUnkeyedCheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class Sha1CheckSum extends AbstractUnkeyedCheckSumTypeHandler { public Sha1CheckSum() { super(new Sha1Provider(), 20, 20); } public CheckSumType cksumType() { return CheckSumType.NIST_SHA; } }
314
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/CmacCamellia128CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia128Provider; import org.apache.kerby.kerberos.kerb.crypto.key.CamelliaKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class CmacCamellia128CheckSum extends CmacKcCheckSum { public CmacCamellia128CheckSum() { super(new Camellia128Provider(), 16, 16); keyMaker(new CamelliaKeyMaker((Camellia128Provider) encProvider())); } public int confounderSize() { return 16; } public CheckSumType cksumType() { return CheckSumType.CMAC_CAMELLIA128; } public boolean isSafe() { return true; } public int cksumSize() { return 16; // bytes } public int keySize() { return 16; // bytes } }
315
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HmacSha1Aes256CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes256Provider; import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class HmacSha1Aes256CheckSum extends HmacKcCheckSum { public HmacSha1Aes256CheckSum() { super(new Aes256Provider(), 20, 12); keyMaker(new AesKeyMaker((Aes256Provider) encProvider())); } public int confounderSize() { return 16; } public CheckSumType cksumType() { return CheckSumType.HMAC_SHA1_96_AES256; } public boolean isSafe() { return true; } public int cksumSize() { return 12; // bytes } public int keySize() { return 32; // bytes } }
316
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HmacKcCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.Hmac; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class HmacKcCheckSum extends KcCheckSum { public HmacKcCheckSum(EncryptProvider encProvider, int computeSize, int outputSize) { super(encProvider, new Sha1Provider(), computeSize, outputSize); } protected byte[] mac(byte[] kc, byte[] data, int start, int len) throws KrbException { return Hmac.hmac(hashProvider(), kc, data, start, len); } }
317
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/Md5HmacRc4CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.Hmac; import org.apache.kerby.kerberos.kerb.crypto.util.Rc4; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Rc4Provider; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class Md5HmacRc4CheckSum extends AbstractKeyedCheckSumTypeHandler { public Md5HmacRc4CheckSum() { super(new Rc4Provider(), new Md5Provider(), 16, 16); } public int confounderSize() { return 8; } public CheckSumType cksumType() { return CheckSumType.MD5_HMAC_ARCFOUR; } public boolean isSafe() { return true; } public int cksumSize() { return 16; // bytes } public int keySize() { return 16; // bytes } @Override protected byte[] doChecksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { byte[] ksign = key; byte[] salt = Rc4.getSalt(usage, false); hashProvider().hash(salt); hashProvider().hash(data, start, len); byte[] hashTmp = hashProvider().output(); return Hmac.hmac(hashProvider(), ksign, hashTmp); } }
318
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/RsaMd5DesCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public final class RsaMd5DesCheckSum extends ConfounderedDesCheckSum { public RsaMd5DesCheckSum() { super(new Md5Provider(), 24, 24); } public CheckSumType cksumType() { return CheckSumType.RSA_MD5_DES; } }
319
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/CmacCamellia256CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia256Provider; import org.apache.kerby.kerberos.kerb.crypto.key.CamelliaKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class CmacCamellia256CheckSum extends CmacKcCheckSum { public CmacCamellia256CheckSum() { super(new Camellia256Provider(), 16, 16); keyMaker(new CamelliaKeyMaker((Camellia256Provider) encProvider())); } public int confounderSize() { return 16; } public CheckSumType cksumType() { return CheckSumType.CMAC_CAMELLIA256; } public boolean isSafe() { return true; } public int cksumSize() { return 16; // bytes } public int keySize() { return 16; // bytes } }
320
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HmacSha1Aes128CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes128Provider; import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class HmacSha1Aes128CheckSum extends HmacKcCheckSum { public HmacSha1Aes128CheckSum() { super(new Aes128Provider(), 20, 12); keyMaker(new AesKeyMaker((Aes128Provider) encProvider())); } public int confounderSize() { return 16; } public CheckSumType cksumType() { return CheckSumType.HMAC_SHA1_96_AES128; } public boolean isSafe() { return true; } public int cksumSize() { return 12; // bytes } public int keySize() { return 16; // bytes } }
321
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HmacSha1Des3CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Des3Provider; import org.apache.kerby.kerberos.kerb.crypto.key.Des3KeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class HmacSha1Des3CheckSum extends HmacKcCheckSum { public HmacSha1Des3CheckSum() { super(new Des3Provider(), 20, 20); keyMaker(new Des3KeyMaker(encProvider())); } public int confounderSize() { return 8; } public CheckSumType cksumType() { return CheckSumType.HMAC_SHA1_DES3; } public boolean isSafe() { return true; } public int cksumSize() { return 20; // bytes } public int keySize() { return 24; // bytes } }
322
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/DesCbcCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class DesCbcCheckSum extends ConfounderedDesCheckSum { public DesCbcCheckSum() { super(null, 8, 8); } public CheckSumType cksumType() { return CheckSumType.DES_CBC; } }
323
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/HmacMd5Rc4CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.Hmac; import org.apache.kerby.kerberos.kerb.crypto.util.Rc4; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import java.nio.charset.StandardCharsets; public class HmacMd5Rc4CheckSum extends AbstractKeyedCheckSumTypeHandler { public HmacMd5Rc4CheckSum() { super(null, new Md5Provider(), 16, 16); } public int confounderSize() { return 8; } public CheckSumType cksumType() { return CheckSumType.HMAC_MD5_ARCFOUR; } public boolean isSafe() { return true; } public int cksumSize() { return 16; // bytes } public int keySize() { return 16; // bytes } @Override protected byte[] doChecksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { byte[] signKey = "signaturekey".getBytes(StandardCharsets.UTF_8); byte[] newSignKey = new byte[signKey.length + 1]; System.arraycopy(signKey, 0, newSignKey, 0, signKey.length); byte[] ksign = Hmac.hmac(hashProvider(), key, newSignKey); byte[] salt = Rc4.getSalt(usage, false); hashProvider().hash(salt); hashProvider().hash(data, start, len); byte[] hashTmp = hashProvider().output(); return Hmac.hmac(hashProvider(), ksign, hashTmp); } }
324
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/KcCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.crypto.key.DkKeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class KcCheckSum extends AbstractKeyedCheckSumTypeHandler { public KcCheckSum(EncryptProvider encProvider, HashProvider hashProvider, int computeSize, int outputSize) { super(encProvider, hashProvider, computeSize, outputSize); } @Override protected byte[] doChecksumWithKey(byte[] data, int start, int len, byte[] key, int usage) throws KrbException { byte[] constant = new byte[5]; BytesUtil.int2bytes(usage, constant, 0, true); constant[4] = (byte) 0x99; byte[] kc = ((DkKeyMaker) keyMaker()).dk(key, constant); return mac(kc, data, start, len); } protected abstract byte[] mac(byte[] kc, byte[] data, int start, int len) throws KrbException; }
325
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/Crc32CheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.AbstractUnkeyedCheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Crc32Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class Crc32CheckSum extends AbstractUnkeyedCheckSumTypeHandler { public Crc32CheckSum() { super(new Crc32Provider(), 4, 4); } public CheckSumType cksumType() { return CheckSumType.CRC32; } }
326
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/RsaMd4DesCheckSum.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md4Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; public class RsaMd4DesCheckSum extends ConfounderedDesCheckSum { public RsaMd4DesCheckSum() { super(new Md4Provider(), 24, 24); } public CheckSumType cksumType() { return CheckSumType.RSA_MD4_DES; } }
327
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/Crc32Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; import org.apache.kerby.kerberos.kerb.crypto.util.Crc32; public class Crc32Provider extends AbstractHashProvider { private byte[] output; public Crc32Provider() { super(4, 1); } @Override public void hash(byte[] data, int start, int size) { output = Crc32.crc(data, start, size); } @Override public byte[] output() { return output.clone(); } }
328
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/MessageDigestHashProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; import org.apache.kerby.kerberos.kerb.KrbException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MessageDigestHashProvider extends AbstractHashProvider { private String algorithm; protected MessageDigest messageDigest; public MessageDigestHashProvider(int hashSize, int blockSize, String algorithm) { super(hashSize, blockSize); this.algorithm = algorithm; init(); } @Override protected void init() { try { messageDigest = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to init JCE provider", e); } } @Override public void hash(byte[] data, int start, int len) throws KrbException { messageDigest.update(data, start, len); } @Override public byte[] output() { return messageDigest.digest(); } }
329
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/AbstractHashProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractHashProvider implements HashProvider { private int blockSize; private int hashSize; public AbstractHashProvider(int hashSize, int blockSize) { this.hashSize = hashSize; this.blockSize = blockSize; } protected void init() { } @Override public int hashSize() { return hashSize; } @Override public int blockSize() { return blockSize; } @Override public void hash(byte[] data) throws KrbException { hash(data, 0, data.length); } }
330
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/AbstractUnkeyedCheckSumTypeHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; import org.apache.kerby.kerberos.kerb.crypto.cksum.AbstractCheckSumTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractUnkeyedCheckSumTypeHandler extends AbstractCheckSumTypeHandler { public AbstractUnkeyedCheckSumTypeHandler(HashProvider hashProvider, int computeSize, int outputSize) { super(null, hashProvider, computeSize, outputSize); } @Override public byte[] checksum(byte[] data, int start, int len) throws KrbException { int outputSize = outputSize(); HashProvider hp = hashProvider(); hp.hash(data, start, len); byte[] workBuffer = hp.output(); if (outputSize < workBuffer.length) { byte[] output = new byte[outputSize]; System.arraycopy(workBuffer, 0, output, 0, outputSize); return output; } return workBuffer; } @Override public boolean verify(byte[] data, int start, int len, byte[] checksum) throws KrbException { byte[] newCksum = checksum(data, start, len); return checksumEqual(newCksum, checksum); } }
331
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/Sha1Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; public class Sha1Provider extends MessageDigestHashProvider { public Sha1Provider() { super(20, 64, "SHA1"); } }
332
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/Md5Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; public class Md5Provider extends MessageDigestHashProvider { public Md5Provider() { super(16, 64, "MD5"); } }
333
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/cksum/provider/Md4Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.cksum.provider; import org.apache.kerby.kerberos.kerb.crypto.util.Md4; public class Md4Provider extends MessageDigestHashProvider { public Md4Provider() { super(16, 64, "MD4"); } @Override protected void init() { messageDigest = new Md4(); } }
334
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/AesKeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.util.Pbkdf; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.AesProvider; import java.security.GeneralSecurityException; public class AesKeyMaker extends DkKeyMaker { public AesKeyMaker(AesProvider encProvider) { super(encProvider); } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { return randomBits; } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { int iterCount = getIterCount(param, 4096); byte[] saltBytes = getSaltBytes(salt, null); int keySize = encProvider().keySize(); byte[] random; try { random = Pbkdf.pbkdf2(string.toCharArray(), saltBytes, iterCount, keySize); } catch (GeneralSecurityException e) { throw new KrbException("pbkdf2 failed", e); } byte[] tmpKey = random2Key(random); return dk(tmpKey, KERBEROS_CONSTANT); } }
335
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/DesKeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.util.Des; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; @SuppressWarnings("PMD") public class DesKeyMaker extends AbstractKeyMaker { public DesKeyMaker(EncryptProvider encProvider) { super(encProvider); } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { String error = null; int type = 0; if (param != null) { if (param.length != 1) { error = "Invalid param to S2K"; } type = param[0]; if (type != 0 && type != 1) { error = "Invalid param to S2K"; } } if (type == 1) { error = "AFS not supported yet"; } if (error != null) { throw new KrbException(error); } return toKey(string, salt); } /** mit_des_string_to_key(string,salt) { odd = 1; s = string | salt; tempstring = 0; // 56-bit string pad(s); // with nulls to 8 byte boundary for (8byteblock in s) { 56bitstring = removeMSBits(8byteblock); if (odd == 0) reverse(56bitstring); odd = ! odd; tempstring = tempstring XOR 56bitstring; } tempkey = key_correction(add_parity_bits(tempstring)); key = key_correction(DES-CBC-check(s,tempkey)); return(key); } */ private byte[] toKey(String string, String salt) throws KrbException { byte[] bytes = makePasswdSalt(string, salt); // padded with zero-valued octets to a multiple of eight octets. byte[] paddedBytes = BytesUtil.padding(bytes, 8); byte[] fanFoldedKey = fanFold(string, salt, paddedBytes); byte[] intermediateKey = intermediateKey(fanFoldedKey); byte[] key = desEncryptedKey(intermediateKey, paddedBytes); keyCorrection(key); return key; } /** * Visible for test * {@inheritDoc} */ public static byte[] fanFold(String string, String salt, byte[] paddedBytes) { if (paddedBytes == null) { byte[] bytes = makePasswdSalt(string, salt); // padded with zero-valued octets to a multiple of eight octets. paddedBytes = BytesUtil.padding(bytes, 8); } int blocksOfbytes8 = paddedBytes.length / 8; boolean odd = true; byte[] bits56 = new byte[8]; byte[] tempString = new byte[8]; for (int i = 0; i < blocksOfbytes8; ++i) { System.arraycopy(paddedBytes, 8 * i, bits56, 0, 8); removeMSBits(bits56); if (!odd) { reverse(bits56); } odd = !odd; BytesUtil.xor(bits56, 0, tempString); } return tempString; } /** * Visible for test * {@inheritDoc} */ public static byte[] intermediateKey(byte[] fanFoldedKey) { byte[] keyBytes = addParityBits(fanFoldedKey); keyCorrection(keyBytes); return keyBytes; } private byte[] desEncryptedKey(byte[] intermediateKey, byte[] originalBytes) throws KrbException { byte[] resultKey = null; if (encProvider().supportCbcMac()) { resultKey = encProvider().cbcMac(intermediateKey, intermediateKey, originalBytes); } else { throw new KrbException("cbcMac should be supported by the provider: " + encProvider().getClass()); } keyCorrection(resultKey); return resultKey; } /** * To turn a 56-bit block into a 64-bit block, see * Ref. eighth_byte in random_to_key.c in MIT krb5 * @param bits56 The 56-bit block * @return The 64-bit block */ private static byte[] getEightBits(byte[] bits56) { byte[] bits64 = new byte[8]; System.arraycopy(bits56, 0, bits64, 0, 7); bits64[7] = (byte) (((bits56[0] & 1) << 1) | ((bits56[1] & 1) << 2) | ((bits56[2] & 1) << 3) | ((bits56[3] & 1) << 4) | ((bits56[4] & 1) << 5) | ((bits56[5] & 1) << 6) | ((bits56[6] & 1) << 7)); return bits64; } /** * Note this isn't hit any test yet, and very probably problematic * {@inheritDoc} */ @Override public byte[] random2Key(byte[] randomBits) throws KrbException { if (randomBits.length != encProvider().keyInputSize()) { throw new KrbException("Invalid random bits, not of correct bytes size"); } byte[] keyBytes = getEightBits(randomBits); addParity(keyBytes); keyCorrection(keyBytes); return keyBytes; } // Processing an 8bytesblock private static byte[] removeMSBits(byte[] bits56) { /** Treats a 64 bit block as 8 octets and removes the MSB in each octet (in big endian mode) and concatenates the result. E.g., the input octet string: 01110000 01100001 11110011 01110011 11110111 01101111 11110010 01100100 => 1110000 1100001 1110011 1110011 1110111 1101111 1110010 1100100 */ /** * We probably do nothing here, just pretending the MSB bit to be discarded, * and ensure the MSB will not be used in the following processing. */ return bits56; } // Processing an 56bitblock private static void reverse(byte[] bits56) { /** Treats a 56-bit block as a binary string and reverses it. E.g., the input string: 1000001 1010100 1001000 1000101 1001110 1000001 0101110 1001101 => 1000001 0010101 0001001 1010001 0111001 1000001 0101110 1011001 => 1011001 0111010 1000001 0111001 1010001 0001001 0010101 1000001 */ // Reversing in a 7bit int t1, t2; byte bt; for (int i = 0; i < 8; ++i) { bt = bits56[i]; t1 = (bt >> 6) & 1; t2 = (bt >> 0) & 1; if (t1 != t2) { bt ^= (1 << 6 | 1 << 0); } t1 = (bt >> 5) & 1; t2 = (bt >> 1) & 1; if (t1 != t2) { bt ^= (1 << 5 | 1 << 1); } t1 = (bt >> 4) & 1; t2 = (bt >> 2) & 1; if (t1 != t2) { bt ^= (1 << 4 | 1 << 2); } bits56[i] = bt; } // Reversing the 8 7bit bt = bits56[7]; bits56[7] = bits56[0]; bits56[0] = bt; bt = bits56[6]; bits56[6] = bits56[1]; bits56[1] = bt; bt = bits56[5]; bits56[5] = bits56[2]; bits56[2] = bt; bt = bits56[4]; bits56[4] = bits56[3]; bits56[3] = bt; } private static byte[] addParityBits(byte[] bits56) { /** Copies a 56-bit block into a 64-bit block, left shifts content in each octet, and add DES parity bit. E.g., the input string: 1100000 0001111 0011100 0110100 1000101 1100100 0110110 0010111 => 11000001 00011111 00111000 01101000 10001010 11001000 01101101 00101111 */ for (int i = 0; i < 8; i++) { bits56[i] <<= 1; } addParity(bits56); return bits56; } private static void keyCorrection(byte[] key) { addParity(key); Des.fixKey(key, 0, key.length); } private static int smask(int step) { return (1 << step) - 1; } private static byte pstep(byte x, int step) { return (byte) ((x & smask(step)) ^ ((x >> step) & smask(step))); } private static byte parityChar(byte abyte) { //#define smask(step) ((1<<step)-1) //#define pstep(x,step) (((x)&smask(step))^(((x)>>step)&smask(step))) //#define parity_char(x) pstep(pstep(pstep((x),4),2),1) return pstep(pstep(pstep(abyte, 4), 2), 1); } private static void addParity(byte[] key) { for (int i = 0; i < key.length; ++i) { key[i] &= 0xfe; key[i] |= 1 ^ parityChar(key[i]); } } // Returns true if the key has correct des parity private static boolean checkKeyParity(byte[] key) { for (int i = 0; i < key.length; ++i) { if ((key[i] & 1) == parityChar((byte) (key[i] & 0xfe))) { return false; } } return true; } }
336
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/CamelliaKeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.util.Cmac; import org.apache.kerby.kerberos.kerb.crypto.util.Pbkdf; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.CamelliaProvider; import org.apache.kerby.kerberos.kerb.KrbException; import java.security.GeneralSecurityException; public class CamelliaKeyMaker extends DkKeyMaker { public CamelliaKeyMaker(CamelliaProvider encProvider) { super(encProvider); } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { return randomBits; } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { int iterCount = getIterCount(param, 32768); byte[] saltBytes = getSaltBytes(salt, getPepper()); int keySize = encProvider().keySize(); byte[] random; try { random = Pbkdf.pbkdf2(string.toCharArray(), saltBytes, iterCount, keySize); } catch (GeneralSecurityException e) { throw new KrbException("pbkdf2 failed", e); } byte[] tmpKey = random2Key(random); return dk(tmpKey, KERBEROS_CONSTANT); } private String getPepper() { int keySize = encProvider().keySize(); return keySize == 16 ? "camellia128-cts-cmac" : "camellia256-cts-cmac"; } /* * NIST SP800-108 KDF in feedback mode (section 5.2). */ @Override protected byte[] dr(byte[] key, byte[] constant) throws KrbException { int blocksize = encProvider().blockSize(); int keyInuptSize = encProvider().keyInputSize(); byte[] keyBytes = new byte[keyInuptSize]; int len = 0; // K(i-1): the previous block of PRF output, initially all-zeros. len += blocksize; // four-byte big-endian binary string giving the block counter len += 4; // the fixed derived-key input len += constant.length; // 0x00: separator byte len += 1; // four-byte big-endian binary string giving the output length len += 4; byte[] ki = new byte[len]; System.arraycopy(constant, 0, ki, blocksize + 4, constant.length); BytesUtil.int2bytes(keyInuptSize * 8, ki, len - 4, true); for (int i = 1, n = 0; n < keyInuptSize; i++) { // Update the block counter BytesUtil.int2bytes(i, ki, blocksize, true); // Compute a CMAC checksum, update Ki with the result byte[] tmp = Cmac.cmac(encProvider(), key, ki); System.arraycopy(tmp, 0, ki, 0, blocksize); if (n + blocksize >= keyInuptSize) { System.arraycopy(ki, 0, keyBytes, n, keyInuptSize - n); break; } System.arraycopy(ki, 0, keyBytes, n, blocksize); n += blocksize; } return keyBytes; } }
337
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/Des3KeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.util.Des; import org.apache.kerby.kerberos.kerb.crypto.util.Nfold; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; public class Des3KeyMaker extends DkKeyMaker { public Des3KeyMaker(EncryptProvider encProvider) { super(encProvider); } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { byte[] utf8Bytes = makePasswdSalt(string, salt); int keyInputSize = encProvider().keyInputSize(); byte[] tmpKey = random2Key(Nfold.nfold(utf8Bytes, keyInputSize)); return dk(tmpKey, KERBEROS_CONSTANT); } /** * To turn a 54-bit block into a 64-bit block, see * Ref. eighth_byte in random_to_key.c in MIT krb5 * @param bits56 * @return */ private static byte[] getEightBits(byte[] bits56) { byte[] bits64 = new byte[8]; System.arraycopy(bits56, 0, bits64, 0, 7); bits64[7] = (byte) (((bits56[0] & 1) << 1) | ((bits56[1] & 1) << 2) | ((bits56[2] & 1) << 3) | ((bits56[3] & 1) << 4) | ((bits56[4] & 1) << 5) | ((bits56[5] & 1) << 6) | ((bits56[6] & 1) << 7)); return bits64; } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { if (randomBits.length != encProvider().keyInputSize()) { throw new KrbException("Invalid random bits, not of correct bytes size"); } /** * Ref. k5_rand2key_des3 in random_to_key.c in MIT krb5 * Take the seven bytes, move them around into the top 7 bits of the * 8 key bytes, then compute the parity bits. Do this three times. */ byte[] key = new byte[encProvider().keySize()]; byte[] tmp1 = new byte[7]; byte[] tmp2; for (int i = 0; i < 3; i++) { System.arraycopy(randomBits, i * 7, key, i * 8, 7); System.arraycopy(randomBits, i * 7, tmp1, 0, 7); tmp2 = getEightBits(tmp1); key[8 * (i + 1) - 1] = tmp2[7]; int nthByte = i * 8; key[nthByte + 7] = (byte) (((key[nthByte + 0] & 1) << 1) | ((key[nthByte + 1] & 1) << 2) | ((key[nthByte + 2] & 1) << 3) | ((key[nthByte + 3] & 1) << 4) | ((key[nthByte + 4] & 1) << 5) | ((key[nthByte + 5] & 1) << 6) | ((key[nthByte + 6] & 1) << 7)); for (int j = 0; j < 8; j++) { int tmp = key[nthByte + j] & 0xfe; tmp |= (Integer.bitCount(tmp) & 1) ^ 1; key[nthByte + j] = (byte) tmp; } } for (int i = 0; i < 3; i++) { Des.fixKey(key, i * 8, 8); } return key; } }
338
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/KeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; public interface KeyMaker { byte[] str2key(String string, String salt, byte[] param) throws KrbException; byte[] random2Key(byte[] randomBits) throws KrbException; }
339
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/DkKeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.util.Nfold; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; public abstract class DkKeyMaker extends AbstractKeyMaker { public DkKeyMaker(EncryptProvider encProvider) { super(encProvider); } // DK(Key, Constant) = random-to-key(DR(Key, Constant)) public byte[] dk(byte[] key, byte[] constant) throws KrbException { return random2Key(dr(key, constant)); } /* * K1 = E(Key, n-fold(Constant), initial-cipher-state) * K2 = E(Key, K1, initial-cipher-state) * K3 = E(Key, K2, initial-cipher-state) * K4 = ... * DR(Key, Constant) = k-truncate(K1 | K2 | K3 | K4 ...) */ protected byte[] dr(byte[] key, byte[] constant) throws KrbException { int blocksize = encProvider().blockSize(); int keyInuptSize = encProvider().keyInputSize(); byte[] keyBytes = new byte[keyInuptSize]; byte[] ki; if (constant.length != blocksize) { ki = Nfold.nfold(constant, blocksize); } else { ki = new byte[constant.length]; System.arraycopy(constant, 0, ki, 0, constant.length); } int n = 0; while (n < keyInuptSize) { encProvider().encrypt(key, ki); if (n + blocksize >= keyInuptSize) { System.arraycopy(ki, 0, keyBytes, n, keyInuptSize - n); break; } System.arraycopy(ki, 0, keyBytes, n, blocksize); n += blocksize; } return keyBytes; } }
340
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/AbstractKeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; import java.nio.charset.StandardCharsets; public abstract class AbstractKeyMaker implements KeyMaker { static final byte[] KERBEROS_CONSTANT = "kerberos".getBytes(StandardCharsets.UTF_8); private EncryptProvider encProvider; public AbstractKeyMaker(EncryptProvider encProvider) { this.encProvider = encProvider; } /** * Visible for test. * @param password The password * @param salt The salt * @return The password salt */ public static byte[] makePasswdSalt(String password, String salt) { char[] chars = new char[password.length() + salt.length()]; System.arraycopy(password.toCharArray(), 0, chars, 0, password.length()); System.arraycopy(salt.toCharArray(), 0, chars, password.length(), salt.length()); return new String(chars).getBytes(StandardCharsets.UTF_8); } protected static int getIterCount(byte[] param, int defCount) { int iterCount = defCount; if (param != null) { if (param.length != 4) { throw new IllegalArgumentException("Invalid param to str2Key"); } iterCount = BytesUtil.bytes2int(param, 0, true); } return iterCount; } protected static byte[] getSaltBytes(String salt, String pepper) { byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8); if (pepper != null && !pepper.isEmpty()) { byte[] pepperBytes = pepper.getBytes(StandardCharsets.UTF_8); int len = saltBytes.length; len += 1 + pepperBytes.length; byte[] results = new byte[len]; System.arraycopy(pepperBytes, 0, results, 0, pepperBytes.length); results[pepperBytes.length] = (byte) 0; System.arraycopy(saltBytes, 0, results, pepperBytes.length + 1, saltBytes.length); return results; } else { return saltBytes; } } protected EncryptProvider encProvider() { return encProvider; } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { return new byte[0]; } }
341
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/key/Rc4KeyMaker.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.key; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.crypto.util.Md4; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public class Rc4KeyMaker extends AbstractKeyMaker { public Rc4KeyMaker(EncryptProvider encProvider) { super(encProvider); } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { if (param != null && param.length > 0) { throw new RuntimeException("Invalid param to str2Key"); } byte[] passwd = string.getBytes(StandardCharsets.UTF_16LE); // to unicode MessageDigest md = new Md4(); md.update(passwd); return md.digest(); } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { if (randomBits.length != encProvider().keyInputSize()) { throw new KrbException("Invalid random bits, not of correct bytes size"); } return randomBits; } }
342
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/KeKiCmacEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler; import org.apache.kerby.kerberos.kerb.crypto.key.DkKeyMaker; import org.apache.kerby.kerberos.kerb.crypto.util.Cmac; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import java.nio.charset.StandardCharsets; public abstract class KeKiCmacEnc extends KeKiEnc { private DkKeyMaker km; private EncryptionType eType; //NOPMD public KeKiCmacEnc(EncryptProvider encProvider, EncryptionType eType, DkKeyMaker km) { super(encProvider, null); this.eType = eType; this.km = km; } @Override public int checksumSize() { return encProvider().blockSize(); } @Override public byte[] prf(byte[] key, byte[] seed) throws KrbException { byte[] prfConst = "prf".getBytes(StandardCharsets.UTF_8); byte[] kp; if (EncryptionHandler.getEncHandler(this.eType()).prfSize() != encProvider().blockSize()) { return null; } kp = km.dk(key, prfConst); return Cmac.cmac(encProvider(), kp, seed); } @Override protected byte[] makeChecksum(byte[] key, byte[] data, int hashSize) throws KrbException { // generate hash byte[] hash = Cmac.cmac(encProvider(), key, data); // truncate hash byte[] output = new byte[hashSize]; System.arraycopy(hash, 0, output, 0, hashSize); return output; } }
343
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/AbstractEncTypeHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.AbstractCryptoTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.EncTypeHandler; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.crypto.key.KeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractEncTypeHandler extends AbstractCryptoTypeHandler implements EncTypeHandler { private int prfSize; private KeyMaker keyMaker; public AbstractEncTypeHandler(EncryptProvider encProvider, HashProvider hashProvider, int prfSize) { super(encProvider, hashProvider); this.prfSize = prfSize; } protected void keyMaker(KeyMaker keyMaker) { this.keyMaker = keyMaker; } protected KeyMaker keyMaker() { return keyMaker; } @Override public int prfSize() { return this.prfSize; } @Override public String name() { return eType().getName(); } @Override public String displayName() { return eType().getDisplayName(); } protected abstract int paddingLength(int inputLen); @Override public int keyInputSize() { return encProvider().keyInputSize(); } @Override public int keySize() { return encProvider().keySize(); } @Override public int confounderSize() { return encProvider().blockSize(); } @Override public int checksumSize() { return hashProvider().hashSize(); } @Override public int paddingSize() { return encProvider().blockSize(); } @Override public byte[] str2key(String string, String salt, byte[] param) throws KrbException { return keyMaker.str2key(string, salt, param); } @Override public byte[] random2Key(byte[] randomBits) throws KrbException { return keyMaker.random2Key(randomBits); } @Override public byte[] encrypt(byte[] data, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; return encrypt(data, key, iv, usage); } @Override public byte[] encrypt(byte[] data, byte[] key, byte[] iv, int usage) throws KrbException { int confounderLen = confounderSize(); int checksumLen = checksumSize(); int headerLen = confounderLen + checksumLen; int inputLen = data.length; int paddingLen = paddingLength(inputLen); /** * E(Confounder | Checksum | Plaintext | Padding), or * header | data | padding | trailer, where trailer may be absent */ int workLength = headerLen + inputLen + paddingLen; byte[] workBuffer = new byte[workLength]; System.arraycopy(data, 0, workBuffer, headerLen, data.length); int[] workLens = new int[] {confounderLen, checksumLen, inputLen, paddingLen}; encryptWith(workBuffer, workLens, key, iv, usage, false); return workBuffer; } @Override public byte[] encryptRaw(byte[] data, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; return encryptRaw(data, key, iv, usage); } @Override public byte[] encryptRaw(byte[] data, byte[] key, byte[] iv, int usage) throws KrbException { int checksumLen = checksumSize(); int[] workLens = new int[] {0, checksumLen, data.length, 0}; byte[] workBuffer = new byte[data.length]; System.arraycopy(data, 0, workBuffer, 0, data.length); encryptWith(workBuffer, workLens, key, iv, usage, true); return workBuffer; } protected void encryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { } public byte[] decrypt(byte[] cipher, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; return decrypt(cipher, key, iv, usage); } public byte[] decrypt(byte[] cipher, byte[] key, byte[] iv, int usage) throws KrbException { int totalLen = cipher.length; int confounderLen = confounderSize(); int checksumLen = checksumSize(); int dataLen = totalLen - (confounderLen + checksumLen); int[] workLens = new int[] {confounderLen, checksumLen, dataLen}; return decryptWith(cipher, workLens, key, iv, usage, false); } @Override public byte[] decryptRaw(byte[] cipher, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; return decryptRaw(cipher, key, iv, usage); } @Override public byte[] decryptRaw(byte[] cipher, byte[] key, byte[] iv, int usage) throws KrbException { int checksumLen = checksumSize(); int[] workLens = new int[] {0, checksumLen, cipher.length}; return decryptWith(cipher, workLens, key, iv, usage, true); } protected byte[] decryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { return null; } }
344
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/DesCbcCrcEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Crc32Provider; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class DesCbcCrcEnc extends DesCbcEnc { public DesCbcCrcEnc() { super(new Crc32Provider()); } public EncryptionType eType() { return EncryptionType.DES_CBC_CRC; } public CheckSumType checksumType() { return CheckSumType.CRC32; } @Override public byte[] encrypt(byte[] data, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; System.arraycopy(key, 0, iv, 0, key.length); return encrypt(data, key, iv, usage); } @Override public byte[] decrypt(byte[] cipher, byte[] key, int usage) throws KrbException { byte[] iv = new byte[encProvider().blockSize()]; System.arraycopy(key, 0, iv, 0, key.length); return decrypt(cipher, key, iv, usage); } }
345
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Camellia256CtsCmacEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia256Provider; import org.apache.kerby.kerberos.kerb.crypto.key.CamelliaKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Camellia256CtsCmacEnc extends KeKiCmacEnc { public Camellia256CtsCmacEnc() { super(new Camellia256Provider(), EncryptionType.CAMELLIA256_CTS_CMAC, new CamelliaKeyMaker(new Camellia256Provider())); keyMaker(new CamelliaKeyMaker((Camellia256Provider) encProvider())); } public EncryptionType eType() { return EncryptionType.CAMELLIA256_CTS_CMAC; } public CheckSumType checksumType() { return CheckSumType.CMAC_CAMELLIA256; } }
346
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/DesCbcEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.crypto.util.Confounder; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.DesProvider; import org.apache.kerby.kerberos.kerb.crypto.key.DesKeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; abstract class DesCbcEnc extends AbstractEncTypeHandler { DesCbcEnc(HashProvider hashProvider) { super(new DesProvider(), hashProvider, 16); keyMaker(new DesKeyMaker(this.encProvider())); } @Override public byte[] prf(byte[] key, byte[] seed) throws KrbException { byte[] output; Md5Provider md5Provider = new Md5Provider(); md5Provider.hash(seed); output = md5Provider.output(); encProvider().encrypt(key, output); return output; } @Override protected int paddingLength(int inputLen) { int payloadLen = confounderSize() + checksumSize() + inputLen; int padding = paddingSize(); if (padding == 0 || (payloadLen % padding) == 0) { return 0; } return padding - (payloadLen % padding); } @Override protected void encryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { if (!raw) { doEncryptWith(workBuffer, workLens, key, iv); } else { encProvider().encrypt(key, iv, workBuffer); } } private void doEncryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv) throws KrbException { int confounderLen = workLens[0]; int checksumLen = workLens[1]; int dataLen = workLens[2]; int paddingLen = workLens[3]; // confounder byte[] confounder = Confounder.makeBytes(confounderLen); System.arraycopy(confounder, 0, workBuffer, 0, confounderLen); // padding for (int i = confounderLen + checksumLen + dataLen; i < paddingLen; ++i) { workBuffer[i] = 0; } // checksum hashProvider().hash(workBuffer); byte[] cksum = hashProvider().output(); System.arraycopy(cksum, 0, workBuffer, confounderLen, checksumLen); encProvider().encrypt(key, iv, workBuffer); } @Override protected byte[] decryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { if (!raw) { return doDecryptWith(workBuffer, workLens, key, iv); } else { encProvider().decrypt(key, iv, workBuffer); byte[] data = new byte[workBuffer.length]; System.arraycopy(workBuffer, 0, data, 0, data.length); return data; } } private byte[] doDecryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv) throws KrbException { int confounderLen = workLens[0]; int checksumLen = workLens[1]; int dataLen = workLens[2]; encProvider().decrypt(key, iv, workBuffer); byte[] checksum = new byte[checksumLen]; for (int i = 0; i < checksumLen; i++) { checksum[i] = workBuffer[confounderLen + i]; workBuffer[confounderLen + i] = 0; } hashProvider().hash(workBuffer); byte[] newChecksum = hashProvider().output(); if (!checksumEqual(checksum, newChecksum)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BAD_INTEGRITY); } byte[] data = new byte[dataLen]; System.arraycopy(workBuffer, confounderLen + checksumLen, data, 0, dataLen); return data; } }
347
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Aes128CtsHmacSha1Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes128Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.AesProvider; import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Aes128CtsHmacSha1Enc extends KeKiHmacSha1Enc { public Aes128CtsHmacSha1Enc() { super(new Aes128Provider(), new Sha1Provider(), new AesKeyMaker(new Aes128Provider())); keyMaker(new AesKeyMaker((AesProvider) encProvider())); } @Override public int checksumSize() { return 96 / 8; } public EncryptionType eType() { return EncryptionType.AES128_CTS_HMAC_SHA1_96; } public CheckSumType checksumType() { return CheckSumType.HMAC_SHA1_96_AES128; } }
348
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/KeKiHmacSha1Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.key.DkKeyMaker; import org.apache.kerby.kerberos.kerb.crypto.util.Hmac; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.KrbException; import java.nio.charset.StandardCharsets; public abstract class KeKiHmacSha1Enc extends KeKiEnc { private DkKeyMaker km; public KeKiHmacSha1Enc(EncryptProvider encProvider, HashProvider hashProvider, DkKeyMaker km) { super(encProvider, hashProvider); this.km = km; } @Override public byte[] prf(byte[] key, byte[] seed) throws KrbException { byte[] prfConst = "prf".getBytes(StandardCharsets.UTF_8); int cksumSize = (hashProvider().hashSize() / encProvider().blockSize()) * encProvider().blockSize(); byte[] cksum = new byte[cksumSize]; byte[] kp; byte[] output = new byte[prfSize()]; hashProvider().hash(seed); System.arraycopy(hashProvider().output(), 0, cksum, 0, cksumSize); kp = km.dk(key, prfConst); encProvider().encrypt(kp, cksum); System.arraycopy(cksum, 0, output, 0, this.prfSize()); return output; } @Override protected byte[] makeChecksum(byte[] key, byte[] data, int hashSize) throws KrbException { // generate hash byte[] hash = Hmac.hmac(hashProvider(), key, data); // truncate hash byte[] output = new byte[hashSize]; System.arraycopy(hash, 0, output, 0, hashSize); return output; } }
349
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Des3CbcSha1Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Des3Provider; import org.apache.kerby.kerberos.kerb.crypto.key.Des3KeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Des3CbcSha1Enc extends KeKiHmacSha1Enc { public Des3CbcSha1Enc() { super(new Des3Provider(), new Sha1Provider(), new Des3KeyMaker(new Des3Provider())); keyMaker(new Des3KeyMaker(this.encProvider())); } @Override public int paddingSize() { return encProvider().blockSize(); } public EncryptionType eType() { return EncryptionType.DES3_CBC_SHA1; } public CheckSumType checksumType() { return CheckSumType.HMAC_SHA1_DES3; } }
350
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Camellia128CtsCmacEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia128Provider; import org.apache.kerby.kerberos.kerb.crypto.key.CamelliaKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Camellia128CtsCmacEnc extends KeKiCmacEnc { public Camellia128CtsCmacEnc() { super(new Camellia128Provider(), EncryptionType.CAMELLIA128_CTS_CMAC, new CamelliaKeyMaker(new Camellia128Provider())); keyMaker(new CamelliaKeyMaker((Camellia128Provider) encProvider())); } public EncryptionType eType() { return EncryptionType.CAMELLIA128_CTS_CMAC; } public CheckSumType checksumType() { return CheckSumType.CMAC_CAMELLIA128; } }
351
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/KeKiEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.util.Confounder; import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider; import org.apache.kerby.kerberos.kerb.crypto.key.DkKeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class KeKiEnc extends AbstractEncTypeHandler { public KeKiEnc(EncryptProvider encProvider, HashProvider hashProvider) { super(encProvider, hashProvider, 16); } @Override public int paddingSize() { return 0; } @Override protected int paddingLength(int inputLen) { int payloadLen = confounderSize() + inputLen; int padding = paddingSize(); if (padding == 0 || (payloadLen % padding) == 0) { return 0; } return padding - (payloadLen % padding); } @Override protected void encryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { int confounderLen = workLens[0]; int checksumLen = workLens[1]; int inputLen = workLens[2]; int paddingLen = workLens[3]; byte[] constant = new byte[5]; constant[0] = (byte) ((usage >> 24) & 0xff); constant[1] = (byte) ((usage >> 16) & 0xff); constant[2] = (byte) ((usage >> 8) & 0xff); constant[3] = (byte) (usage & 0xff); constant[4] = (byte) 0xaa; byte[] ke = ((DkKeyMaker) keyMaker()).dk(key, constant); constant[4] = (byte) 0x55; byte[] ki = ((DkKeyMaker) keyMaker()).dk(key, constant); /** * Instead of E(Confounder | Checksum | Plaintext | Padding), * E(Confounder | Plaintext | Padding) | Checksum, * so need to adjust the workBuffer arrangement */ if (!raw) { byte[] tmpEnc = new byte[confounderLen + inputLen + paddingLen]; // confounder byte[] confounder = Confounder.makeBytes(confounderLen); System.arraycopy(confounder, 0, tmpEnc, 0, confounderLen); // data System.arraycopy(workBuffer, confounderLen + checksumLen, tmpEnc, confounderLen, inputLen); // padding for (int i = confounderLen + inputLen; i < paddingLen; ++i) { tmpEnc[i] = 0; } // checksum & encrypt byte[] checksum = makeChecksum(ki, tmpEnc, checksumLen); encProvider().encrypt(ke, iv, tmpEnc); System.arraycopy(tmpEnc, 0, workBuffer, 0, tmpEnc.length); System.arraycopy(checksum, 0, workBuffer, tmpEnc.length, checksum.length); } else { encProvider().encrypt(ke, iv, workBuffer); } } @Override protected byte[] decryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { int confounderLen = workLens[0]; int checksumLen = workLens[1]; int dataLen = workLens[2]; byte[] constant = new byte[5]; BytesUtil.int2bytes(usage, constant, 0, true); constant[4] = (byte) 0xaa; byte[] ke = ((DkKeyMaker) keyMaker()).dk(key, constant); constant[4] = (byte) 0x55; byte[] ki = ((DkKeyMaker) keyMaker()).dk(key, constant); // decrypt and verify checksum byte[] tmpEnc = new byte[confounderLen + dataLen]; System.arraycopy(workBuffer, 0, tmpEnc, 0, confounderLen + dataLen); if (!raw) { byte[] checksum = new byte[checksumLen]; System.arraycopy(workBuffer, confounderLen + dataLen, checksum, 0, checksumLen); encProvider().decrypt(ke, iv, tmpEnc); byte[] newChecksum = makeChecksum(ki, tmpEnc, checksumLen); if (!checksumEqual(checksum, newChecksum)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BAD_INTEGRITY); } byte[] data = new byte[dataLen]; System.arraycopy(tmpEnc, confounderLen, data, 0, dataLen); return data; } else { encProvider().decrypt(ke, iv, tmpEnc); return tmpEnc; } } protected abstract byte[] makeChecksum(byte[] key, byte[] data, int hashSize) throws KrbException; }
352
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Aes256CtsHmacSha1Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes256Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.AesProvider; import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Aes256CtsHmacSha1Enc extends KeKiHmacSha1Enc { public Aes256CtsHmacSha1Enc() { super(new Aes256Provider(), new Sha1Provider(), new AesKeyMaker(new Aes256Provider())); keyMaker(new AesKeyMaker((AesProvider) encProvider())); } public EncryptionType eType() { return EncryptionType.AES256_CTS_HMAC_SHA1_96; } public CheckSumType checksumType() { return CheckSumType.HMAC_SHA1_96_AES256; } @Override public int checksumSize() { return 96 / 8; } }
353
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Rc4HmacEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Sha1Provider; import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil; import org.apache.kerby.kerberos.kerb.crypto.util.Confounder; import org.apache.kerby.kerberos.kerb.crypto.util.Rc4; import org.apache.kerby.kerberos.kerb.crypto.util.Hmac; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Rc4Provider; import org.apache.kerby.kerberos.kerb.crypto.key.Rc4KeyMaker; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Rc4HmacEnc extends AbstractEncTypeHandler { private boolean exportable; public Rc4HmacEnc() { this(false); } public Rc4HmacEnc(boolean exportable) { super(new Rc4Provider(), new Md5Provider(), 20); keyMaker(new Rc4KeyMaker(this.encProvider())); this.exportable = exportable; } public EncryptionType eType() { return EncryptionType.ARCFOUR_HMAC; } @Override public byte[] prf(byte[] key, byte[] seed) throws KrbException { return Hmac.hmac(new Sha1Provider(), key, seed, 20); } @Override protected int paddingLength(int inputLen) { int payloadLen = confounderSize() + inputLen; int padding = paddingSize(); if (padding == 0 || (payloadLen % padding) == 0) { return 0; } return padding - (payloadLen % padding); } @Override public int confounderSize() { return 8; } @Override public int paddingSize() { return 0; } public CheckSumType checksumType() { return CheckSumType.HMAC_MD5_ARCFOUR; } @Override protected void encryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { if (raw) { throw new KrbException(KrbErrorCode.KDC_ERR_ETYPE_NOSUPP, "Raw mode not supported for this encryption type"); } int confounderLen = workLens[0]; int checksumLen = workLens[1]; int dataLen = workLens[2]; /** * Instead of E(Confounder | Checksum | Plaintext | Padding), * Checksum | E(Confounder | Plaintext) */ // confounder byte[] confounder = Confounder.makeBytes(confounderLen); System.arraycopy(confounder, 0, workBuffer, checksumLen, confounderLen); // no padding /* checksum and encryption */ byte[] usageKey = makeUsageKey(key, usage); byte[] checksum = Hmac.hmac(hashProvider(), usageKey, workBuffer, checksumLen, confounderLen + dataLen); byte[] encKey = makeEncKey(usageKey, checksum); byte[] tmpEnc = new byte[confounderLen + dataLen]; System.arraycopy(workBuffer, checksumLen, tmpEnc, 0, confounderLen + dataLen); encProvider().encrypt(encKey, iv, tmpEnc); System.arraycopy(checksum, 0, workBuffer, 0, checksumLen); System.arraycopy(tmpEnc, 0, workBuffer, checksumLen, tmpEnc.length); } protected byte[] makeUsageKey(byte[] key, int usage) throws KrbException { byte[] salt = Rc4.getSalt(usage, exportable); return Hmac.hmac(hashProvider(), key, salt); } protected byte[] makeEncKey(byte[] usageKey, byte[] checksum) throws KrbException { byte[] tmpKey = usageKey; if (exportable) { tmpKey = BytesUtil.duplicate(usageKey); for (int i = 0; i < 9; ++i) { tmpKey[i + 7] = (byte) 0xab; } } return Hmac.hmac(hashProvider(), tmpKey, checksum); } @Override protected byte[] decryptWith(byte[] workBuffer, int[] workLens, byte[] key, byte[] iv, int usage, boolean raw) throws KrbException { if (raw) { throw new KrbException(KrbErrorCode.KDC_ERR_ETYPE_NOSUPP, "Raw mode not supported for this encryption type"); } int confounderLen = workLens[0]; int checksumLen = workLens[1]; int dataLen = workLens[2]; /* checksum and decryption */ byte[] usageKey = makeUsageKey(key, usage); byte[] checksum = new byte[checksumLen]; System.arraycopy(workBuffer, 0, checksum, 0, checksumLen); byte[] encKey = makeEncKey(usageKey, checksum); byte[] tmpEnc = new byte[confounderLen + dataLen]; System.arraycopy(workBuffer, checksumLen, tmpEnc, 0, confounderLen + dataLen); encProvider().decrypt(encKey, iv, tmpEnc); byte[] newChecksum = Hmac.hmac(hashProvider(), usageKey, tmpEnc); if (!checksumEqual(checksum, newChecksum)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BAD_INTEGRITY); } byte[] data = new byte[dataLen]; System.arraycopy(tmpEnc, confounderLen, data, 0, dataLen); return data; } }
354
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/DesCbcMd5Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md5Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class DesCbcMd5Enc extends DesCbcEnc { public DesCbcMd5Enc() { super(new Md5Provider()); } public EncryptionType eType() { return EncryptionType.DES_CBC_MD5; } public CheckSumType checksumType() { return CheckSumType.RSA_MD5_DES; } }
355
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/EncryptProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.KrbException; /** * Ref. MIT Krb5:krb5_enc_provider */ /** * Encryption provider that provides encryption/decryption functions * for implementing an encryption type defined by Kerberos RFC3961. */ public interface EncryptProvider { int keyInputSize(); //input size to make key int keySize(); //output key size int blockSize(); //crypto block size void encrypt(byte[] key, byte[] cipherState, byte[] data) throws KrbException; void decrypt(byte[] key, byte[] cipherState, byte[] data) throws KrbException; void encrypt(byte[] key, byte[] data) throws KrbException; void decrypt(byte[] key, byte[] data) throws KrbException; byte[] cbcMac(byte[] key, byte[] iv, byte[] data) throws KrbException; boolean supportCbcMac(); }
356
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/Rc4HmacExpEnc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class Rc4HmacExpEnc extends Rc4HmacEnc { public Rc4HmacExpEnc() { super(true); } public EncryptionType eType() { return EncryptionType.ARCFOUR_HMAC_EXP; } }
357
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/DesCbcMd4Enc.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc; import org.apache.kerby.kerberos.kerb.crypto.cksum.provider.Md4Provider; import org.apache.kerby.kerberos.kerb.type.base.CheckSumType; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; public class DesCbcMd4Enc extends DesCbcEnc { public DesCbcMd4Enc() { super(new Md4Provider()); } public EncryptionType eType() { return EncryptionType.DES_CBC_MD4; } public CheckSumType checksumType() { return CheckSumType.RSA_MD4_DES; } }
358
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/AbstractEncryptProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class AbstractEncryptProvider implements EncryptProvider { private int blockSize; private int keyInputSize; private int keySize; public AbstractEncryptProvider(int blockSize, int keyInputSize, int keySize) { this.blockSize = blockSize; this.keyInputSize = keyInputSize; this.keySize = keySize; } @Override public int keyInputSize() { return keyInputSize; } @Override public int keySize() { return keySize; } @Override public int blockSize() { return blockSize; } @Override public void encrypt(byte[] key, byte[] cipherState, byte[] data) throws KrbException { doEncrypt(data, key, cipherState, true); } @Override public void decrypt(byte[] key, byte[] cipherState, byte[] data) throws KrbException { doEncrypt(data, key, cipherState, false); } @Override public void encrypt(byte[] key, byte[] data) throws KrbException { byte[] cipherState = new byte[blockSize()]; encrypt(key, cipherState, data); } @Override public void decrypt(byte[] key, byte[] data) throws KrbException { byte[] cipherState = new byte[blockSize()]; decrypt(key, cipherState, data); } protected abstract void doEncrypt(byte[] data, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException; @Override public byte[] cbcMac(byte[] key, byte[] iv, byte[] data) throws KrbException { throw new UnsupportedOperationException(); } @Override public boolean supportCbcMac() { return false; } }
359
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Rc4Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.KrbException; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.security.GeneralSecurityException; public class Rc4Provider extends AbstractEncryptProvider { public Rc4Provider() { super(1, 16, 16); } @Override protected void doEncrypt(byte[] data, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException { try { Cipher cipher = Cipher.getInstance("ARCFOUR"); SecretKeySpec secretKey = new SecretKeySpec(key, "ARCFOUR"); cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, secretKey); byte[] output = cipher.doFinal(data); System.arraycopy(output, 0, data, 0, output.length); } catch (GeneralSecurityException e) { KrbException ke = new KrbException(e.getMessage()); ke.initCause(e); throw ke; } } }
360
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Aes128Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; public class Aes128Provider extends AesProvider { public Aes128Provider() { super(16, 16, 16); } }
361
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Camellia128Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; public class Camellia128Provider extends CamelliaProvider { public Camellia128Provider() { super(16, 16, 16); } }
362
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/AesProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.KrbException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.GeneralSecurityException; public abstract class AesProvider extends AbstractEncryptProvider { public AesProvider(int blockSize, int keyInputSize, int keySize) { super(blockSize, keyInputSize, keySize); } @Override protected void doEncrypt(byte[] data, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException { Cipher cipher = null; try { cipher = Cipher.getInstance("AES/CTS/NoPadding"); } catch (GeneralSecurityException e) { KrbException ke = new KrbException("JCE provider may not be installed. " + e.getMessage()); ke.initCause(e); throw ke; } try { SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); IvParameterSpec param = new IvParameterSpec(cipherState); cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, secretKey, param); byte[] output = cipher.doFinal(data); System.arraycopy(output, 0, data, 0, output.length); } catch (GeneralSecurityException e) { KrbException ke = new KrbException(e.getMessage()); ke.initCause(e); throw ke; } } }
363
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Aes256Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; public class Aes256Provider extends AesProvider { public Aes256Provider() { super(16, 32, 32); } }
364
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Camellia256Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; public class Camellia256Provider extends CamelliaProvider { public Camellia256Provider() { super(16, 32, 32); } }
365
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/CamelliaProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.crypto.util.Camellia; import org.apache.kerby.kerberos.kerb.KrbException; public abstract class CamelliaProvider extends AbstractEncryptProvider { public CamelliaProvider(int blockSize, int keyInputSize, int keySize) { super(blockSize, keyInputSize, keySize); } @Override protected void doEncrypt(byte[] data, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException { Camellia cipher = new Camellia(); cipher.setKey(encrypt, key); if (encrypt) { cipher.encrypt(data, cipherState); } else { cipher.decrypt(data, cipherState); } } @Override public boolean supportCbcMac() { return true; } @Override public byte[] cbcMac(byte[] key, byte[] cipherState, byte[] data) { Camellia cipher = new Camellia(); cipher.setKey(true, key); int blocksNum = data.length / blockSize(); cipher.cbcEnc(data, 0, blocksNum, cipherState); return data; } }
366
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/DesProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.KrbException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.GeneralSecurityException; public class DesProvider extends AbstractEncryptProvider { public DesProvider() { super(8, 7, 8); } @Override protected void doEncrypt(byte[] input, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException { Cipher cipher = null; try { cipher = Cipher.getInstance("DES/CBC/NoPadding"); } catch (GeneralSecurityException e) { throw new KrbException("Failed to init cipher", e); } IvParameterSpec params = new IvParameterSpec(cipherState); SecretKeySpec skSpec = new SecretKeySpec(key, "DES"); try { cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, skSpec, params); byte[] output = cipher.doFinal(input); System.arraycopy(output, 0, input, 0, output.length); } catch (GeneralSecurityException e) { KrbException ke = new KrbException(e.getMessage()); ke.initCause(e); throw ke; } } @Override public byte[] cbcMac(byte[] key, byte[] cipherState, byte[] data) throws KrbException { Cipher cipher = null; try { cipher = Cipher.getInstance("DES/CBC/NoPadding"); } catch (GeneralSecurityException e) { throw new KrbException("Failed to init cipher", e); } IvParameterSpec params = new IvParameterSpec(cipherState); SecretKeySpec skSpec = new SecretKeySpec(key, "DES"); byte[] output = null; try { cipher.init(Cipher.ENCRYPT_MODE, skSpec, params); for (int i = 0; i < data.length / 8; i++) { output = cipher.doFinal(data, i * 8, 8); cipher.init(Cipher.ENCRYPT_MODE, skSpec, new IvParameterSpec(output)); } } catch (GeneralSecurityException e) { KrbException ke = new KrbException(e.getMessage()); ke.initCause(e); throw ke; } return output; } @Override public boolean supportCbcMac() { return true; } }
367
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/enc/provider/Des3Provider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.enc.provider; import org.apache.kerby.kerberos.kerb.KrbException; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import java.security.GeneralSecurityException; import java.security.spec.KeySpec; public class Des3Provider extends AbstractEncryptProvider { public Des3Provider() { super(8, 21, 24); } @Override protected void doEncrypt(byte[] input, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException { Cipher cipher = null; try { cipher = Cipher.getInstance("DESede/CBC/NoPadding"); } catch (GeneralSecurityException e) { throw new KrbException("Failed to init cipher", e); } try { IvParameterSpec params = new IvParameterSpec(cipherState); KeySpec skSpec = new DESedeKeySpec(key, 0); SecretKeyFactory skf = SecretKeyFactory.getInstance("desede"); SecretKey secretKey = skf.generateSecret(skSpec); cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, secretKey, params); byte[] output = cipher.doFinal(input); System.arraycopy(output, 0, input, 0, output.length); } catch (GeneralSecurityException e) { throw new KrbException("Failed to doEncrypt", e); } } }
368
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/random/JavaRandom.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.random; import java.security.SecureRandom; /** * Use jdk {@link SecureRandom} to implement {@link RandomProvider}, * so it can be used on windows and linux. */ public class JavaRandom implements RandomProvider { private SecureRandom random = new SecureRandom(); @Override public void init() { } @Override public void setSeed(byte[] seed) { random.setSeed(seed); } @Override public void nextBytes(byte[] bytes) { random.nextBytes(bytes); } @Override public void destroy() { } }
369
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/random/RandomProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.random; /** * A provider to generate random and secure bytes provided with seeds, as Java * SecureRandom does. */ public interface RandomProvider { /** * To init. */ void init(); /** * Provide entropy seed for the provider. * @param seed The seed */ void setSeed(byte[] seed); /** * Generate random bytes into the specified array. * @param bytes The bytes */ void nextBytes(byte[] bytes); /** * To clean up. */ void destroy(); }
370
0
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto
Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/random/NativeRandom.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.crypto.random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; /** * use "/dev/urandom", which is on linux, to implement RandomProvider, so it should be used on linux. */ public class NativeRandom implements RandomProvider { private static final Logger LOG = LoggerFactory .getLogger(NativeRandom.class); private InputStream input; private String randFile = "/dev/urandom"; @Override public void init() { try { input = Files.newInputStream(Paths.get(randFile)); } catch (IOException e) { LOG.error("Failed to init from file: " + randFile + ". " + e.toString()); } } @Override public void setSeed(byte[] seed) { OutputStream output = null; try { output = Files.newOutputStream(Paths.get(randFile)); output.write(seed); output.flush(); } catch (IOException e) { LOG.error("Failed to write seed to the file: " + randFile + ". " + e.toString()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { LOG.error("Failed to close output stream. " + e.toString()); } } } } @Override public void nextBytes(byte[] bytes) { try { if (input.read(bytes) == -1) { throw new IOException(); } } catch (IOException e) { LOG.error("Failed to read nextBytes. " + e.toString()); } } @Override public void destroy() { try { input.close(); } catch (IOException e) { LOG.error("Failed to close input stream. " + e.toString()); } } }
371
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/BackendTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static org.apache.kerby.kerberos.kerb.identity.backend.BackendTestUtil.TEST_PRINCIPAL; import static org.assertj.core.api.Assertions.assertThat; /** * A common backend test utility */ public abstract class BackendTest { protected void testGet(IdentityBackend backend) throws KrbException { KrbIdentity kid = BackendTestUtil.createOneIdentity(TEST_PRINCIPAL); backend.addIdentity(kid); // clear the identity cache. backend.release(); KrbIdentity identity = backend.getIdentity(TEST_PRINCIPAL); assertThat(identity).isNotNull(); assertThat(identity.getExpireTime()).isEqualTo(kid.getExpireTime()); assertThat(identity.isDisabled()).isEqualTo(kid.isDisabled()); assertThat(identity.getKeyVersion()).isEqualTo(kid.getKeyVersion()); for (EncryptionKey expectedKey : kid.getKeys().values()) { EncryptionType actualType = EncryptionType.fromValue(expectedKey.getKeyType().getValue()); EncryptionKey actualKey = identity.getKey(actualType); assertThat(actualKey.getKeyType().getValue()).isEqualTo(expectedKey.getKeyType().getValue()); assertThat(actualKey.getKeyData()).isEqualTo(expectedKey.getKeyData()); assertThat(actualKey.getKvno()).isEqualTo(expectedKey.getKvno()); } //tearDown backend.deleteIdentity(TEST_PRINCIPAL); } protected void testStore(IdentityBackend backend) throws KrbException { KrbIdentity kid = BackendTestUtil.createOneIdentity(TEST_PRINCIPAL); backend.addIdentity(kid); // clear the identity cache. backend.release(); KrbIdentity kid2 = backend.getIdentity(TEST_PRINCIPAL); assertThat(kid).isEqualTo(kid2); //tearDown backend.deleteIdentity(TEST_PRINCIPAL); } protected void testUpdate(IdentityBackend backend) throws KrbException { KrbIdentity kid = BackendTestUtil.createOneIdentity(TEST_PRINCIPAL); backend.addIdentity(kid); kid.setDisabled(true); backend.updateIdentity(kid); // clear the identity cache. backend.release(); assertThat(backend.getIdentity(TEST_PRINCIPAL)).isEqualTo(kid); //tearDown backend.deleteIdentity(TEST_PRINCIPAL); } protected void testDelete(IdentityBackend backend) throws KrbException { KrbIdentity kid = BackendTestUtil.createOneIdentity(TEST_PRINCIPAL); backend.addIdentity(kid); // clear the identity cache. backend.release(); assertThat(backend.getIdentity(TEST_PRINCIPAL)).isNotNull(); backend.deleteIdentity(TEST_PRINCIPAL); assertThat(backend.getIdentity(TEST_PRINCIPAL)).isNull(); } protected void testGetIdentities(IdentityBackend backend) throws KrbException { KrbIdentity[] identities = BackendTestUtil.createManyIdentities(); for (KrbIdentity identity : identities) { backend.addIdentity(identity); } // clear the identity cache. backend.release(); Iterable<String> principals = backend.getIdentities(); Iterator<String> iterator = principals.iterator(); List<String> principalList = new LinkedList<>(); while (iterator.hasNext()) { principalList.add(iterator.next()); } assertThat(principalList).hasSize(identities.length) .contains(identities[0].getPrincipalName()) .contains(identities[1].getPrincipalName()) .contains(identities[2].getPrincipalName()) .contains(identities[3].getPrincipalName()) .contains(identities[4].getPrincipalName()); //tearDown for (KrbIdentity identity : identities) { backend.deleteIdentity(identity.getPrincipalName()); } } protected void cleanIdentities(IdentityBackend backend) throws KrbException { Iterable<String> identities = backend.getIdentities(); Iterator<String> iterator = identities.iterator(); while (iterator.hasNext()) { backend.deleteIdentity(iterator.next()); } } }
372
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/BackendTestBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.kerberos.kerb.KrbException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * Json backend test */ public abstract class BackendTestBase extends BackendTest { protected static IdentityBackend backend; /** * Create and prepare an identity backend for the tests. Must override. * @throws Exception e */ @BeforeAll public static void setup() throws Exception { backend = null; } @Test public void testGet() throws KrbException { super.testGet(backend); } @Test public void testStore() throws KrbException { super.testStore(backend); } @Test public void testUpdate() throws KrbException { testUpdate(backend); } @Test public void testDelete() throws KrbException { testDelete(backend); } @Test public void testGetIdentities() throws KrbException { testGetIdentities(backend); } @AfterAll public static void tearDown() throws KrbException { if (backend != null) { backend.stop(); backend.release(); } } }
373
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity-test/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/BackendTestUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.type.KerberosTime; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A common backend test utility */ public final class BackendTestUtil { static final String TEST_PRINCIPAL_PREFIX = "test"; static final String TEST_REALM = "EXAMPLE.COM"; public static final String TEST_PRINCIPAL = TEST_PRINCIPAL_PREFIX + "@" + TEST_REALM; static final EncryptionType[] ENC_TYPES = new EncryptionType[]{ EncryptionType.AES128_CTS, EncryptionType.DES3_CBC_SHA1_KD }; public static void createManyIdentities(IdentityBackend backend, int count) throws KrbException { int howMany = count > 0 ? count : 20; List<KrbIdentity> identities = createManyIdentities(howMany); for (KrbIdentity identity : identities) { backend.addIdentity(identity); } } public static KrbIdentity[] createManyIdentities() throws KrbException { List<KrbIdentity> results = createManyIdentities(20); return results.toArray(new KrbIdentity[results.size()]); } public static List<KrbIdentity> createManyIdentities( int count) throws KrbException { List<KrbIdentity> results = new ArrayList<>(count); for (int i = 0; i < count; ++i) { String tmp = TEST_PRINCIPAL_PREFIX + i + "@" + TEST_REALM; results.add(createOneIdentity(tmp)); } return results; } public static void createTheTestIdentity( IdentityBackend backend) throws KrbException { backend.addIdentity(createOneIdentity(TEST_PRINCIPAL)); } public static void getTheTestIdentity( IdentityBackend backend) throws KrbException { KrbIdentity identity = backend.getIdentity(TEST_PRINCIPAL); if (identity == null) { throw new KrbException("Failed to get the test principal"); } } public static KrbIdentity createOneIdentity() throws KrbException { return createOneIdentity(TEST_PRINCIPAL); } public static KrbIdentity createOneIdentity(String principal) throws KrbException { KrbIdentity kid = new KrbIdentity(principal); kid.setCreatedTime(KerberosTime.now()); kid.setExpireTime(KerberosTime.now()); kid.setDisabled(false); kid.setKeyVersion(1); kid.setLocked(false); kid.addKeys(generateKeys()); return kid; } public static List<EncryptionKey> generateKeys() throws KrbException { return EncryptionUtil.generateKeys(getEncryptionTypes()); } public static List<EncryptionType> getEncryptionTypes() { return Arrays.asList(ENC_TYPES); } }
374
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/test/java/org/apache/kerby/kerberos/kerb/server/KdcConfigLoadTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static org.assertj.core.api.Assertions.assertThat; public class KdcConfigLoadTest { @Test public void test() throws URISyntaxException, IOException { URL confFileUrl = KdcConfigLoadTest.class.getResource("/kdc.conf"); File confFile = new File(confFileUrl.toURI()); KdcConfig kdcConfig = new KdcConfig(); kdcConfig.addKrb5Config(confFile); assertThat(kdcConfig.getKdcHost()).isEqualTo("localhost"); assertThat(kdcConfig.getKdcUdpPort()).isEqualTo(88); assertThat(kdcConfig.getKdcTcpPort()).isEqualTo(8014); assertThat(kdcConfig.getKdcRealm()).isEqualTo("TEST.COM"); assertThat(kdcConfig.isRestrictAnonymousToTgt()).isTrue(); assertThat(kdcConfig.getKdcMaxDgramReplySize()).isEqualTo(4096); } @Test public void testManualConfiguration() { KdcConfig kdcConfig = new KdcConfig(); kdcConfig.setString(KdcConfigKey.KDC_HOST, "localhost"); kdcConfig.setInt(KdcConfigKey.KDC_TCP_PORT, 12345); kdcConfig.setString(KdcConfigKey.KDC_REALM, "TEST2.COM"); assertThat(kdcConfig.getKdcHost()).isEqualTo("localhost"); assertThat(kdcConfig.getKdcTcpPort()).isEqualTo(12345); assertThat(kdcConfig.getKdcRealm()).isEqualTo("TEST2.COM"); } @Test public void testConfigurationDefaults() { KdcConfig kdcConfig = new KdcConfig(); assertThat(kdcConfig.getKdcHost()).isEqualTo( KdcConfigKey.KDC_HOST.getDefaultValue()); assertThat(kdcConfig.getKdcTcpPort()).isEqualTo(-1); assertThat(kdcConfig.getKdcRealm()).isEqualTo( KdcConfigKey.KDC_REALM.getDefaultValue() ); } }
375
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/test/java/org/apache/kerby/kerberos/kerb/server/KdcServerTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.util.NetworkUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; public class KdcServerTest { private String serverHost = "localhost"; private int serverPort = -1; private KdcServer kdcServer; @BeforeEach public void setUp() throws Exception { kdcServer = new KdcServer(); kdcServer.setKdcHost(serverHost); kdcServer.setAllowUdp(false); kdcServer.setAllowTcp(true); serverPort = NetworkUtil.getServerPort(); kdcServer.setKdcTcpPort(serverPort); kdcServer.init(); kdcServer.start(); } @Test public void testKdc() throws IOException, InterruptedException { Thread.sleep(15); try (SocketChannel socketChannel = SocketChannel.open()) { socketChannel.configureBlocking(true); SocketAddress sa = new InetSocketAddress(serverHost, serverPort); socketChannel.connect(sa); Assertions.assertTrue(socketChannel.isConnected()); } } @AfterEach public void tearDown() throws Exception { kdcServer.stop(); } }
376
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcServerOption.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.KOption; import org.apache.kerby.KOptionInfo; import org.apache.kerby.KOptionType; /** * KDC server startup options */ public enum KdcServerOption implements KOption { NONE(null), INNER_KDC_IMPL(new KOptionInfo("inner KDC impl", "inner KDC impl", KOptionType.OBJ)), KDC_REALM(new KOptionInfo("kdc realm", "kdc realm", KOptionType.STR)), KDC_HOST(new KOptionInfo("kdc host", "kdc host", KOptionType.STR)), KDC_PORT(new KOptionInfo("kdc port", "kdc port", KOptionType.INT)), ALLOW_TCP(new KOptionInfo("allow tcp", "allow tcp", KOptionType.BOOL)), KDC_TCP_PORT(new KOptionInfo("kdc tcp port", "kdc tcp port", KOptionType.INT)), ALLOW_UDP(new KOptionInfo("allow udp", "allow udp", KOptionType.BOOL)), KDC_UDP_PORT(new KOptionInfo("kdc udp port", "kdc udp port", KOptionType.INT)), WORK_DIR(new KOptionInfo("work dir", "work dir", KOptionType.DIR)), ENABLE_DEBUG(new KOptionInfo("enable debug", "enable debug", KOptionType.BOOL)); private final KOptionInfo optionInfo; KdcServerOption(KOptionInfo optionInfo) { this.optionInfo = optionInfo; } @Override public KOptionInfo getOptionInfo() { return optionInfo; } }
377
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.identity.backend.MemoryIdentityBackend; import org.apache.kerby.kerberos.kerb.transport.TransportPair; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; /** * KDC side utilities. */ public final class KdcUtil { private KdcUtil() { } /** * Get kdc configuration * @param confDir configuration directory * @return kdc configuration * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public static KdcConfig getKdcConfig(File confDir) throws KrbException { File kdcConfFile = new File(confDir, "kdc.conf"); if (kdcConfFile.exists()) { KdcConfig kdcConfig = new KdcConfig(); try { kdcConfig.addKrb5Config(kdcConfFile); } catch (IOException e) { throw new KrbException("Can not load the kdc configuration file " + kdcConfFile.getAbsolutePath()); } return kdcConfig; } return null; } /** * Get backend configuration * @param confDir configuration directory * @return backend configuration * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public static BackendConfig getBackendConfig(File confDir) throws KrbException { File backendConfigFile = new File(confDir, "backend.conf"); if (backendConfigFile.exists()) { BackendConfig backendConfig = new BackendConfig(); try { backendConfig.addIniConfig(backendConfigFile); } catch (IOException e) { throw new KrbException("Can not load the backend configuration file " + backendConfigFile.getAbsolutePath()); } return backendConfig; } return null; } /** * Init the identity backend from backend configuration. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. * @param backendConfig backend configuration information * @return backend */ public static IdentityBackend getBackend( BackendConfig backendConfig) throws KrbException { String backendClassName = backendConfig.getString( KdcConfigKey.KDC_IDENTITY_BACKEND, true); if (backendClassName == null) { backendClassName = MemoryIdentityBackend.class.getCanonicalName(); } Class<?> backendClass; try { backendClass = Class.forName(backendClassName); } catch (ClassNotFoundException e) { throw new KrbException("Failed to load backend class: " + backendClassName); } IdentityBackend backend; try { backend = (IdentityBackend) backendClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new KrbException("Failed to create backend: " + backendClassName); } backend.setConfig(backendConfig); backend.initialize(); return backend; } /** * Get KDC network transport addresses according to KDC setting. * @param setting kdc setting * @return UDP and TCP addresses pair * @throws KrbException e */ public static TransportPair getTransportPair( KdcSetting setting) throws KrbException { TransportPair result = new TransportPair(); int tcpPort = setting.checkGetKdcTcpPort(); if (tcpPort > 0) { result.tcpAddress = new InetSocketAddress( setting.getKdcHost(), tcpPort); } int udpPort = setting.checkGetKdcUdpPort(); if (udpPort > 0) { result.udpAddress = new InetSocketAddress( setting.getKdcHost(), udpPort); } return result; } }
378
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcServer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.KOption; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.server.impl.DefaultInternalKdcServerImpl; import org.apache.kerby.kerberos.kerb.server.impl.InternalKdcServer; import java.io.File; /** * The implemented Kerberos Server API. */ public class KdcServer { private final KdcConfig kdcConfig; private final BackendConfig backendConfig; private final KdcSetting kdcSetting; private final KOptions startupOptions; private InternalKdcServer innerKdc; /** * Constructor passing both kdcConfig and backendConfig. * @param kdcConfig The kdc config * @param backendConfig The backend config * @throws KrbException e */ public KdcServer(KdcConfig kdcConfig, BackendConfig backendConfig) throws KrbException { this.kdcConfig = kdcConfig; this.backendConfig = backendConfig; startupOptions = new KOptions(); kdcSetting = new KdcSetting(startupOptions, kdcConfig, backendConfig); } /** * Constructor given confDir where 'kdc.conf' and 'backend.conf' should be * available. * kdc.conf, that contains kdc server related items. * backend.conf, that contains identity backend related items. * * @param confDir The conf dir * @throws KrbException e */ public KdcServer(File confDir) throws KrbException { KdcConfig tmpKdcConfig = KdcUtil.getKdcConfig(confDir); if (tmpKdcConfig == null) { tmpKdcConfig = new KdcConfig(); } this.kdcConfig = tmpKdcConfig; BackendConfig tmpBackendConfig = KdcUtil.getBackendConfig(confDir); if (tmpBackendConfig == null) { tmpBackendConfig = new BackendConfig(); } tmpBackendConfig.setConfDir(confDir); this.backendConfig = tmpBackendConfig; startupOptions = new KOptions(); kdcSetting = new KdcSetting(startupOptions, kdcConfig, backendConfig); } /** * Default constructor. */ public KdcServer() { kdcConfig = new KdcConfig(); backendConfig = new BackendConfig(); startupOptions = new KOptions(); kdcSetting = new KdcSetting(startupOptions, kdcConfig, backendConfig); } /** * Set KDC realm for ticket request * @param realm The kdc realm */ public void setKdcRealm(String realm) { startupOptions.add(KdcServerOption.KDC_REALM, realm); } /** * Set KDC host. * @param kdcHost The kdc host */ public void setKdcHost(String kdcHost) { startupOptions.add(KdcServerOption.KDC_HOST, kdcHost); } /** * Set KDC port. * @param kdcPort The kdc port */ public void setKdcPort(int kdcPort) { startupOptions.add(KdcServerOption.KDC_PORT, kdcPort); } /** * Get the KDC port, if it has been set. */ public int getKdcPort() { KOption option = startupOptions.getOption(KdcServerOption.KDC_PORT); if (option != null) { return (Integer) option.getOptionInfo().getValue(); } return 0; } /** * Set KDC tcp port. * @param kdcTcpPort The kdc tcp port */ public void setKdcTcpPort(int kdcTcpPort) { startupOptions.add(KdcServerOption.KDC_TCP_PORT, kdcTcpPort); } /** * Get the KDC Tcp port, if it has been set. */ public int getKdcTcpPort() { KOption option = startupOptions.getOption(KdcServerOption.KDC_TCP_PORT); if (option != null) { return (Integer) option.getOptionInfo().getValue(); } return 0; } /** * Set to allow UDP or not. * @param allowUdp true if allow udp */ public void setAllowUdp(boolean allowUdp) { startupOptions.add(KdcServerOption.ALLOW_UDP, allowUdp); } /** * Set to allow TCP or not. * @param allowTcp true if allow tcp */ public void setAllowTcp(boolean allowTcp) { startupOptions.add(KdcServerOption.ALLOW_TCP, allowTcp); } /** * Set KDC udp port. Only makes sense when allowUdp is set. * @param kdcUdpPort The kdc udp port */ public void setKdcUdpPort(int kdcUdpPort) { startupOptions.add(KdcServerOption.KDC_UDP_PORT, kdcUdpPort); } /** * Get the KDC udp port, if it has been set. */ public int getKdcUdpPort() { KOption option = startupOptions.getOption(KdcServerOption.KDC_UDP_PORT); if (option != null) { return (Integer) option.getOptionInfo().getValue(); } return 0; } /** * Set runtime folder. * @param workDir The work dir */ public void setWorkDir(File workDir) { startupOptions.add(KdcServerOption.WORK_DIR, workDir); } /** * Allow to debug so have more logs. */ public void enableDebug() { startupOptions.add(KdcServerOption.ENABLE_DEBUG); } /** * Allow to hook customized kdc implementation. * * @param innerKdcImpl The inner kdc implementation */ public void setInnerKdcImpl(InternalKdcServer innerKdcImpl) { startupOptions.add(KdcServerOption.INNER_KDC_IMPL, innerKdcImpl); } /** * Get KDC setting from startup options and configs. * @return setting */ public KdcSetting getKdcSetting() { return kdcSetting; } /** * Get the KDC config. * @return KdcConfig */ public KdcConfig getKdcConfig() { return kdcConfig; } /** * Get backend config. * * @return backend configuration */ public BackendConfig getBackendConfig() { return backendConfig; } /** * Get identity service. * @return IdentityService */ public IdentityBackend getIdentityService() { if (innerKdc == null) { throw new RuntimeException("Not init yet"); } return innerKdc.getIdentityBackend(); } /** * Initialize. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public void init() throws KrbException { if (startupOptions.contains(KdcServerOption.INNER_KDC_IMPL)) { innerKdc = (InternalKdcServer) startupOptions.getOptionValue( KdcServerOption.INNER_KDC_IMPL); } else { innerKdc = new DefaultInternalKdcServerImpl(kdcSetting); } innerKdc.init(); } /** * Start the KDC server. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public void start() throws KrbException { if (innerKdc == null) { throw new RuntimeException("Not init yet"); } innerKdc.start(); } /** * Stop the KDC server. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public void stop() throws KrbException { if (innerKdc != null) { innerKdc.stop(); } } }
379
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/ServerSetting.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; /** * Super clsss of KdcSetting and AdminServer Setting. * This class is used to solve the problem of member variable in * LocalKadminImpl (KdcSetting or AdminServerSetting). */ public interface ServerSetting { String getKdcRealm(); KdcConfig getKdcConfig(); BackendConfig getBackendConfig(); }
380
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcSetting.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; /** * KDC setting that combines startup options and kdc config. */ public class KdcSetting implements ServerSetting { private final KOptions startupOptions; private final KdcConfig kdcConfig; private final BackendConfig backendConfig; /** * KdcSetting constructor * @param startupOptions startup options * @param config kdc configuration * @param backendConfig backend configuration */ public KdcSetting(KOptions startupOptions, KdcConfig config, BackendConfig backendConfig) { this.startupOptions = startupOptions; this.kdcConfig = config; this.backendConfig = backendConfig; } public KdcSetting(KdcConfig kdcConfig, BackendConfig backendConfig) { this(new KOptions(), kdcConfig, backendConfig); } /** * Get the KDC config. * @return kdc configuration */ public KdcConfig getKdcConfig() { return kdcConfig; } /** * Get the backend config. * @return backend configuration */ public BackendConfig getBackendConfig() { return backendConfig; } public String getKdcHost() { String kdcHost = startupOptions.getStringOption( KdcServerOption.KDC_HOST); if (kdcHost == null) { kdcHost = kdcConfig.getKdcHost(); } return kdcHost; } /** * Check kdc tcp setting and see if any bad. * @return valid tcp port or -1 if not allowTcp * @throws org.apache.kerby.kerberos.kerb.KrbException e */ public int checkGetKdcTcpPort() throws KrbException { if (allowTcp()) { int kdcPort = getKdcTcpPort(); if (kdcPort < 1) { throw new KrbException("KDC tcp port isn't set or configured"); } return kdcPort; } return -1; } /** * Check kdc udp setting and see if any bad. * @return valid udp port or -1 if not allowUdp * @throws KrbException e */ public int checkGetKdcUdpPort() throws KrbException { if (allowUdp()) { int kdcPort = getKdcUdpPort(); if (kdcPort < 1) { throw new KrbException("KDC udp port isn't set or configured"); } return kdcPort; } return -1; } /** * Get kdc tcp port * * @return kdc tcp port */ public int getKdcTcpPort() { int tcpPort = startupOptions.getIntegerOption(KdcServerOption.KDC_TCP_PORT); if (tcpPort < 1) { tcpPort = kdcConfig.getKdcTcpPort(); } if (tcpPort < 1) { tcpPort = getKdcPort(); } return tcpPort; } /** * Get kdc port * * @return kdc port */ public int getKdcPort() { int kdcPort = startupOptions.getIntegerOption(KdcServerOption.KDC_PORT); if (kdcPort < 1) { kdcPort = kdcConfig.getKdcPort(); } return kdcPort; } /** * Get whether tcp protocol is allowed * @return tcp protocol is allowed or not */ public boolean allowTcp() { return startupOptions.getBooleanOption( KdcServerOption.ALLOW_TCP, kdcConfig.allowTcp()); } /** * Get whether udp protocol is allowed * @return udp protocol is allowed or not */ public boolean allowUdp() { return startupOptions.getBooleanOption( KdcServerOption.ALLOW_UDP, kdcConfig.allowUdp()); } /** * Get kdc udp port * * @return udp port */ public int getKdcUdpPort() { int udpPort = startupOptions.getIntegerOption(KdcServerOption.KDC_UDP_PORT); if (udpPort < 1) { udpPort = kdcConfig.getKdcUdpPort(); } if (udpPort < 1) { udpPort = getKdcPort(); } return udpPort; } /** * Get KDC realm. * @return KDC realm */ public String getKdcRealm() { String kdcRealm = startupOptions.getStringOption(KdcServerOption.KDC_REALM); if (kdcRealm == null || kdcRealm.isEmpty()) { kdcRealm = kdcConfig.getKdcRealm(); } return kdcRealm; } }
381
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcRecoverableException.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbErrorException; import org.apache.kerby.kerberos.kerb.type.base.KrbError; /** * KDC side recoverable exception, where retrying will be made. */ public class KdcRecoverableException extends KrbErrorException { private static final long serialVersionUID = -3472169380126256193L; public KdcRecoverableException(KrbError krbError) { super(krbError); } }
382
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcConfig.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.common.Krb5Conf; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import java.util.Arrays; import java.util.List; /** * Kerb KDC side configuration API. */ public class KdcConfig extends Krb5Conf { private static final String KDCDEFAULT = "kdcdefaults"; public boolean enableDebug() { return getBoolean(KdcConfigKey.KRB_DEBUG, true, KDCDEFAULT); } public String getKdcServiceName() { return getString(KdcConfigKey.KDC_SERVICE_NAME, true, KDCDEFAULT); } public String getKdcHost() { return getString(KdcConfigKey.KDC_HOST, true, KDCDEFAULT); } public int getKdcPort() { Integer kdcPort = getInt(KdcConfigKey.KDC_PORT, true, KDCDEFAULT); if (kdcPort != null && kdcPort > 0) { return kdcPort.intValue(); } return -1; } public int getKdcTcpPort() { Integer kdcTcpPort = getInt(KdcConfigKey.KDC_TCP_PORT, true, KDCDEFAULT); if (kdcTcpPort != null && kdcTcpPort > 0) { return kdcTcpPort.intValue(); } return getKdcPort(); } /** * Is to allow TCP for KDC * @return true to allow TCP, false otherwise */ public Boolean allowTcp() { return getBoolean(KdcConfigKey.KDC_ALLOW_TCP, true, KDCDEFAULT) || getInt(KdcConfigKey.KDC_TCP_PORT, true, KDCDEFAULT) != null || getInt(KdcConfigKey.KDC_PORT, false, KDCDEFAULT) != null; } /** * Is to allow UDP for KDC * @return true to allow UDP, false otherwise */ public Boolean allowUdp() { return getBoolean(KdcConfigKey.KDC_ALLOW_UDP, true, KDCDEFAULT) || getInt(KdcConfigKey.KDC_UDP_PORT, true, KDCDEFAULT) != null || getInt(KdcConfigKey.KDC_PORT, false, KDCDEFAULT) != null; } public int getKdcUdpPort() { Integer kdcUdpPort = getInt(KdcConfigKey.KDC_UDP_PORT, true, KDCDEFAULT); if (kdcUdpPort != null && kdcUdpPort > 0) { return kdcUdpPort.intValue(); } return getKdcPort(); } public String getKdcRealm() { return getString(KdcConfigKey.KDC_REALM, true, KDCDEFAULT); } public String getKdcDomain() { return getString(KdcConfigKey.KDC_DOMAIN, true, KDCDEFAULT); } public boolean isPreauthRequired() { return getBoolean(KdcConfigKey.PREAUTH_REQUIRED, true, KDCDEFAULT); } public boolean isAllowTokenPreauth() { return getBoolean(KdcConfigKey.ALLOW_TOKEN_PREAUTH, true, KDCDEFAULT); } public long getAllowableClockSkew() { return getLong(KdcConfigKey.ALLOWABLE_CLOCKSKEW, true, KDCDEFAULT); } public boolean isEmptyAddressesAllowed() { return getBoolean(KdcConfigKey.EMPTY_ADDRESSES_ALLOWED, true, KDCDEFAULT); } public boolean isForwardableAllowed() { return getBoolean(KdcConfigKey.FORWARDABLE_ALLOWED, true, KDCDEFAULT); } public boolean isPostdatedAllowed() { return getBoolean(KdcConfigKey.POSTDATED_ALLOWED, true, KDCDEFAULT); } public boolean isProxiableAllowed() { return getBoolean(KdcConfigKey.PROXIABLE_ALLOWED, true, KDCDEFAULT); } public boolean isRenewableAllowed() { return getBoolean(KdcConfigKey.RENEWABLE_ALLOWED, true, KDCDEFAULT); } public long getMaximumRenewableLifetime() { return getLong(KdcConfigKey.MAXIMUM_RENEWABLE_LIFETIME, true, KDCDEFAULT); } public long getMaximumTicketLifetime() { return getLong(KdcConfigKey.MAXIMUM_TICKET_LIFETIME, true, KDCDEFAULT); } public long getMinimumTicketLifetime() { return getLong(KdcConfigKey.MINIMUM_TICKET_LIFETIME, true, KDCDEFAULT); } public List<EncryptionType> getEncryptionTypes() { return getEncTypes(KdcConfigKey.ENCRYPTION_TYPES, true, KDCDEFAULT); } public boolean isPaEncTimestampRequired() { return getBoolean(KdcConfigKey.PA_ENC_TIMESTAMP_REQUIRED, true, KDCDEFAULT); } public boolean isBodyChecksumVerified() { return getBoolean(KdcConfigKey.VERIFY_BODY_CHECKSUM, true, KDCDEFAULT); } public boolean isRestrictAnonymousToTgt() { return getBoolean(KdcConfigKey.RESTRICT_ANONYMOUS_TO_TGT, true, KDCDEFAULT); } public int getKdcMaxDgramReplySize() { return getInt(KdcConfigKey.KDC_MAX_DGRAM_REPLY_SIZE, true, KDCDEFAULT); } public String getVerifyKeyConfig() { return getString(KdcConfigKey.TOKEN_VERIFY_KEYS, true, KDCDEFAULT); } public String getDecryptionKeyConfig() { return getString(KdcConfigKey.TOKEN_DECRYPTION_KEYS, true, KDCDEFAULT); } public List<String> getIssuers() { return Arrays.asList(getStringArray(KdcConfigKey.TOKEN_ISSUERS, true, KDCDEFAULT)); } public List<String> getPkinitAnchors() { return Arrays.asList(getString( KdcConfigKey.PKINIT_ANCHORS, true, KDCDEFAULT)); } public String getPkinitIdentity() { return getString( KdcConfigKey.PKINIT_IDENTITY, true, KDCDEFAULT); } }
383
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbCodec; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.server.request.AsRequest; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.server.request.TgsRequest; import org.apache.kerby.kerberos.kerb.type.KerberosTime; import org.apache.kerby.kerberos.kerb.type.base.KrbError; import org.apache.kerby.kerberos.kerb.type.base.KrbMessage; import org.apache.kerby.kerberos.kerb.type.base.KrbMessageType; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; import org.apache.kerby.kerberos.kerb.type.kdc.AsReq; import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq; import org.apache.kerby.kerberos.kerb.type.kdc.TgsReq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; /** * KDC handler to process client requests. Currently only one realm is supported. */ public class KdcHandler { private static final Logger LOG = LoggerFactory.getLogger(KdcHandler.class); private final KdcContext kdcContext; /** * Constructor with kdc context. * * @param kdcContext kdc context */ public KdcHandler(KdcContext kdcContext) { this.kdcContext = kdcContext; } /** * Process the client request message. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param receivedMessage The client request message * @param isTcp whether the protocol is tcp * @param remoteAddress Address from remote side * @return The response message */ public ByteBuffer handleMessage(ByteBuffer receivedMessage, boolean isTcp, InetAddress remoteAddress) throws KrbException { KrbMessage krbRequest; KdcRequest kdcRequest = null; KrbMessage krbResponse; ByteBuffer message = receivedMessage.duplicate(); try { krbRequest = KrbCodec.decodeMessage(receivedMessage); } catch (IOException e) { LOG.error("Krb decoding message failed", e); throw new KrbException(KrbErrorCode.KRB_AP_ERR_MSG_TYPE, "Krb decoding message failed"); } KrbMessageType messageType = krbRequest.getMsgType(); if (messageType == KrbMessageType.TGS_REQ || messageType == KrbMessageType.AS_REQ) { KdcReq kdcReq = (KdcReq) krbRequest; String realm = getRequestRealm(kdcReq); if (realm == null || !kdcContext.getKdcRealm().equals(realm)) { LOG.error("Invalid realm from kdc request: " + realm); throw new KrbException(KrbErrorCode.WRONG_REALM, "Invalid realm from kdc request: " + realm); } if (messageType == KrbMessageType.TGS_REQ) { kdcRequest = new TgsRequest((TgsReq) kdcReq, kdcContext); } else if (messageType == KrbMessageType.AS_REQ) { kdcRequest = new AsRequest((AsReq) kdcReq, kdcContext); } else { LOG.error("Invalid message type: " + messageType); throw new KrbException(KrbErrorCode.KRB_AP_ERR_MSG_TYPE); } } // For checksum if (kdcRequest == null) { throw new KrbException("Kdc request is null."); } kdcRequest.setReqPackage(message); if (remoteAddress == null) { throw new KrbException("Remote address is null, not available."); } kdcRequest.setClientAddress(remoteAddress); kdcRequest.isTcp(isTcp); try { kdcRequest.process(); krbResponse = kdcRequest.getReply(); } catch (Throwable e) { if (e instanceof KdcRecoverableException) { krbResponse = handleRecoverableException( (KdcRecoverableException) e, kdcRequest); } else { KrbError krbError = new KrbError(); krbError.setStime(KerberosTime.now()); krbError.setSusec(100); KrbErrorCode errorCode = KrbErrorCode.UNKNOWN_ERR; if (e instanceof KrbException && ((KrbException) e).getKrbErrorCode() != null) { errorCode = ((KrbException) e).getKrbErrorCode(); } krbError.setErrorCode(errorCode); krbError.setCrealm(kdcContext.getKdcRealm()); if (kdcRequest.getClientPrincipal() != null) { krbError.setCname(kdcRequest.getClientPrincipal()); } krbError.setRealm(kdcContext.getKdcRealm()); if (kdcRequest.getServerPrincipal() != null) { krbError.setSname(kdcRequest.getServerPrincipal()); } else { PrincipalName serverPrincipal = kdcRequest.getKdcReq().getReqBody().getSname(); serverPrincipal.setRealm(kdcRequest.getKdcReq().getReqBody().getRealm()); krbError.setSname(serverPrincipal); } if (KrbErrorCode.KRB_AP_ERR_BAD_INTEGRITY.equals(errorCode)) { krbError.setEtext("PREAUTH_FAILED"); } else { krbError.setEtext(e.getMessage()); } krbResponse = krbError; } } int bodyLen = krbResponse.encodingLength(); ByteBuffer responseMessage; if (isTcp) { responseMessage = ByteBuffer.allocate(bodyLen + 4); responseMessage.putInt(bodyLen); } else { responseMessage = ByteBuffer.allocate(bodyLen); } KrbCodec.encode(krbResponse, responseMessage); responseMessage.flip(); return responseMessage; } /** * Process the recoverable exception. * * @param e The exception return by kdc * @param kdcRequest kdc request * @return The KrbError */ private KrbMessage handleRecoverableException(KdcRecoverableException e, KdcRequest kdcRequest) throws KrbException { LOG.info("KRB error occurred while processing request: " + e.getMessage()); KrbError error = e.getKrbError(); error.setStime(KerberosTime.now()); error.setSusec(100); error.setErrorCode(e.getKrbError().getErrorCode()); error.setRealm(kdcContext.getKdcRealm()); if (kdcRequest != null) { error.setSname(kdcRequest.getKdcReq().getReqBody().getCname()); } else { error.setSname(new PrincipalName("NONE")); } error.setEtext(e.getMessage()); return error; } /** * Get request realm. * @param kdcReq kdc request * @return realm */ private String getRequestRealm(KdcReq kdcReq) { String realm = kdcReq.getReqBody().getRealm(); if (realm == null && kdcReq.getReqBody().getCname() != null) { realm = kdcReq.getReqBody().getCname().getRealm(); } return realm; } }
384
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.identity.IdentityService; import org.apache.kerby.kerberos.kerb.server.preauth.PreauthHandler; import org.apache.kerby.kerberos.kerb.server.replay.ReplayCheckService; public class KdcContext { private final KdcSetting kdcSetting; private IdentityService identityService; private ReplayCheckService replayCache; private PreauthHandler preauthHandler; public KdcContext(KdcSetting kdcSetting) { this.kdcSetting = kdcSetting; } public KdcSetting getKdcSetting() { return kdcSetting; } public KdcConfig getConfig() { return kdcSetting.getKdcConfig(); } public void setPreauthHandler(PreauthHandler preauthHandler) { this.preauthHandler = preauthHandler; } public PreauthHandler getPreauthHandler() { return this.preauthHandler; } public void setReplayCache(ReplayCheckService replayCache) { this.replayCache = replayCache; } public ReplayCheckService getReplayCache() { return replayCache; } public void setIdentityService(IdentityService identityService) { this.identityService = identityService; } public IdentityService getIdentityService() { return identityService; } public String getKdcRealm() { return kdcSetting.getKdcRealm(); } }
385
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/KdcConfigKey.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.config.ConfigKey; public enum KdcConfigKey implements ConfigKey { KRB_DEBUG(true), KDC_SERVICE_NAME("KDC-Server"), KDC_IDENTITY_BACKEND, KDC_HOST("127.0.0.1"), KDC_PORT, KDC_ALLOW_TCP(true), KDC_ALLOW_UDP(true), KDC_UDP_PORT, KDC_TCP_PORT, KDC_DOMAIN("example.com"), KDC_REALM("EXAMPLE.COM"), PREAUTH_REQUIRED(true), ALLOW_TOKEN_PREAUTH(true), ALLOWABLE_CLOCKSKEW(5 * 60L), EMPTY_ADDRESSES_ALLOWED(true), PA_ENC_TIMESTAMP_REQUIRED(true), MAXIMUM_TICKET_LIFETIME(24 * 3600L), MINIMUM_TICKET_LIFETIME(1 * 3600L), MAXIMUM_RENEWABLE_LIFETIME(48 * 3600L), FORWARDABLE_ALLOWED(true), POSTDATED_ALLOWED(true), PROXIABLE_ALLOWED(true), RENEWABLE_ALLOWED(true), VERIFY_BODY_CHECKSUM(true), ENCRYPTION_TYPES("aes128-cts-hmac-sha1-96 des3-cbc-sha1-kd"), RESTRICT_ANONYMOUS_TO_TGT(false), KDC_MAX_DGRAM_REPLY_SIZE(4096), TOKEN_VERIFY_KEYS(), TOKEN_DECRYPTION_KEYS(), TOKEN_ISSUERS(), PKINIT_IDENTITY(null), PKINIT_ANCHORS(null); private Object defaultValue; KdcConfigKey() { this.defaultValue = null; } KdcConfigKey(Object defaultValue) { this.defaultValue = defaultValue; } @Override public String getPropertyKey() { return name().toLowerCase(); } @Override public Object getDefaultValue() { return this.defaultValue; } }
386
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/impl/InternalKdcServer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.impl; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.server.KdcSetting; /** * An internal KDC server interface. */ public interface InternalKdcServer { /** * Initialize. * @throws KrbException e */ void init() throws KrbException; /** * Start the KDC server. * @throws KrbException e */ void start() throws KrbException; /** * Stop the KDC server. * @throws KrbException e */ void stop() throws KrbException; /** * Get KDC setting. * @return setting */ KdcSetting getSetting(); /** * Get identity backend. * @return IdentityBackend */ IdentityBackend getIdentityBackend(); }
387
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/impl/AbstractInternalKdcServer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.impl; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.IdentityService; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.server.KdcSetting; import org.apache.kerby.kerberos.kerb.server.KdcUtil; /** * Abstract KDC server implementation. */ public class AbstractInternalKdcServer implements InternalKdcServer { private boolean started; private final KdcConfig kdcConfig; private final BackendConfig backendConfig; private final KdcSetting kdcSetting; private IdentityBackend backend; public AbstractInternalKdcServer(KdcSetting kdcSetting) { this.kdcSetting = kdcSetting; this.kdcConfig = kdcSetting.getKdcConfig(); this.backendConfig = kdcSetting.getBackendConfig(); } @Override public KdcSetting getSetting() { return kdcSetting; } public boolean isStarted() { return started; } protected String getServiceName() { return kdcConfig.getKdcServiceName(); } protected IdentityService getIdentityService() { return backend; } @Override public void init() throws KrbException { backend = KdcUtil.getBackend(backendConfig); } @Override public void start() throws KrbException { try { doStart(); } catch (Exception e) { throw new KrbException("Failed to start " + getServiceName() + ". " + e.getMessage()); } started = true; } public boolean enableDebug() { return kdcConfig.enableDebug(); } @Override public IdentityBackend getIdentityBackend() { return backend; } protected void doStart() throws Exception { backend.start(); } public void stop() throws KrbException { try { doStop(); } catch (Exception e) { throw new KrbException("Failed to stop " + getServiceName(), e); } started = false; } protected void doStop() throws Exception { backend.stop(); } }
388
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/impl/DefaultKdcHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.impl; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.KdcHandler; import org.apache.kerby.kerberos.kerb.transport.KrbTcpTransport; import org.apache.kerby.kerberos.kerb.transport.KrbTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; public class DefaultKdcHandler extends KdcHandler implements Runnable { private static Logger logger = LoggerFactory.getLogger(DefaultKdcHandler.class); private final KrbTransport transport; public DefaultKdcHandler(KdcContext kdcContext, KrbTransport transport) { super(kdcContext); this.transport = transport; } @Override public void run() { while (true) { try { ByteBuffer message = transport.receiveMessage(); if (message == null) { logger.debug("No valid request recved. Disconnect actively"); transport.release(); break; } handleMessage(message); } catch (IOException e) { transport.release(); logger.debug("Transport or decoding error occurred, " + "disconnecting abnormally", e); break; } } } protected void handleMessage(ByteBuffer message) { InetAddress clientAddress = transport.getRemoteAddress(); boolean isTcp = transport instanceof KrbTcpTransport; try { ByteBuffer krbResponse = handleMessage(message, isTcp, clientAddress); transport.sendMessage(krbResponse); } catch (Exception e) { transport.release(); logger.error("Error occured while processing request:", e); } } }
389
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/impl/DefaultInternalKdcServerImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.impl; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.KdcSetting; import org.apache.kerby.kerberos.kerb.server.KdcUtil; import org.apache.kerby.kerberos.kerb.server.preauth.PreauthHandler; import org.apache.kerby.kerberos.kerb.transport.KdcNetwork; import org.apache.kerby.kerberos.kerb.transport.KrbTransport; import org.apache.kerby.kerberos.kerb.transport.TransportPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * A default KDC server implementation. */ public class DefaultInternalKdcServerImpl extends AbstractInternalKdcServer { private static final Logger LOG = LoggerFactory.getLogger(DefaultInternalKdcServerImpl.class); private ExecutorService executor; private KdcContext kdcContext; private KdcNetwork network; public DefaultInternalKdcServerImpl(KdcSetting kdcSetting) { super(kdcSetting); } @Override protected void doStart() throws Exception { super.doStart(); prepareHandler(); executor = Executors.newCachedThreadPool(); network = new KdcNetwork() { @Override protected void onNewTransport(KrbTransport transport) { DefaultKdcHandler kdcHandler = new DefaultKdcHandler(kdcContext, transport); executor.execute(kdcHandler); } }; network.init(); TransportPair tpair = KdcUtil.getTransportPair(getSetting()); network.listen(tpair); network.start(); } private void prepareHandler() { kdcContext = new KdcContext(getSetting()); kdcContext.setIdentityService(getIdentityService()); PreauthHandler preauthHandler = new PreauthHandler(); preauthHandler.init(); kdcContext.setPreauthHandler(preauthHandler); } @Override protected void doStop() throws Exception { super.doStop(); if (network != null) { network.stop(); } if (executor != null) { executor.shutdown(); try { boolean terminated = false; do { // wait until the pool has terminated terminated = executor.awaitTermination(60, TimeUnit.SECONDS); } while (!terminated); } catch (InterruptedException e) { executor.shutdownNow(); LOG.warn("waitForTermination interrupted"); } } LOG.info("Default Internal kdc server stopped."); } }
390
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/KdcPreauth.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.preauth.PaFlags; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.PreauthPluginMeta; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; /** * KDC side preauth plugin module */ public interface KdcPreauth extends PreauthPluginMeta { /** * Initializing plugin context for each realm * @param context kdc context */ void initWith(KdcContext context); /** * Initializing request context * @param kdcRequest kdc context * @return request context */ PluginRequestContext initRequestContext(KdcRequest kdcRequest); /** * Optional: provide pa_data to send to the client as part of the "you need to * use preauthentication" error. * * @param kdcRequest kdc request * @param requestContext request context * @param outPaData out preauthentication data * @throws KrbException e */ void provideEdata(KdcRequest kdcRequest, PluginRequestContext requestContext, PaData outPaData) throws KrbException; /** * Optional: verify preauthentication data sent by the client, setting the * TKT_FLG_PRE_AUTH or TKT_FLG_HW_AUTH flag in the enc_tkt_reply's "flags" * field as appropriate. * @param kdcRequest kdc request * @param requestContext request context * @param paData preauthentication data * @return true if verify success * @throws KrbException e */ boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException; /** * Optional: generate preauthentication response data to send to the client as * part of the AS-REP. * @param kdcRequest kdc request * @param requestContext request context * @param paData preauthentication data */ void providePaData(KdcRequest kdcRequest, PluginRequestContext requestContext, PaData paData); /** * Return PA_REAL if pa_type is a real preauthentication type or PA_INFO if it is * an informational type. * @param kdcRequest kdc request * @param requestContext request context * @param paType preauthentication type * @return PaFlags */ PaFlags getFlags(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataType paType); /** * When exiting... */ void destroy(); }
391
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/PreauthHandle.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; public class PreauthHandle { public KdcPreauth preauth; public PluginRequestContext requestContext; public PreauthHandle(KdcPreauth preauth) { this.preauth = preauth; } public void initRequestContext(KdcRequest kdcRequest) { requestContext = preauth.initRequestContext(kdcRequest); } public void provideEdata(KdcRequest kdcRequest, PaData outPaData) throws KrbException { preauth.provideEdata(kdcRequest, requestContext, outPaData); } public void verify(KdcRequest kdcRequest, PaDataEntry paData) throws KrbException { preauth.verify(kdcRequest, requestContext, paData); } public void providePaData(KdcRequest kdcRequest, PaData paData) { preauth.providePaData(kdcRequest, requestContext, paData); } public void destroy() { preauth.destroy(); } }
392
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/KdcFastContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.fast.FastOptions; import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq; /** * Maintaining FAST processing state in KDC side per request. */ public class KdcFastContext { private EncryptionKey armorKey; private EncryptionKey strengthenKey; private FastOptions fastOptions; private int fastFlags; public EncryptionKey getArmorKey() { return armorKey; } public void setArmorKey(EncryptionKey armorKey) { this.armorKey = armorKey; } public EncryptionKey getStrengthenKey() { return strengthenKey; } public void setStrengthenKey(EncryptionKey strengthenKey) { this.strengthenKey = strengthenKey; } public FastOptions getFastOptions() { return fastOptions; } public void setFastOptions(FastOptions fastOptions) { this.fastOptions = fastOptions; } public int getFastFlags() { return fastFlags; } public void setFastFlags(int fastFlags) { this.fastFlags = fastFlags; } /*private void armorApRequest(KrbFastArmor armor) { } private byte[] encryptFastReply(KrbFastResponse fastResp) { return null; }*/ public byte[] findAndProcessFast(KdcReq kdcReq, byte[] checksumData, EncryptionKey tgsSubKey, EncryptionKey tgsSessionKey) { return null; } }
393
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/AbstractPreauthPlugin.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.preauth.PaFlags; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.PreauthPluginMeta; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; public class AbstractPreauthPlugin implements KdcPreauth { private PreauthPluginMeta pluginMeta; public AbstractPreauthPlugin(PreauthPluginMeta meta) { this.pluginMeta = meta; } @Override public String getName() { return pluginMeta.getName(); } public int getVersion() { return pluginMeta.getVersion(); } public PaDataType[] getPaTypes() { return pluginMeta.getPaTypes(); } @Override public void initWith(KdcContext kdcContext) { } @Override public PluginRequestContext initRequestContext(KdcRequest kdcRequest) { return null; } @Override public void provideEdata(KdcRequest kdcRequest, PluginRequestContext requestContext, PaData outPaData) throws KrbException { } @Override public boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException { return false; } @Override public void providePaData(KdcRequest kdcRequest, PluginRequestContext requestContext, PaData paData) { } @Override public PaFlags getFlags(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataType paType) { return null; } @Override public void destroy() { } }
394
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/PreauthHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.preauth.builtin.EncTsPreauth; import org.apache.kerby.kerberos.kerb.server.preauth.builtin.TgtPreauth; import org.apache.kerby.kerberos.kerb.server.preauth.pkinit.PkinitPreauth; import org.apache.kerby.kerberos.kerb.server.preauth.token.TokenPreauth; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; import java.util.ArrayList; import java.util.List; public class PreauthHandler { private List<KdcPreauth> preauths; /** * Should be called only once, for global */ public void init() { loadPreauthPlugins(); } private void loadPreauthPlugins() { preauths = new ArrayList<>(); KdcPreauth preauth = new EncTsPreauth(); preauths.add(preauth); preauth = new TgtPreauth(); preauths.add(preauth); preauth = new TokenPreauth(); preauths.add(preauth); preauth = new PkinitPreauth(); preauths.add(preauth); } /** * Should be called per realm * @param context The kdc context */ public void initWith(KdcContext context) { for (KdcPreauth preauth : preauths) { preauth.initWith(context); } } public PreauthContext preparePreauthContext(KdcRequest kdcRequest) { PreauthContext preauthContext = new PreauthContext(); KdcContext kdcContext = kdcRequest.getKdcContext(); initWith(kdcContext); preauthContext.setPreauthRequired(kdcContext.getConfig().isPreauthRequired()); for (KdcPreauth preauth : preauths) { PreauthHandle handle = new PreauthHandle(preauth); handle.initRequestContext(kdcRequest); preauthContext.getHandles().add(handle); } return preauthContext; } public void provideEdata(KdcRequest kdcRequest, PaData outPaData) throws KrbException { PreauthContext preauthContext = kdcRequest.getPreauthContext(); for (PreauthHandle handle : preauthContext.getHandles()) { handle.provideEdata(kdcRequest, outPaData); } } public void verify(KdcRequest kdcRequest, PaData paData) throws KrbException { for (PaDataEntry paEntry : paData.getElements()) { PreauthHandle handle = findHandle(kdcRequest, paEntry.getPaDataType()); if (handle != null) { handle.verify(kdcRequest, paEntry); } } } public void providePaData(KdcRequest kdcRequest, PaData paData) { PreauthContext preauthContext = kdcRequest.getPreauthContext(); for (PreauthHandle handle : preauthContext.getHandles()) { handle.providePaData(kdcRequest, paData); } } private PreauthHandle findHandle(KdcRequest kdcRequest, PaDataType paType) { PreauthContext preauthContext = kdcRequest.getPreauthContext(); for (PreauthHandle handle : preauthContext.getHandles()) { for (PaDataType pt : handle.preauth.getPaTypes()) { if (pt == paType) { return handle; } } } return null; } public void destroy() { for (KdcPreauth preauth : preauths) { preauth.destroy(); } } public static boolean isToken(PaData paData) { if (paData != null) { for (PaDataEntry paEntry : paData.getElements()) { if (paEntry.getPaDataType() == PaDataType.TOKEN_REQUEST) { return true; } } } return false; } public static boolean isPkinit(PaData paData) { if (paData != null) { for (PaDataEntry paEntry : paData.getElements()) { if (paEntry.getPaDataType() == PaDataType.PK_AS_REQ) { return true; } } } return false; } }
395
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/PreauthContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.pa.PaData; import java.util.ArrayList; import java.util.List; public class PreauthContext { private boolean preauthRequired = true; private List<PreauthHandle> handles = new ArrayList<>(5); private PaData outputPaData; public PreauthContext() { this.outputPaData = new PaData(); } public boolean isPreauthRequired() { return preauthRequired; } public void setPreauthRequired(boolean preauthRequired) { this.preauthRequired = preauthRequired; } public List<PreauthHandle> getHandles() { return handles; } public void reset() { this.outputPaData = new PaData(); } public PaData getOutputPaData() throws KrbException { return outputPaData; } }
396
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/token/TokenRequestContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth.token; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; public class TokenRequestContext implements PluginRequestContext { private boolean doIdentityMatching; private PaDataType paType; private boolean identityInitialized; private boolean identityPrompted; public boolean isDoIdentityMatching() { return doIdentityMatching; } public void setDoIdentityMatching(boolean doIdentityMatching) { this.doIdentityMatching = doIdentityMatching; } public PaDataType getPaType() { return paType; } public void setPaType(PaDataType paType) { this.paType = paType; } public boolean isIdentityInitialized() { return identityInitialized; } public void setIdentityInitialized(boolean identityInitialized) { this.identityInitialized = identityInitialized; } public boolean isIdentityPrompted() { return identityPrompted; } public void setIdentityPrompted(boolean identityPrompted) { this.identityPrompted = identityPrompted; } }
397
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/token/TokenPreauth.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth.token; import org.apache.kerby.kerberos.kerb.KrbCodec; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.KrbRuntime; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.common.PrivateKeyReader; import org.apache.kerby.kerberos.kerb.common.PublicKeyReader; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.token.TokenPreauthMeta; import org.apache.kerby.kerberos.kerb.provider.TokenDecoder; import org.apache.kerby.kerberos.kerb.server.preauth.AbstractPreauthPlugin; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.base.AuthToken; import org.apache.kerby.kerberos.kerb.type.base.EncryptedData; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.KeyUsage; import org.apache.kerby.kerberos.kerb.type.base.KrbTokenBase; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; import org.apache.kerby.kerberos.kerb.type.pa.token.PaTokenRequest; import org.apache.kerby.kerberos.kerb.type.pa.token.TokenInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.security.PrivateKey; import java.security.PublicKey; import java.util.List; public class TokenPreauth extends AbstractPreauthPlugin { private static final Logger LOG = LoggerFactory.getLogger(TokenPreauth.class); public TokenPreauth() { super(new TokenPreauthMeta()); } @Override public boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException { if (!kdcRequest.getKdcContext().getConfig().isAllowTokenPreauth()) { throw new KrbException(KrbErrorCode.TOKEN_PREAUTH_NOT_ALLOWED, "Token preauth is not allowed."); } if (paData.getPaDataType() == PaDataType.TOKEN_REQUEST) { PaTokenRequest paTokenRequest; if (kdcRequest.isHttps()) { paTokenRequest = KrbCodec.decode(paData.getPaDataValue(), PaTokenRequest.class); } else { EncryptedData encData = KrbCodec.decode(paData.getPaDataValue(), EncryptedData.class); EncryptionKey clientKey = kdcRequest.getArmorKey(); kdcRequest.setClientKey(clientKey); paTokenRequest = EncryptionUtil.unseal(encData, clientKey, KeyUsage.PA_TOKEN, PaTokenRequest.class); } KrbTokenBase token = paTokenRequest.getToken(); List<String> issuers = kdcRequest.getKdcContext().getConfig().getIssuers(); TokenInfo tokenInfo = paTokenRequest.getTokenInfo(); String issuer = tokenInfo.getTokenVendor(); if (!issuers.contains(issuer)) { throw new KrbException("Unconfigured issuer: " + issuer); } // Configure keys TokenDecoder tokenDecoder = KrbRuntime.getTokenProvider("JWT").createTokenDecoder(); configureKeys(tokenDecoder, kdcRequest, issuer); AuthToken authToken; try { authToken = tokenDecoder.decodeFromBytes(token.getTokenValue()); if (!tokenDecoder.isSigned()) { throw new KrbException("Token should be signed."); } } catch (IOException e) { throw new KrbException("Decoding failed", e); } if (authToken == null) { throw new KrbException("Token Decoding failed"); } List<String> audiences = authToken.getAudiences(); PrincipalName serverPrincipal = kdcRequest.getKdcReq().getReqBody().getSname(); serverPrincipal.setRealm(kdcRequest.getKdcReq().getReqBody().getRealm()); kdcRequest.setServerPrincipal(serverPrincipal); if (audiences == null || !audiences.contains(serverPrincipal.getName())) { throw new KrbException( "The token audience does not match with the target server principal! " + "Server principal is: " + serverPrincipal); } kdcRequest.setToken(authToken); return true; } else { return false; } } private void configureKeys(TokenDecoder tokenDecoder, KdcRequest kdcRequest, String issuer) { String verifyKeyPath = kdcRequest.getKdcContext().getConfig().getVerifyKeyConfig(); if (verifyKeyPath != null) { try (InputStream verifyKeyFile = getKeyFileStream(verifyKeyPath, issuer)) { if (verifyKeyFile != null) { PublicKey verifyKey = PublicKeyReader.loadPublicKey(verifyKeyFile); tokenDecoder.setVerifyKey(verifyKey); } } catch (FileNotFoundException e) { LOG.error("The verify key path is wrong. " + e.getMessage()); } catch (Exception e) { LOG.error("Failed to load public key. " + e.getMessage()); } } String decryptionKeyPath = kdcRequest.getKdcContext().getConfig().getDecryptionKeyConfig(); if (decryptionKeyPath != null) { try (InputStream decryptionKeyFile = getKeyFileStream(decryptionKeyPath, issuer)) { if (decryptionKeyFile != null) { PrivateKey decryptionKey = PrivateKeyReader.loadPrivateKey(decryptionKeyFile); tokenDecoder.setDecryptionKey(decryptionKey); } } catch (FileNotFoundException e) { LOG.error("The decryption key path is wrong. " + e); } catch (Exception e) { LOG.error("Fail to load private key. " + e); } } } private InputStream getKeyFileStream(String path, String issuer) throws IOException { File file = new File(path); if (file.isDirectory()) { File[] listOfFiles = file.listFiles(); File verifyKeyFile = null; if (listOfFiles == null) { throw new FileNotFoundException("The key path is incorrect"); } for (File f : listOfFiles) { if (f.isFile() && f.getName().contains(issuer)) { verifyKeyFile = f; break; } } if (verifyKeyFile == null) { throw new FileNotFoundException("No key found that matches the issuer name"); } return Files.newInputStream(verifyKeyFile.toPath()); } else if (file.isFile()) { return Files.newInputStream(file.toPath()); } // Not a directory or a file...maybe it's a resource on the classpath return this.getClass().getClassLoader().getResourceAsStream(path); } }
398
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/pkinit/PkinitRequestContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.kerby.kerberos.kerb.server.preauth.pkinit; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.type.pa.PaDataType; import org.apache.kerby.kerberos.kerb.type.pa.pkinit.AuthPack; public class PkinitRequestContext implements PluginRequestContext { public AuthPack authPack; public PaDataType paType; }
399