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-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbClientBase.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.client;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.ccache.Credential;
import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.client.impl.DefaultInternalKrbClient;
import org.apache.kerby.kerberos.kerb.client.impl.InternalKrbClient;
import org.apache.kerby.kerberos.kerb.type.kdc.EncAsRepPart;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* A Krb client API for applications to interact with KDC
*/
public class KrbClientBase {
private final KrbConfig krbConfig;
private final KOptions commonOptions;
private final KrbSetting krbSetting;
private InternalKrbClient innerClient;
private static final Logger LOG = LoggerFactory.getLogger(KrbClientBase.class);
/**
* Default constructor.
* @throws KrbException e
*/
public KrbClientBase() throws KrbException {
this.krbConfig = ClientUtil.getDefaultConfig();
this.commonOptions = new KOptions();
this.krbSetting = new KrbSetting(commonOptions, krbConfig);
}
/**
* Construct with prepared KrbConfig.
* @param krbConfig The krb config
*/
public KrbClientBase(KrbConfig krbConfig) {
this.krbConfig = krbConfig;
this.commonOptions = new KOptions();
this.krbSetting = new KrbSetting(commonOptions, krbConfig);
}
/**
* Constructor with conf dir
* @param confDir The conf dir
* @throws KrbException e
*/
public KrbClientBase(File confDir) throws KrbException {
this.commonOptions = new KOptions();
this.krbConfig = ClientUtil.getConfig(confDir);
this.krbSetting = new KrbSetting(commonOptions, krbConfig);
}
/**
* Constructor with prepared KrbClientBase.
* @param krbClient The krb client
*/
public KrbClientBase(KrbClientBase krbClient) {
this.commonOptions = krbClient.commonOptions;
this.krbConfig = krbClient.krbConfig;
this.krbSetting = krbClient.krbSetting;
this.innerClient = krbClient.innerClient;
}
/**
* Set KDC realm for ticket request
* @param realm The realm
*/
public void setKdcRealm(String realm) {
commonOptions.add(KrbOption.KDC_REALM, realm);
}
/**
* Set KDC host.
* @param kdcHost The kdc host
*/
public void setKdcHost(String kdcHost) {
commonOptions.add(KrbOption.KDC_HOST, kdcHost);
}
/**
* Set KDC tcp port.
* @param kdcTcpPort The kdc tcp port
*/
public void setKdcTcpPort(int kdcTcpPort) {
if (kdcTcpPort < 1) {
throw new IllegalArgumentException("Invalid port");
}
commonOptions.add(KrbOption.KDC_TCP_PORT, kdcTcpPort);
setAllowTcp(true);
}
/**
* Set to allow UDP or not.
* @param allowUdp true if allow udp
*/
public void setAllowUdp(boolean allowUdp) {
commonOptions.add(KrbOption.ALLOW_UDP, allowUdp);
}
/**
* Set to allow TCP or not.
* @param allowTcp true if allow tcp
*/
public void setAllowTcp(boolean allowTcp) {
commonOptions.add(KrbOption.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) {
if (kdcUdpPort < 1) {
throw new IllegalArgumentException("Invalid port");
}
commonOptions.add(KrbOption.KDC_UDP_PORT, kdcUdpPort);
setAllowUdp(true);
}
/**
* Set time out for connection
* @param timeout in seconds
*/
public void setTimeout(int timeout) {
commonOptions.add(KrbOption.CONN_TIMEOUT, timeout);
}
/**
* Init the client.
* @throws KrbException e
*/
public void init() throws KrbException {
innerClient = new DefaultInternalKrbClient(krbSetting);
innerClient.init();
}
/**
* Get krb client settings from options and configs.
* @return setting
*/
public KrbSetting getSetting() {
return krbSetting;
}
public KrbConfig getKrbConfig() {
return krbConfig;
}
/**
* Request a TGT with using well prepared requestOptions.
* @param requestOptions The request options
* @return TGT
* @throws KrbException e
*/
public TgtTicket requestTgt(KOptions requestOptions) throws KrbException {
if (requestOptions == null) {
throw new IllegalArgumentException("Null requestOptions specified");
}
return innerClient.requestTgt(requestOptions);
}
/**
* Request a service ticket with a TGT targeting for a server
* @param tgt The tgt ticket
* @param serverPrincipal The server principal
* @return Service ticket
* @throws KrbException e
*/
public SgtTicket requestSgt(TgtTicket tgt,
String serverPrincipal) throws KrbException {
KOptions requestOptions = new KOptions();
requestOptions.add(KrbOption.USE_TGT, tgt);
requestOptions.add(KrbOption.SERVER_PRINCIPAL, serverPrincipal);
return innerClient.requestSgt(requestOptions);
}
/**
* Request a service ticket provided request options
* @param requestOptions The request options
* @return service ticket
* @throws KrbException e
*/
public SgtTicket requestSgt(KOptions requestOptions) throws KrbException {
return innerClient.requestSgt(requestOptions);
}
/**
* Request a service ticket
* @param ccFile The credential cache file
* @param servicePrincipal The service principal
* @return service ticket
* @throws KrbException e
*/
public SgtTicket requestSgt(File ccFile, String servicePrincipal) throws KrbException {
Credential credential = getCredentialFromFile(ccFile);
TgtTicket tgt = getTgtTicketFromCredential(credential);
KOptions requestOptions = new KOptions();
// Renew ticket if argument named servicePrincipal is null
if (servicePrincipal == null) {
requestOptions.add(KrbKdcOption.RENEW);
servicePrincipal = credential.getServicePrincipal().getName();
}
requestOptions.add(KrbOption.USE_TGT, tgt);
requestOptions.add(KrbOption.SERVER_PRINCIPAL, servicePrincipal);
SgtTicket sgtTicket = innerClient.requestSgt(requestOptions);
sgtTicket.setClientPrincipal(tgt.getClientPrincipal());
return sgtTicket;
}
/**
* Store tgt into the specified credential cache file.
* @param tgtTicket The tgt ticket
* @param ccacheFile The credential cache file
* @throws KrbException e
*/
public void storeTicket(TgtTicket tgtTicket,
File ccacheFile) throws KrbException {
LOG.info("Storing the tgt to the credential cache file.");
if (!ccacheFile.exists()) {
createCacheFile(ccacheFile);
}
if (ccacheFile.exists() && ccacheFile.canWrite()) {
CredentialCache cCache = new CredentialCache(tgtTicket);
try {
cCache.store(ccacheFile);
} catch (IOException e) {
throw new KrbException("Failed to store tgt", e);
}
} else {
throw new IllegalArgumentException("Invalid ccache file, "
+ "not exist or writable: " + ccacheFile.getAbsolutePath());
}
}
/**
* Store sgt into the specified credential cache file.
* @param sgtTicket The sgt ticket
* @param ccacheFile The credential cache file
* @throws KrbException e
*/
public void storeTicket(SgtTicket sgtTicket, File ccacheFile) throws KrbException {
LOG.info("Storing the sgt to the credential cache file.");
boolean createCache = !ccacheFile.exists() || ccacheFile.length() == 0;
if (createCache) {
createCacheFile(ccacheFile);
}
if (ccacheFile.exists() && ccacheFile.canWrite()) {
try {
CredentialCache cCache;
if (!createCache) {
cCache = new CredentialCache();
cCache.load(ccacheFile);
cCache.addCredential(new Credential(sgtTicket, sgtTicket.getClientPrincipal()));
} else {
//Remind: contructor sets the cCache client principal from the sgtTicket one
cCache = new CredentialCache(sgtTicket);
}
cCache.store(ccacheFile);
} catch (IOException e) {
throw new KrbException("Failed to store sgt", e);
}
} else {
throw new IllegalArgumentException("Invalid ccache file, "
+ "not exist or writable: " + ccacheFile.getAbsolutePath());
}
}
/**
* Store sgt into the specified credential cache file.
* @param sgtTicket The sgt ticket
* @param ccacheFile The credential cache file
* @throws KrbException e
*/
public void renewTicket(SgtTicket sgtTicket, File ccacheFile) throws KrbException {
LOG.info("Renewing the ticket to the credential cache file.");
if (!ccacheFile.exists()) {
createCacheFile(ccacheFile);
}
if (ccacheFile.exists() && ccacheFile.canWrite()) {
CredentialCache cCache = new CredentialCache(sgtTicket);
try {
cCache.store(ccacheFile);
} catch (IOException e) {
throw new KrbException("Failed to renew ticket", e);
}
} else {
throw new IllegalArgumentException("Invalid ccache file, "
+ "not exist or writable: " + ccacheFile.getAbsolutePath());
}
}
/**
* Create the specified credential cache file.
*/
private void createCacheFile(File ccacheFile) throws KrbException {
try {
if (!ccacheFile.createNewFile()) {
throw new KrbException("Failed to create ccache file "
+ ccacheFile.getAbsolutePath());
}
// sets read-write permissions to owner only
ccacheFile.setReadable(true, true);
if (!ccacheFile.setWritable(true, true)) {
throw new KrbException("Cache file is not readable.");
}
} catch (IOException e) {
throw new KrbException("Failed to create ccache file "
+ ccacheFile.getAbsolutePath(), e);
}
}
public TgtTicket getTgtTicketFromCredential(Credential cc) {
EncAsRepPart encAsRepPart = new EncAsRepPart();
encAsRepPart.setAuthTime(cc.getAuthTime());
encAsRepPart.setCaddr(cc.getClientAddresses());
encAsRepPart.setEndTime(cc.getEndTime());
encAsRepPart.setFlags(cc.getTicketFlags());
encAsRepPart.setKey(cc.getKey());
// encAsRepPart.setKeyExpiration();
// encAsRepPart.setLastReq();
// encAsRepPart.setNonce();
encAsRepPart.setRenewTill(cc.getRenewTill());
encAsRepPart.setSname(cc.getServerName());
encAsRepPart.setSrealm(cc.getServerName().getRealm());
encAsRepPart.setStartTime(cc.getStartTime());
TgtTicket tgtTicket = new TgtTicket(cc.getTicket(), encAsRepPart, cc.getClientName());
return tgtTicket;
}
public Credential getCredentialFromFile(File ccFile) throws KrbException {
CredentialCache cc;
try {
cc = resolveCredCache(ccFile);
} catch (IOException e) {
throw new KrbException("Failed to load armor cache file");
}
return cc.getCredentials().iterator().next();
}
public CredentialCache resolveCredCache(File ccacheFile) throws IOException {
CredentialCache cc = new CredentialCache();
cc.load(ccacheFile);
return cc;
}
}
| 200 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbSetting.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.client;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
/**
* Krb client setting that combines common options and client config.
*/
public class KrbSetting {
private final KOptions commonOptions;
private final KrbConfig krbConfig;
public KrbSetting(KOptions commonOptions, KrbConfig config) {
this.commonOptions = commonOptions;
this.krbConfig = config;
}
public KrbSetting(KrbConfig config) {
this.commonOptions = new KOptions();
this.krbConfig = config;
}
public KrbConfig getKrbConfig() {
return krbConfig;
}
public String getKdcRealm() {
String kdcRealm = commonOptions.getStringOption(KrbOption.KDC_REALM);
if (kdcRealm == null || kdcRealm.isEmpty()) {
kdcRealm = krbConfig.getKdcRealm();
}
return kdcRealm;
}
public String getKdcHost() {
String kdcHost = commonOptions.getStringOption(KrbOption.KDC_HOST);
if (kdcHost == null) {
return krbConfig.getKdcHost();
}
return kdcHost;
}
/**
* Check kdc tcp setting and see if any bad.
* @return valid tcp port or -1 if not allowTcp
* @throws 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;
}
public int getKdcTcpPort() {
int tcpPort = commonOptions.getIntegerOption(KrbOption.KDC_TCP_PORT);
if (tcpPort > 0) {
return tcpPort;
}
return krbConfig.getKdcTcpPort();
}
public boolean allowUdp() {
return commonOptions.getBooleanOption(
KrbOption.ALLOW_UDP, krbConfig.allowUdp());
}
public boolean allowTcp() {
return commonOptions.getBooleanOption(
KrbOption.ALLOW_TCP, krbConfig.allowTcp());
}
public int getKdcUdpPort() {
int udpPort = commonOptions.getIntegerOption(KrbOption.KDC_UDP_PORT);
if (udpPort > 0) {
return udpPort;
}
return krbConfig.getKdcUdpPort();
}
public int getTimeout() {
int timeout = commonOptions.getIntegerOption(KrbOption.CONN_TIMEOUT);
if (timeout > 0) {
return timeout;
}
return 1000; // by default
}
}
| 201 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbClient.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.client;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import java.io.File;
/**
* A Krb client API for applications to interact with KDC
*/
public class KrbClient extends KrbClientBase {
/**
* Default constructor.
* @throws KrbException e
*/
public KrbClient() throws KrbException {
super();
}
/**
* Construct with prepared KrbConfig.
* @param krbConfig The krb config
*/
public KrbClient(KrbConfig krbConfig) {
super(krbConfig);
}
/**
* Constructor with conf dir
* @param confDir The conf dir
* @throws KrbException e
*/
public KrbClient(File confDir) throws KrbException {
super(confDir);
}
/**
* Request a TGT with user plain credential
* @param principal The principal
* @param password The password
* @return The tgt ticket
* @throws KrbException e
*/
public TgtTicket requestTgt(String principal,
String password) throws KrbException {
KOptions requestOptions = new KOptions();
requestOptions.add(KrbOption.CLIENT_PRINCIPAL, principal);
requestOptions.add(KrbOption.USE_PASSWD, true);
requestOptions.add(KrbOption.USER_PASSWD, password);
return requestTgt(requestOptions);
}
/**
* Request a TGT with user plain credential
* @param principal The principal
* @param keytabFile The keytab file
* @return TGT
* @throws KrbException e
*/
public TgtTicket requestTgt(String principal,
File keytabFile) throws KrbException {
KOptions requestOptions = new KOptions();
requestOptions.add(KrbOption.CLIENT_PRINCIPAL, principal);
requestOptions.add(KrbOption.USE_KEYTAB, true);
requestOptions.add(KrbOption.KEYTAB_FILE, keytabFile);
return requestTgt(requestOptions);
}
}
| 202 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbConfigKey.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.client;
import org.apache.kerby.config.ConfigKey;
public enum KrbConfigKey implements ConfigKey {
KRB_DEBUG(true),
KDC_HOST("localhost"),
KDC_PORT(88),
KDC_ALLOW_UDP(false),
KDC_ALLOW_TCP(false),
KDC_UDP_PORT(88),
KDC_TCP_PORT(88),
KDC_DOMAIN("example.com"),
KDC_REALM("EXAMPLE.COM"),
TGS_PRINCIPAL("krbtgt@EXAMPLE.COM"),
PREAUTH_REQUIRED(true),
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(true),
POSTDATED_ALLOWED(true),
PROXIABLE(true),
RENEWABLE_ALLOWED(true),
VERIFY_BODY_CHECKSUM(true),
PERMITTED_ENCTYPES("aes128-cts-hmac-sha1-96"),
DEFAULT_REALM(null),
DNS_LOOKUP_KDC(false),
DNS_LOOKUP_REALM(false),
ALLOW_WEAK_CRYPTO(true),
TICKET_LIFETIME(24 * 3600L),
RENEW_LIFETIME(48 * 3600L),
DEFAULT_TGS_ENCTYPES("aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 "
+ "des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac "
+ "camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4"),
DEFAULT_TKT_ENCTYPES("aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 "
+ "des3-cbc-sha1 arcfour-hmac-md5 camellia256-cts-cmac "
+ "camellia128-cts-cmac des-cbc-crc des-cbc-md5 des-cbc-md4"),
PKINIT_ANCHORS(null),
PKINIT_IDENTITIES(null),
PKINIT_KDC_HOSTNAME();
private Object defaultValue;
KrbConfigKey() {
this.defaultValue = null;
}
KrbConfigKey(Object defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public String getPropertyKey() {
return name().toLowerCase();
}
@Override
public Object getDefaultValue() {
return this.defaultValue;
}
}
| 203 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/TokenOption.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.client;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptionInfo;
import org.apache.kerby.KOptionType;
/**
* This defines all the token options.
*/
public enum TokenOption implements KOption {
NONE(null),
USE_TOKEN(new KOptionInfo("use-id-token", "Using identity token")),
USER_ID_TOKEN(new KOptionInfo("user-id-token", "User identity token",
KOptionType.STR)),
USER_AC_TOKEN(new KOptionInfo("user-ac-token", "User access token",
KOptionType.STR));
private final KOptionInfo optionInfo;
TokenOption(KOptionInfo optionInfo) {
this.optionInfo = optionInfo;
}
@Override
public KOptionInfo getOptionInfo() {
return optionInfo;
}
public static TokenOption fromOptionName(String optionName) {
if (optionName != null) {
for (TokenOption ko : values()) {
if (ko.optionInfo != null
&& ko.optionInfo.getName().equals(optionName)) {
return ko;
}
}
}
return NONE;
}
}
| 204 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbHandler.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.client;
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.client.preauth.PreauthHandler;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.transport.KrbTransport;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.EtypeInfo2;
import org.apache.kerby.kerberos.kerb.type.base.EtypeInfo2Entry;
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.MethodData;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public abstract class KrbHandler {
private static final Logger LOG = LoggerFactory.getLogger(KrbHandler.class);
private PreauthHandler preauthHandler;
/**
* Init with krbcontext.
*
* @param context The krbcontext
*/
public void init(KrbContext context) {
preauthHandler = new PreauthHandler();
preauthHandler.init(context);
}
/**
* Handle the kdc request.
*
* @param kdcRequest The kdc request
* @param tryNextKdc try next kdc or not
* @throws KrbException e
*/
public void handleRequest(KdcRequest kdcRequest, boolean tryNextKdc) throws KrbException {
if (!tryNextKdc || kdcRequest.getKdcReq() == null) {
kdcRequest.process();
}
KdcReq kdcReq = kdcRequest.getKdcReq();
int bodyLen = kdcReq.encodingLength();
KrbTransport transport = (KrbTransport) kdcRequest.getSessionData();
boolean isTcp = transport.isTcp();
ByteBuffer requestMessage;
if (!isTcp) {
requestMessage = ByteBuffer.allocate(bodyLen);
} else {
requestMessage = ByteBuffer.allocate(bodyLen + 4);
requestMessage.putInt(bodyLen);
}
KrbCodec.encode(kdcReq, requestMessage);
requestMessage.flip();
try {
sendMessage(kdcRequest, requestMessage);
} catch (IOException e) {
throw new KrbException("sending message failed", e);
}
}
/**
* Process the response message from kdc.
*
* @param kdcRequest The kdc request
* @param responseMessage The message from kdc
* @throws KrbException e
*/
public void onResponseMessage(
KdcRequest kdcRequest, ByteBuffer responseMessage) throws KrbException {
KrbMessage kdcRep = null;
try {
kdcRep = KrbCodec.decodeMessage(responseMessage);
} catch (IOException e) {
throw new KrbException("Krb decoding message failed", e);
}
KrbMessageType messageType = kdcRep.getMsgType();
if (messageType == KrbMessageType.AS_REP) {
kdcRequest.processResponse((KdcRep) kdcRep);
} else if (messageType == KrbMessageType.TGS_REP) {
kdcRequest.processResponse((KdcRep) kdcRep);
} else if (messageType == KrbMessageType.KRB_ERROR) {
KrbError error = (KrbError) kdcRep;
LOG.info("KDC server response with message: "
+ error.getErrorCode().getMessage());
if (error.getErrorCode() == KrbErrorCode.KDC_ERR_PREAUTH_REQUIRED) {
MethodData methodData = KrbCodec.decode(error.getEdata(), MethodData.class);
List<PaDataEntry> paDataEntryList = methodData.getElements();
List<EncryptionType> encryptionTypes = new ArrayList<>();
for (PaDataEntry paDataEntry : paDataEntryList) {
if (paDataEntry.getPaDataType() == PaDataType.ETYPE_INFO2) {
EtypeInfo2 etypeInfo2 = KrbCodec.decode(paDataEntry.getPaDataValue(),
EtypeInfo2.class);
List<EtypeInfo2Entry> info2Entries = etypeInfo2.getElements();
for (EtypeInfo2Entry info2Entry : info2Entries) {
encryptionTypes.add(info2Entry.getEtype());
}
}
}
kdcRequest.setEncryptionTypes(encryptionTypes);
kdcRequest.setPreauthRequired(true);
kdcRequest.resetPrequthContxt();
handleRequest(kdcRequest, false);
LOG.info("Retry with the new kdc request including pre-authentication.");
} else {
LOG.info(error.getErrorCode().getMessage());
throw new KrbException(error.getErrorCode(), error.getEtext());
}
}
}
/**
* Send message to kdc.
*
* @param kdcRequest The kdc request
* @param requestMessage The request message to kdc
* @throws IOException e
*/
protected abstract void sendMessage(KdcRequest kdcRequest,
ByteBuffer requestMessage) throws IOException;
}
| 205 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbKdcOption.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.client;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptionInfo;
/**
* This defines KDC options for client side API to use.
*/
public enum KrbKdcOption implements KOption {
NONE(null),
/* KDC flags */
FORWARDABLE(new KOptionInfo("-f", "forwardable",
KrbOptionGroup.KDC_FLAGS)),
NOT_FORWARDABLE(new KOptionInfo("-F", "not forwardable",
KrbOptionGroup.KDC_FLAGS)),
PROXIABLE(new KOptionInfo("-p", "proxiable",
KrbOptionGroup.KDC_FLAGS)),
NOT_PROXIABLE(new KOptionInfo("-P", "not proxiable",
KrbOptionGroup.KDC_FLAGS)),
REQUEST_ANONYMOUS(new KOptionInfo("-n",
"request anonymous", KrbOptionGroup.KDC_FLAGS)),
VALIDATE(new KOptionInfo("-v", "validate",
KrbOptionGroup.KDC_FLAGS)),
RENEW(new KOptionInfo("-R", "renew",
KrbOptionGroup.KDC_FLAGS)),
RENEWABLE(new KOptionInfo("-r", "renewable-life",
KrbOptionGroup.KDC_FLAGS)),
RENEWABLE_OK(new KOptionInfo("renewable-ok", "renewable ok",
KrbOptionGroup.KDC_FLAGS)),
CANONICALIZE(new KOptionInfo("-C", "canonicalize",
KrbOptionGroup.KDC_FLAGS)),
ANONYMOUS(new KOptionInfo("-n", "anonymous",
KrbOptionGroup.KDC_FLAGS));
private final KOptionInfo optionInfo;
KrbKdcOption(KOptionInfo optionInfo) {
this.optionInfo = optionInfo;
}
@Override
public KOptionInfo getOptionInfo() {
return optionInfo;
}
public static KrbKdcOption fromOptionName(String optionName) {
if (optionName != null) {
for (KrbKdcOption ko : values()) {
if (ko.optionInfo != null
&& ko.optionInfo.getName().equals(optionName)) {
return ko;
}
}
}
return NONE;
}
}
| 206 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/ClientUtil.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.client;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.transport.TransportPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class ClientUtil {
private ClientUtil() { }
private static final Logger LOG = LoggerFactory.getLogger(ClientUtil.class);
private static final String KRB5_FILE_NAME = "krb5.conf";
private static final String KRB5_ENV_NAME = "KRB5_CONFIG";
/**
* Load krb5.conf from specified conf dir.
* @param conf The conf file or dir, default file name 'krb5.conf' is used if dir
* @return KrbConfig
* @throws KrbException e
*/
public static KrbConfig getConfig(File conf) throws KrbException {
if (conf == null || !conf.exists()) {
throw new KrbException(conf + " not found");
}
File confFile = conf.isDirectory() ? new File(conf, KRB5_FILE_NAME) : conf;
if (!confFile.exists()) {
throw new KrbException(KRB5_FILE_NAME + " not found");
}
KrbConfig krbConfig = new KrbConfig();
try {
krbConfig.addKrb5Config(confFile);
return krbConfig;
} catch (IOException e) {
throw new KrbException("Failed to load krb config "
+ confFile.getAbsolutePath());
}
}
/**
* Load default krb5.conf
* @return The KrbConfig
* @throws KrbException e
*/
public static KrbConfig getDefaultConfig() throws KrbException {
File confFile = null;
File confDir;
String tmpEnv;
try {
Map<String, String> mapEnv = System.getenv();
tmpEnv = mapEnv.get(KRB5_ENV_NAME);
} catch (SecurityException e) {
tmpEnv = null;
}
if (tmpEnv != null) {
confFile = new File(tmpEnv);
if (!confFile.exists()) {
throw new KrbException("krb5 conf not found. Invalid env "
+ KRB5_ENV_NAME);
}
} else {
confDir = new File("/etc/"); // for Linux. TODO: fix for Win etc.
if (confDir.exists()) {
confFile = new File(confDir, "krb5.conf");
}
}
KrbConfig krbConfig = new KrbConfig();
if (confFile != null && confFile.exists()) {
try {
krbConfig.addKrb5Config(confFile);
} catch (IOException e) {
throw new KrbException("Failed to load krb config "
+ confFile.getAbsolutePath());
}
}
return krbConfig;
}
/**
* Get KDC network transport addresses according to krb client setting.
* @param setting The krb setting
* @param kdcString The kdc string, may include the port number
* @return UDP and TCP addresses pair
* @throws KrbException e
*/
public static TransportPair getTransportPair(
KrbSetting setting, String kdcString) throws KrbException, IOException {
TransportPair result = new TransportPair();
int tcpPort = setting.checkGetKdcTcpPort();
int udpPort = setting.checkGetKdcUdpPort();
int port = 0;
String kdc;
String portStr = null;
// Explicit IPv6 in []
if (kdcString.charAt(0) == '[') {
int pos = kdcString.indexOf(']', 1);
if (pos == -1) {
throw new IOException("Illegal KDC: " + kdcString);
}
kdc = kdcString.substring(1, pos);
// with port number
if (pos != kdcString.length() - 1) {
if (kdcString.charAt(pos + 1) != ':') {
throw new IOException("Illegal KDC: " + kdcString);
}
portStr = kdcString.substring(pos + 2);
}
} else {
int colon = kdcString.indexOf(':');
// Hostname or IPv4 host only
if (colon == -1) {
kdc = kdcString;
} else {
int nextColon = kdcString.indexOf(':', colon + 1);
// >=2 ":", IPv6 with no port
if (nextColon > 0) {
kdc = kdcString;
} else {
// 1 ":", hostname or IPv4 with port
kdc = kdcString.substring(0, colon);
portStr = kdcString.substring(colon + 1);
}
}
}
if (portStr != null) {
int tempPort = parsePositiveIntString(portStr);
if (tempPort > 0) {
port = tempPort;
}
}
if (port != 0) {
tcpPort = port;
udpPort = port;
}
if (tcpPort > 0) {
result.tcpAddress = new InetSocketAddress(
kdc, tcpPort);
}
if (udpPort > 0) {
result.udpAddress = new InetSocketAddress(
kdc, udpPort);
}
return result;
}
private static int parsePositiveIntString(String intString) {
if (intString == null) {
return -1;
}
int ret = -1;
try {
ret = Integer.parseInt(intString);
} catch (Exception exc) {
return -1;
}
if (ret >= 0) {
return ret;
}
return -1;
}
/**
* Returns a list of KDC
*
* @throws KrbException if there's no way to find KDC for the realm
* @return the list of KDC, always non null
*/
public static List<String> getKDCList(String realm, KrbSetting krbSetting) throws KrbException {
List<String> kdcList = new ArrayList<>();
if (realm != null) {
KrbConfig krbConfig = krbSetting.getKrbConfig();
List<Object> kdcs = krbConfig.getRealmSectionItems(realm, "kdc");
if (!kdcs.isEmpty()) {
for (Object object : kdcs) {
kdcList.add(object != null ? object.toString() : null);
}
}
if (kdcList.isEmpty()) {
LOG.warn("Cannot get kdc for realm " + realm);
kdcList.add(krbSetting.getKdcHost());
}
} else {
throw new KrbException("Can't get the realm");
}
return kdcList;
}
}
| 207 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbContext.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.client;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.client.preauth.PreauthHandler;
import org.apache.kerby.kerberos.kerb.crypto.util.Nonce;
public class KrbContext {
private KrbSetting krbSetting;
private PreauthHandler preauthHandler;
/**
* Init with krbsetting.
* @param krbSetting The krb setting
*/
public void init(KrbSetting krbSetting) {
this.krbSetting = krbSetting;
preauthHandler = new PreauthHandler();
preauthHandler.init(this);
}
/**
* Get krbsetting.
* @return The krb setting
*/
public KrbSetting getKrbSetting() {
return krbSetting;
}
/**
* Get krbconfig.
* @return The krb config
*/
public KrbConfig getConfig() {
return krbSetting.getKrbConfig();
}
/**
* Generate nonce.
* @return nonce
*/
public int generateNonce() {
return Nonce.value();
}
/**
* Get ticket valid time.
* @return The ticket valid time
*/
public long getTicketValidTime() {
String ticketValidTimeStr = getConfig().getTicketLifetime();
long ticketValidTime = KOptions.parseDuration(ticketValidTimeStr);
return ticketValidTime * 1000;
}
/**
* Get preauth handler.
* @return The preauth handler
*/
public PreauthHandler getPreauthHandler() {
return preauthHandler;
}
}
| 208 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbConfig.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.client;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.common.Krb5Conf;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Kerb client side configuration API.
*/
public class KrbConfig extends Krb5Conf {
private static final String LIBDEFAULT = "libdefaults";
private static final String REALMS = "realms";
private static final String CAPATHS = "capaths";
public boolean enableDebug() {
return getBoolean(KrbConfigKey.KRB_DEBUG, true, LIBDEFAULT);
}
/**
* Get KDC host name
*
* @return The kdc host
*/
public String getKdcHost() {
return getString(
KrbConfigKey.KDC_HOST, true, LIBDEFAULT);
}
/**
* Get KDC port, as both TCP and UDP ports
*
* @return The kdc host
*/
public int getKdcPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_PORT, true, LIBDEFAULT);
if (kdcPort != null) {
return kdcPort.intValue();
}
return -1;
}
/**
* Get KDC TCP port
*
* @return The kdc tcp port
*/
public int getKdcTcpPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_TCP_PORT, true, LIBDEFAULT);
if (kdcPort != null && kdcPort > 0) {
return kdcPort.intValue();
}
return getKdcPort();
}
/**
* Is to allow UDP for KDC
*
* @return true to allow UDP, false otherwise
*/
public boolean allowUdp() {
return getBoolean(KrbConfigKey.KDC_ALLOW_UDP, true, LIBDEFAULT)
|| getInt(KrbConfigKey.KDC_UDP_PORT, true, LIBDEFAULT) != null
|| getInt(KrbConfigKey.KDC_PORT, false, LIBDEFAULT) != null;
}
/**
* Is to allow TCP for KDC
*
* @return true to allow TCP, false otherwise
*/
public boolean allowTcp() {
return getBoolean(KrbConfigKey.KDC_ALLOW_TCP, true, LIBDEFAULT)
|| getInt(KrbConfigKey.KDC_TCP_PORT, true, LIBDEFAULT) != null
|| getInt(KrbConfigKey.KDC_PORT, false, LIBDEFAULT) != null;
}
/**
* Get KDC UDP port
*
* @return The kdc udp port
*/
public int getKdcUdpPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_UDP_PORT, true, LIBDEFAULT);
if (kdcPort != null && kdcPort > 0) {
return kdcPort.intValue();
}
return getKdcPort();
}
/**
* Get KDC realm.
* @return The kdc realm
*/
public String getKdcRealm() {
String realm = getString(KrbConfigKey.KDC_REALM, false, LIBDEFAULT);
if (realm == null) {
realm = getString(KrbConfigKey.DEFAULT_REALM, false, LIBDEFAULT);
if (realm == null) {
realm = (String) KrbConfigKey.KDC_REALM.getDefaultValue();
}
}
return realm;
}
/**
* Get whether preauth is required.
* @return true if preauth required
*/
public boolean isPreauthRequired() {
return getBoolean(KrbConfigKey.PREAUTH_REQUIRED, true, LIBDEFAULT);
}
/**
* Get tgs principal.
* @return The tgs principal
*/
public String getTgsPrincipal() {
return getString(KrbConfigKey.TGS_PRINCIPAL, true, LIBDEFAULT);
}
/**
* Get allowable clock skew.
* @return The allowable clock skew
*/
public long getAllowableClockSkew() {
return getLong(KrbConfigKey.CLOCKSKEW, true, LIBDEFAULT);
}
/**
* Get whether empty addresses allowed.
* @return true if empty address is allowed
*/
public boolean isEmptyAddressesAllowed() {
return getBoolean(KrbConfigKey.EMPTY_ADDRESSES_ALLOWED, true, LIBDEFAULT);
}
/**
* Get whether forward is allowed.
* @return true if forward is allowed
*/
public boolean isForwardableAllowed() {
return getBoolean(KrbConfigKey.FORWARDABLE, true, LIBDEFAULT);
}
/**
* Get whether post dated is allowed.
* @return true if post dated is allowed
*/
public boolean isPostdatedAllowed() {
return getBoolean(KrbConfigKey.POSTDATED_ALLOWED, true, LIBDEFAULT);
}
/**
* Get whether proxy is allowed.
* @return true if proxy is allowed
*/
public boolean isProxiableAllowed() {
return getBoolean(KrbConfigKey.PROXIABLE, true, LIBDEFAULT);
}
/**
* Get whether renew is allowed.
* @return true if renew is allowed
*/
public boolean isRenewableAllowed() {
return getBoolean(KrbConfigKey.RENEWABLE_ALLOWED, true, LIBDEFAULT);
}
/**
* Get maximum renewable life time.
* @return The maximum renewable life time
*/
public long getMaximumRenewableLifetime() {
return getLong(KrbConfigKey.MAXIMUM_RENEWABLE_LIFETIME, true, LIBDEFAULT);
}
/**
* Get maximum ticket life time.
* @return The maximum ticket life time
*/
public long getMaximumTicketLifetime() {
return getLong(KrbConfigKey.MAXIMUM_TICKET_LIFETIME, true, LIBDEFAULT);
}
/**
* Get minimum ticket life time.
* @return The minimum ticket life time
*/
public long getMinimumTicketLifetime() {
return getLong(KrbConfigKey.MINIMUM_TICKET_LIFETIME, true, LIBDEFAULT);
}
/**
* Get encryption types.
* @return encryption type list
*/
public List<EncryptionType> getEncryptionTypes() {
return getEncTypes(KrbConfigKey.PERMITTED_ENCTYPES, true, LIBDEFAULT);
}
/**
* Get whether pa encrypt timestamp required.
* @return true if pa encrypt time required
*/
public boolean isPaEncTimestampRequired() {
return getBoolean(KrbConfigKey.PA_ENC_TIMESTAMP_REQUIRED, true, LIBDEFAULT);
}
/**
* Get whether body checksum verified.
* @return true if body checksum verified
*/
public boolean isBodyChecksumVerified() {
return getBoolean(KrbConfigKey.VERIFY_BODY_CHECKSUM, true, LIBDEFAULT);
}
/**
* Get default realm.
* @return The default realm
*/
public String getDefaultRealm() {
return getString(KrbConfigKey.DEFAULT_REALM, true, LIBDEFAULT);
}
/**
* Get whether dns look up kdc.
* @return true if dnc look up kdc
*/
public boolean getDnsLookUpKdc() {
return getBoolean(KrbConfigKey.DNS_LOOKUP_KDC, true, LIBDEFAULT);
}
/**
* Get whether dns look up realm.
* @return true if dns look up realm
*/
public boolean getDnsLookUpRealm() {
return getBoolean(KrbConfigKey.DNS_LOOKUP_REALM, true, LIBDEFAULT);
}
/**
* Get whether allow weak crypto.
* @return true if allow weak crypto
*/
public boolean getAllowWeakCrypto() {
return getBoolean(KrbConfigKey.ALLOW_WEAK_CRYPTO, true, LIBDEFAULT);
}
/**
* Get ticket life time.
* @return The ticket life time
*/
public String getTicketLifetime() {
try {
return Long.toString(getLong(KrbConfigKey.TICKET_LIFETIME, true, LIBDEFAULT));
} catch (Exception e) {
return getString(KrbConfigKey.TICKET_LIFETIME, true, LIBDEFAULT);
}
}
/**
* Get renew life time.
* @return The renew life time
*/
public String getRenewLifetime() {
try {
return Long.toString(getLong(KrbConfigKey.RENEW_LIFETIME, true, LIBDEFAULT));
} catch (Exception e) {
return getString(KrbConfigKey.RENEW_LIFETIME, true, LIBDEFAULT);
}
}
/**
* Get default tgs encryption types.
* @return The tgs encryption type list
*/
public List<EncryptionType> getDefaultTgsEnctypes() {
return getEncTypes(KrbConfigKey.DEFAULT_TGS_ENCTYPES, true, LIBDEFAULT);
}
/**
* Get default ticket encryption types.
* @return The encryption type list
*/
public List<EncryptionType> getDefaultTktEnctypes() {
return getEncTypes(KrbConfigKey.DEFAULT_TKT_ENCTYPES, true, LIBDEFAULT);
}
public List<String> getPkinitAnchors() {
return Arrays.asList(getStringArray(
KrbConfigKey.PKINIT_ANCHORS, true, LIBDEFAULT));
}
public List<String> getPkinitIdentities() {
return Arrays.asList(getStringArray(
KrbConfigKey.PKINIT_IDENTITIES, true, LIBDEFAULT));
}
public String getPkinitKdcHostName() {
return getString(
KrbConfigKey.PKINIT_KDC_HOSTNAME, true, LIBDEFAULT);
}
public List<Object> getRealmSectionItems(String realm, String key) {
Map<String, Object> map = getRealmSection(realm);
if (map.isEmpty()) {
return Collections.emptyList();
}
List<Object> items = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(key)) {
items.add(entry.getValue());
}
}
return items;
}
public Map<String, Object> getRealmSection(String realm) {
Object realms = getSection(REALMS);
if (realms != null) {
Map<String, Object> map = (Map) realms;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(realm)) {
return (Map) entry.getValue();
}
}
}
return Collections.emptyMap();
}
/**
* Get capath of specified realms.
* @param sourceRealm source realm
* @param destRealm dest realm
* @return The capath from sourceRealm to destRealm
*/
public LinkedList<String> getCapath(String sourceRealm, String destRealm) throws KrbException {
Map<String, Object> capathsMap = getCapaths(sourceRealm);
if (capathsMap.isEmpty()) {
throw new KrbException("Capaths of " + sourceRealm + " is not given in conf file.");
}
LinkedList<String> items = new LinkedList<>();
boolean valid = false;
items.addFirst(destRealm);
for (Map.Entry<String, Object> entry : capathsMap.entrySet()) {
if (entry.getKey().equals(destRealm)) {
valid = true;
String value = (String) entry.getValue();
if (value.equals(".")) {
break;
} else if (!value.equals(sourceRealm) && !value.equals(destRealm) && !items.contains(value)
&& !value.isEmpty()) {
items.addFirst(value);
}
}
}
if (!valid) {
throw new KrbException("Capaths from " + sourceRealm + " to " + destRealm + " is not given in conf file.");
}
items.addFirst(sourceRealm);
return items;
}
/**
* Get capaths of specified realm.
*/
private Map<String, Object> getCapaths(String realm) {
Map<String, Object> caPaths = (Map) getSection(CAPATHS);
if (caPaths != null) {
for (Map.Entry<String, Object> entry : caPaths.entrySet()) {
if (entry.getKey().equals(realm)) {
return (Map) entry.getValue();
}
}
}
return Collections.emptyMap();
}
}
| 209 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbPkinitClient.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.client;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbConstant;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import java.io.File;
/**
* A krb PKINIT client API for applications to interact with KDC using PKINIT.
*/
public class KrbPkinitClient extends KrbClientBase {
/**
* Default constructor.
* @throws KrbException e
*/
public KrbPkinitClient() throws KrbException {
super();
}
/**
* Construct with prepared KrbConfig.
* @param krbConfig The krb config
*/
public KrbPkinitClient(KrbConfig krbConfig) {
super(krbConfig);
}
/**
* Constructor with conf dir
* @param confDir The conf dir
* @throws KrbException e
*/
public KrbPkinitClient(File confDir) throws KrbException {
super(confDir);
}
/**
* Constructor with prepared KrbClient.
* @param krbClient The krb client
*/
public KrbPkinitClient(KrbClient krbClient) {
super(krbClient);
}
/**
* Request a TGT with user x509 certificate credential
* @param principal The principal
* @param certificate The certificate
* @param privateKey The private key
* @return TGT
* @throws KrbException e
*/
public TgtTicket requestTgt(String principal, String certificate,
String privateKey) throws KrbException {
KOptions requestOptions = new KOptions();
requestOptions.add(KrbOption.CLIENT_PRINCIPAL, principal);
requestOptions.add(PkinitOption.USE_PKINIT);
requestOptions.add(PkinitOption.USING_RSA);
requestOptions.add(PkinitOption.X509_IDENTITY, certificate);
requestOptions.add(PkinitOption.X509_PRIVATE_KEY, privateKey);
return requestTgt(requestOptions);
}
/**
* Request a TGT with using Anonymous PKINIT
* @return TGT
* @throws KrbException e
*/
public TgtTicket requestTgt() throws KrbException {
KOptions requestOptions = new KOptions();
requestOptions.add(PkinitOption.USE_ANONYMOUS);
requestOptions.add(KrbOption.CLIENT_PRINCIPAL,
KrbConstant.ANONYMOUS_PRINCIPAL);
return requestTgt(requestOptions);
}
}
| 210 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/impl/InternalKrbClient.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.client.impl;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbSetting;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
/**
* An internal krb client interface.
*/
public interface InternalKrbClient {
/**
* Init with all the necessary options.
* @throws KrbException e
*/
void init() throws KrbException;
/**
* Get krb client settings.
* @return setting
*/
KrbSetting getSetting();
/**
* Request a Ticket Granting Ticket.
* @param requestOptions The request options
* @return a TGT
* @throws KrbException e
*/
TgtTicket requestTgt(KOptions requestOptions) throws KrbException;
/**
* Request a service ticket provided request options
* @param requestOptions The request options
* @return service ticket
* @throws KrbException e
*/
SgtTicket requestSgt(KOptions requestOptions) throws KrbException;
}
| 211 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/impl/DefaultKrbHandler.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.client.impl;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbHandler;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.transport.KrbTransport;
import java.io.IOException;
import java.nio.ByteBuffer;
public class DefaultKrbHandler extends KrbHandler {
/**
* {@inheritDoc}
*/
@Override
public void handleRequest(KdcRequest kdcRequest, boolean tryNextKdc) throws KrbException {
KrbTransport transport = (KrbTransport) kdcRequest.getSessionData();
transport.setAttachment(kdcRequest);
super.handleRequest(kdcRequest, tryNextKdc);
ByteBuffer receivedMessage = null;
try {
receivedMessage = transport.receiveMessage();
} catch (IOException e) {
throw new KrbException("Receiving response message failed", e);
}
super.onResponseMessage(kdcRequest, receivedMessage);
}
/**
* {@inheritDoc}
*/
@Override
protected void sendMessage(KdcRequest kdcRequest,
ByteBuffer requestMessage) throws IOException {
KrbTransport transport = (KrbTransport) kdcRequest.getSessionData();
transport.sendMessage(requestMessage);
}
}
| 212 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/impl/DefaultInternalKrbClient.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.client.impl;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.ClientUtil;
import org.apache.kerby.kerberos.kerb.client.KrbSetting;
import org.apache.kerby.kerberos.kerb.client.request.AsRequest;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequest;
import org.apache.kerby.kerberos.kerb.transport.KrbNetwork;
import org.apache.kerby.kerberos.kerb.transport.KrbTransport;
import org.apache.kerby.kerberos.kerb.transport.TransportPair;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
/**
* A default krb client implementation.
*/
public class DefaultInternalKrbClient extends AbstractInternalKrbClient {
private static final Logger LOG = LoggerFactory.getLogger(DefaultInternalKrbClient.class);
private DefaultKrbHandler krbHandler;
private KrbTransport transport;
public DefaultInternalKrbClient(KrbSetting krbSetting) {
super(krbSetting);
}
/**
* {@inheritDoc}
*/
@Override
public void init() throws KrbException {
super.init();
this.krbHandler = new DefaultKrbHandler();
krbHandler.init(getContext());
}
private void doRequest(KdcRequest request) throws KrbException { //NOPMD
String realm = getSetting().getKdcRealm();
PrincipalName serverPrincipalName = request.getServerPrincipal();
if (serverPrincipalName != null && serverPrincipalName.getRealm() != null) {
realm = serverPrincipalName.getRealm();
}
List<String> kdcList = ClientUtil.getKDCList(realm, getSetting());
// tempKdc may include the port number
Iterator<String> tempKdc = kdcList.iterator();
if (!tempKdc.hasNext()) {
throw new KrbException("Cannot get kdc for realm " + getSetting().getKdcRealm());
}
try {
sendIfPossible(request, tempKdc.next(), getSetting(), false);
LOG.info("Send to kdc success.");
} catch (Exception first) {
boolean ok = false;
while (tempKdc.hasNext()) {
try {
sendIfPossible(request, tempKdc.next(), getSetting(), true);
ok = true;
LOG.info("Send to kdc success.");
break;
} catch (Exception ignore) {
LOG.info("ignore this kdc");
}
}
if (!ok) {
if (first instanceof KrbException) {
throw (KrbException) first;
}
throw new KrbException("The request failed " + first.getMessage(), first);
}
} finally {
if (transport != null) {
transport.release();
}
}
}
private void sendIfPossible(KdcRequest request, String kdcString, KrbSetting setting,
boolean tryNextKdc)
throws KrbException, IOException {
TransportPair tpair = ClientUtil.getTransportPair(setting, kdcString);
KrbNetwork network = new KrbNetwork();
network.setSocketTimeout(setting.getTimeout());
transport = network.connect(tpair);
request.setSessionData(transport);
krbHandler.handleRequest(request, tryNextKdc);
}
/**
* {@inheritDoc}
*/
@Override
protected TgtTicket doRequestTgt(AsRequest tgtTktReq) throws KrbException {
doRequest(tgtTktReq);
return tgtTktReq.getTicket();
}
/**
* {@inheritDoc}
*/
@Override
protected SgtTicket doRequestSgt(TgsRequest ticketReq) throws KrbException {
doRequest(ticketReq);
return ticketReq.getSgt();
}
}
| 213 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/impl/AbstractInternalKrbClient.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.client.impl;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.client.KrbSetting;
import org.apache.kerby.kerberos.kerb.client.KrbConfig;
import org.apache.kerby.kerberos.kerb.client.PkinitOption;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.client.request.AsRequest;
import org.apache.kerby.kerberos.kerb.client.request.AsRequestWithCert;
import org.apache.kerby.kerberos.kerb.client.request.AsRequestWithKeytab;
import org.apache.kerby.kerberos.kerb.client.request.AsRequestWithPasswd;
import org.apache.kerby.kerberos.kerb.client.request.AsRequestWithToken;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequest;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequestWithTgt;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequestWithToken;
import org.apache.kerby.kerberos.kerb.common.KrbUtil;
import org.apache.kerby.kerberos.kerb.type.base.NameType;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import java.util.LinkedList;
/**
* A krb client API for applications to interact with KDC
*/
public abstract class AbstractInternalKrbClient implements InternalKrbClient {
private KrbContext context;
private final KrbSetting krbSetting;
public AbstractInternalKrbClient(KrbSetting krbSetting) {
this.krbSetting = krbSetting;
}
protected KrbContext getContext() {
return context;
}
/**
* {@inheritDoc}
*/
@Override
public KrbSetting getSetting() {
return krbSetting;
}
/**
* {@inheritDoc}
*/
@Override
public void init() throws KrbException {
context = new KrbContext();
context.init(krbSetting);
}
/**
* {@inheritDoc}
*/
@Override
public TgtTicket requestTgt(KOptions requestOptions) throws KrbException {
AsRequest asRequest = null;
PrincipalName clientPrincipalName = null;
if (requestOptions.contains(KrbOption.USE_PASSWD)) {
asRequest = new AsRequestWithPasswd(context);
} else if (requestOptions.contains(KrbOption.USE_KEYTAB)) {
asRequest = new AsRequestWithKeytab(context);
} else if (requestOptions.contains(PkinitOption.USE_ANONYMOUS)) {
asRequest = new AsRequestWithCert(context);
} else if (requestOptions.contains(PkinitOption.USE_PKINIT)) {
asRequest = new AsRequestWithCert(context);
} else if (requestOptions.contains(TokenOption.USE_TOKEN)) {
asRequest = new AsRequestWithToken(context);
} else if (requestOptions.contains(TokenOption.USER_ID_TOKEN)) {
asRequest = new AsRequestWithToken(context);
}
if (asRequest == null) {
throw new IllegalArgumentException(
"No valid krb client request option found");
}
if (requestOptions.contains(KrbOption.CLIENT_PRINCIPAL)) {
String clientPrincipalString = requestOptions.getStringOption(KrbOption.CLIENT_PRINCIPAL);
clientPrincipalString = fixPrincipal(clientPrincipalString);
clientPrincipalName = new PrincipalName(clientPrincipalString);
if (requestOptions.contains(PkinitOption.USE_ANONYMOUS)) {
clientPrincipalName.setNameType(NameType.NT_WELLKNOWN);
}
asRequest.setClientPrincipal(clientPrincipalName);
}
if (requestOptions.contains(KrbOption.SERVER_PRINCIPAL)) {
String serverPrincipalString = requestOptions.getStringOption(KrbOption.SERVER_PRINCIPAL);
serverPrincipalString = fixPrincipal(serverPrincipalString);
PrincipalName serverPrincipalName = new PrincipalName(serverPrincipalString, NameType.NT_PRINCIPAL);
asRequest.setServerPrincipal(serverPrincipalName);
} else if (clientPrincipalName != null) {
String realm = clientPrincipalName.getRealm();
PrincipalName serverPrincipalName = KrbUtil.makeTgsPrincipal(realm);
asRequest.setServerPrincipal(serverPrincipalName);
}
asRequest.setRequestOptions(requestOptions);
return doRequestTgt(asRequest);
}
/**
* {@inheritDoc}
*/
@Override
public SgtTicket requestSgt(KOptions requestOptions) throws KrbException {
TgsRequest tgsRequest = null;
TgtTicket tgtTicket = null;
if (requestOptions.contains(TokenOption.USER_AC_TOKEN)) {
tgsRequest = new TgsRequestWithToken(context);
} else if (requestOptions.contains(KrbOption.USE_TGT)) {
KOption kOpt = requestOptions.getOption(KrbOption.USE_TGT);
tgtTicket = (TgtTicket) kOpt.getOptionInfo().getValue();
tgsRequest = new TgsRequestWithTgt(context, tgtTicket);
}
if (tgsRequest == null) {
throw new IllegalArgumentException(
"No valid krb client request option found");
}
String serverPrincipalString = fixPrincipal(requestOptions.
getStringOption(KrbOption.SERVER_PRINCIPAL));
PrincipalName serverPrincipalName = new PrincipalName(serverPrincipalString);
PrincipalName clientPrincipalName = null;
if (tgtTicket != null) {
String sourceRealm = tgtTicket.getRealm();
String destRealm = serverPrincipalName.getRealm();
clientPrincipalName = tgtTicket.getClientPrincipal();
if (!sourceRealm.equals(destRealm)) {
KrbConfig krbConfig = krbSetting.getKrbConfig();
LinkedList<String> capath = krbConfig.getCapath(sourceRealm, destRealm);
for (int i = 0; i < capath.size() - 1; i++) {
PrincipalName tgsPrincipalName = KrbUtil.makeTgsPrincipal(
capath.get(i), capath.get(i + 1));
tgsRequest.setServerPrincipal(tgsPrincipalName);
tgsRequest.setRequestOptions(requestOptions);
SgtTicket sgtTicket = doRequestSgt(tgsRequest);
sgtTicket.setClientPrincipal(clientPrincipalName);
tgsRequest = new TgsRequestWithTgt(context, sgtTicket);
}
}
} else {
//This code is for the no-tgt case but works only with CLIENT_PRINCIPAL option
//Should be expanded later to encompass more use-cases
String clientPrincipalString = (String) requestOptions.getOptionValue(KrbOption.CLIENT_PRINCIPAL);
if (clientPrincipalString != null) {
clientPrincipalName = new PrincipalName(clientPrincipalString);
}
}
tgsRequest.setServerPrincipal(serverPrincipalName);
tgsRequest.setRequestOptions(requestOptions);
SgtTicket sgtTicket = doRequestSgt(tgsRequest);
if (clientPrincipalName != null) {
sgtTicket.setClientPrincipal(clientPrincipalName);
}
return sgtTicket;
}
protected abstract TgtTicket doRequestTgt(
AsRequest tgtTktReq) throws KrbException;
protected abstract SgtTicket doRequestSgt(
TgsRequest tgsRequest) throws KrbException;
/**
* Fix principal name.
*
* @param principal The principal name
* @return The fixed principal
*/
protected String fixPrincipal(String principal) {
if (!principal.contains("@")) {
principal += "@" + krbSetting.getKdcRealm();
}
return principal;
}
}
| 214 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/KrbPreauth.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.client.preauth;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
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.type.base.EncryptionType;
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.List;
/**
* Client side preauth plugin module
*/
public interface KrbPreauth extends PreauthPluginMeta {
/**
* Initializing preauth plugin context
* @param krbContext The krb context
*/
void init(KrbContext krbContext);
/**
* Initializing request context
* @param kdcRequest The kdc request
* @return PluginRequestContext
*/
PluginRequestContext initRequestContext(KdcRequest kdcRequest);
/**
* Prepare questions to prompt to you asking for credential
* @param kdcRequest The kdc request
* @param requestContext The request context
* @throws KrbException e
*/
void prepareQuestions(KdcRequest kdcRequest,
PluginRequestContext requestContext) throws KrbException;
/**
* Get supported encryption types
* @param kdcRequest The kdc request
* @param requestContext The request context
* @return The encryption type list
*/
List<EncryptionType> getEncTypes(KdcRequest kdcRequest,
PluginRequestContext requestContext);
/**
* Set krb options passed from user
* @param kdcRequest The kdc request
* @param requestContext The request context
* @param preauthOptions The preauth options
*/
void setPreauthOptions(KdcRequest kdcRequest,
PluginRequestContext requestContext,
KOptions preauthOptions);
/**
* Attempt to try any initial padata derived from user options
* @param kdcRequest The kdc request
* @param requestContext The request context
* @param outPadata The outPadata
* @throws KrbException e
*/
void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException;
/**
* Process server returned paData and return back any result paData
* @param kdcRequest The kdc request
* @param requestContext The request context
* @param inPadata The inPadata
* @param outPadata The outPadata
* @return true indicating padata is added
* @throws KrbException e
*/
boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataEntry inPadata,
PaData outPadata) throws KrbException;
/**
* When another request to server in the 4 pass, any paData to provide?
* @param kdcRequest The kdc request
* @param requestContext The request context
* @param preauthType The preauth type
* @param errPadata The error padata
* @param outPadata The outPadata
* @return true indicating padata is added
*/
boolean tryAgain(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataType preauthType,
PaData errPadata,
PaData outPadata);
/**
* Return PA_REAL if pa_type is a real preauthentication type or PA_INFO if it is
* an informational type.
* @param paType The pa_type
* @return PaFlags
*/
PaFlags getFlags(PaDataType paType);
/**
* When exiting...
*/
void destroy();
}
| 215 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/UserResponser.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.client.preauth;
import java.util.ArrayList;
import java.util.List;
public class UserResponser {
private final List<UserResponseItem> items = new ArrayList<>(1);
/**
* Let customize an interface like CMD or WEB UI to selectively respond all the questions
*/
public void respondQuestions() {
// TODO
}
public UserResponseItem findQuestion(String question) {
for (UserResponseItem ri : items) {
if (ri.question.equals(question)) {
return ri;
}
}
return null;
}
public void askQuestion(String question, String challenge) {
UserResponseItem ri = findQuestion(question);
if (ri == null) {
items.add(new UserResponseItem(question, challenge));
} else {
ri.challenge = challenge;
}
}
public String getChallenge(String question) {
UserResponseItem ri = findQuestion(question);
if (ri != null) {
return ri.challenge;
}
return null;
}
public void setAnswer(String question, String answer) {
UserResponseItem ri = findQuestion(question);
if (ri == null) {
throw new IllegalArgumentException("Question isn't exist for the answer");
}
ri.answer = answer;
}
public String getAnswer(String question) {
UserResponseItem ri = findQuestion(question);
if (ri != null) {
return ri.answer;
}
return null;
}
}
| 216 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.preauth.PaFlags;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
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 PreauthHandle {
public KrbPreauth preauth;
public PluginRequestContext requestContext;
public PreauthHandle(KrbPreauth preauth) {
this.preauth = preauth;
}
public void initRequestContext(KdcRequest kdcRequest) {
requestContext = preauth.initRequestContext(kdcRequest);
}
public void prepareQuestions(KdcRequest kdcRequest) throws KrbException {
preauth.prepareQuestions(kdcRequest, requestContext);
}
public void setPreauthOptions(KdcRequest kdcRequest,
KOptions preauthOptions) throws KrbException {
preauth.setPreauthOptions(kdcRequest, requestContext, preauthOptions);
}
public void tryFirst(KdcRequest kdcRequest, PaData outPadata) throws KrbException {
preauth.tryFirst(kdcRequest, requestContext, outPadata);
}
public boolean process(KdcRequest kdcRequest,
PaDataEntry inPadata, PaData outPadata) throws KrbException {
return preauth.process(kdcRequest, requestContext, inPadata, outPadata);
}
public boolean tryAgain(KdcRequest kdcRequest,
PaDataType paType, PaData errPadata, PaData paData) {
return preauth.tryAgain(kdcRequest, requestContext, paType, errPadata, paData);
}
public boolean isReal(PaDataType paType) {
PaFlags paFlags = preauth.getFlags(paType);
return paFlags.isReal();
}
}
| 217 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.preauth.PaFlag;
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.type.base.EncryptionType;
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.Collections;
import java.util.List;
public class AbstractPreauthPlugin implements KrbPreauth {
private PreauthPluginMeta pluginMeta;
protected KrbContext context;
public AbstractPreauthPlugin(PreauthPluginMeta meta) {
this.pluginMeta = meta;
}
/**
* Get plugin name.
*/
@Override
public String getName() {
return pluginMeta.getName();
}
/**
* Get plugin version.
*/
public int getVersion() {
return pluginMeta.getVersion();
}
/**
* Get padata type.
*/
public PaDataType[] getPaTypes() {
return pluginMeta.getPaTypes();
}
/**
* {@inheritDoc}
*/
public void init(KrbContext context) {
this.context = context;
}
/**
* {@inheritDoc}
*/
@Override
public PluginRequestContext initRequestContext(KdcRequest kdcRequest) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void prepareQuestions(KdcRequest kdcRequest,
PluginRequestContext requestContext) throws KrbException {
kdcRequest.needAsKey();
}
/**
* {@inheritDoc}
*/
@Override
public List<EncryptionType> getEncTypes(KdcRequest kdcRequest,
PluginRequestContext requestContext) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
@Override
public void setPreauthOptions(KdcRequest kdcRequest,
PluginRequestContext requestContext, KOptions options) {
}
/**
* {@inheritDoc}
*/
@Override
public void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException {
}
/**
* {@inheritDoc}
*/
@Override
public boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext, PaDataEntry inPadata,
PaData outPadata) throws KrbException {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean tryAgain(KdcRequest kdcRequest,
PluginRequestContext requestContext, PaDataType preauthType,
PaData errPadata, PaData outPadata) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public PaFlags getFlags(PaDataType paType) {
PaFlags paFlags = new PaFlags(0);
paFlags.setFlag(PaFlag.PA_REAL);
return paFlags;
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
}
}
| 218 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/UserResponseItem.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.client.preauth;
public class UserResponseItem {
protected String question;
protected String challenge;
protected String answer;
public UserResponseItem(String question, String challenge) {
this.question = question;
this.challenge = challenge;
}
}
| 219 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.preauth.builtin.EncTsPreauth;
import org.apache.kerby.kerberos.kerb.client.preauth.builtin.TgtPreauth;
import org.apache.kerby.kerberos.kerb.client.preauth.pkinit.PkinitPreauth;
import org.apache.kerby.kerberos.kerb.client.preauth.token.TokenPreauth;
import org.apache.kerby.kerberos.kerb.client.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 KrbContext krbContext;
private List<KrbPreauth> preauths;
public void init(KrbContext krbContext) {
this.krbContext = krbContext;
loadPreauthPlugins(krbContext);
}
private void loadPreauthPlugins(KrbContext context) {
preauths = new ArrayList<>();
KrbPreauth preauth = new EncTsPreauth();
preauth.init(context);
preauths.add(preauth);
preauth = new TgtPreauth();
preauth.init(context);
preauths.add(preauth);
preauth = new PkinitPreauth();
preauth.init(context);
preauths.add(preauth);
preauth = new TokenPreauth();
preauth.init(context);
preauths.add(preauth);
}
public PreauthContext preparePreauthContext(KdcRequest kdcRequest) {
PreauthContext preauthContext = new PreauthContext();
preauthContext.setPreauthRequired(krbContext.getConfig().isPreauthRequired());
for (KrbPreauth preauth : preauths) {
PreauthHandle handle = new PreauthHandle(preauth);
handle.initRequestContext(kdcRequest);
preauthContext.getHandles().add(handle);
}
return preauthContext;
}
/**
* Process preauth inputs and options, prepare and generate pdata to be out
* @param kdcRequest The kdc request
* @throws KrbException e
*/
public void preauth(KdcRequest kdcRequest) throws KrbException {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
if (!preauthContext.isPreauthRequired()) {
return;
}
setPreauthOptions(kdcRequest, kdcRequest.getPreauthOptions());
if (!preauthContext.hasInputPaData()) {
tryFirst(kdcRequest, preauthContext.getOutputPaData());
return;
}
// attemptETypeInfo(kdcRequest, preauthContext.getInputPaData());
prepareUserResponses(kdcRequest, preauthContext.getInputPaData());
preauthContext.getUserResponser().respondQuestions();
if (!kdcRequest.isRetrying()) {
process(kdcRequest, preauthContext.getInputPaData(),
preauthContext.getOutputPaData());
} else {
tryAgain(kdcRequest, preauthContext.getInputPaData(),
preauthContext.getOutputPaData());
}
}
public void prepareUserResponses(KdcRequest kdcRequest,
PaData inPadata) throws KrbException {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
for (PaDataEntry pae : inPadata.getElements()) {
if (!preauthContext.isPaTypeAllowed(pae.getPaDataType())) {
continue;
}
PreauthHandle handle = findHandle(kdcRequest, pae.getPaDataType());
if (handle == null) {
continue;
}
handle.prepareQuestions(kdcRequest);
}
}
public void setPreauthOptions(KdcRequest kdcRequest,
KOptions preauthOptions) throws KrbException {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
for (PreauthHandle handle : preauthContext.getHandles()) {
handle.setPreauthOptions(kdcRequest, preauthOptions);
}
}
public void tryFirst(KdcRequest kdcRequest,
PaData outPadata) throws KrbException {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
PreauthHandle handle = findHandle(kdcRequest,
preauthContext.getAllowedPaType());
handle.tryFirst(kdcRequest, outPadata);
}
public void process(KdcRequest kdcRequest,
PaData inPadata, PaData outPadata) throws KrbException {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
/**
* Process all informational padata types, then the first real preauth type
* we succeed on
*/
for (int real = 0; real <= 1; real++) {
for (PaDataEntry pae : inPadata.getElements()) {
// Restrict real mechanisms to the chosen one if we have one
if (real > 0 && !preauthContext.isPaTypeAllowed(pae.getPaDataType())) {
continue;
}
PreauthHandle handle = findHandle(kdcRequest,
preauthContext.getAllowedPaType());
if (handle == null) {
continue;
}
// Make sure this type is for the current pass
// TODO
// int tmpReal = handle.isReal(pae.getPaDataType()) ? 1 : 0;
// if (tmpReal != real) {
// continue;
// }
if (real > 0 && preauthContext.checkAndPutTried(pae.getPaDataType())) {
continue;
}
boolean gotData = handle.process(kdcRequest, pae, outPadata);
if (real > 0 && gotData) {
return;
}
}
}
}
public void tryAgain(KdcRequest kdcRequest,
PaData inPadata, PaData outPadata) {
PreauthContext preauthContext = kdcRequest.getPreauthContext();
for (PaDataEntry pae : inPadata.getElements()) {
PreauthHandle handle = findHandle(kdcRequest, pae.getPaDataType());
if (handle != null) {
// boolean gotData =
handle.tryAgain(kdcRequest,
pae.getPaDataType(), preauthContext.getErrorPaData(), outPadata);
}
}
}
public void destroy() {
for (KrbPreauth preauth : preauths) {
preauth.destroy();
}
}
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;
}
/*
private void attemptETypeInfo(KdcRequest kdcRequest,
PaData inPadata) throws KrbException {
// Find an etype-info2 or etype-info element in padata
EtypeInfo etypeInfo = null;
EtypeInfo2 etypeInfo2 = null;
PaDataEntry pae = inPadata.findEntry(PaDataType.ETYPE_INFO);
if (pae != null) {
etypeInfo = KrbCodec.decode(pae.getPaDataValue(), EtypeInfo.class);
} else {
pae = inPadata.findEntry(PaDataType.ETYPE_INFO2);
if (pae != null) {
etypeInfo2 = KrbCodec.decode(pae.getPaDataValue(), EtypeInfo2.class);
}
}
if (etypeInfo == null && etypeInfo2 == null) {
attemptSalt(kdcRequest, inPadata);
}
}
private void attemptSalt(KdcRequest kdcRequest,
PaData inPadata) throws KrbException {
}
*/
}
| 220 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.type.pa.PaData;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
import java.util.ArrayList;
import java.util.List;
public class PreauthContext {
private boolean preauthRequired = true;
private PaData inputPaData;
private PaData outputPaData;
private PaData errorPaData;
private UserResponser userResponser = new UserResponser();
private PaDataType allowedPaType;
private final List<PaDataType> triedPaTypes = new ArrayList<>(1);
private final List<PreauthHandle> handles = new ArrayList<>(5);
public PreauthContext() {
this.allowedPaType = PaDataType.NONE;
this.outputPaData = new PaData();
}
public void reset() {
this.outputPaData = new PaData();
}
public boolean isPreauthRequired() {
return preauthRequired;
}
public void setPreauthRequired(boolean preauthRequired) {
this.preauthRequired = preauthRequired;
}
public UserResponser getUserResponser() {
return userResponser;
}
public boolean isPaTypeAllowed(PaDataType paType) {
return allowedPaType == PaDataType.NONE || allowedPaType == paType;
}
public PaData getOutputPaData() throws KrbException {
return outputPaData;
}
public boolean hasInputPaData() {
return inputPaData != null && !inputPaData.isEmpty();
}
public PaData getInputPaData() {
return inputPaData;
}
public void setInputPaData(PaData inputPaData) {
this.inputPaData = inputPaData;
}
public PaData getErrorPaData() {
return errorPaData;
}
public void setErrorPaData(PaData errorPaData) {
this.errorPaData = errorPaData;
}
public void setAllowedPaType(PaDataType paType) {
this.allowedPaType = paType;
}
public List<PreauthHandle> getHandles() {
return handles;
}
public PaDataType getAllowedPaType() {
return allowedPaType;
}
public boolean checkAndPutTried(PaDataType paType) {
for (PaDataType pt : triedPaTypes) {
if (pt == paType) {
return true;
}
}
triedPaTypes.add(paType);
return false;
}
}
| 221 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/KrbFastRequestState.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.client.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.fast.KrbFastArmor;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq;
/**
* Maintaining FAST processing state in client side per request.
*/
public class KrbFastRequestState {
private KdcReq fastOuterRequest;
private EncryptionKey armorKey;
private KrbFastArmor fastArmor;
private FastOptions fastOptions;
private int nonce;
private int fastFlags;
public KdcReq getFastOuterRequest() {
return fastOuterRequest;
}
public void setFastOuterRequest(KdcReq fastOuterRequest) {
this.fastOuterRequest = fastOuterRequest;
}
public EncryptionKey getArmorKey() {
return armorKey;
}
public void setArmorKey(EncryptionKey armorKey) {
this.armorKey = armorKey;
}
public KrbFastArmor getFastArmor() {
return fastArmor;
}
public void setFastArmor(KrbFastArmor fastArmor) {
this.fastArmor = fastArmor;
}
public FastOptions getFastOptions() {
return fastOptions;
}
public void setFastOptions(FastOptions fastOptions) {
this.fastOptions = fastOptions;
}
public int getNonce() {
return nonce;
}
public void setNonce(int nonce) {
this.nonce = nonce;
}
public int getFastFlags() {
return fastFlags;
}
public void setFastFlags(int fastFlags) {
this.fastFlags = fastFlags;
}
}
| 222 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/token/TokenContext.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.client.preauth.token;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
public class TokenContext {
private boolean usingIdToken = true;
private AuthToken token = null;
public boolean isUsingIdToken() {
return usingIdToken;
}
public void setUsingIdToken(boolean usingIdToken) {
this.usingIdToken = usingIdToken;
}
public AuthToken getToken() {
return token;
}
public void setToken(AuthToken token) {
this.token = token;
}
}
| 223 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.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;
}
}
| 224 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth.token;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbCodec;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.client.preauth.AbstractPreauthPlugin;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.preauth.PaFlag;
import org.apache.kerby.kerberos.kerb.preauth.PaFlags;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
import org.apache.kerby.kerberos.kerb.preauth.token.TokenPreauthMeta;
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.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.kerberos.kerb.type.base.KrbToken;
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 org.apache.kerby.kerberos.kerb.type.pa.token.PaTokenRequest;
import org.apache.kerby.kerberos.kerb.type.pa.token.TokenInfo;
import java.util.Collections;
import java.util.List;
public class TokenPreauth extends AbstractPreauthPlugin {
private TokenContext tokenContext;
public TokenPreauth() {
super(new TokenPreauthMeta());
}
/**
* {@inheritDoc}
*/
@Override
public void init(KrbContext context) {
super.init(context);
this.tokenContext = new TokenContext();
}
/**
* {@inheritDoc}
*/
@Override
public PluginRequestContext initRequestContext(KdcRequest kdcRequest) {
TokenRequestContext reqCtx = new TokenRequestContext();
return reqCtx;
}
/**
* {@inheritDoc}
*/
@Override
public void prepareQuestions(KdcRequest kdcRequest,
PluginRequestContext requestContext) {
}
/**
* {@inheritDoc}
*/
@Override
public List<EncryptionType> getEncTypes(KdcRequest kdcRequest,
PluginRequestContext requestContext) {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*/
@Override
public void setPreauthOptions(KdcRequest kdcRequest,
PluginRequestContext requestContext,
KOptions options) {
tokenContext.setUsingIdToken(options.getBooleanOption(TokenOption.USE_TOKEN, false));
if (tokenContext.isUsingIdToken()) {
if (options.contains(TokenOption.USER_ID_TOKEN)) {
tokenContext.setToken((AuthToken) options.getOptionValue(TokenOption.USER_ID_TOKEN));
}
} else {
if (options.contains(TokenOption.USER_AC_TOKEN)) {
tokenContext.setToken((AuthToken) options.getOptionValue(TokenOption.USER_AC_TOKEN));
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException {
if (kdcRequest.getAsKey() == null) {
kdcRequest.needAsKey();
}
outPadata.addElement(makeEntry(kdcRequest));
}
/**
* {@inheritDoc}
*/
@Override
public boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataEntry inPadata,
PaData outPadata) throws KrbException {
if (kdcRequest.getAsKey() == null) {
kdcRequest.needAsKey();
}
outPadata.addElement(makeEntry(kdcRequest));
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean tryAgain(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataType preauthType,
PaData errPadata,
PaData outPadata) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public PaFlags getFlags(PaDataType paType) {
PaFlags paFlags = new PaFlags(0);
paFlags.setFlag(PaFlag.PA_REAL);
return paFlags;
}
/**
* Make padata entry.
*
* @param kdcRequest The kdc request
* @return PaDataEntry to be made.
*/
private PaDataEntry makeEntry(KdcRequest kdcRequest) throws KrbException {
KOptions options = kdcRequest.getPreauthOptions();
KOption idToken = options.getOption(TokenOption.USER_ID_TOKEN);
KOption acToken = options.getOption(TokenOption.USER_AC_TOKEN);
KrbToken krbToken;
if (idToken != null) {
krbToken = (KrbToken) idToken.getOptionInfo().getValue();
} else if (acToken != null) {
krbToken = (KrbToken) acToken.getOptionInfo().getValue();
} else {
throw new KrbException("missing token.");
}
PaTokenRequest tokenPa = new PaTokenRequest();
tokenPa.setToken(krbToken);
TokenInfo info = new TokenInfo();
info.setTokenVendor(krbToken.getIssuer());
tokenPa.setTokenInfo(info);
EncryptedData paDataValue = EncryptionUtil.seal(tokenPa,
kdcRequest.getAsKey(), KeyUsage.PA_TOKEN);
PaDataEntry paDataEntry = new PaDataEntry();
paDataEntry.setPaDataType(PaDataType.TOKEN_REQUEST);
paDataEntry.setPaDataValue(KrbCodec.encode(paDataValue));
return paDataEntry;
}
} | 225 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/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.client.preauth.pkinit;
import org.apache.kerby.kerberos.kerb.crypto.dh.DiffieHellmanClient;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.IdentityOpts;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PluginOpts;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
public class PkinitRequestContext implements PluginRequestContext {
private PkinitRequestOpts requestOpts = new PkinitRequestOpts();
private IdentityOpts identityOpts = new IdentityOpts();
private PaDataType paType;
private boolean identityInitialized;
private DiffieHellmanClient dhClient;
public void updateRequestOpts(PluginOpts pluginOpts) {
requestOpts.setRequireEku(pluginOpts.isRequireEku());
requestOpts.setAcceptSecondaryEku(pluginOpts.isAcceptSecondaryEku());
requestOpts.setAllowUpn(pluginOpts.isAllowUpn());
requestOpts.setUsingRsa(pluginOpts.isUsingRsa());
requestOpts.setRequireCrlChecking(pluginOpts.isRequireCrlChecking());
}
public void setDhClient(DiffieHellmanClient client) {
this.dhClient = client;
}
public DiffieHellmanClient getDhClient() {
return this.dhClient;
}
public boolean isIdentityInitialized() {
return identityInitialized;
}
public void setIdentityInitialized(boolean identityInitialized) {
this.identityInitialized = identityInitialized;
}
public IdentityOpts getIdentityOpts() {
return identityOpts;
}
public void setIdentityOpts(IdentityOpts identityOpts) {
this.identityOpts = identityOpts;
}
public PaDataType getPaType() {
return paType;
}
public void setPaType(PaDataType paType) {
this.paType = paType;
}
}
| 226 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/pkinit/ClientConfiguration.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.client.preauth.pkinit;
import org.apache.kerby.kerberos.kerb.crypto.dh.DhGroup;
import javax.crypto.spec.DHParameterSpec;
/**
* Client configuration settings.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ClientConfiguration {
/**
* The location of the user certificate.
*/
private String certificatePath;
/**
* The CMS types to use.
*/
private String cmsType;
/**
* Whether or not to use Diffie-Hellman. The alternative is the "public key"
* method.
*/
private boolean isDhUsed = true;
/**
* The Diffie-Hellman group to use.
*/
private DHParameterSpec dhGroup = DhGroup.MODP_GROUP2;
/**
* Whether or not to reuse Diffie-Hellman keys.
*/
private boolean isDhKeysReused;
/**
* @return the certificatePath
*/
public String getCertificatePath() {
return certificatePath;
}
/**
* @param certificatePath the certificatePath to set
*/
public void setCertificatePath(String certificatePath) {
this.certificatePath = certificatePath;
}
/**
* @return the cmsType
*/
public String getCmsType() {
return cmsType;
}
/**
* @param cmsType the cmsType to set
*/
public void setCmsType(String cmsType) {
this.cmsType = cmsType;
}
/**
* @return the isDhUsed
*/
public boolean isDhUsed() {
return isDhUsed;
}
/**
* @param isDhUsed the isDhUsed to set
*/
public void setDhUsed(boolean isDhUsed) {
this.isDhUsed = isDhUsed;
}
/**
* @return the dhGroup
*/
public DHParameterSpec getDhGroup() {
return dhGroup;
}
/**
* @param dhGroup the dhGroup to set
*/
public void setDhGroup(DHParameterSpec dhGroup) {
this.dhGroup = dhGroup;
}
/**
* @return the isDhKeysReused
*/
public boolean isDhKeysReused() {
return isDhKeysReused;
}
/**
* @param isDhKeysReused the isDhKeysReused to set
*/
public void setDhKeysReused(boolean isDhKeysReused) {
this.isDhKeysReused = isDhKeysReused;
}
}
| 227 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/pkinit/ServerConfiguration.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.client.preauth.pkinit;
import org.apache.kerby.kerberos.kerb.crypto.dh.DhGroup;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import javax.crypto.spec.DHParameterSpec;
/**
* Server configuration settings.
*
* TODO - Whether to use user cert vs. SAN binding.
* TODO - What trusted roots to use.
* TODO - The minimum allowed enc_types.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ServerConfiguration {
/**
* Whether or not to use Diffie-Hellman. The alternative is the "public key"
* method.
*/
private boolean isDhUsed;
/**
* The Diffie-Hellman group to use.
*/
private DHParameterSpec dhGroup = DhGroup.MODP_GROUP2;
/**
* Whether or not to reuse Diffie-Hellman keys.
*/
private boolean isDhKeysReused;
/**
* The length of time Diffie-Hellman keys can be reused.
*/
private long dhKeyExpiration = KerberosTime.DAY;
/**
* The length of the Diffie-Hellman nonces.
*/
private int dhNonceLength = 32;
/**
* @return the isDhUsed
*/
public boolean isDhUsed() {
return isDhUsed;
}
/**
* @param isDhUsed the isDhUsed to set
*/
public void setDhUsed(boolean isDhUsed) {
this.isDhUsed = isDhUsed;
}
/**
* @return the dhGroup
*/
public DHParameterSpec getDhGroup() {
return dhGroup;
}
/**
* @param dhGroup the dhGroup to set
*/
public void setDhGroup(DHParameterSpec dhGroup) {
this.dhGroup = dhGroup;
}
/**
* @return the isDhKeysReused
*/
public boolean isDhKeysReused() {
return isDhKeysReused;
}
/**
* @param isDhKeysReused the isDhKeysReused to set
*/
public void setDhKeysReused(boolean isDhKeysReused) {
this.isDhKeysReused = isDhKeysReused;
}
/**
* @return the dhKeyExpiration
*/
public long getDhKeyExpiration() {
return dhKeyExpiration;
}
/**
* @param dhKeyExpiration the dhKeyExpiration to set
*/
public void setDhKeyExpiration(long dhKeyExpiration) {
this.dhKeyExpiration = dhKeyExpiration;
}
/**
* @return the dhNonceLength
*/
public int getDhNonceLength() {
return dhNonceLength;
}
/**
* @param dhNonceLength the dhNonceLength to set
*/
public void setDhNonceLength(int dhNonceLength) {
this.dhNonceLength = dhNonceLength;
}
}
| 228 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/pkinit/PkinitPreauth.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.client.preauth.pkinit;
import org.apache.kerby.KOptions;
import org.apache.kerby.asn1.type.Asn1Integer;
import org.apache.kerby.asn1.type.Asn1ObjectIdentifier;
import org.apache.kerby.cms.type.CertificateChoices;
import org.apache.kerby.cms.type.CertificateSet;
import org.apache.kerby.cms.type.ContentInfo;
import org.apache.kerby.cms.type.SignedData;
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.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.PkinitOption;
import org.apache.kerby.kerberos.kerb.client.preauth.AbstractPreauthPlugin;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.common.CheckSumUtil;
import org.apache.kerby.kerberos.kerb.common.KrbUtil;
import org.apache.kerby.kerberos.kerb.crypto.dh.DhGroup;
import org.apache.kerby.kerberos.kerb.crypto.dh.DiffieHellmanClient;
import org.apache.kerby.kerberos.kerb.preauth.PaFlag;
import org.apache.kerby.kerberos.kerb.preauth.PaFlags;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.CertificateHelper;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.CmsMessageType;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitCrypto;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitIdentity;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitPlgCryptoContext;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitPreauthMeta;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
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 org.apache.kerby.kerberos.kerb.type.pa.pkinit.AuthPack;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.DhRepInfo;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.KdcDhKeyInfo;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.PaPkAsRep;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.PaPkAsReq;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.PkAuthenticator;
import org.apache.kerby.kerberos.kerb.type.pa.pkinit.TrustedCertifiers;
import org.apache.kerby.x509.type.AlgorithmIdentifier;
import org.apache.kerby.x509.type.Certificate;
import org.apache.kerby.x509.type.DhParameter;
import org.apache.kerby.x509.type.SubjectPublicKeyInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class PkinitPreauth extends AbstractPreauthPlugin {
private static final Logger LOG = LoggerFactory.getLogger(PkinitPreauth.class);
private PkinitContext pkinitContext;
public PkinitPreauth() {
super(new PkinitPreauthMeta());
}
/**
* {@inheritDoc}
*/
@Override
public void init(KrbContext context) {
super.init(context);
this.pkinitContext = new PkinitContext();
}
/**
* {@inheritDoc}
*/
@Override
public PluginRequestContext initRequestContext(KdcRequest kdcRequest) {
PkinitRequestContext reqCtx = new PkinitRequestContext();
reqCtx.updateRequestOpts(pkinitContext.getPluginOpts());
return reqCtx;
}
/**
* {@inheritDoc}
*/
@Override
public void setPreauthOptions(KdcRequest kdcRequest,
PluginRequestContext requestContext,
KOptions options) {
if (options.contains(PkinitOption.X509_IDENTITY)) {
pkinitContext.getIdentityOpts().setIdentity(options.getStringOption(PkinitOption.X509_IDENTITY));
}
if (options.contains(PkinitOption.X509_ANCHORS)) {
String anchorsString = options.getStringOption(PkinitOption.X509_ANCHORS);
List<String> anchors;
if (anchorsString == null) {
anchors = kdcRequest.getContext().getConfig().getPkinitAnchors();
} else {
anchors = Arrays.asList(anchorsString);
}
pkinitContext.getIdentityOpts().getAnchors().addAll(anchors);
}
if (options.contains(PkinitOption.USING_RSA)) {
pkinitContext.getPluginOpts().setUsingRsa(options.getBooleanOption(PkinitOption.USING_RSA, true));
}
}
/**
* {@inheritDoc}
*/
@Override
public void prepareQuestions(KdcRequest kdcRequest,
PluginRequestContext requestContext) {
PkinitRequestContext reqCtx = (PkinitRequestContext) requestContext;
if (!reqCtx.isIdentityInitialized()) {
PkinitIdentity.initialize(reqCtx.getIdentityOpts(), kdcRequest.getClientPrincipal());
reqCtx.setIdentityInitialized(true);
}
// Might have questions asking for password to access the private key
}
/**
* {@inheritDoc}
*/
@Override
public void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException {
/* XXX PKINIT RFC says that nonce in PKAuthenticator doesn't have be the
* same as in the AS_REQ. However, if we pick a different nonce, then we
* need to remember that info when AS_REP is returned. Here choose to
* reuse the AS_REQ nonce.
*/
int nonce = kdcRequest.getChosenNonce();
// Get the current time
long now = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(now));
int cusec = calendar.get(Calendar.SECOND);
KerberosTime ctime = new KerberosTime(now);
/* checksum of the encoded KDC-REQ-BODY */
CheckSum checkSum = null;
try {
checkSum = CheckSumUtil.makeCheckSum(CheckSumType.NIST_SHA,
KrbCodec.encode(kdcRequest.getKdcReq().getReqBody()));
} catch (KrbException e) {
throw new KrbException("Fail to encode checksum.", e);
}
PaPkAsReq paPkAsReq = makePaPkAsReq(kdcRequest, (PkinitRequestContext) requestContext,
cusec, ctime, nonce, checkSum);
outPadata.addElement(makeEntry(paPkAsReq));
}
/**
* {@inheritDoc}
*/
@Override
public boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataEntry inPadata,
PaData outPadata) throws KrbException {
PkinitRequestContext reqCtx = (PkinitRequestContext) requestContext;
if (inPadata == null) {
return false;
}
boolean processingRequest = false;
switch (inPadata.getPaDataType()) {
case PK_AS_REQ:
processingRequest = true;
break;
case PK_AS_REP:
default:
break;
}
if (processingRequest) {
generateRequest(reqCtx, kdcRequest, outPadata);
return true;
} else {
EncryptionType encType = kdcRequest.getEncType();
processReply(kdcRequest, reqCtx, inPadata, encType);
return true;
}
}
@SuppressWarnings("unused")
private void generateRequest(PkinitRequestContext reqCtx, KdcRequest kdcRequest,
PaData outPadata) {
}
@SuppressWarnings("unused")
private PaPkAsReq makePaPkAsReq(KdcRequest kdcRequest,
PkinitRequestContext reqCtx,
int cusec, KerberosTime ctime, int nonce, CheckSum checkSum) throws KrbException {
LOG.info("Making the PK_AS_REQ.");
PaPkAsReq paPkAsReq = new PaPkAsReq();
AuthPack authPack = new AuthPack();
PkAuthenticator pkAuthen = new PkAuthenticator();
boolean usingRsa = pkinitContext.getPluginOpts().isUsingRsa();
reqCtx.setPaType(PaDataType.PK_AS_REQ);
pkAuthen.setCusec(cusec);
pkAuthen.setCtime(ctime);
pkAuthen.setNonce(nonce);
pkAuthen.setPaChecksum(checkSum.getChecksum());
authPack.setPkAuthenticator(pkAuthen);
authPack.setsupportedCmsTypes(pkinitContext.getPluginOpts().createSupportedCMSTypes());
if (!usingRsa) {
// DH case
LOG.info("DH key transport algorithm.");
String content = "0x06 07 2A 86 48 ce 3e 02 01";
Asn1ObjectIdentifier dhOid = PkinitCrypto.createOid(content);
AlgorithmIdentifier dhAlg = new AlgorithmIdentifier();
dhAlg.setAlgorithm(dhOid.getValue());
DiffieHellmanClient client = new DiffieHellmanClient();
DHPublicKey clientPubKey = null;
try {
clientPubKey = client.init(DhGroup.MODP_GROUP2);
} catch (Exception e) {
LOG.error("DiffieHellmanClient init with failure. " + e);
}
reqCtx.setDhClient(client);
DHParameterSpec type = null;
try {
type = clientPubKey.getParams();
} catch (Exception e) {
LOG.error("Fail to get params from client public key. " + e);
}
BigInteger q = type.getP().shiftRight(1);
DhParameter dhParameter = new DhParameter();
dhParameter.setP(type.getP());
dhParameter.setG(type.getG());
dhParameter.setQ(q);
dhAlg.setParameters(dhParameter);
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo();
pubInfo.setAlgorithm(dhAlg);
Asn1Integer publickey = new Asn1Integer(clientPubKey.getY());
pubInfo.setSubjectPubKey(KrbCodec.encode(publickey));
authPack.setClientPublicValue(pubInfo);
// DhNonce dhNonce = new DhNonce();
// authPack.setClientDhNonce(dhNonce);
byte[] signedAuthPack = signAuthPack(authPack);
paPkAsReq.setSignedAuthPack(signedAuthPack);
} else {
LOG.info("RSA key transport algorithm");
// authPack.setClientPublicValue(null);
}
TrustedCertifiers trustedCertifiers = pkinitContext.getPluginOpts().createTrustedCertifiers();
paPkAsReq.setTrustedCertifiers(trustedCertifiers);
// byte[] kdcPkId = pkinitContext.pluginOpts.createIssuerAndSerial();
// paPkAsReq.setKdcPkId(kdcPkId);
return paPkAsReq;
}
private byte[] signAuthPack(AuthPack authPack) throws KrbException {
String oid = PkinitPlgCryptoContext.getIdPkinitAuthDataOID();
byte[] signedDataBytes = PkinitCrypto.eContentInfoCreate(
KrbCodec.encode(authPack), oid);
return signedDataBytes;
}
private void processReply(KdcRequest kdcRequest,
PkinitRequestContext reqCtx,
PaDataEntry paEntry,
EncryptionType encType) throws KrbException {
// Parse PA-PK-AS-REP message.
if (paEntry.getPaDataType() == PaDataType.PK_AS_REP) {
LOG.info("processing PK_AS_REP");
PaPkAsRep paPkAsRep = KrbCodec.decode(paEntry.getPaDataValue(), PaPkAsRep.class);
DhRepInfo dhRepInfo = paPkAsRep.getDHRepInfo();
byte[] dhSignedData = dhRepInfo.getDHSignedData();
ContentInfo contentInfo = new ContentInfo();
try {
contentInfo.decode(dhSignedData);
} catch (IOException e) {
LOG.error("Fail to decode dhSignedData. " + e);
}
SignedData signedData = contentInfo.getContentAs(SignedData.class);
PkinitCrypto.verifyCmsSignedData(
CmsMessageType.CMS_SIGN_SERVER, signedData);
if (kdcRequest.getContext().getConfig().getPkinitAnchors().isEmpty()) {
LOG.error("No PKINIT anchors specified");
throw new KrbException("No PKINIT anchors specified");
}
String anchorFileName = kdcRequest.getContext().getConfig().getPkinitAnchors().get(0);
X509Certificate x509Certificate = null;
try {
List<java.security.cert.Certificate> certs =
CertificateHelper.loadCerts(anchorFileName);
if (certs != null && !certs.isEmpty()) {
x509Certificate = (X509Certificate) certs.iterator().next();
}
} catch (KrbException e) {
LOG.error("Fail to load certs from archor file. " + e);
}
if (x509Certificate == null) {
LOG.error("Failed to load PKINIT anchor");
throw new KrbException("Failed to load PKINIT anchor");
}
CertificateSet certificateSet = signedData.getCertificates();
if (certificateSet == null || certificateSet.getElements().isEmpty()) {
throw new KrbException("No PKINIT Certs");
}
List<Certificate> certificates = new ArrayList<>();
List<CertificateChoices> certificateChoicesList = certificateSet.getElements();
for (CertificateChoices certificateChoices : certificateChoicesList) {
certificates.add(certificateChoices.getCertificate());
}
try {
PkinitCrypto.validateChain(certificates, x509Certificate);
} catch (Exception e) {
throw new KrbException(KrbErrorCode.KDC_ERR_INVALID_CERTIFICATE, e);
}
PrincipalName kdcPrincipal = KrbUtil.makeTgsPrincipal(
kdcRequest.getContext().getConfig().getKdcRealm());
//TODO USE CertificateSet
boolean validSan = PkinitCrypto.verifyKdcSan(
kdcRequest.getContext().getConfig().getPkinitKdcHostName(), kdcPrincipal,
certificates);
if (!validSan) {
LOG.error("Did not find an acceptable SAN in KDC certificate");
}
LOG.info("skipping EKU check");
LOG.info("as_rep: DH key transport algorithm");
KdcDhKeyInfo kdcDhKeyInfo = new KdcDhKeyInfo();
try {
kdcDhKeyInfo.decode(signedData.getEncapContentInfo().getContent());
} catch (IOException e) {
String errMessage = "failed to decode KdcDhKeyInfo " + e.getMessage();
LOG.error(errMessage);
throw new KrbException(errMessage);
}
byte[] subjectPublicKey = kdcDhKeyInfo.getSubjectPublicKey().getValue();
Asn1Integer clientPubKey = KrbCodec.decode(subjectPublicKey, Asn1Integer.class);
BigInteger y = clientPubKey.getValue();
DiffieHellmanClient client = reqCtx.getDhClient();
BigInteger p = client.getDhParam().getP();
BigInteger g = client.getDhParam().getG();
DHPublicKey dhPublicKey = PkinitCrypto.createDHPublicKey(p, g, y);
EncryptionKey secretKey = null;
try {
client.doPhase(dhPublicKey.getEncoded());
secretKey = client.generateKey(null, null, encType);
} catch (Exception e) {
LOG.error("DiffieHellmanClient do parse failed. " + e);
}
// Set the DH shared key as the client key
if (secretKey == null) {
throw new KrbException("Fail to create client key.");
} else {
kdcRequest.setAsKey(secretKey);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean tryAgain(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataType preauthType,
PaData errPadata,
PaData outPadata) {
PkinitRequestContext reqCtx = (PkinitRequestContext) requestContext;
if (reqCtx.getPaType() != preauthType && errPadata == null) {
return false;
}
boolean doAgain = false;
for (PaDataEntry pde : errPadata.getElements()) {
// switch (pde.getPaDataType()) {
// TODO
// }
System.out.println(pde.getPaDataType());
}
if (doAgain) {
generateRequest(reqCtx, kdcRequest, outPadata);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public PaFlags getFlags(PaDataType paType) {
PaFlags paFlags = new PaFlags(0);
paFlags.setFlag(PaFlag.PA_REAL);
return paFlags;
}
/**
* Make padata entry.
*
* @param paPkAsReq The PaPkAsReq
* @return PaDataEntry to be made.
*/
private PaDataEntry makeEntry(PaPkAsReq paPkAsReq) throws KrbException {
PaDataEntry paDataEntry = new PaDataEntry();
paDataEntry.setPaDataType(PaDataType.PK_AS_REQ);
paDataEntry.setPaDataValue(KrbCodec.encode(paPkAsReq));
return paDataEntry;
}
}
| 229 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/pkinit/PkinitContext.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.client.preauth.pkinit;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.IdentityOpts;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitPlgCryptoContext;
import org.apache.kerby.kerberos.kerb.preauth.pkinit.PluginOpts;
/*
* Ref. _pkinit_context in MIT krb5 project.
*/
public class PkinitContext {
private PkinitPlgCryptoContext cryptoctx = new PkinitPlgCryptoContext();
private PluginOpts pluginOpts = new PluginOpts();
private IdentityOpts identityOpts = new IdentityOpts();
public PkinitPlgCryptoContext getCryptoctx() {
return cryptoctx;
}
public void setCryptoctx(PkinitPlgCryptoContext cryptoctx) {
this.cryptoctx = cryptoctx;
}
public PluginOpts getPluginOpts() {
return pluginOpts;
}
public void setPluginOpts(PluginOpts pluginOpts) {
this.pluginOpts = pluginOpts;
}
public IdentityOpts getIdentityOpts() {
return identityOpts;
}
public void setIdentityOpts(IdentityOpts identityOpts) {
this.identityOpts = identityOpts;
}
}
| 230 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/pkinit/PkinitRequestOpts.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.client.preauth.pkinit;
public class PkinitRequestOpts {
// From MIT Krb5 _pkinit_plg_opts
// require EKU checking (default is true)
private boolean requireEku = true;
// accept secondary EKU (default is false)
private boolean acceptSecondaryEku = false;
// allow UPN-SAN instead of pkinit-SAN
private boolean allowUpn = true;
// selects DH or RSA based pkinit
private boolean usingRsa = false;
// require CRL for a CA (default is false)
private boolean requireCrlChecking = false;
// initial request DH modulus size (default=1024)
private int dhSize = 1024;
private boolean requireHostnameMatch = true;
public boolean isRequireEku() {
return requireEku;
}
public void setRequireEku(boolean requireEku) {
this.requireEku = requireEku;
}
public boolean isAcceptSecondaryEku() {
return acceptSecondaryEku;
}
public void setAcceptSecondaryEku(boolean acceptSecondaryEku) {
this.acceptSecondaryEku = acceptSecondaryEku;
}
public boolean isAllowUpn() {
return allowUpn;
}
public void setAllowUpn(boolean allowUpn) {
this.allowUpn = allowUpn;
}
public boolean isUsingRsa() {
return usingRsa;
}
public void setUsingRsa(boolean usingRsa) {
this.usingRsa = usingRsa;
}
public boolean isRequireCrlChecking() {
return requireCrlChecking;
}
public void setRequireCrlChecking(boolean requireCrlChecking) {
this.requireCrlChecking = requireCrlChecking;
}
public int getDhSize() {
return dhSize;
}
public void setDhSize(int dhSize) {
this.dhSize = dhSize;
}
public boolean isRequireHostnameMatch() {
return requireHostnameMatch;
}
public void setRequireHostnameMatch(boolean requireHostnameMatch) {
this.requireHostnameMatch = requireHostnameMatch;
}
}
| 231 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/builtin/TgtPreauth.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.client.preauth.builtin;
import org.apache.kerby.kerberos.kerb.KrbCodec;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.preauth.AbstractPreauthPlugin;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.client.request.TgsRequestWithTgt;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
import org.apache.kerby.kerberos.kerb.preauth.builtin.TgtPreauthMeta;
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 TgtPreauth extends AbstractPreauthPlugin {
public TgtPreauth() {
super(new TgtPreauthMeta());
}
/**
* {@inheritDoc}
*/
@Override
public void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException {
outPadata.addElement(makeEntry(kdcRequest));
}
/**
* {@inheritDoc}
*/
@Override
public boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataEntry inPadata,
PaData outPadata) throws KrbException {
outPadata.addElement(makeEntry(kdcRequest));
return true;
}
/**
* Make padata entry.
*
* @param kdcRequest The kdc request
* @return PaDataEntry to be made.
*/
private PaDataEntry makeEntry(KdcRequest kdcRequest) throws KrbException {
TgsRequestWithTgt tgsRequest = (TgsRequestWithTgt) kdcRequest;
PaDataEntry paEntry = new PaDataEntry();
paEntry.setPaDataType(PaDataType.TGS_REQ);
paEntry.setPaDataValue(KrbCodec.encode(tgsRequest.getApReq()));
return paEntry;
}
}
| 232 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/preauth/builtin/EncTsPreauth.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.client.preauth.builtin;
import org.apache.kerby.kerberos.kerb.KrbCodec;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.preauth.AbstractPreauthPlugin;
import org.apache.kerby.kerberos.kerb.client.request.KdcRequest;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.preauth.PaFlag;
import org.apache.kerby.kerberos.kerb.preauth.PaFlags;
import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext;
import org.apache.kerby.kerberos.kerb.preauth.builtin.EncTsPreauthMeta;
import org.apache.kerby.kerberos.kerb.type.base.EncryptedData;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
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 org.apache.kerby.kerberos.kerb.type.pa.PaEncTsEnc;
public class EncTsPreauth extends AbstractPreauthPlugin {
public EncTsPreauth() {
super(new EncTsPreauthMeta());
}
/**
* {@inheritDoc}
*/
@Override
public void prepareQuestions(KdcRequest kdcRequest,
PluginRequestContext requestContext) throws KrbException {
kdcRequest.needAsKey();
}
/**
* {@inheritDoc}
*/
@Override
public void tryFirst(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaData outPadata) throws KrbException {
if (kdcRequest.getAsKey() == null) {
kdcRequest.needAsKey();
}
outPadata.addElement(makeEntry(kdcRequest));
}
/**
* {@inheritDoc}
*/
@Override
public boolean process(KdcRequest kdcRequest,
PluginRequestContext requestContext,
PaDataEntry inPadata,
PaData outPadata) throws KrbException {
if (kdcRequest.getAsKey() == null) {
kdcRequest.needAsKey();
}
outPadata.addElement(makeEntry(kdcRequest));
return true;
}
/**
* {@inheritDoc}
*/
@Override
public PaFlags getFlags(PaDataType paType) {
PaFlags paFlags = new PaFlags(0);
paFlags.setFlag(PaFlag.PA_REAL);
return paFlags;
}
/**
* Make padata entry.
*
* @param kdcRequest The kdc request
* @return PaDataEntry to be made.
*/
private PaDataEntry makeEntry(KdcRequest kdcRequest) throws KrbException {
PaEncTsEnc paTs = new PaEncTsEnc();
paTs.setPaTimestamp(kdcRequest.getPreauthTime());
EncryptedData paDataValue = EncryptionUtil.seal(paTs,
kdcRequest.getAsKey(), KeyUsage.AS_REQ_PA_ENC_TS);
PaDataEntry tsPaEntry = new PaDataEntry();
tsPaEntry.setPaDataType(PaDataType.ENC_TIMESTAMP);
tsPaEntry.setPaDataValue(KrbCodec.encode(paDataValue));
return tsPaEntry;
}
}
| 233 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/AsRequestWithToken.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
/**
* This initiates an AS-REQ using TokenPreauth mechanism.
*/
public class AsRequestWithToken extends ArmoredAsRequest {
public AsRequestWithToken(KrbContext context) {
super(context);
setAllowedPreauth(PaDataType.TOKEN_REQUEST);
}
@Override
public KOptions getPreauthOptions() {
KOptions results = super.getPreauthOptions();
KOptions krbOptions = getRequestOptions();
results.add(krbOptions.getOption(TokenOption.USE_TOKEN));
results.add(krbOptions.getOption(TokenOption.USER_ID_TOKEN));
//results.add(krbOptions.getOption(KrbOption.USER_AC_TOKEN));
return results;
}
} | 234 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/ArmoredRequest.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbCodec;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.ccache.Credential;
import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.client.preauth.KrbFastRequestState;
import org.apache.kerby.kerberos.kerb.common.CheckSumUtil;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.crypto.fast.FastUtil;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.ap.ApOptions;
import org.apache.kerby.kerberos.kerb.type.ap.ApReq;
import org.apache.kerby.kerberos.kerb.type.ap.Authenticator;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
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.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.kerberos.kerb.type.fast.ArmorType;
import org.apache.kerby.kerberos.kerb.type.fast.KrbFastArmor;
import org.apache.kerby.kerberos.kerb.type.fast.KrbFastArmoredReq;
import org.apache.kerby.kerberos.kerb.type.fast.KrbFastReq;
import org.apache.kerby.kerberos.kerb.type.fast.PaFxFastRequest;
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.KdcReqBody;
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.ticket.TgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.Ticket;
import java.io.File;
import java.io.IOException;
public class ArmoredRequest {
private Credential credential;
private EncryptionKey subKey;
private EncryptionKey armorCacheKey;
private KdcRequest kdcRequest;
public ArmoredRequest(KdcRequest kdcRequest) {
this.kdcRequest = kdcRequest;
}
public void process() throws KrbException {
KdcReq kdcReq = kdcRequest.getKdcReq();
KrbFastRequestState state = kdcRequest.getFastRequestState();
fastAsArmor(state, kdcRequest.getArmorKey(), subKey, credential, kdcReq);
kdcRequest.setFastRequestState(state);
kdcRequest.setOuterRequestBody(KrbCodec.encode(state.getFastOuterRequest().getReqBody()));
kdcReq.getPaData().addElement(makeFastEntry(state, kdcReq,
kdcRequest.getOuterRequestBody()));
}
protected void preauth() throws KrbException {
KOptions preauthOptions = getPreauthOptions();
getCredential(preauthOptions);
armorCacheKey = getArmorCacheKey(credential);
subKey = getSubKey(armorCacheKey.getKeyType());
EncryptionKey armorKey = makeArmorKey(subKey, armorCacheKey);
kdcRequest.getFastRequestState().setArmorKey(armorKey);
}
private void getCredential(KOptions kOptions) throws KrbException {
if (kOptions.contains(KrbOption.ARMOR_CACHE)) {
String ccache = kOptions.getStringOption(KrbOption.ARMOR_CACHE);
credential = getCredentialFromFile(ccache);
} else if (kOptions.contains(KrbOption.TGT)) {
TgtTicket tgt = (TgtTicket) kOptions.getOptionValue(KrbOption.TGT);
credential = new Credential(tgt);
}
}
public KOptions getPreauthOptions() {
KOptions results = new KOptions();
KOptions krbOptions = kdcRequest.getRequestOptions();
if (krbOptions.contains(KrbOption.ARMOR_CACHE)) {
results.add(krbOptions.getOption(KrbOption.ARMOR_CACHE));
} else if (krbOptions.contains(KrbOption.TGT)) {
results.add(krbOptions.getOption(KrbOption.TGT));
}
return results;
}
public EncryptionKey getClientKey() throws KrbException {
return kdcRequest.getFastRequestState().getArmorKey();
}
public EncryptionKey getArmorCacheKey() {
return armorCacheKey;
}
private Credential getCredentialFromFile(String ccache) throws KrbException {
File ccacheFile = new File(ccache);
CredentialCache cc = null;
try {
cc = resolveCredCache(ccacheFile);
} catch (IOException e) {
throw new KrbException("Failed to load armor cache file");
}
// TODO: get the right credential.
return cc.getCredentials().iterator().next();
}
private static CredentialCache resolveCredCache(File ccacheFile) throws IOException {
CredentialCache cc = new CredentialCache();
cc.load(ccacheFile);
return cc;
}
private void fastAsArmor(KrbFastRequestState state,
EncryptionKey armorKey, EncryptionKey subKey,
Credential credential, KdcReq kdcReq)
throws KrbException {
state.setArmorKey(armorKey);
state.setFastArmor(fastArmorApRequest(subKey, credential));
KdcReq fastOuterRequest = new AsReq();
fastOuterRequest.setReqBody(kdcReq.getReqBody());
fastOuterRequest.setPaData(null);
state.setFastOuterRequest(fastOuterRequest);
}
private PaDataEntry makeFastEntry(KrbFastRequestState state, KdcReq kdcReq,
byte[] outerRequestBody) throws KrbException {
KrbFastReq fastReq = new KrbFastReq();
fastReq.setKdcReqBody(kdcReq.getReqBody());
fastReq.setFastOptions(state.getFastOptions());
PaFxFastRequest paFxFastRequest = new PaFxFastRequest();
KrbFastArmoredReq armoredReq = new KrbFastArmoredReq();
armoredReq.setArmor(state.getFastArmor());
CheckSum reqCheckSum = CheckSumUtil.makeCheckSumWithKey(CheckSumType.NONE,
outerRequestBody, state.getArmorKey(), KeyUsage.FAST_REQ_CHKSUM);
armoredReq.setReqChecksum(reqCheckSum);
armoredReq.setEncryptedFastReq(EncryptionUtil.seal(fastReq, state.getArmorKey(), KeyUsage.FAST_ENC));
paFxFastRequest.setFastArmoredReq(armoredReq);
PaDataEntry paDataEntry = new PaDataEntry();
paDataEntry.setPaDataType(PaDataType.FX_FAST);
paDataEntry.setPaDataValue(KrbCodec.encode(paFxFastRequest));
return paDataEntry;
}
private KrbFastArmor fastArmorApRequest(EncryptionKey subKey, Credential credential)
throws KrbException {
KrbFastArmor fastArmor = new KrbFastArmor();
fastArmor.setArmorType(ArmorType.ARMOR_AP_REQUEST);
ApReq apReq = makeApReq(subKey, credential);
fastArmor.setArmorValue(KrbCodec.encode(apReq));
return fastArmor;
}
private ApReq makeApReq(EncryptionKey subKey, Credential credential)
throws KrbException {
ApReq apReq = new ApReq();
ApOptions apOptions = new ApOptions();
apReq.setApOptions(apOptions);
Ticket ticket = credential.getTicket();
apReq.setTicket(ticket);
Authenticator authenticator = makeAuthenticator(credential, subKey);
apReq.setAuthenticator(authenticator);
EncryptedData authnData = EncryptionUtil.seal(authenticator,
credential.getKey(), KeyUsage.AP_REQ_AUTH);
apReq.setEncryptedAuthenticator(authnData);
return apReq;
}
/**
* Prepare FAST armor key.
* @return
* @throws KrbException
*/
private EncryptionKey makeArmorKey(EncryptionKey subKey, EncryptionKey armorCacheKey)
throws KrbException {
EncryptionKey armorKey = FastUtil.makeArmorKey(subKey, armorCacheKey);
return armorKey;
}
private EncryptionKey getSubKey(EncryptionType type) throws KrbException {
return EncryptionHandler.random2Key(type);
}
/**
* Get armor cache key.
* @return armor cache key
* @throws KrbException
*/
private EncryptionKey getArmorCacheKey(Credential credential) throws KrbException {
EncryptionKey armorCacheKey = credential.getKey();
return armorCacheKey;
}
protected Authenticator makeAuthenticator(Credential credential,
EncryptionKey subKey) throws KrbException {
Authenticator authenticator = new Authenticator();
authenticator.setAuthenticatorVno(5);
authenticator.setCname(credential.getClientName());
authenticator.setCrealm(credential.getClientRealm());
authenticator.setCtime(KerberosTime.now());
authenticator.setCusec(0);
authenticator.setSubKey(subKey);
KdcReqBody reqBody = kdcRequest.getReqBody(null);
CheckSum checksum = CheckSumUtil.seal(reqBody, null,
subKey, KeyUsage.TGS_REQ_AUTH_CKSUM);
authenticator.setCksum(checksum);
return authenticator;
}
}
| 235 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/ArmoredTgsRequest.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
public class ArmoredTgsRequest extends TgsRequest {
private final ArmoredRequest armoredRequest;
public ArmoredTgsRequest(KrbContext context) {
super(context);
armoredRequest = new ArmoredRequest(this);
}
@Override
public void process() throws KrbException {
super.process();
armoredRequest.process();
}
@Override
protected void preauth() throws KrbException {
armoredRequest.preauth();
super.preauth();
}
@Override
public KOptions getPreauthOptions() {
return armoredRequest.getPreauthOptions();
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return armoredRequest.getClientKey();
}
@Override
public EncryptionKey getSessionKey() {
return armoredRequest.getArmorCacheKey();
}
}
| 236 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/TgsRequestWithToken.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.client.request;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
/**
* Tgs request with an Access Token.
*/
public class TgsRequestWithToken extends ArmoredTgsRequest {
public TgsRequestWithToken(KrbContext context) throws KrbException {
super(context);
setAllowedPreauth(PaDataType.TOKEN_REQUEST);
}
@Override
public KOptions getPreauthOptions() {
KOptions results = super.getPreauthOptions();
KOptions krbOptions = getRequestOptions();
results.add(krbOptions.getOption(TokenOption.USE_TOKEN));
results.add(krbOptions.getOption(TokenOption.USER_AC_TOKEN));
return results;
}
@Override
public PrincipalName getClientPrincipal() {
KOption acToken = getPreauthOptions().getOption(TokenOption.USER_AC_TOKEN);
AuthToken authToken = (AuthToken) acToken.getOptionInfo().getValue();
return new PrincipalName(authToken.getSubject());
}
}
| 237 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/KdcRequest.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.client.request;
import org.apache.kerby.KOption;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbKdcOption;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.client.KrbOptionGroup;
import org.apache.kerby.kerberos.kerb.client.preauth.KrbFastRequestState;
import org.apache.kerby.kerberos.kerb.client.preauth.PreauthContext;
import org.apache.kerby.kerberos.kerb.client.preauth.PreauthHandler;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
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.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.HostAddress;
import org.apache.kerby.kerberos.kerb.type.base.HostAddresses;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcOption;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcOptions;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A wrapper for KdcReq request
*/
public abstract class KdcRequest {
protected Map<String, Object> credCache;
private KrbContext context;
private Object sessionData;
private KOptions requestOptions;
private PrincipalName serverPrincipal;
private List<HostAddress> hostAddresses = new ArrayList<>();
private KdcOptions kdcOptions = new KdcOptions();
private List<EncryptionType> encryptionTypes;
private EncryptionType chosenEncryptionType;
private int chosenNonce;
private KdcReq kdcReq;
private KdcReqBody reqBody;
private KdcRep kdcRep;
private PreauthContext preauthContext;
private KrbFastRequestState fastRequestState;
private EncryptionKey asKey;
private byte[] outerRequestBody;
private boolean isRetrying;
public KdcRequest(KrbContext context) {
this.context = context;
this.isRetrying = false;
this.credCache = new HashMap<>();
this.preauthContext = context.getPreauthHandler()
.preparePreauthContext(this);
this.fastRequestState = new KrbFastRequestState();
}
public KrbFastRequestState getFastRequestState() {
return fastRequestState;
}
public void setFastRequestState(KrbFastRequestState state) {
this.fastRequestState = state;
}
public byte[] getOuterRequestBody() {
return outerRequestBody.clone();
}
public void setOuterRequestBody(byte[] outerRequestBody) {
this.outerRequestBody = outerRequestBody.clone();
}
public Object getSessionData() {
return this.sessionData;
}
public void setSessionData(Object sessionData) {
this.sessionData = sessionData;
}
public KOptions getRequestOptions() {
return requestOptions;
}
public void setRequestOptions(KOptions options) {
this.requestOptions = options;
}
public boolean isRetrying() {
return isRetrying;
}
public EncryptionKey getAsKey() throws KrbException {
return asKey;
}
public void setAsKey(EncryptionKey asKey) {
this.asKey = asKey;
}
public void setAllowedPreauth(PaDataType paType) {
preauthContext.setAllowedPaType(paType);
}
public Map<String, Object> getCredCache() {
return credCache;
}
public void setPreauthRequired(boolean preauthRequired) {
preauthContext.setPreauthRequired(preauthRequired);
}
public void resetPrequthContxt() {
preauthContext.reset();
}
public PreauthContext getPreauthContext() {
return preauthContext;
}
public KdcReq getKdcReq() {
return kdcReq;
}
public void setKdcReq(KdcReq kdcReq) {
this.kdcReq = kdcReq;
}
protected KdcReqBody getReqBody(KerberosTime renewTill) throws KrbException {
if (reqBody == null) {
reqBody = makeReqBody(renewTill);
}
return reqBody;
}
public KdcRep getKdcRep() {
return kdcRep;
}
public void setKdcRep(KdcRep kdcRep) {
this.kdcRep = kdcRep;
}
protected KdcReqBody makeReqBody(KerberosTime renewTill) throws KrbException {
KdcReqBody body = new KdcReqBody();
long startTime = System.currentTimeMillis();
body.setFrom(new KerberosTime(startTime));
PrincipalName cName = getClientPrincipal();
body.setCname(cName);
PrincipalName sName = getServerPrincipal();
body.setSname(sName);
String realm = getContext().getKrbSetting().getKdcRealm();
if (sName != null && sName.getRealm() != null) {
realm = sName.getRealm();
}
body.setRealm(realm);
long tillTime = startTime + getTicketValidTime();
body.setTill(new KerberosTime(tillTime));
KerberosTime rtime;
if (renewTill != null) {
rtime = renewTill;
} else {
long renewLifetime;
if (getRequestOptions().contains(KrbOption.RENEWABLE_TIME)) {
renewLifetime = getRequestOptions().getIntegerOption(KrbOption.RENEWABLE_TIME);
} else {
String renewLifetimeStr = getContext().getKrbSetting().getKrbConfig().getRenewLifetime();
renewLifetime = KOptions.parseDuration(renewLifetimeStr);
}
rtime = new KerberosTime(startTime + renewLifetime * 1000);
}
body.setRtime(rtime);
int nonce = generateNonce();
body.setNonce(nonce);
setChosenNonce(nonce);
body.setKdcOptions(getKdcOptions());
HostAddresses addresses = getHostAddresses();
if (addresses != null) {
body.setAddresses(addresses);
}
body.setEtypes(getEncryptionTypes());
return body;
}
public KdcOptions getKdcOptions() {
return kdcOptions;
}
public void setKdcOptions(KdcOptions kdcOptions) {
this.kdcOptions = kdcOptions;
}
public HostAddresses getHostAddresses() {
HostAddresses addresses = null;
if (!hostAddresses.isEmpty()) {
addresses = new HostAddresses();
for (HostAddress ha : hostAddresses) {
addresses.addElement(ha);
}
}
return addresses;
}
public void setHostAddresses(List<HostAddress> hostAddresses) {
this.hostAddresses = hostAddresses;
}
public KrbContext getContext() {
return context;
}
public void setContext(KrbContext context) {
this.context = context;
}
protected byte[] decryptWithClientKey(EncryptedData data,
KeyUsage usage) throws KrbException {
EncryptionKey tmpKey = getClientKey();
if (tmpKey == null) {
throw new KrbException("Client key isn't availalbe");
}
return EncryptionHandler.decrypt(data, tmpKey, usage);
}
public abstract PrincipalName getClientPrincipal();
public PrincipalName getServerPrincipal() {
return serverPrincipal;
}
public void setServerPrincipal(PrincipalName serverPrincipal) {
this.serverPrincipal = serverPrincipal;
}
public List<EncryptionType> getEncryptionTypes() {
if (encryptionTypes == null) {
encryptionTypes = context.getConfig().getEncryptionTypes();
}
return EncryptionUtil.orderEtypesByStrength(encryptionTypes);
}
public void setEncryptionTypes(List<EncryptionType> encryptionTypes) {
this.encryptionTypes = encryptionTypes;
}
public EncryptionType getChosenEncryptionType() {
return chosenEncryptionType;
}
public void setChosenEncryptionType(EncryptionType chosenEncryptionType) {
this.chosenEncryptionType = chosenEncryptionType;
}
public int generateNonce() {
return context.generateNonce();
}
public int getChosenNonce() {
return chosenNonce;
}
public void setChosenNonce(int nonce) {
this.chosenNonce = nonce;
}
public abstract EncryptionKey getClientKey() throws KrbException;
public long getTicketValidTime() {
if (getRequestOptions().contains(KrbOption.LIFE_TIME)) {
return getRequestOptions().getIntegerOption(KrbOption.LIFE_TIME) * 1000L;
} else {
return context.getTicketValidTime();
}
}
public KerberosTime getTicketTillTime() {
long now = System.currentTimeMillis();
return new KerberosTime(now + (long) KerberosTime.MINUTE * 60 * 1000);
}
public void addHost(String hostNameOrIpAddress) throws UnknownHostException {
InetAddress address = InetAddress.getByName(hostNameOrIpAddress);
hostAddresses.add(new HostAddress(address));
}
public void process() throws KrbException {
processKdcOptions();
preauth();
}
public abstract void processResponse(KdcRep kdcRep) throws KrbException;
public KOptions getPreauthOptions() {
return new KOptions();
}
protected void preauth() throws KrbException {
List<EncryptionType> etypes = getEncryptionTypes();
if (etypes.isEmpty()) {
throw new KrbException("No encryption type is configured and available");
}
EncryptionType encryptionType = etypes.iterator().next();
setChosenEncryptionType(encryptionType);
getPreauthHandler().preauth(this);
}
protected PreauthHandler getPreauthHandler() {
return getContext().getPreauthHandler();
}
/**
* Indicate interest in the AS key.
* @throws KrbException e
*/
public void needAsKey() throws KrbException {
EncryptionKey clientKey = getClientKey();
if (clientKey == null) {
throw new RuntimeException("Client key should be prepared or prompted at this time!");
}
setAsKey(clientKey);
}
/**
* Get the enctype expected to be used to encrypt the encrypted portion of
* the AS_REP packet. When handling a PREAUTH_REQUIRED error, this
* typically comes from etype-info2. When handling an AS reply, it is
* initialized from the AS reply itself.
* @return The encryption type
*/
public EncryptionType getEncType() {
return getChosenEncryptionType();
}
public void askQuestion(String question, String challenge) {
preauthContext.getUserResponser().askQuestion(question, challenge);
}
/**
* Get a pointer to the FAST armor key, or NULL if the client is not using FAST.
* @return The encryption key
*/
public EncryptionKey getArmorKey() {
return fastRequestState.getArmorKey();
}
/**
* Get the current time for use in a preauth response. If
* allow_unauth_time is true and the library has been configured to allow
* it, the current time will be offset using unauthenticated timestamp
* information received from the KDC in the preauth-required error, if one
* has been received. Otherwise, the timestamp in a preauth-required error
* will only be used if it is protected by a FAST channel. Only set
* allow_unauth_time if using an unauthenticated time offset would not
* create a security issue.
* @return The current kerberos time
*/
public KerberosTime getPreauthTime() {
return KerberosTime.now();
}
/**
* Get a state item from an input ccache, which may allow it
* to retrace the steps it took last time. The returned data string is an
* alias and should not be freed.
* @param key The key string
* @return The item
*/
public Object getCacheValue(String key) {
return credCache.get(key);
}
/**
* Set a state item which will be recorded to an output
* ccache, if the calling application supplied one. Both key and data
* should be valid UTF-8 text.
* @param key The key string
* @param value The value
*/
public void cacheValue(String key, Object value) {
credCache.put(key, value);
}
protected void processKdcOptions() {
// By default enforce these flags
kdcOptions.setFlag(KdcOption.FORWARDABLE);
kdcOptions.setFlag(KdcOption.PROXIABLE);
kdcOptions.setFlag(KdcOption.RENEWABLE_OK);
for (KOption kOpt: requestOptions.getOptions()) {
if (kOpt.getOptionInfo().getGroup() == KrbOptionGroup.KDC_FLAGS) {
KrbKdcOption krbKdcOption = (KrbKdcOption) kOpt;
boolean flagValue = requestOptions.getBooleanOption(kOpt, true);
if (kOpt.equals(KrbKdcOption.NOT_FORWARDABLE)) {
krbKdcOption = KrbKdcOption.FORWARDABLE;
flagValue = !flagValue;
}
if (kOpt.equals(KrbKdcOption.NOT_PROXIABLE)) {
krbKdcOption = KrbKdcOption.PROXIABLE;
flagValue = !flagValue;
}
KdcOption kdcOption = KdcOption.valueOf(krbKdcOption.name());
kdcOptions.setFlag(kdcOption, flagValue);
}
}
}
} | 238 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/TgsRequest.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.client.request;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
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.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.kdc.EncTgsRepPart;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.kdc.TgsRep;
import org.apache.kerby.kerberos.kerb.type.kdc.TgsReq;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TgsRequest extends KdcRequest {
private static final Logger LOG = LoggerFactory.getLogger(TgsRequest.class);
public TgsRequest(KrbContext context) {
super(context);
}
@Override
public PrincipalName getClientPrincipal() {
return null;
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return null;
}
public EncryptionKey getSessionKey() {
return null;
}
@Override
public void process() throws KrbException {
if (getServerPrincipal() == null) {
String serverPrincipalString = getRequestOptions().getStringOption(KrbOption.SERVER_PRINCIPAL);
if (serverPrincipalString == null) {
LOG.warn("Server principal is null.");
}
setServerPrincipal(new PrincipalName(serverPrincipalString));
}
super.process();
TgsReq tgsReq = new TgsReq();
KdcReqBody tgsReqBody = getReqBody(null);
tgsReq.setReqBody(tgsReqBody);
tgsReq.setPaData(getPreauthContext().getOutputPaData());
setKdcReq(tgsReq);
}
@Override
public void processResponse(KdcRep kdcRep) throws KrbException {
setKdcRep(kdcRep);
TgsRep tgsRep = (TgsRep) getKdcRep();
EncTgsRepPart encTgsRepPart;
try {
encTgsRepPart = EncryptionUtil.unseal(tgsRep.getEncryptedEncPart(),
getSessionKey(),
KeyUsage.TGS_REP_ENCPART_SESSKEY, EncTgsRepPart.class);
} catch (KrbException e) {
encTgsRepPart = EncryptionUtil.unseal(tgsRep.getEncryptedEncPart(),
getSessionKey(),
KeyUsage.TGS_REP_ENCPART_SUBKEY, EncTgsRepPart.class);
}
tgsRep.setEncPart(encTgsRepPart);
if (getChosenNonce() != encTgsRepPart.getNonce()) {
LOG.error("Nonce " + getChosenNonce() + "didn't match " + encTgsRepPart.getNonce());
throw new KrbException("Nonce didn't match");
}
}
public SgtTicket getSgt() {
SgtTicket serviceTkt = new SgtTicket(getKdcRep().getTicket(),
(EncTgsRepPart) getKdcRep().getEncPart());
return serviceTkt;
}
}
| 239 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/TgsRequestWithTgt.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.client.request;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbKdcOption;
import org.apache.kerby.kerberos.kerb.common.CheckSumUtil;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.ap.ApOptions;
import org.apache.kerby.kerberos.kerb.type.ap.ApReq;
import org.apache.kerby.kerberos.kerb.type.ap.Authenticator;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
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.PrincipalName;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
import org.apache.kerby.kerberos.kerb.type.ticket.KrbTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
public class TgsRequestWithTgt extends TgsRequest {
private ApReq apReq;
private KrbTicket ticket;
private PrincipalName clientPrincipal;
public TgsRequestWithTgt(KrbContext context, TgtTicket tgt) {
super(context);
setAllowedPreauth(PaDataType.TGS_REQ);
ticket = tgt;
clientPrincipal = tgt.getClientPrincipal();
if (clientPrincipal.getRealm() == null) {
clientPrincipal.setRealm(tgt.getRealm());
}
}
public TgsRequestWithTgt(KrbContext context, SgtTicket sgt) {
super(context);
setAllowedPreauth(PaDataType.TGS_REQ);
ticket = sgt;
clientPrincipal = sgt.getClientPrincipal();
if (clientPrincipal.getRealm() == null) {
clientPrincipal.setRealm(sgt.getRealm());
}
}
public PrincipalName getClientPrincipal() {
return clientPrincipal;
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return getSessionKey();
}
@Override
public EncryptionKey getSessionKey() {
return ticket.getSessionKey();
}
private ApReq makeApReq() throws KrbException {
ApReq apReq = new ApReq();
Authenticator authenticator = makeAuthenticator();
EncryptionKey sessionKey = ticket.getSessionKey();
EncryptedData authnData = EncryptionUtil.seal(authenticator,
sessionKey, KeyUsage.TGS_REQ_AUTH);
apReq.setEncryptedAuthenticator(authnData);
apReq.setAuthenticator(authenticator);
apReq.setTicket(ticket.getTicket());
ApOptions apOptions = new ApOptions();
apReq.setApOptions(apOptions);
return apReq;
}
public ApReq getApReq() throws KrbException {
if (apReq == null) {
apReq = makeApReq();
}
return apReq;
}
private Authenticator makeAuthenticator() throws KrbException {
Authenticator authenticator = new Authenticator();
authenticator.setAuthenticatorVno(5);
authenticator.setCname(clientPrincipal);
authenticator.setCrealm(clientPrincipal.getRealm());
authenticator.setCtime(KerberosTime.now());
authenticator.setCusec(0);
authenticator.setSubKey(ticket.getSessionKey());
KerberosTime renewTill = null;
if (getRequestOptions().contains(KrbKdcOption.RENEW)) {
renewTill = ticket.getEncKdcRepPart().getRenewTill();
}
KdcReqBody reqBody = getReqBody(renewTill);
CheckSum checksum = CheckSumUtil.seal(reqBody, null,
ticket.getSessionKey(), KeyUsage.TGS_REQ_AUTH_CKSUM);
authenticator.setCksum(checksum);
return authenticator;
}
}
| 240 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/AsRequestWithKeytab.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.keytab.Keytab;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
import java.io.File;
import java.io.IOException;
public class AsRequestWithKeytab extends AsRequest {
public AsRequestWithKeytab(KrbContext context) {
super(context);
setAllowedPreauth(PaDataType.ENC_TIMESTAMP);
}
private Keytab getKeytab() {
File keytabFile = null;
KOptions kOptions = getRequestOptions();
if (kOptions.contains(KrbOption.KEYTAB_FILE)) {
keytabFile = kOptions.getFileOption(KrbOption.KEYTAB_FILE);
}
if (kOptions.contains(KrbOption.USE_DFT_KEYTAB)) {
final String clientKeytabEnv = System.getenv("KRB5_CLIENT_KTNAME");
final String clientKeytabDft = getContext().getConfig().getString(
"default_client_keytab_name");
if (clientKeytabEnv != null) {
keytabFile = new File(clientKeytabEnv);
} else if (clientKeytabDft != null) {
keytabFile = new File(clientKeytabDft);
} else {
System.err.println("Default client keytab file not found.");
}
}
Keytab keytab = null;
try {
keytab = Keytab.loadKeytab(keytabFile);
} catch (IOException e) {
String path = keytabFile != null ? keytabFile.getAbsolutePath() : "";
System.err.println("Can not load keytab from file" + path);
}
return keytab;
}
@Override
public EncryptionKey getClientKey() throws KrbException {
if (super.getClientKey() == null) {
EncryptionKey tmpKey = getKeytab().getKey(getClientPrincipal(),
getChosenEncryptionType());
setClientKey(tmpKey);
}
return super.getClientKey();
}
}
| 241 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/AsRequestWithCert.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.PkinitOption;
import org.apache.kerby.kerberos.kerb.client.preauth.PreauthContext;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.kdc.AsReq;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcOption;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
public class AsRequestWithCert extends AsRequest {
public static final String ANONYMOUS_PRINCIPAL = "ANONYMOUS@WELLKNOWN:ANONYMOUS";
public AsRequestWithCert(KrbContext context) {
super(context);
setAllowedPreauth(PaDataType.PK_AS_REQ);
}
@Override
public void process() throws KrbException {
KdcReqBody body = getReqBody(null);
AsReq asReq = new AsReq();
asReq.setReqBody(body);
setKdcReq(asReq);
preauth();
asReq.setPaData(getPreauthContext().getOutputPaData());
setKdcReq(asReq);
}
@Override
public KOptions getPreauthOptions() {
KOptions results = new KOptions();
KOptions krbOptions = getRequestOptions();
results.add(krbOptions.getOption(PkinitOption.X509_CERTIFICATE));
results.add(krbOptions.getOption(PkinitOption.X509_ANCHORS));
results.add(krbOptions.getOption(PkinitOption.X509_PRIVATE_KEY));
results.add(krbOptions.getOption(PkinitOption.X509_IDENTITY));
results.add(krbOptions.getOption(PkinitOption.USING_RSA));
if (krbOptions.contains(PkinitOption.USE_ANONYMOUS)) {
getKdcOptions().setFlag(KdcOption.REQUEST_ANONYMOUS);
}
return results;
}
@Override
public void processResponse(KdcRep kdcRep) throws KrbException {
PreauthContext preauthContext = getPreauthContext();
preauthContext.setInputPaData(kdcRep.getPaData());
preauth();
super.processResponse(kdcRep);
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return getAsKey();
}
}
| 242 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/ArmoredAsRequest.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.client.request;
import org.apache.kerby.KOptions;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
/**
* This initiates an armor protected AS-REQ using FAST/Pre-auth.
*/
public abstract class ArmoredAsRequest extends AsRequest {
private final ArmoredRequest armoredRequest;
public ArmoredAsRequest(KrbContext context) {
super(context);
armoredRequest = new ArmoredRequest(this);
}
@Override
public void process() throws KrbException {
super.process();
armoredRequest.process();
}
@Override
protected void preauth() throws KrbException {
armoredRequest.preauth();
super.preauth();
}
@Override
public KOptions getPreauthOptions() {
return armoredRequest.getPreauthOptions();
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return armoredRequest.getClientKey();
}
} | 243 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/AsRequest.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.client.request;
import org.apache.kerby.kerberos.kerb.KrbErrorCode;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.PkinitOption;
import org.apache.kerby.kerberos.kerb.client.TokenOption;
import org.apache.kerby.kerberos.kerb.common.KrbUtil;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.HostAddress;
import org.apache.kerby.kerberos.kerb.type.base.HostAddresses;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
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.EncAsRepPart;
import org.apache.kerby.kerberos.kerb.type.kdc.EncKdcRepPart;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcRep;
import org.apache.kerby.kerberos.kerb.type.kdc.KdcReqBody;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class AsRequest extends KdcRequest {
private PrincipalName clientPrincipal;
private EncryptionKey clientKey;
public AsRequest(KrbContext context) {
super(context);
setServerPrincipal(makeTgsPrincipal());
}
public PrincipalName getClientPrincipal() {
return clientPrincipal;
}
public void setClientPrincipal(PrincipalName clientPrincipal) {
this.clientPrincipal = clientPrincipal;
}
public void setClientKey(EncryptionKey clientKey) {
this.clientKey = clientKey;
}
@Override
public EncryptionKey getClientKey() throws KrbException {
return clientKey;
}
@Override
public void process() throws KrbException {
super.process();
KdcReqBody body = getReqBody(null);
AsReq asReq = new AsReq();
asReq.setReqBody(body);
asReq.setPaData(getPreauthContext().getOutputPaData());
setKdcReq(asReq);
}
@Override
public void processResponse(KdcRep kdcRep) throws KrbException {
setKdcRep(kdcRep);
PrincipalName clientPrincipal = getKdcRep().getCname();
String clientRealm = getKdcRep().getCrealm();
clientPrincipal.setRealm(clientRealm);
if (!(getRequestOptions().contains(PkinitOption.USE_ANONYMOUS)
&& KrbUtil.pricipalCompareIgnoreRealm(clientPrincipal, getClientPrincipal()))
&& !getRequestOptions().contains(TokenOption.USER_ID_TOKEN)
&& !clientPrincipal.equals(getClientPrincipal())) {
throw new KrbException(KrbErrorCode.KDC_ERR_CLIENT_NAME_MISMATCH);
}
byte[] decryptedData = decryptWithClientKey(getKdcRep().getEncryptedEncPart(),
KeyUsage.AS_REP_ENCPART);
if ((decryptedData[0] & 0x1f) == 26) {
decryptedData[0] = (byte) (decryptedData[0] - 1);
}
EncKdcRepPart encKdcRepPart = new EncAsRepPart();
try {
encKdcRepPart.decode(decryptedData);
} catch (IOException e) {
throw new KrbException("Failed to decode EncAsRepPart", e);
}
getKdcRep().setEncPart(encKdcRepPart);
if (getChosenNonce() != encKdcRepPart.getNonce()) {
throw new KrbException("Nonce didn't match");
}
PrincipalName returnedServerPrincipal = encKdcRepPart.getSname();
returnedServerPrincipal.setRealm(encKdcRepPart.getSrealm());
PrincipalName requestedServerPrincipal = getServerPrincipal();
if (requestedServerPrincipal.getRealm() == null) {
requestedServerPrincipal.setRealm(getContext().getKrbSetting().getKdcRealm());
}
if (!returnedServerPrincipal.equals(requestedServerPrincipal)) {
throw new KrbException(KrbErrorCode.KDC_ERR_SERVER_NOMATCH);
}
HostAddresses hostAddresses = getHostAddresses();
if (hostAddresses != null) {
List<HostAddress> requestHosts = hostAddresses.getElements();
if (!requestHosts.isEmpty()) {
List<HostAddress> responseHosts = encKdcRepPart.getCaddr().getElements();
for (HostAddress h : requestHosts) {
if (!responseHosts.contains(h)) {
throw new KrbException("Unexpected client host");
}
}
}
}
}
public TgtTicket getTicket() {
TgtTicket tgtTicket = new TgtTicket(getKdcRep().getTicket(),
(EncAsRepPart) getKdcRep().getEncPart(), getKdcRep().getCname());
return tgtTicket;
}
private PrincipalName makeTgsPrincipal() {
return KrbUtil.makeTgsPrincipal(getContext().getKrbSetting().getKdcRealm());
}
protected CredentialCache resolveCredCache(File ccacheFile) throws IOException {
CredentialCache cc = new CredentialCache();
cc.load(ccacheFile);
return cc;
}
} | 244 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/request/AsRequestWithPasswd.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.client.request;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbContext;
import org.apache.kerby.kerberos.kerb.client.KrbOption;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.pa.PaDataType;
public class AsRequestWithPasswd extends AsRequest {
public AsRequestWithPasswd(KrbContext context) {
super(context);
setAllowedPreauth(PaDataType.ENC_TIMESTAMP);
}
public String getPassword() {
return getRequestOptions().getStringOption(KrbOption.USER_PASSWD);
}
@Override
public EncryptionKey getClientKey() throws KrbException {
if (super.getClientKey() == null) {
EncryptionKey tmpKey = EncryptionHandler.string2Key(getClientPrincipal().getName(),
getPassword(), getChosenEncryptionType());
setClientKey(tmpKey);
}
return super.getClientKey();
}
}
| 245 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/jaas/TokenAuthLoginModule.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.client.jaas;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.KrbRuntime;
import org.apache.kerby.kerberos.kerb.client.KrbClient;
import org.apache.kerby.kerberos.kerb.client.KrbConfig;
import org.apache.kerby.kerberos.kerb.client.KrbTokenClient;
import org.apache.kerby.kerberos.kerb.common.PrivateKeyReader;
import org.apache.kerby.kerberos.kerb.provider.TokenDecoder;
import org.apache.kerby.kerberos.kerb.provider.TokenEncoder;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
import org.apache.kerby.kerberos.kerb.type.base.KrbToken;
import org.apache.kerby.kerberos.kerb.type.base.TokenFormat;
import org.apache.kerby.kerberos.kerb.type.kdc.EncKdcRepPart;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.apache.kerby.kerberos.provider.token.JwtAuthToken;
import org.apache.kerby.kerberos.provider.token.JwtTokenEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
/**
* This <code>LoginModule</code> authenticates users using token.
* tokenStr: token-string
* tokenCache: token-cache-file
* armorCache: armor-cache-file
*/
public class TokenAuthLoginModule implements LoginModule {
public static final String PRINCIPAL = "principal";
public static final String TOKEN = "token";
public static final String TOKEN_CACHE = "tokenCache";
public static final String ARMOR_CACHE = "armorCache";
public static final String CREDENTIAL_CACHE = "credentialCache";
public static final String SIGN_KEY_FILE = "signKeyFile";
private static final Logger LOG = LoggerFactory.getLogger(TokenAuthLoginModule.class);
/** initial state*/
private Subject subject;
/** configurable option*/
private String tokenCacheName = null;
/** the authentication status*/
private boolean succeeded = false;
private boolean commitSucceeded = false;
private String princName = null;
private String tokenStr = null;
private AuthToken authToken = null;
private KrbToken krbToken = null;
private File armorCache;
private File cCache;
private File signKeyFile;
private TgtTicket tgtTicket;
/**
* {@inheritDoc}
*/
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
/** initialize any configured options*/
princName = (String) options.get(PRINCIPAL);
tokenStr = (String) options.get(TOKEN);
tokenCacheName = (String) options.get(TOKEN_CACHE);
if ((String) options.get(ARMOR_CACHE) != null) {
armorCache = new File((String) options.get(ARMOR_CACHE));
}
if ((String) options.get(CREDENTIAL_CACHE) != null) {
cCache = new File((String) options.get(CREDENTIAL_CACHE));
}
if ((String) options.get(SIGN_KEY_FILE) != null) {
signKeyFile = new File((String) options.get(SIGN_KEY_FILE));
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean login() throws LoginException {
validateConfiguration();
succeeded = tokenLogin();
return succeeded;
}
/**
* {@inheritDoc}
*/
@Override
public boolean commit() throws LoginException {
if (!succeeded) {
cleanup();
return false;
} else {
KerberosTicket ticket = null;
try {
EncKdcRepPart encKdcRepPart = tgtTicket.getEncKdcRepPart();
boolean[] flags = new boolean[7];
int flag = encKdcRepPart.getFlags().getFlags();
for (int i = 6; i >= 0; i--) {
flags[i] = (flag & (1 << i)) != 0;
}
Date startTime = null;
if (encKdcRepPart.getStartTime() != null) {
startTime = encKdcRepPart.getStartTime().getValue();
}
ticket = new KerberosTicket(tgtTicket.getTicket().encode(),
new KerberosPrincipal(tgtTicket.getClientPrincipal().getName()),
new KerberosPrincipal(tgtTicket.getEncKdcRepPart().getSname().getName()),
encKdcRepPart.getKey().getKeyData(),
encKdcRepPart.getKey().getKeyType().getValue(),
flags,
encKdcRepPart.getAuthTime().getValue(),
startTime,
encKdcRepPart.getEndTime().getValue(),
encKdcRepPart.getRenewTill().getValue(),
null
);
} catch (IOException e) {
LOG.error("Commit Failed. " + e.toString());
}
subject.getPrivateCredentials().add(ticket);
if (princName != null) {
subject.getPrincipals().add(new KerberosPrincipal(princName));
}
}
commitSucceeded = true;
LOG.info("Commit Succeeded \n");
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean abort() throws LoginException {
if (!succeeded) {
return false;
} else if (succeeded && commitSucceeded) {
// we succeeded, but another required module failed
logout();
} else {
// our commit failed
succeeded = false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean logout() throws LoginException {
LOG.info("\t\t[TokenAuthLoginModule]: Entering logout");
if (subject.isReadOnly()) {
throw new LoginException("Subject is Readonly");
}
for (Principal principal: subject.getPrincipals()) {
if (principal.getName().equals(princName)) {
subject.getPrincipals().remove(principal);
}
}
// Let us remove all Kerberos credentials stored in the Subject
Iterator<Object> it = subject.getPrivateCredentials().iterator();
while (it.hasNext()) {
Object o = it.next();
if (o instanceof KrbToken) {
it.remove();
}
}
cleanup();
succeeded = false;
commitSucceeded = false;
LOG.info("\t\t[TokenAuthLoginModule]: logged out Subject");
return true;
}
private void validateConfiguration() throws LoginException {
if (armorCache == null) {
throw new LoginException("An armor cache must be specified via the armorCache configuration option");
}
if (cCache == null) {
LOG.info("No credential cache was specified via 'credentialCache'. "
+ "The TGT will be stored internally instead");
}
String error = "";
if (tokenStr == null && tokenCacheName == null) {
error = "useToken is specified but no token or token cache is provided";
} else if (tokenStr != null && tokenCacheName != null) {
error = "either token or token cache should be provided but not both";
}
if (!error.isEmpty()) {
throw new LoginException(error);
}
}
private boolean tokenLogin() throws LoginException {
if (tokenStr == null) {
tokenStr = TokenCache.readToken(tokenCacheName);
if (tokenStr == null) {
throw new LoginException("No valid token was found in token cache: " + tokenCacheName);
}
}
krbToken = new KrbToken();
// Sign the token.
if (signKeyFile != null) {
try {
TokenDecoder tokenDecoder = KrbRuntime.getTokenProvider("JWT").createTokenDecoder();
try {
authToken = tokenDecoder.decodeFromString(tokenStr);
} catch (IOException e) {
LOG.error("Token decode failed. " + e.toString());
}
TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
if (tokenEncoder instanceof JwtTokenEncoder) {
PrivateKey signKey = null;
try (InputStream is = Files.newInputStream(signKeyFile.toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
} catch (IOException e) {
LOG.error("Failed to load private key from file: "
+ signKeyFile.getName());
} catch (Exception e) {
LOG.error(e.toString());
}
((JwtTokenEncoder) tokenEncoder).setSignKey((RSAPrivateKey) signKey);
}
krbToken.setTokenValue(tokenEncoder.encodeAsBytes(authToken));
} catch (KrbException e) {
throw new RuntimeException("Failed to encode AuthToken", e);
}
} else {
// Otherwise just write out the token (which could be already signed)
krbToken.setTokenValue(tokenStr.getBytes());
if (authToken == null) {
try {
JWT jwt = JWTParser.parse(tokenStr);
authToken = new JwtAuthToken(jwt.getJWTClaimsSet());
} catch (ParseException e) {
// Invalid JWT encoding
throw new RuntimeException("Failed to parse JWT token string", e);
}
}
}
krbToken.setInnerToken(authToken);
krbToken.setTokenType();
krbToken.setTokenFormat(TokenFormat.JWT);
KrbClient krbClient = null;
try {
File confFile = new File(System.getProperty("java.security.krb5.conf"));
KrbConfig krbConfig = new KrbConfig();
krbConfig.addKrb5Config(confFile);
krbClient = new KrbClient(krbConfig);
krbClient.init();
} catch (KrbException | IOException e) {
LOG.error("KrbClient init failed. " + e.toString());
throw new RuntimeException("KrbClient init failed", e);
}
KrbTokenClient tokenClient = new KrbTokenClient(krbClient);
try {
tgtTicket = tokenClient.requestTgt(krbToken,
armorCache.getAbsolutePath());
} catch (KrbException e) {
throwWith("Failed to do login with token: " + tokenStr, e);
return false;
}
// Write the TGT out to the credential cache if it is specified in the configuration
if (cCache != null) {
try {
cCache = makeTgtCache();
} catch (IOException e) {
LOG.error("Failed to make tgtCache. " + e.toString());
}
try {
krbClient.storeTicket(tgtTicket, cCache);
} catch (KrbException e) {
LOG.error("Failed to store tgtTicket to " + cCache.getName());
}
}
return true;
}
private File makeTgtCache() throws IOException {
if (!cCache.exists() && !cCache.createNewFile()) {
throw new IOException("Failed to create tgtcache file "
+ cCache.getAbsolutePath());
}
cCache.setExecutable(false);
cCache.setReadable(true);
cCache.setWritable(true);
return cCache;
}
private void cleanup() {
if (cCache != null && cCache.exists()) {
boolean delete = cCache.delete();
if (!delete) {
throw new RuntimeException("File delete error!");
}
}
tgtTicket = null;
krbToken = null;
}
private void throwWith(String error, Exception cause) throws LoginException {
LoginException le = new LoginException(error);
le.initCause(cause);
throw le;
}
}
| 246 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/jaas/TokenJaasKrbUtil.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.client.jaas;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* JAAS utilities for token login.
*/
public class TokenJaasKrbUtil {
/**
* Login using token cache.
*
* @param principal The client principal name
* @param tokenCache the token cache for login
* @param armorCache the armor cache for fast preauth
* @param ccache The file to store the tgt ticket
* @return the authenticated Subject
* @throws LoginException e
*/
public static Subject loginUsingToken(
String principal, File tokenCache, File armorCache, File ccache, File signKeyFile)
throws LoginException {
Subject subject = new Subject(false, new HashSet<Principal>(),
new HashSet<Object>(), new HashSet<Object>());
Configuration conf = useTokenCache(principal, tokenCache, armorCache, ccache, signKeyFile);
String confName = "TokenCacheConf";
LoginContext loginContext = new LoginContext(confName, subject, null, conf);
loginContext.login();
return loginContext.getSubject();
}
/**
* Login using token string.
*
* @param principal The client principal name
* @param tokenStr the token string for login
* @param armorCache the armor cache for fast preauth
* @param ccache The file to store the tgt ticket
* @return the authenticated Subject
* @throws LoginException e
*/
public static Subject loginUsingToken(
String principal, String tokenStr, File armorCache, File ccache, File signKeyFile)
throws LoginException {
Set<Principal> principals = new HashSet<>();
principals.add(new KerberosPrincipal(principal));
Subject subject = new Subject(false, principals,
new HashSet<Object>(), new HashSet<Object>());
Configuration conf = useTokenStr(principal, tokenStr, armorCache, ccache, signKeyFile);
String confName = "TokenStrConf";
LoginContext loginContext = new LoginContext(confName, subject, null, conf);
loginContext.login();
return loginContext.getSubject();
}
private static Configuration useTokenCache(String principal, File tokenCache,
File armorCache, File tgtCache, File signKeyFile) {
return new TokenJaasConf(principal, tokenCache, armorCache, tgtCache, signKeyFile);
}
private static Configuration useTokenStr(String principal, String tokenStr,
File armorCache, File tgtCache, File signKeyFile) {
return new TokenJaasConf(principal, tokenStr, armorCache, tgtCache, signKeyFile);
}
/**
* Token Jaas config.
*/
static class TokenJaasConf extends Configuration {
private String principal;
private File tokenCache;
private String tokenStr;
private File armorCache;
private File ccache;
private File signKeyFile;
TokenJaasConf(String principal, File tokenCache, File armorCache, File ccache,
File signKeyFile) {
this.principal = principal;
this.tokenCache = tokenCache;
this.armorCache = armorCache;
this.ccache = ccache;
this.signKeyFile = signKeyFile;
}
TokenJaasConf(String principal, String tokenStr, File armorCache, File ccache,
File signKeyFile) {
this.principal = principal;
this.tokenStr = tokenStr;
this.armorCache = armorCache;
this.ccache = ccache;
this.signKeyFile = signKeyFile;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<>();
options.put(TokenAuthLoginModule.PRINCIPAL, principal);
if (tokenCache != null) {
options.put(TokenAuthLoginModule.TOKEN_CACHE, tokenCache.getAbsolutePath());
} else if (tokenStr != null) {
options.put(TokenAuthLoginModule.TOKEN, tokenStr);
}
options.put(TokenAuthLoginModule.ARMOR_CACHE, armorCache.getAbsolutePath());
if (ccache != null) {
options.put(TokenAuthLoginModule.CREDENTIAL_CACHE, ccache.getAbsolutePath());
}
if (signKeyFile != null) {
options.put(TokenAuthLoginModule.SIGN_KEY_FILE, signKeyFile.getAbsolutePath());
}
return new AppConfigurationEntry[]{
new AppConfigurationEntry(
"org.apache.kerby.kerberos.kerb.client.jaas.TokenAuthLoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
options)};
}
}
}
| 247 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client | Create_ds/directory-kerby/kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/jaas/TokenCache.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.client.jaas;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
/**
* This class provides APIs for converting token cache file with token string.
*/
public class TokenCache {
private static final Logger LOG = LoggerFactory
.getLogger(TokenCache.class);
private static final String DEFAULT_TOKEN_CACHE_PATH = ".tokenauth";
private static final String TOKEN_CACHE_FILE = ".tokenauth.token";
/**
* Obtain token string from token cache file.
*
* @param tokenCacheFile The file stored token
* @return Token string
*/
public static String readToken(String tokenCacheFile) {
File cacheFile;
if (tokenCacheFile != null && !tokenCacheFile.isEmpty()) {
cacheFile = new File(tokenCacheFile);
if (!cacheFile.exists()) {
throw new RuntimeException("Invalid token cache specified: " + tokenCacheFile);
}
} else {
cacheFile = getDefaultTokenCache();
if (!cacheFile.exists()) {
throw new RuntimeException("No token cache available by default");
}
}
String token = null;
try {
List<String> lines = Files.readAllLines(cacheFile.toPath(), StandardCharsets.UTF_8);
if (lines != null && !lines.isEmpty()) {
token = lines.get(0);
}
} catch (IOException ex) {
LOG.error("Failed to read file: " + cacheFile.getName());
}
return token;
}
/**
* Write the token string to token cache file.
*
* @param token The token string
*/
public static void writeToken(String token, String tokenCacheFile) throws IOException {
File cacheFile = new File(tokenCacheFile);
try (Writer writer = new FileWriterWithEncoding(cacheFile, StandardCharsets.UTF_8)) {
writer.write(token);
writer.flush();
// sets read-write permissions to owner only
cacheFile.setReadable(false, false);
cacheFile.setReadable(true, true);
if (!cacheFile.setWritable(true, true)) {
throw new KrbException("Cache file is not readable.");
}
} catch (IOException ioe) {
// if case of any error we just delete the cache, if user-only
// write permissions are not properly set a security exception
// is thrown and the file will be deleted.
if (cacheFile.delete()) {
System.err.println("Cache file is deleted.");
}
} catch (KrbException e) {
LOG.error("Failed to write token to cache File. " + e.toString());
}
}
/**
* Get the default token cache.
*
* @return The default token cache
*/
public static File getDefaultTokenCache() {
String homeDir = System.getProperty("user.home", DEFAULT_TOKEN_CACHE_PATH);
return new File(homeDir, TOKEN_CACHE_FILE);
}
}
| 248 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/TokenLoginWithTokenPreauthEnabledTest.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.integration.test;
import org.apache.kerby.kerberos.kerb.server.KerberosClientExceptionAction;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.security.Principal;
import java.util.Set;
/**
* Test login with token when token preauth is allowed by kdc.
*/
public class TokenLoginWithTokenPreauthEnabledTest extends TokenLoginTestBase {
@Override
protected Boolean isTokenPreauthAllowed() {
return true;
}
@Test
public void testLoginWithTokenStr() throws Exception {
super.testLoginWithTokenStr();
}
@Test
public void testLoginWithTokenCache() throws Exception {
super.testLoginWithTokenCache();
}
@Test
public void testLoginWithTokenCacheGSS() throws Exception {
Subject subject = super.testLoginWithTokenCacheAndRetSubject();
Set<Principal> clientPrincipals = subject.getPrincipals();
// Get the service ticket
KerberosClientExceptionAction action =
new KerberosClientExceptionAction(clientPrincipals.iterator().next(),
getServerPrincipal());
byte[] kerberosToken = (byte[]) Subject.doAs(subject, action);
Assertions.assertNotNull(kerberosToken);
}
@Test
public void testUntrustedSignature() throws Exception {
String tokenStr = createTokenAndArmorCache();
File signKeyFile = new File(this.getClass().getResource("/kdckeytest.pem").getPath());
try {
loginClientUsingTokenStr(tokenStr, getArmorCache(), getTGTCache(), signKeyFile);
Assertions.fail("Failure expected on a signature that is not trusted");
} catch (LoginException ex) { //NOPMD
// expected
}
}
@Test
public void testUnsignedToken() throws Exception {
String tokenStr = createTokenAndArmorCache();
try {
loginClientUsingTokenStr(tokenStr, getArmorCache(), getTGTCache(), null);
Assertions.fail("Failure expected on an unsigned token");
} catch (LoginException ex) { //NOPMD
// expected
}
}
}
| 249 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/NamePasswordCallbackHandler.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.integration.test;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
public class NamePasswordCallbackHandler implements CallbackHandler {
private String username;
private String password;
public NamePasswordCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
}
}
}
} | 250 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/KerbyGssAppTest.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.integration.test;
import org.apache.kerby.kerberos.kerb.gss.KerbyGssProvider;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.security.Provider;
public class KerbyGssAppTest extends GssAppTest {
@BeforeEach
@Override
public void setUp() throws Exception {
Provider provider = new KerbyGssProvider();
java.security.Security.insertProviderAt(provider, 1);
super.setUp();
}
@Test
public void testServerWithoutInitialCredential() throws Exception {
String version = System.getProperty("java.version");
// See DIRKRB-647
if (!version.startsWith("1.7")) {
super.testServerWithoutInitialCredential();
}
}
}
| 251 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/GssAppTest.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.integration.test;
import java.security.PrivilegedAction;
import javax.security.auth.Subject;
import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil;
import org.apache.kerby.kerberos.kerb.integration.test.gss.GssAppClient;
import org.apache.kerby.kerberos.kerb.integration.test.gss.GssAppServer;
import org.apache.kerby.util.NetworkUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GssAppTest extends AppTest {
private static final Logger LOG = LoggerFactory.getLogger(GssAppTest.class);
private int serverPort2;
private int serverPort3;
private AppServer appServer2;
private AppServer appServer3;
@BeforeEach
@Override
public void setUp() throws Exception {
super.setUp();
serverPort2 = NetworkUtil.getServerPort();
serverPort3 = NetworkUtil.getServerPort();
setupAppServer2();
setupAppServer3();
}
@Override
protected AppServer createAppServer() throws Exception {
return new GssAppServer(new String[] {
String.valueOf(getServerPort()),
getServerPrincipal()
});
}
@Test
public void test() throws Exception {
runAppClient(createAppClient());
}
@Test
public void testWithoutInitialCredential() throws Exception {
AppClient appClient = createAppClient();
((GssAppClient) appClient).setCreateContextWithCred(false);
runAppClient(appClient);
}
@Test
public void testServerWithoutInitialCredential() throws Exception {
AppClient appClient =
new GssAppClient(new String[] {
getHostname(),
String.valueOf(serverPort2),
getClientPrincipal(),
getServerPrincipal()
});
runAppClient(appClient);
}
// Here the server is using a password to get a TGT, not a keytab
@Test
public void testServerUsingPassword() throws Exception {
AppClient appClient =
new GssAppClient(new String[] {
getHostname(),
String.valueOf(serverPort3),
getClientPrincipal(),
getServerPrincipal()
});
runAppClient(appClient);
}
private AppClient createAppClient() throws Exception {
return new GssAppClient(new String[] {
getHostname(),
String.valueOf(getServerPort()),
getClientPrincipal(),
getServerPrincipal()
});
}
private void setupAppServer2() throws Exception {
Subject subject = loginServiceUsingKeytab();
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appServer2 =
new GssAppServer(new String[] {
String.valueOf(serverPort2),
getServerPrincipal()
});
((GssAppServer) appServer2).setCreateContextWithCred(false);
appServer2.start();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
}
private void setupAppServer3() throws Exception {
Subject subject = JaasKrbUtil.loginUsingPassword(getServerPrincipal(), getServerPassword());
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appServer3 =
new GssAppServer(new String[] {
String.valueOf(serverPort3),
getServerPrincipal()
});
appServer3.start();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
}
} | 252 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/TokenLoginWithTokenPreauthDisabledTest.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.integration.test;
import javax.security.auth.login.LoginException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test login with token when token preauth is not allowed by kdc.
*/
public class TokenLoginWithTokenPreauthDisabledTest extends TokenLoginTestBase {
@Override
protected Boolean isTokenPreauthAllowed() {
return false;
}
@Test
public void testLoginWithTokenStr() throws Exception {
Assertions.assertThrows(LoginException.class, () -> {
super.testLoginWithTokenStr();
});
}
@Test
public void testLoginWithTokenCache() throws Exception {
Assertions.assertThrows(LoginException.class, () -> {
super.testLoginWithTokenCache();
});
}
} | 253 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/KerbyTokenAppTest.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.integration.test;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.interfaces.RSAPrivateKey;
import java.util.Collections;
import javax.security.auth.Subject;
import org.apache.kerby.kerberos.kerb.KrbRuntime;
import org.apache.kerby.kerberos.kerb.common.PrivateKeyReader;
import org.apache.kerby.kerberos.kerb.gss.KerbyGssProvider;
import org.apache.kerby.kerberos.kerb.integration.test.gss.GssAppClient;
import org.apache.kerby.kerberos.kerb.integration.test.gss.GssAppServer;
import org.apache.kerby.kerberos.kerb.provider.TokenEncoder;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
import org.apache.kerby.kerberos.kerb.type.base.KrbToken;
import org.apache.kerby.kerberos.kerb.type.base.TokenFormat;
import org.apache.kerby.kerberos.provider.token.JwtTokenEncoder;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class KerbyTokenAppTest extends TokenAppTest {
private static final Logger LOG = LoggerFactory.getLogger(KerbyGssAppTest.class);
@BeforeEach
@Override
public void setUp() throws Exception {
Provider provider = new KerbyGssProvider();
java.security.Security.insertProviderAt(provider, 1);
super.setUp();
}
// Here the client is sending a JWT token to the service as an "access token", to be
// inserted into the AuthorizationData part of the service ticket.
@Test
public void testJwtAccessToken() throws Exception {
// See DIRKRB-728 - KerbyTokenAppTest fails with Java 11
String javaVersion = System.getProperty("java.version");
if (javaVersion != null) {
String version = javaVersion.trim();
if (version.contains(".")) {
version = version.substring(0, version.indexOf('.'));
}
Assumptions.assumeFalse(Integer.parseInt(version) >= 9);
}
runAppClientWithToken(createAppClient());
KrbToken receivedToken = ((GssAppServer) appServer).getReceivedAccessToken();
assertNotNull(receivedToken);
assertEquals(getClientPrincipal(), receivedToken.getSubject());
assertEquals(getServerPrincipal(), receivedToken.getAudiences().get(0));
}
private void runAppClientWithToken(final AppClient appClient) throws Exception {
Subject subject = loginClientUsingPassword();
// Get an AuthToken
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
// Sign it
try (InputStream is = this.getClass().getResource("/private_key.pem").openStream()) {
PrivateKey signKey = PrivateKeyReader.loadPrivateKey(is);
krbToken.setTokenValue(signToken(authToken, signKey));
}
// Add KrbToken to the private creds
subject.getPrivateCredentials().add(krbToken);
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appClient.run();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
assertTrue(appClient.isTestOK(), "Client successfully connected and authenticated to server");
}
private byte[] signToken(AuthToken authToken, PrivateKey signKey) throws Exception {
TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
assertTrue(tokenEncoder instanceof JwtTokenEncoder);
((JwtTokenEncoder) tokenEncoder).setSignKey((RSAPrivateKey) signKey);
return tokenEncoder.encodeAsBytes(authToken);
}
@Override
protected AppServer createAppServer() throws Exception {
return new GssAppServer(new String[] {
String.valueOf(getServerPort()),
getServerPrincipal()
});
}
private AppClient createAppClient() throws Exception {
return new GssAppClient(new String[] {
getHostname(),
String.valueOf(getServerPort()),
getClientPrincipal(),
getServerPrincipal()
});
}
}
| 254 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/SaslAppTest.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.integration.test;
import org.apache.kerby.kerberos.kerb.integration.test.sasl.SaslAppClient;
import org.apache.kerby.kerberos.kerb.integration.test.sasl.SaslAppServer;
import org.junit.jupiter.api.Test;
public class SaslAppTest extends AppTest {
@Override
protected AppServer createAppServer() throws Exception {
return new SaslAppServer(new String[] {
String.valueOf(getServerPort()),
getServerPrincipalName(),
getHostname()
});
}
@Test
public void test() throws Exception {
runAppClient(createAppClient());
}
private AppClient createAppClient() throws Exception {
return new SaslAppClient(new String[] {
getHostname(),
String.valueOf(getServerPort()),
getServerPrincipalName(),
getHostname()
});
}
}
| 255 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/JWTTokenTest.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.integration.test;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Collections;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.KrbRuntime;
import org.apache.kerby.kerberos.kerb.ccache.Credential;
import org.apache.kerby.kerberos.kerb.ccache.CredentialCache;
import org.apache.kerby.kerberos.kerb.client.KrbClient;
import org.apache.kerby.kerberos.kerb.client.KrbTokenClient;
import org.apache.kerby.kerberos.kerb.common.EncryptionUtil;
import org.apache.kerby.kerberos.kerb.common.PrivateKeyReader;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.provider.TokenEncoder;
import org.apache.kerby.kerberos.kerb.type.ad.AdToken;
import org.apache.kerby.kerberos.kerb.type.ad.AuthorizationData;
import org.apache.kerby.kerberos.kerb.type.ad.AuthorizationDataEntry;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
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.KrbToken;
import org.apache.kerby.kerberos.kerb.type.base.TokenFormat;
import org.apache.kerby.kerberos.kerb.type.ticket.EncTicketPart;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.Ticket;
import org.apache.kerby.kerberos.provider.token.JwtTokenEncoder;
import static org.junit.jupiter.api.Assertions.*;
/**
* Some tests for JWT tokens using the Kerby client API
*/
public class JWTTokenTest extends TokenLoginTestBase {
@org.junit.jupiter.api.Test
public void accessToken() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a SGT using the JWT
SgtTicket tkt = tokenClient.requestSgt(krbToken, getServerPrincipal(), cCacheFile.getPath());
assertTrue(tkt != null);
// Decrypt the ticket
Ticket ticket = tkt.getTicket();
EncryptionKey key = EncryptionHandler.string2Key(getServerPrincipal(), getServerPassword(),
ticket.getEncryptedEncPart().getEType());
EncTicketPart encPart =
EncryptionUtil.unseal(ticket.getEncryptedEncPart(),
key, KeyUsage.KDC_REP_TICKET, EncTicketPart.class);
// Examine the authorization data
AuthorizationData authzData = encPart.getAuthorizationData();
assertEquals(1, authzData.getElements().size());
AuthorizationDataEntry dataEntry = authzData.getElements().iterator().next();
AdToken token = dataEntry.getAuthzDataAs(AdToken.class);
KrbToken decodedKrbToken = token.getToken();
assertEquals(getClientPrincipal(), decodedKrbToken.getSubject());
assertEquals(getServerPrincipal(), decodedKrbToken.getAudiences().get(0));
cCacheFile.delete();
}
@org.junit.jupiter.api.Test
public void accessTokenInvalidAudience() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token with an invalid audience
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal() + "_"));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestSgt(krbToken, getServerPrincipal(), cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
@org.junit.jupiter.api.Test
public void accessTokenInvalidSignature() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token with an invalid audience
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
krbToken.setTokenValue(signToken(authToken, keyPair.getPrivate()));
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestSgt(krbToken, getServerPrincipal(), cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
@org.junit.jupiter.api.Test
public void accessTokenNoSignature() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token with an invalid audience
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
assertTrue(tokenEncoder instanceof JwtTokenEncoder);
krbToken.setTokenValue(tokenEncoder.encodeAsBytes(authToken));
// Now get a SGT using the JWT
try {
tokenClient.requestSgt(krbToken, getServerPrincipal(), cCacheFile.getPath());
fail("Failure expected on no signature");
} catch (KrbException ex) {
assertTrue(ex.getMessage().contains("Token should be signed"));
} finally {
cCacheFile.delete();
}
}
@org.junit.jupiter.api.Test
public void accessTokenUnknownIssuer() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token with an invalid audience
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
authToken.setIssuer("unknown-issuer");
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a SGT using the JWT
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestSgt(krbToken, getServerPrincipal(), cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
// Use the TGT here instead of an armor cache
@org.junit.jupiter.api.Test
public void accessTokenUsingTicket() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
authToken.isAcToken(true);
authToken.isIdToken(false);
authToken.setAudiences(Collections.singletonList(getServerPrincipal()));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a SGT using the JWT
SgtTicket tkt = tokenClient.requestSgt(krbToken, getServerPrincipal(), tgt);
assertTrue(tkt != null);
// Decrypt the ticket
Ticket ticket = tkt.getTicket();
EncryptionKey key = EncryptionHandler.string2Key(getServerPrincipal(), getServerPassword(),
ticket.getEncryptedEncPart().getEType());
EncTicketPart encPart =
EncryptionUtil.unseal(ticket.getEncryptedEncPart(),
key, KeyUsage.KDC_REP_TICKET, EncTicketPart.class);
// Examine the authorization data
AuthorizationData authzData = encPart.getAuthorizationData();
assertEquals(1, authzData.getElements().size());
AuthorizationDataEntry dataEntry = authzData.getElements().iterator().next();
AdToken token = dataEntry.getAuthzDataAs(AdToken.class);
KrbToken decodedKrbToken = token.getToken();
assertEquals(getClientPrincipal(), decodedKrbToken.getSubject());
assertEquals(getServerPrincipal(), decodedKrbToken.getAudiences().get(0));
}
@org.junit.jupiter.api.Test
public void identityToken() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a TGT using the JWT token
tgt = tokenClient.requestTgt(krbToken, cCacheFile.getPath());
// Now get a SGT using the TGT
SgtTicket tkt = tokenClient.requestSgt(tgt, getServerPrincipal());
assertTrue(tkt != null);
// Decrypt the ticket
Ticket ticket = tkt.getTicket();
EncryptionKey key = EncryptionHandler.string2Key(getServerPrincipal(), getServerPassword(),
ticket.getEncryptedEncPart().getEType());
EncTicketPart encPart =
EncryptionUtil.unseal(ticket.getEncryptedEncPart(),
key, KeyUsage.KDC_REP_TICKET, EncTicketPart.class);
// Check the authorization data is not present
AuthorizationData authzData = encPart.getAuthorizationData();
assertNull(authzData);
cCacheFile.delete();
}
@org.junit.jupiter.api.Test
public void identityTokenInvalidAudience() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
authToken.setAudiences(Collections.singletonList(authToken.getAudiences().get(0) + "_"));
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a TGT using the JWT token
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestTgt(krbToken, cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
@org.junit.jupiter.api.Test
public void identityTokenInvalidSignature() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
krbToken.setTokenValue(signToken(authToken, keyPair.getPrivate()));
// Now get a TGT using the JWT token
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestTgt(krbToken, cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
@org.junit.jupiter.api.Test
public void identityTokenNoSignature() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
assertTrue(tokenEncoder instanceof JwtTokenEncoder);
krbToken.setTokenValue(tokenEncoder.encodeAsBytes(authToken));
// Now get a TGT using the JWT token
try {
tokenClient.requestTgt(krbToken, cCacheFile.getPath());
fail("Failure expected on an invalid signature");
} catch (KrbException ex) {
assertTrue(ex.getMessage().contains("Token should be signed"));
} finally {
cCacheFile.delete();
}
}
@org.junit.jupiter.api.Test
public void identityTokenUnknownIssuer() throws Exception {
KrbClient client = getKrbClient();
// Get a TGT
TgtTicket tgt = client.requestTgt(getClientPrincipal(), getClientPassword());
assertNotNull(tgt);
// Write to cache
Credential credential = new Credential(tgt);
CredentialCache cCache = new CredentialCache();
cCache.addCredential(credential);
cCache.setPrimaryPrincipal(tgt.getClientPrincipal());
File cCacheFile = Files.createTempFile("krb5_" + getClientPrincipal(), "cc").toFile();
cCache.store(cCacheFile);
KrbTokenClient tokenClient = new KrbTokenClient(client);
tokenClient.setKdcHost(client.getSetting().getKdcHost());
tokenClient.setKdcTcpPort(client.getSetting().getKdcTcpPort());
tokenClient.setKdcRealm(client.getSetting().getKdcRealm());
tokenClient.init();
// Create a JWT token
AuthToken authToken = issueToken(getClientPrincipal());
authToken.setIssuer("unknown-issuer");
KrbToken krbToken = new KrbToken(authToken, TokenFormat.JWT);
PrivateKey signKey;
try (InputStream is = Files.newInputStream(getSignKeyFile().toPath())) {
signKey = PrivateKeyReader.loadPrivateKey(is);
}
krbToken.setTokenValue(signToken(authToken, signKey));
// Now get a TGT using the JWT token
assertThrows(KrbException.class, () -> {
try {
tokenClient.requestTgt(krbToken, cCacheFile.getPath());
} finally {
cCacheFile.delete();
}
});
}
private byte[] signToken(AuthToken authToken, PrivateKey signKey) throws Exception {
TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
assertTrue(tokenEncoder instanceof JwtTokenEncoder);
((JwtTokenEncoder) tokenEncoder).setSignKey((RSAPrivateKey) signKey);
return tokenEncoder.encodeAsBytes(authToken);
}
}
| 256 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/TokenAppTest.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.integration.test;
import org.apache.kerby.util.NetworkUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import java.security.PrivilegedAction;
public abstract class TokenAppTest extends TokenLoginTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TokenAppTest.class);
private int serverPort;
protected AppServer appServer;
@BeforeEach
@Override
public void setUp() throws Exception {
super.setUp();
serverPort = NetworkUtil.getServerPort();
setupAppServer();
}
protected int getServerPort() {
return serverPort;
}
protected void setupAppServer() throws Exception {
Subject subject = loginServiceUsingKeytab();
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appServer = createAppServer();
appServer.start();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
}
protected abstract AppServer createAppServer() throws Exception;
protected void runAppClient(final AppClient appClient) throws Exception {
Subject subject = loginClientUsingTicketCache();
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appClient.run();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
Assertions.assertTrue(appClient.isTestOK(),
"Client successfully connected and authenticated to server");
}
}
| 257 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/TokenLoginTestBase.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.integration.test;
import org.apache.kerby.kerberos.kerb.KrbRuntime;
import org.apache.kerby.kerberos.kerb.client.jaas.TokenCache;
import org.apache.kerby.kerberos.kerb.client.jaas.TokenJaasKrbUtil;
import org.apache.kerby.kerberos.kerb.common.KrbUtil;
import org.apache.kerby.kerberos.kerb.provider.TokenEncoder;
import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
import org.apache.kerby.kerberos.kerb.server.LoginTestBase;
import org.apache.kerby.kerberos.kerb.server.TestKdcServer;
import org.apache.kerby.kerberos.kerb.type.base.AuthToken;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TokenLoginTestBase extends LoginTestBase {
private static final Logger LOG = LoggerFactory
.getLogger(TokenLoginTestBase.class);
private File tokenCache;
private File armorCache;
private File tgtCache;
private File signKeyFile;
static final String GROUP = "sales-group";
static final String ROLE = "ADMIN";
@BeforeEach
@Override
public void setUp() throws Exception {
super.setUp();
armorCache = new File(getTestDir(), "armorcache.cc");
tgtCache = new File(getTestDir(), "tgtcache.cc");
signKeyFile = new File(this.getClass().getResource("/private_key.pem").getPath());
tokenCache = Files.createTempFile("tokencache", null).toFile();
}
@AfterEach
public void cleanup() throws Exception {
tokenCache.delete();
}
@Override
protected void configKdcSeverAndClient() {
super.configKdcSeverAndClient();
getKdcServer().getKdcConfig().setBoolean(KdcConfigKey.ALLOW_TOKEN_PREAUTH,
isTokenPreauthAllowed());
String verifyKeyFile = this.getClass().getResource("/").getPath();
getKdcServer().getKdcConfig().setString(KdcConfigKey.TOKEN_VERIFY_KEYS, verifyKeyFile);
getKdcServer().getKdcConfig().setString(KdcConfigKey.TOKEN_ISSUERS, "token-service");
}
protected Boolean isTokenPreauthAllowed() {
return true;
}
protected String createTokenAndArmorCache() throws Exception {
TokenEncoder tokenEncoder = null;
try {
tokenEncoder = KrbRuntime.getTokenProvider("JWT").createTokenEncoder();
} catch (Exception e) {
LOG.error("Failed to create token. " + e.toString());
}
AuthToken token = issueToken(getClientPrincipal());
String tokenStr = tokenEncoder.encodeAsString(token);
TokenCache.writeToken(tokenStr, tokenCache.getPath());
// System.out.println("Issued token: " + tokenStr);
TgtTicket tgt = getKrbClient().requestTgt(getClientPrincipal(),
getClientPassword());
getKrbClient().storeTicket(tgt, armorCache);
return tokenStr;
}
protected AuthToken issueToken(String principal) {
AuthToken authToken = KrbRuntime.getTokenProvider("JWT").createTokenFactory().createToken();
String iss = "token-service";
authToken.setIssuer(iss);
String sub = principal;
authToken.setSubject(sub);
authToken.addAttribute("group", GROUP);
authToken.addAttribute("role", ROLE);
List<String> aud = new ArrayList<>();
aud.add(KrbUtil.makeTgsPrincipal(TestKdcServer.KDC_REALM).getName());
authToken.setAudiences(aud);
// Set expiration in 60 minutes
final Date now = new Date();
Date exp = new Date(now.getTime() + 1000 * 60 * 60);
authToken.setExpirationTime(exp);
Date nbf = now;
authToken.setNotBeforeTime(nbf);
Date iat = now;
authToken.setIssueTime(iat);
return authToken;
}
protected Subject loginClientUsingTokenStr(String tokenStr, File armorCache, File tgtCache,
File signKeyFile) throws Exception {
return TokenJaasKrbUtil.loginUsingToken(getClientPrincipal(), tokenStr, armorCache,
tgtCache, signKeyFile);
}
private Subject loginClientUsingTokenCache(File tokenCache, File armorCache, File tgtCache,
File signKeyFile) throws Exception {
return TokenJaasKrbUtil.loginUsingToken(getClientPrincipal(), tokenCache, armorCache,
tgtCache, signKeyFile);
}
protected void testLoginWithTokenStr() throws Exception {
String tokenStr = createTokenAndArmorCache();
Subject subj = loginClientUsingTokenStr(tokenStr, armorCache, tgtCache, signKeyFile);
checkSubject(subj);
}
protected void testLoginWithTokenCache() throws Exception {
createTokenAndArmorCache();
checkSubject(loginClientUsingTokenCache(tokenCache, armorCache, tgtCache, signKeyFile));
}
protected Subject testLoginWithTokenCacheAndRetSubject() throws Exception {
createTokenAndArmorCache();
Subject subj = loginClientUsingTokenCache(tokenCache, armorCache, tgtCache, signKeyFile);
checkSubject(subj);
return subj;
}
protected File getArmorCache() {
return armorCache;
}
protected File getTGTCache() {
return tgtCache;
}
protected File getSignKeyFile() {
return signKeyFile;
}
}
| 258 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/test/java/org/apache/kerby/kerberos/kerb/integration/test/AppTest.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.integration.test;
import org.apache.kerby.kerberos.kerb.server.LoginTestBase;
import org.apache.kerby.util.NetworkUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import java.security.PrivilegedAction;
public abstract class AppTest extends LoginTestBase {
private static final Logger LOG = LoggerFactory.getLogger(AppTest.class);
private int serverPort;
protected AppServer appServer;
@BeforeEach
@Override
public void setUp() throws Exception {
super.setUp();
serverPort = NetworkUtil.getServerPort();
setupAppServer();
}
protected int getServerPort() {
return serverPort;
}
protected void setupAppServer() throws Exception {
Subject subject = loginServiceUsingKeytab();
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appServer = createAppServer();
appServer.start();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
}
protected abstract AppServer createAppServer() throws Exception;
protected void runAppClient(final AppClient appClient) throws Exception {
Subject subject = loginClientUsingTicketCache();
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
appClient.run();
} catch (Exception ex) {
LOG.error(ex.toString());
}
return null;
}
});
Assertions.assertTrue(appClient.isTestOK(), "Client successfully connected and authenticated to server");
}
}
| 259 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/AppUtil.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.integration.test;
public class AppUtil {
public static final String JGSS_KERBEROS_OID = "1.2.840.113554.1.2.2";
}
| 260 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/Transport.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.integration.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Transport {
private static final Logger LOG = LoggerFactory
.getLogger(Transport.class);
public static class Acceptor {
ServerSocket serverSocket;
public Acceptor(int listenPort) throws IOException {
this.serverSocket = new ServerSocket(listenPort);
}
public Connection accept() {
try {
Socket socket = serverSocket.accept();
return new Connection(socket);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public void close() {
try {
serverSocket.close();
} catch (IOException e) {
LOG.error("Failed to close acceptor. " + e.toString());
}
}
}
public static class Connector {
public static Connection connect(String host,
int port) throws IOException {
Socket socket = new Socket(host, port);
return new Connection(socket);
}
}
public static class Connection {
private Socket socket;
private DataInputStream instream;
private DataOutputStream outstream;
public Connection(Socket socket) throws IOException {
this.socket = socket;
instream = new DataInputStream(socket.getInputStream());
outstream = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException {
socket.close();
}
public void sendToken(byte[] token) throws IOException {
if (token != null) {
outstream.writeInt(token.length);
outstream.write(token);
} else {
outstream.writeInt(0);
}
outstream.flush();
}
public void sendMessage(Message msg) throws IOException {
if (msg != null) {
sendToken(msg.header);
sendToken(msg.body);
}
}
public void sendMessage(byte[] header, byte[] body) throws IOException {
sendMessage(new Message(header, body));
}
public void sendMessage(String header, byte[] body) throws IOException {
sendMessage(new Message(header, body));
}
public byte[] recvToken() throws IOException {
int len = instream.readInt();
if (len > 0) {
byte[] token = new byte[len];
instream.readFully(token);
return token;
}
return null;
}
public Message recvMessage() throws IOException {
byte[] header = recvToken();
byte[] body = recvToken();
Message msg = new Message(header, body);
return msg;
}
}
public static class Message {
public byte[] header;
public byte[] body;
Message(byte[] header, byte[] body) {
this.header = header;
this.body = body;
}
public Message(String header, byte[] body) {
this.header = header.getBytes(StandardCharsets.UTF_8);
this.body = body;
}
}
}
| 261 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/AppClient.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.integration.test;
import java.io.IOException;
public abstract class AppClient {
private Transport.Connection conn;
private boolean isTestOK = false;
public AppClient(String[] args) throws Exception {
usage(args);
String hostName = args[0];
int port = Integer.parseInt(args[1]);
this.conn = Transport.Connector.connect(hostName, port);
}
protected void usage(String[] args) {
if (args.length < 2) {
System.err.println("Usage: java <options> AppClient "
+ "<server-host> <server-port>");
throw new RuntimeException("Arguments are invalid.");
}
}
public void run() {
// System.out.println("Connected to server");
try {
withConnection(conn);
} catch (Exception e) {
System.err.println("Failed to connect. " + e.toString());
} finally {
try {
conn.close();
} catch (IOException e) {
System.err.println("Failed to close connection. "
+ e.toString());
}
}
}
protected abstract void withConnection(Transport.Connection conn) throws Exception;
public boolean isTestOK() {
return isTestOK;
}
protected synchronized void setTestOK(boolean isOK) {
this.isTestOK = isOK;
}
}
| 262 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/AppServer.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.integration.test;
import java.io.IOException;
/**
* Making it runnable because the server will be launched in a separate thread
* in a test.
*/
public abstract class AppServer implements Runnable {
protected Transport.Acceptor acceptor;
private boolean terminated = false;
public AppServer(String[] args) throws IOException {
usage(args);
int listenPort = Integer.parseInt(args[0]);
this.acceptor = new Transport.Acceptor(listenPort);
}
protected void usage(String[] args) {
if (args.length < 1) {
System.err.println("Usage: AppServer <ListenPort>");
throw new RuntimeException("Usage: AppServer <ListenPort>");
}
}
public synchronized void start() {
new Thread(this).start();
}
public synchronized void stop() {
terminated = true;
}
@Override
public void run() {
try {
synchronized (this) {
while (!terminated) {
runOnce();
}
}
} finally {
acceptor.close();
}
}
private void runOnce() {
// System.out.println("Waiting for incoming connection...");
Transport.Connection conn = acceptor.accept();
// System.out.println("Got connection from client");
try {
onConnection(conn);
} catch (Exception e) {
System.err.println("Failed to set onConnection. " + e.toString());
} finally {
try {
conn.close();
} catch (IOException e) {
System.err.println("Failed to close connection. "
+ e.toString());
}
}
}
protected abstract void onConnection(Transport.Connection conn) throws Exception;
}
| 263 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/gss/GssAppServer.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.integration.test.gss;
import org.apache.kerby.kerberos.kerb.integration.test.AppServer;
import org.apache.kerby.kerberos.kerb.integration.test.AppUtil;
import org.apache.kerby.kerberos.kerb.integration.test.Transport;
import org.apache.kerby.kerberos.kerb.type.ad.AdToken;
import org.apache.kerby.kerberos.kerb.type.base.KrbToken;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.MessageProp;
import org.ietf.jgss.Oid;
import com.sun.security.jgss.AuthorizationDataEntry;
import com.sun.security.jgss.ExtendedGSSContext;
import com.sun.security.jgss.InquireType;
public class GssAppServer extends AppServer {
private String serverPrincipal;
private GSSManager manager;
private GSSContext context;
private boolean createContextWithCred = true;
private KrbToken receivedAccessToken;
public GssAppServer(String[] args) throws Exception {
super(args);
if (args.length < 2) {
usage(args);
}
this.serverPrincipal = args[1];
this.manager = GSSManager.getInstance();
}
public static void main(String[] args) throws Exception {
new GssAppServer(args).run();
}
protected void usage(String[] args) {
if (args.length < 1) {
System.err.println("Usage: AppServer <ListenPort> <server-principal>");
throw new RuntimeException("Usage: AppServer <ListenPort> <server-principal>");
}
}
@Override
protected void onConnection(Transport.Connection conn) throws Exception {
GSSName gssService = manager.createName(serverPrincipal, GSSName.NT_USER_NAME);
Oid oid = new Oid(AppUtil.JGSS_KERBEROS_OID);
if (createContextWithCred) {
GSSCredential credentials =
manager.createCredential(gssService, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.ACCEPT_ONLY);
this.context = manager.createContext(credentials);
} else {
this.context = manager.createContext(gssService.canonicalize(oid),
oid, null, GSSContext.DEFAULT_LIFETIME);
}
byte[] token;
// System.out.print("Starting negotiating security context");
while (!context.isEstablished()) {
token = conn.recvToken();
token = context.acceptSecContext(token, 0, token.length);
if (token != null) {
conn.sendToken(token);
}
}
// System.out.print("Context Established! ");
// System.out.println("Client is " + context.getSrcName());
// System.out.println("Server is " + context.getTargName());
// Store any received access token for later retrieval
ExtendedGSSContext extendedContext = (ExtendedGSSContext) context;
AuthorizationDataEntry[] authzDataEntries =
(AuthorizationDataEntry[]) extendedContext.inquireSecContext(InquireType.KRB5_GET_AUTHZ_DATA);
if (authzDataEntries != null && authzDataEntries.length > 0) {
byte[] data = authzDataEntries[0].getData();
AdToken adToken = new AdToken();
adToken.decode(data);
receivedAccessToken = adToken.getToken();
}
doWith(context, conn);
context.dispose();
}
protected void doWith(GSSContext context,
Transport.Connection conn) throws Exception {
//if (context.getMutualAuthState()) {
// System.out.println("Mutual authentication took place!");
//}
MessageProp prop = new MessageProp(0, false);
byte[] token = conn.recvToken();
byte[] bytes = context.unwrap(token, 0, token.length, prop);
//String str = new String(bytes, StandardCharsets.UTF_8);
// System.out.println("Received data \""
// + str + "\" of length " + str.length());
//System.out.println("Confidentiality applied: "
// + prop.getPrivacy());
prop.setQOP(0);
token = context.getMIC(bytes, 0, bytes.length, prop);
//System.out.println("Will send MIC token of size "
//+ token.length);
conn.sendToken(token);
}
public void setCreateContextWithCred(boolean createContextWithCred) {
this.createContextWithCred = createContextWithCred;
}
public KrbToken getReceivedAccessToken() {
return receivedAccessToken;
}
}
| 264 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/gss/GssAppClient.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.integration.test.gss;
import org.apache.kerby.kerberos.kerb.integration.test.AppClient;
import org.apache.kerby.kerberos.kerb.integration.test.AppUtil;
import org.apache.kerby.kerberos.kerb.integration.test.Transport;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.MessageProp;
import org.ietf.jgss.Oid;
import java.nio.charset.StandardCharsets;
public class GssAppClient extends AppClient {
private String clientPrincipal;
private String serverPrincipal;
private GSSManager manager;
private boolean createContextWithCred = true;
public GssAppClient(String[] args) throws Exception {
super(args);
clientPrincipal = args[2];
serverPrincipal = args[3];
this.manager = GSSManager.getInstance();
}
public static void main(String[] args) throws Exception {
new GssAppClient(args).run();
}
@Override
protected void usage(String[] args) {
if (args.length < 3) {
System.err.println("Usage: GssAppClient <server-host> <server-port> "
+ "<client-principal> <server-principal> ");
throw new RuntimeException("Usage: GssAppClient <server-host> <server-port> \"\n"
+ " + \"<client-principal> <server-principal> ");
}
}
@Override
protected void withConnection(Transport.Connection conn) throws Exception {
Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
GSSName serverName = manager.createName(serverPrincipal,
GSSName.NT_USER_NAME);
Oid oid = new Oid(AppUtil.JGSS_KERBEROS_OID);
GSSName clientName = manager.createName(clientPrincipal,
GSSName.NT_USER_NAME);
GSSCredential myCred = null;
if (createContextWithCred) {
myCred = manager.createCredential(clientName,
GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
}
GSSContext context = manager.createContext(serverName,
krb5Oid, myCred, GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true);
context.requestConf(true);
context.requestInteg(true);
byte[] token = new byte[0];
while (!context.isEstablished()) {
token = context.initSecContext(token, 0, token.length);
if (token != null) {
conn.sendToken(token);
}
if (!context.isEstablished()) {
token = conn.recvToken();
}
}
//System.out.println("Context Established! ");
//System.out.println("Client is " + context.getSrcName());
//System.out.println("Server is " + context.getTargName());
//if (context.getMutualAuthState()) {
//System.out.println("Mutual authentication took place!");
//}
byte[] messageBytes = "Hello There!\0".getBytes(StandardCharsets.UTF_8);
MessageProp prop = new MessageProp(0, true);
token = context.wrap(messageBytes, 0, messageBytes.length, prop);
//System.out.println("Will send wrap token of size " + token.length);
conn.sendToken(token);
token = conn.recvToken();
context.verifyMIC(token, 0, token.length,
messageBytes, 0, messageBytes.length, prop);
setTestOK(true);
//System.out.println("Verified received MIC for message.");
context.dispose();
}
public void setCreateContextWithCred(boolean createContextWithCred) {
this.createContextWithCred = createContextWithCred;
}
}
| 265 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/sasl/SaslAppServer.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.integration.test.sasl;
import org.apache.kerby.kerberos.kerb.integration.test.AppServer;
import org.apache.kerby.kerberos.kerb.integration.test.Transport;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SaslAppServer extends AppServer {
private String mechanism;
private String serviceProtocol;
private String serverFqdn;
public SaslAppServer(String[] args) throws Exception {
super(args);
this.mechanism = "GSSAPI";
this.serviceProtocol = args[1];
this.serverFqdn = args[2];
}
public static void main(String[] args) throws Exception {
new SaslAppServer(args).run();
}
@Override
protected void usage(String[] args) {
if (args.length < 3) {
System.err.println("Usage: SaslAppServer "
+ "<ListenPort> <service-protocol> <server-fqdn>");
throw new RuntimeException("Usage: SaslAppServer "
+ "<ListenPort> <service-protocol> <server-fqdn>");
}
}
@Override
protected void onConnection(Transport.Connection conn) throws Exception {
// System.out.print("Starting negotiating security context");
//mechanism, protocol, serverId, saslProperties, callback
CallbackHandler callbackHandler = new SaslGssCallbackHandler();
Map<String, Object> props = new HashMap<>();
props.put(Sasl.QOP, "auth");
SaslServer ss = Sasl.createSaslServer(mechanism,
serviceProtocol, serverFqdn, props, callbackHandler);
Transport.Message msg = conn.recvMessage();
while (!ss.isComplete()) {
try {
byte[] respToken = ss.evaluateResponse(msg.body);
if (ss.isComplete()) {
conn.sendMessage("OK", respToken);
} else {
conn.sendMessage("CONT", respToken);
msg = conn.recvMessage();
}
} catch (SaslException e) {
conn.sendMessage("ERR", null);
ss.dispose();
break;
}
}
// System.out.print("Context Established! ");
doWith(ss, props, conn);
ss.dispose();
}
protected void doWith(SaslServer ss, Map<String, Object> props,
Transport.Connection conn) throws IOException, Exception {
conn.recvToken();
//byte[] token = conn.recvToken();
//String str = new String(token, StandardCharsets.UTF_8);
// System.out.println("Received data \""
// + str + "\" of length " + str.length());
}
public static class SaslGssCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] callbacks) throws
UnsupportedCallbackException {
AuthorizeCallback ac = null;
for (Callback callback : callbacks) {
if (callback instanceof AuthorizeCallback) {
ac = (AuthorizeCallback) callback;
} else {
throw new UnsupportedCallbackException(callback,
"Unrecognized SASL GSSAPI Callback");
}
}
if (ac != null) {
String authid = ac.getAuthenticationID();
String authzid = ac.getAuthorizationID();
if (authid.equals(authzid)) {
ac.setAuthorized(true);
} else {
ac.setAuthorized(false);
}
if (ac.isAuthorized()) {
// System.out.println("SASL server GSSAPI callback: setting "
//+ "canonicalized client ID: " + authzid);
ac.setAuthorizedID(authzid);
}
}
}
}
}
| 266 |
0 | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test | Create_ds/directory-kerby/kerby-kerb/integration-test/src/main/java/org/apache/kerby/kerberos/kerb/integration/test/sasl/SaslAppClient.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.integration.test.sasl;
import org.apache.kerby.kerberos.kerb.integration.test.AppClient;
import org.apache.kerby.kerberos.kerb.integration.test.Transport;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class SaslAppClient extends AppClient {
private SaslClient saslClient;
public SaslAppClient(String[] args) throws Exception {
super(args);
String protocol = args[2];
String serverFqdn = args[3];
Map<String, String> props = new HashMap<>();
props.put(Sasl.QOP, "auth");
this.saslClient = Sasl.createSaslClient(new String[]{"GSSAPI"}, null,
protocol, serverFqdn, props, null);
}
public static void main(String[] args) throws Exception {
new SaslAppClient(args).run();
}
@Override
protected void usage(String[] args) {
if (args.length < 4) {
System.err.println("Usage: SaslAppClient "
+ "<server-host> <server-port> <service-protocol> <server-fqdn>");
throw new RuntimeException("Usage: SaslAppClient "
+ "<server-host> <server-port> <service-protocol> <server-fqdn>");
}
}
@Override
protected void withConnection(Transport.Connection conn) throws Exception {
byte[] token = saslClient.hasInitialResponse() ? new byte[0] : null;
token = saslClient.evaluateChallenge(token);
conn.sendMessage("CONT", token);
Transport.Message msg = conn.recvMessage();
while (!saslClient.isComplete() && (isContinue(msg) || isOK(msg))) {
byte[] respToken = saslClient.evaluateChallenge(msg.body);
if (isOK(msg)) {
if (respToken != null) {
throw new IOException("Attempting to send response after completion");
}
break;
} else {
conn.sendMessage("CONT", respToken);
msg = conn.recvMessage();
}
}
//System.out.println("Context Established! ");
token = "Hello There!\0".getBytes(StandardCharsets.UTF_8);
//System.out.println("Will send wrap token of size " + token.length);
conn.sendToken(token);
setTestOK(true);
saslClient.dispose();
}
private boolean isOK(Transport.Message msg) {
if (msg.header != null) {
return new String(msg.header, StandardCharsets.UTF_8).equals("OK");
}
return false;
}
private boolean isContinue(Transport.Message msg) {
if (msg.header != null) {
return new String(msg.header, StandardCharsets.UTF_8).equals("CONT");
}
return false;
}
}
| 267 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/CmacTest.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;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia128Provider;
import org.apache.kerby.kerberos.kerb.crypto.util.Cmac;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Ref. t_cmac.c test in MIT krb5 project.
*/
public class CmacTest {
/* All examples use the following Camellia-128 key. */
static String keyBytes = "2b7e151628aed2a6" + "abf7158809cf4f3c";
/* Example inputs are this message truncated to 0, 16, 40, and 64 bytes. */
static String inputBytes = "6bc1bee22e409f96"
+ "e93d7e117393172a"
+ "ae2d8a571e03ac9c"
+ "9eb76fac45af8e51"
+ "30c81c46a35ce411"
+ "e5fbc1191a0a52ef"
+ "f69f2445df4f9b17"
+ "ad2b417be66c3710";
/* Expected result of CMAC on empty inputBytes. */
static String cmac1 = "ba925782aaa1f5d9" + "a00f89648094fc71";
/* Expected result of CMAC on first 16 bytes of inputBytes. */
static String cmac2 = "6d962854a3b9fda5" + "6d7d45a95ee17993";
/* Expected result of CMAC on first 40 bytes of inputBytes. */
static String cmac3 = "5c18d119ccd67661" + "44ac1866131d9f22";
/* Expected result of CMAC on all 64 bytes of inputBytes. */
static String cmac4 = "c2699a6eba55ce9d" + "939a8a4e19466ee9";
@Test
public void testCmac() throws KrbException, KrbException {
byte[] key = HexUtil.hex2bytes(keyBytes);
byte[] input = HexUtil.hex2bytes(inputBytes);
EncryptProvider encProvider = new Camellia128Provider();
// test 1
byte[] result = Cmac.cmac(encProvider, key, input, 0, 0);
assertThat(result).as("Test 1").isEqualTo(HexUtil.hex2bytes(cmac1));
// test 2
result = Cmac.cmac(encProvider, key, input, 0, 16);
assertThat(result).as("Test 2").isEqualTo(HexUtil.hex2bytes(cmac2));
// test 3
result = Cmac.cmac(encProvider, key, input, 0, 40);
assertThat(result).as("Test 3").isEqualTo(HexUtil.hex2bytes(cmac3));
// test 4
result = Cmac.cmac(encProvider, key, input, 0, 64);
assertThat(result).as("Test 4").isEqualTo(HexUtil.hex2bytes(cmac4));
}
}
| 268 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/Crc32Test.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;
import org.apache.kerby.kerberos.kerb.crypto.util.Crc32;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Ref. t_crc.c test in MIT krb5 project.
*/
public class Crc32Test {
static class TestCase {
String data;
long answer;
TestCase(String data, long answer) {
this.data = data;
this.answer = answer;
}
}
static TestCase[] testCases = new TestCase[] {
new TestCase("01", 0x77073096),
new TestCase("02", 0xee0e612c),
new TestCase("04", 0x076dc419),
new TestCase("08", 0x0edb8832),
new TestCase("10", 0x1db71064),
new TestCase("20", 0x3b6e20c8),
new TestCase("40", 0x76dc4190),
new TestCase("80", 0xedb88320),
new TestCase("0100", 0x191b3141),
new TestCase("0200", 0x32366282),
new TestCase("0400", 0x646cc504),
new TestCase("0800", 0xc8d98a08),
new TestCase("1000", 0x4ac21251),
new TestCase("2000", 0x958424a2),
new TestCase("4000", 0xf0794f05),
new TestCase("8000", 0x3b83984b),
new TestCase("0001", 0x77073096),
new TestCase("0002", 0xee0e612c),
new TestCase("0004", 0x076dc419),
new TestCase("0008", 0x0edb8832),
new TestCase("0010", 0x1db71064),
new TestCase("0020", 0x3b6e20c8),
new TestCase("0040", 0x76dc4190),
new TestCase("0080", 0xedb88320),
new TestCase("01000000", 0xb8bc6765),
new TestCase("02000000", 0xaa09c88b),
new TestCase("04000000", 0x8f629757),
new TestCase("08000000", 0xc5b428ef),
new TestCase("10000000", 0x5019579f),
new TestCase("20000000", 0xa032af3e),
new TestCase("40000000", 0x9b14583d),
new TestCase("80000000", 0xed59b63b),
new TestCase("00010000", 0x01c26a37),
new TestCase("00020000", 0x0384d46e),
new TestCase("00040000", 0x0709a8dc),
new TestCase("00080000", 0x0e1351b8),
new TestCase("00100000", 0x1c26a370),
new TestCase("00200000", 0x384d46e0),
new TestCase("00400000", 0x709a8dc0),
new TestCase("00800000", 0xe1351b80),
new TestCase("00000100", 0x191b3141),
new TestCase("00000200", 0x32366282),
new TestCase("00000400", 0x646cc504),
new TestCase("00000800", 0xc8d98a08),
new TestCase("00001000", 0x4ac21251),
new TestCase("00002000", 0x958424a2),
new TestCase("00004000", 0xf0794f05),
new TestCase("00008000", 0x3b83984b),
new TestCase("00000001", 0x77073096),
new TestCase("00000002", 0xee0e612c),
new TestCase("00000004", 0x076dc419),
new TestCase("00000008", 0x0edb8832),
new TestCase("00000010", 0x1db71064),
new TestCase("00000020", 0x3b6e20c8),
new TestCase("00000040", 0x76dc4190),
new TestCase("00000080", 0xedb88320),
new TestCase("666F6F", 0x7332bc33),
new TestCase("7465737430313233343536373839", 0xb83e88d6),
new TestCase("4D4153534143485653455454532049"
+ "4E53544954565445204F4620544543484E4F4C4F4759", 0xe34180f7)
};
@Test
public void testCrc32() {
boolean isOk = true;
for (TestCase tc : testCases) {
if (!testWith(tc)) {
isOk = false;
System.err.println("Test with data " + tc.data + " failed");
}
}
assertThat(isOk).isTrue();
}
private boolean testWith(TestCase testCase) {
byte[] data = HexUtil.hex2bytes(testCase.data);
long value = Crc32.crc(0, data, 0, data.length);
return value == testCase.answer;
}
}
| 269 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/CheckSumsTest.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;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Ref. t_cksums.c in MIT krb5 project.
*
* These are to test the checksums of good answers, and the checksums
* are deterministic. For other cases, look at CheckSumTest.
*/
public class CheckSumsTest {
private static class CksumTest {
String plainText;
CheckSumType cksumType;
EncryptionType encType;
String key;
int keyUsage;
String answer;
CksumTest(String plainText, CheckSumType cksumType, EncryptionType encType,
int keyUsage, String key, String answer) {
this.plainText = plainText;
this.cksumType = cksumType;
this.encType = encType;
this.key = key;
this.keyUsage = keyUsage;
this.answer = answer;
}
}
@Test
public void testCheckSums_CRC32() throws Exception {
performTest(new CksumTest(
"abc",
CheckSumType.CRC32, EncryptionType.NONE, 0, "",
"D09865CA"
));
}
@Test
public void testCheckSums_RSA_MD4() throws Exception {
performTest(new CksumTest(
"one",
CheckSumType.RSA_MD4, EncryptionType.NONE, 0, "",
"305DCC2C0FDD5339969552C7B8996348"
));
}
@Test
public void testCheckSums_RSA_MD5() throws Exception {
performTest(new CksumTest(
"two three four five",
CheckSumType.RSA_MD5, EncryptionType.NONE, 0, "",
"BAB5321551E1084490869635B3C26815"
));
}
@Test
public void testCheckSums_NIST_SHA() throws Exception {
performTest(new CksumTest(
"",
CheckSumType.NIST_SHA, EncryptionType.NONE, 0, "",
"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709"
));
}
@Test
public void testCheckSums_HMAC_SHA1_DES3() throws Exception {
performTest(new CksumTest(
"six seven",
CheckSumType.HMAC_SHA1_DES3, EncryptionType.DES3_CBC_SHA1, 2,
"7A25DF8992296DCEDA0E135BC4046E2375B3C14C98FBC162",
"0EEFC9C3E049AABC1BA5C401677D9AB699082BB4"
));
}
@Test
public void testCheckSums_HMAC_SHA1_96_AES128() throws Exception {
performTest(new CksumTest(
"eight nine ten eleven twelve thirteen",
CheckSumType.HMAC_SHA1_96_AES128, EncryptionType.AES128_CTS_HMAC_SHA1_96, 3,
"9062430C8CDA3388922E6D6A509F5B7A",
"01A4B088D45628F6946614E3"
));
}
@Test
public void testCheckSums_HMAC_SHA1_96_AES256() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new CksumTest(
"fourteen",
CheckSumType.HMAC_SHA1_96_AES256, EncryptionType.AES256_CTS_HMAC_SHA1_96, 4,
"B1AE4CD8462AFF1677053CC9279AAC30B796FB81CE21474DD3DDBCFEA4EC76D7",
"E08739E3279E2903EC8E3836"
));
}
@Test
public void testCheckSums_MD5_HMAC_ARCFOUR() throws Exception {
performTest(new CksumTest(
"fifteen sixteen",
CheckSumType.MD5_HMAC_ARCFOUR, EncryptionType.ARCFOUR_HMAC, 5,
"F7D3A155AF5E238A0B7A871A96BA2AB2",
"9F41DF304907DE735447001FD2A197B9"
));
}
@Test
public void testCheckSums_HMAC_MD5_ARCFOUR() throws Exception {
performTest(new CksumTest(
"seventeen eighteen nineteen twenty",
CheckSumType.HMAC_MD5_ARCFOUR, EncryptionType.ARCFOUR_HMAC, 6,
"F7D3A155AF5E238A0B7A871A96BA2AB2",
"EB38CC97E2230F59DA4117DC5859D7EC"
));
}
@Test
public void testCheckSums_CMAC_CAMELLIA128_1() throws Exception {
performTest(new CksumTest(
"abcdefghijk",
CheckSumType.CMAC_CAMELLIA128, EncryptionType.CAMELLIA128_CTS_CMAC, 7,
"1DC46A8D763F4F93742BCBA3387576C3",
"1178E6C5C47A8C1AE0C4B9C7D4EB7B6B"
));
}
@Test
public void testCheckSums_CMAC_CAMELLIA128_2() throws Exception {
performTest(new CksumTest(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CheckSumType.CMAC_CAMELLIA128, EncryptionType.CAMELLIA128_CTS_CMAC, 8,
"5027BC231D0F3A9D23333F1CA6FDBE7C",
"D1B34F7004A731F23A0C00BF6C3F753A"
));
}
@Test
public void testCheckSums_CMAC_CAMELLIA256_1() throws Exception {
performTest(new CksumTest(
"123456789",
CheckSumType.CMAC_CAMELLIA256, EncryptionType.CAMELLIA256_CTS_CMAC, 9,
"B61C86CC4E5D2757545AD423399FB7031ECAB913CBB900BD7A3C6DD8BF92015B",
"87A12CFD2B96214810F01C826E7744B1"
));
}
@Test
public void testCheckSums_CMAC_CAMELLIA256_2() throws Exception {
performTest(new CksumTest(
"!@#$%^&*()!@#$%^&*()!@#$%^&*()",
CheckSumType.CMAC_CAMELLIA256, EncryptionType.CAMELLIA256_CTS_CMAC, 10,
"32164C5B434D1D1538E4CFD9BE8040FE8C4AC7ACC4B93D3314D2133668147A05",
"3FA0B42355E52B189187294AA252AB64"
));
}
/**
* Perform checksum checks using the testcase data object
* @param testCase
* @throws Exception
*/
private static void performTest(CksumTest testCase) throws Exception {
byte[] answer = HexUtil.hex2bytes(testCase.answer);
byte[] plainData = testCase.plainText.getBytes();
CheckSum newCksum;
if (!CheckSumHandler.isImplemented(testCase.cksumType)) {
fail("Checksum type not supported yet: "
+ testCase.cksumType.getName());
return;
}
if (testCase.encType != EncryptionType.NONE) {
/**
* For keyed checksum types
*/
if (!EncryptionHandler.isImplemented(testCase.encType)) {
fail("Key type not supported yet: " + testCase.encType.getName());
return;
}
byte[] key = HexUtil.hex2bytes(testCase.key);
KeyUsage keyUsage = KeyUsage.fromValue(testCase.keyUsage);
newCksum = CheckSumHandler.checksumWithKey(testCase.cksumType, plainData, key, keyUsage);
if (!CheckSumHandler.verifyWithKey(newCksum, plainData, key, keyUsage)) {
fail("Checksum test failed for " + testCase.cksumType.getName());
}
} else {
/**
* For un-keyed checksum types
*/
newCksum = CheckSumHandler.checksum(testCase.cksumType, plainData);
if (!CheckSumHandler.verify(newCksum, plainData)) {
fail("Checksum and verifying failed for " + testCase.cksumType.getName());
}
}
if (!newCksum.isEqual(answer)) {
fail("Checksum test failed for " + testCase.cksumType.getName());
}
}
}
| 270 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/String2keyTest.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;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* By ref. MIT krb5 t_str2key.c and RFC3961 test vectors
*
* String 2 key test with known values.
*/
public class String2keyTest {
static class TestCase {
EncryptionType encType;
String password;
String salt;
String param;
String answer;
boolean allowWeak;
TestCase(EncryptionType encType, String password, String salt, String param,
String answer, boolean allowWeak) {
this.encType = encType;
this.password = password;
this.salt = salt;
this.param = param;
this.answer = answer;
this.allowWeak = allowWeak;
}
}
/**
* Test vectors from RFC 3961 appendix A.2.
*/
@Test
public void test_DES_CBC_CRC_0() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"password",
"ATHENA.MIT.EDUraeburn",
"00",
"CBC22FAE235298E3",
false));
}
@Test
public void test_DES_CBC_CRC_1() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"potatoe",
"WHITEHOUSE.GOVdanny",
"00",
"DF3D32A74FD92A01",
false));
}
@Test
public void test_DES_CBC_CRC_2() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
toUtf8("F09D849E"),
"EXAMPLE.COMpianist",
"00",
"4FFB26BAB0CD9413",
false));
}
@Test
public void test_DES_CBC_CRC_3() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
toUtf8("C39F"),
"ATHENA.MIT.EDUJuri" + toUtf8("C5A169C487"),
"00",
"62C81A5232B5E69D",
false));
}
@Test
public void test_DES_CBC_CRC_4() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"11119999",
"AAAAAAAA",
"00",
"984054d0f1a73e31",
false));
}
@Test
public void test_DES_CBC_CRC_5() {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"NNNN6666",
"FFFFAAAA",
"00",
"C4BF6B25ADF7A4F8",
false));
}
// Test vectors from RFC 3961 appendix A.4.
@Test
public void test_DES3_CBC_SHA1_0() {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"password",
"ATHENA.MIT.EDUraeburn",
null,
"850BB51358548CD05E86768C"
+ "313E3BFEF7511937DCF72C3E",
false));
}
@Test
public void test_DES3_CBC_SHA1_1() {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"potatoe",
"WHITEHOUSE.GOVdanny",
null,
"DFCD233DD0A43204EA6DC437"
+ "FB15E061B02979C1F74F377A",
false));
}
@Test
public void test_DES3_CBC_SHA1_2() {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"penny",
"EXAMPLE.COMbuckaroo",
null,
"6D2FCDF2D6FBBC3DDCADB5DA"
+ "5710A23489B0D3B69D5D9D4A",
false));
}
@Test
public void test_DES3_CBC_SHA1_3() {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
toUtf8("C39F"),
"ATHENA.MIT.EDUJuri" + toUtf8("C5A169C487"),
null,
"16D5A40E1CE3BACB61B9DCE0"
+ "0470324C831973A7B952FEB0",
false));
}
@Test
public void test_DES3_CBC_SHA1_4() {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
toUtf8("F09D849E"),
"EXAMPLE.COMpianist",
null,
"85763726585DBC1CCE6EC43E"
+ "1F751F07F1C4CBB098F40B19",
false));
}
// Test vectors from RFC 3962 appendix B.
@Test
public void test_AES128_CTS_HMAC_SHA1_96_0() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"00000001",
"42263C6E89F4FC28B8DF68EE09799F15",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_1() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"00000002",
"C651BF29E2300AC27FA469D693BDDA13",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_2() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"000004B0", // 1200
"4C01CD46D632D01E6DBE230A01ED642A",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_3() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"password",
toUtf8("1234567878563412"),
"00000005",
"E9B23D52273747DD5C35CB55BE619D8E",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_4() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase exceeds block size",
"000004B0", // 1200
"CB8005DC5F90179A7F02104C0018751D",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_5() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
toUtf8("F09D849E"),
"EXAMPLE.COMpianist",
"00000032", // 50
"F149C1F2E154A73452D43E7FE62A56E5",
true));
}
@Test
public void test_AES128_CTS_HMAC_SHA1_96_6() {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase equals block size",
"000004B0", // 1200
"59D1BB789A828B1AA54EF9C2883F69ED",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_0() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"00000001",
"FE697B52BC0D3CE14432BA036A92E65B"
+ "BB52280990A2FA27883998D72AF30161",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_1() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"00000002",
"A2E16D16B36069C135D5E9D2E25F8961"
+ "02685618B95914B467C67622225824FF",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_2() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"password",
"ATHENA.MIT.EDUraeburn",
"000004B0", // 1200
"55A6AC740AD17B4846941051E1E8B0A7"
+ "548D93B0AB30A8BC3FF16280382B8C2A",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_3() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"password",
toUtf8("1234567878563412"),
"00000005",
"97A4E786BE20D81A382D5EBC96D5909C"
+ "ABCDADC87CA48F574504159F16C36E31",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_4() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase equals block size",
"000004B0", // 1200
"89ADEE3608DB8BC71F1BFBFE459486B0"
+ "5618B70CBAE22092534E56C553BA4B34",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_5() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase exceeds block size",
"000004B0", // 1200
"D78C5C9CB872A8C9DAD4697F0BB5B2D2"
+ "1496C82BEB2CAEDA2112FCEEA057401B",
true));
}
@Test
public void test_AES256_CTS_HMAC_SHA1_96_6() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
toUtf8("F09D849E"),
"EXAMPLE.COMpianist",
"00000032", // 50
"4B6D9839F84406DF1F09CC166DB4B83C"
+ "571848B784A3D6BDC346589A3E393F9E",
true));
}
// Check for KRB5_ERR_BAD_S2K_PARAMS return when weak iteration counts are forbidden
@Test
public void test_AES256_CTS_HMAC_SHA1_96_7() {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
toUtf8("F09D849E"),
"EXAMPLE.COMpianist",
"00000032", // 50
"4B6D9839F84406DF1F09CC166DB4B83C"
+ "571848B784A3D6BDC346589A3E393F9E",
false));
}
// The same inputs applied to Camellia enctypes.
@Test
public void test_CAMELLIA128_CTS_CMAC_0() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"00000001",
"57D0297298FFD9D35DE5A47FB4BDE24B",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_1() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"00000002",
"73F1B53AA0F310F93B1DE8CCAA0CB152",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_2() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"000004B0", // 1200
"8E571145452855575FD916E7B04487AA",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_3() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"password",
toUtf8("1234567878563412"),
"00000005",
"00498FD916BFC1C2B1031C170801B381",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_4() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase equals block size",
"000004B0", // 1200
"8BF6C3EF709B981DBB585D086843BE05",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_5() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase exceeds block size",
"000004B0", // 1200
"5752AC8D6AD1CCFE8430B312871C2F74",
true));
}
@Test
public void test_CAMELLIA128_CTS_CMAC_6() {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
toUtf8("f09d849e"),
"EXAMPLE.COMpianist",
"00000032", // 50
"CC75C7FD260F1C1658011FCC0D560616",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_1() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"00000001",
"B9D6828B2056B7BE656D88A123B1FAC6"
+ "8214AC2B727ECF5F69AFE0C4DF2A6D2C",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_2() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"00000002",
"83FC5866E5F8F4C6F38663C65C87549F"
+ "342BC47ED394DC9D3CD4D163ADE375E3",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_3() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"password",
"ATHENA.MIT.EDUraeburn",
"000004B0", // 1200
"77F421A6F25E138395E837E5D85D385B"
+ "4C1BFD772E112CD9208CE72A530B15E6",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_4() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"password",
toUtf8("1234567878563412"),
"00000005",
"11083A00BDFE6A41B2F19716D6202F0A"
+ "FA94289AFE8B27A049BD28B1D76C389A",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_5() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase equals block size",
"000004B0", // 1200
"119FE2A1CB0B1BE010B9067A73DB63ED"
+ "4665B4E53A98D178035DCFE843A6B9B0",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_6() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"pass phrase exceeds block size",
"000004B0", // 1200
"614D5DFC0BA6D390B412B89AE4D5B088"
+ "B612B316510994679DDB4383C7126DDF",
true));
}
@Test
public void test_CAMELLIA256_CTS_CMAC_7() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
toUtf8("f09d849e"),
"EXAMPLE.COMpianist",
"00000032", // 50
"163B768C6DB148B4EEC7163DF5AED70E"
+ "206B68CEC078BC069ED68A7ED36B1ECC",
true));
}
// Check for KRB5_ERR_BAD_S2K_PARAMS return when weak iteration counts are forbidden.
@Test
public void test_CAMELLIA256_CTS_CMAC_8() {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
toUtf8("f09d849e"),
"EXAMPLE.COMpianist",
"00000032", // 50
"163B768C6DB148B4EEC7163DF5AED70E"
+ "206B68CEC078BC069ED68A7ED36B1ECC",
false));
}
/**
* Convert hex string into password
*/
private static String toUtf8(String string) {
return new String(HexUtil.hex2bytes(string), StandardCharsets.UTF_8); // Per spec
}
/**
* Perform all the checks for a testcase
*/
private void performTest(TestCase testCase) {
//assertThat(EncryptionHandler.isImplemented(testCase.encType)).isTrue();
if (!EncryptionHandler.isImplemented(testCase.encType)) {
System.err.println("Not implemented yet: " + testCase.encType.getDisplayName());
return;
}
try {
assertThat(testWith(testCase)).isTrue();
} catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Do the actual test work
*/
private boolean testWith(TestCase tc) throws Exception {
byte[] answer = HexUtil.hex2bytes(tc.answer);
byte[] params = tc.param != null ? HexUtil.hex2bytes(tc.param) : null;
EncryptionKey outkey = EncryptionHandler.string2Key(tc.password, tc.salt, params, tc.encType);
if (!Arrays.equals(answer, outkey.getKeyData())) {
System.err.println("failed with:" + tc.salt);
System.err.println("outKey:" + HexUtil.bytesToHex(outkey.getKeyData()));
System.err.println("answer:" + tc.answer);
return false;
}
return true;
}
} | 271 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/KeyDeriveTest.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;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes128Provider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Aes256Provider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia128Provider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia256Provider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Des3Provider;
import org.apache.kerby.kerberos.kerb.crypto.key.AesKeyMaker;
import org.apache.kerby.kerberos.kerb.crypto.key.CamelliaKeyMaker;
import org.apache.kerby.kerberos.kerb.crypto.key.Des3KeyMaker;
import org.apache.kerby.kerberos.kerb.crypto.key.DkKeyMaker;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Ref. t_derive.c test in MIT krb5 project.
*
* Key derivation test with known values.
*/
public class KeyDeriveTest {
static class TestCase {
EncryptionType encType;
String inkey;
String constant;
String answer;
TestCase(EncryptionType encType, String inkey,
String constant, String answer) {
this.encType = encType;
this.inkey = inkey;
this.constant = constant;
this.answer = answer;
}
}
@Test
public void testKeyDerive_DES3_CBC_SHA1_299() throws Exception {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"850BB51358548CD05E86768C313E3BFE"
+ "F7511937DCF72C3E",
"0000000299",
"F78C496D16E6C2DAE0E0B6C24057A84C"
+ "0426AEEF26FD6DCE"
));
}
@Test
public void testKeyDerive_DES3_CBC_SHA1_2AA() throws Exception {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"850BB51358548CD05E86768C313E3BFE"
+ "F7511937DCF72C3E",
"00000002AA",
"5B5723D0B634CB684C3EBA5264E9A70D"
+ "52E683231AD3C4CE"
));
}
@Test
public void testKeyDerive_DES3_CBC_SHA1_255() throws Exception {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"850BB51358548CD05E86768C313E3BFE"
+ "F7511937DCF72C3E",
"0000000255",
"A77C94980E9B7345A81525C423A737CE"
+ "67F4CD91B6B3DA45"
));
}
@Test
public void testKeyDerive_AES128_CTS_HMAC_SHA1_96_299() throws Exception {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"42263C6E89F4FC28B8DF68EE09799F15",
"0000000299",
"34280A382BC92769B2DA2F9EF066854B"
));
}
@Test
public void testKeyDerive_AES128_CTS_HMAC_SHA1_96_2AA() throws Exception {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"42263C6E89F4FC28B8DF68EE09799F15",
"00000002AA",
"5B14FC4E250E14DDF9DCCF1AF6674F53"
));
}
@Test
public void testKeyDerive_AES128_CTS_HMAC_SHA1_96_255() throws Exception {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"42263C6E89F4FC28B8DF68EE09799F15",
"0000000255",
"4ED31063621684F09AE8D89991AF3E8F"
));
}
@Test
public void testKeyDerive_AES256_CTS_HMAC_SHA1_96_299() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"FE697B52BC0D3CE14432BA036A92E65B"
+ "BB52280990A2FA27883998D72AF30161",
"0000000299",
"BFAB388BDCB238E9F9C98D6A878304F0"
+ "4D30C82556375AC507A7A852790F4674"
));
}
@Test
public void testKeyDerive_AES256_CTS_HMAC_SHA1_96_2AA() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"FE697B52BC0D3CE14432BA036A92E65B"
+ "BB52280990A2FA27883998D72AF30161",
"00000002AA",
"C7CFD9CD75FE793A586A542D87E0D139"
+ "6F1134A104BB1A9190B8C90ADA3DDF37"
));
}
@Test
public void testKeyDerive_AES256_CTS_HMAC_SHA1_96_255() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"FE697B52BC0D3CE14432BA036A92E65B"
+ "BB52280990A2FA27883998D72AF30161",
"0000000255",
"97151B4C76945063E2EB0529DC067D97"
+ "D7BBA90776D8126D91F34F3101AEA8BA"
));
}
@Test
public void testKeyDerive_CAMELLIA128_CTS_CMAC_299() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"57D0297298FFD9D35DE5A47FB4BDE24B",
"0000000299",
"D155775A209D05F02B38D42A389E5A56"
));
}
@Test
public void testKeyDerive_CAMELLIA128_CTS_CMAC_2AA() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"57D0297298FFD9D35DE5A47FB4BDE24B",
"00000002AA",
"64DF83F85A532F17577D8C37035796AB"
));
}
@Test
public void testKeyDerive_CAMELLIA128_CTS_CMAC_255() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"57D0297298FFD9D35DE5A47FB4BDE24B",
"0000000255",
"3E4FBDF30FB8259C425CB6C96F1F4635"
));
}
@Test
public void testKeyDerive_CAMELLIA256_CTS_CMAC_299() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"B9D6828B2056B7BE656D88A123B1FAC6"
+ "8214AC2B727ECF5F69AFE0C4DF2A6D2C",
"0000000299",
"E467F9A9552BC7D3155A6220AF9C1922"
+ "0EEED4FF78B0D1E6A1544991461A9E50"
));
}
@Test
public void testKeyDerive_CAMELLIA256_CTS_CMAC_2AA() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"B9D6828B2056B7BE656D88A123B1FAC6"
+ "8214AC2B727ECF5F69AFE0C4DF2A6D2C",
"00000002AA",
"412AEFC362A7285FC3966C6A5181E760"
+ "5AE675235B6D549FBFC9AB6630A4C604"
));
}
@Test
public void testKeyDerive_CAMELLIA256_CTS_CMAC_255() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"B9D6828B2056B7BE656D88A123B1FAC6"
+ "8214AC2B727ECF5F69AFE0C4DF2A6D2C",
"0000000255",
"FA624FA0E523993FA388AEFDC67E67EB"
+ "CD8C08E8A0246B1D73B0D1DD9FC582B0"
));
}
static DkKeyMaker getKeyMaker(EncryptionType encType) {
switch (encType) {
case DES3_CBC_SHA1:
return new Des3KeyMaker(new Des3Provider());
case AES128_CTS_HMAC_SHA1_96:
return new AesKeyMaker(new Aes128Provider());
case AES256_CTS_HMAC_SHA1_96:
return new AesKeyMaker(new Aes256Provider());
case CAMELLIA128_CTS_CMAC:
return new CamelliaKeyMaker(new Camellia128Provider());
case CAMELLIA256_CTS_CMAC:
return new CamelliaKeyMaker(new Camellia256Provider());
default:
return null;
}
}
/**
* Perform key derive tests using the testCase data object
* @param testCase
* @throws Exception
*/
private static void performTest(TestCase testCase) throws Exception {
byte[] answer = HexUtil.hex2bytes(testCase.answer);
byte[] inkey = HexUtil.hex2bytes(testCase.inkey);
byte[] constant = HexUtil.hex2bytes(testCase.constant);
byte[] outkey;
DkKeyMaker km = getKeyMaker(testCase.encType);
outkey = km.dk(inkey, constant);
if (!Arrays.equals(answer, outkey)) {
System.err.println("failed with:");
System.err.println("outKey:" + HexUtil.bytesToHex(outkey));
System.err.println("answer:" + testCase.answer);
fail("KeyDerive test failed for " + testCase.encType.getName());
}
}
}
| 272 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/PrfTest.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;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Ref. t_prf.c test in MIT krb5 project.
*/
public class PrfTest {
private static void performTest(TestCase testCase) throws Exception {
byte[] keyData = EncryptionHandler.getEncHandler(testCase.encType)
.str2key(testCase.keyData, testCase.keyData, null);
byte[] seed = HexUtil.hex2bytes(testCase.seed);
byte[] answer = HexUtil.hex2bytes(testCase.answer);
byte[] outkey = EncryptionHandler.getEncHandler(testCase.encType).prf(keyData, seed);
if (!Arrays.equals(answer, outkey)) {
System.err.println("failed with:");
System.err.println("outKey:" + HexUtil.bytesToHex(outkey));
System.err.println("answer:" + testCase.answer);
fail("KeyDerive test failed for " + testCase.encType.getName());
}
}
@Test
public void testPrf_DES_CBC_CRC() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"key1",
"0161",
"e91cff96b939270009308b073b66313e"
));
}
@Test
public void testPrf_DES_CBC_MD4() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_MD4,
"key1",
"0161",
"e91cff96b939270009308b073b66313e"
));
}
@Test
public void testPrf_DES_CBC_MD5() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_MD5,
"key1",
"0161",
"e91cff96b939270009308b073b66313e"
));
}
@Test
public void testPrf_AES128_CTS_HMAC_SHA1() throws Exception {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"key1",
"0161",
"77b39a37a868920f2a51f9dd150c5717"
));
}
@Test
public void testPrf_AES256_CTS_HMAC_SHA1() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"key1",
"0161",
"b2628c788e2e9c4a9bb4644678c29f2f"
));
}
@Test
public void testPrf_DES3_CBC_SHA1() throws Exception {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"key1",
"0161",
"bb6f4a7caa25fce1ee9baef36f1f9ee7"
));
}
@Test
public void testPrf_CAMELLIA128_CTS_CMAC() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"key1",
"0161",
"e9bfccec1ec08740efcfdb020b48cf17"
));
}
@Test
public void testPrf_CAMELLIA256_CTS_CMAC() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"key1",
"0161",
"d0bb1a19fd311388dc2eeb67268ff90b"
));
}
@Test
public void testPrf_RC4_HMAC() throws Exception {
performTest(new TestCase(
EncryptionType.RC4_HMAC,
"key1",
"0161",
"c882f5310c3b65e4b99c19709d986dedc154f234"
));
}
@Test
public void testPrf_RC4_HMAC_EXP() throws Exception {
performTest(new TestCase(
EncryptionType.RC4_HMAC_EXP,
"key1",
"0161",
"c882f5310c3b65e4b99c19709d986dedc154f234"
));
}
static class TestCase {
EncryptionType encType;
String keyData;
String seed;
String answer;
TestCase(EncryptionType encType, String keyData,
String seed, String answer) {
this.encType = encType;
this.keyData = keyData;
this.seed = seed;
this.answer = answer;
}
}
}
| 273 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/CamelliaEncTest.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;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia128Provider;
import org.apache.kerby.kerberos.kerb.crypto.enc.provider.Camellia256Provider;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Ref. camellia-test.c test in MIT krb5 project.
*/
public class CamelliaEncTest {
private List<String> outputs = new ArrayList<>();
private byte[] plain = new byte[16];
private byte[] cipher = new byte[16];
private EncryptProvider encProvider;
private List<String> getExpectedLines() throws IOException {
try (InputStream res = getClass().getResourceAsStream("/camellia-expect-vt.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(res))) {
List<String> results = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
results.add(line);
}
}
return results;
}
}
@Test
public void testEnc() throws IOException, KrbException {
List<String> expectedLines = getExpectedLines();
testWith(16);
outputs.add("==========");
testWith(32);
outputs.add("==========");
List<String> newLines = expectedLines;
assertThat(newLines).as("Comparing new lines with expected lines").isEqualTo(outputs);
}
private void testWith(int keySize) throws KrbException {
outputs.add("KEYSIZE=" + (keySize * 8));
encProvider = keySize == 16 ? new Camellia128Provider() : new Camellia256Provider();
byte[] key = new byte[keySize];
Arrays.fill(key, (byte) 0);
hexDump("KEY", key);
for (int i = 0; i < 16 * 8; ++i) {
Arrays.fill(plain, (byte) 0);
setBit(plain, i);
outputs.add("I=" + (i + 1));
hexDump("PT", plain);
encWith(key);
hexDump("CT", cipher);
}
}
private void hexDump(String label, byte[] bytes) {
String line = label + "=" + HexUtil.bytesToHex(bytes);
outputs.add(line);
}
private static void setBit(byte[] bytes, int bitnum) {
int bytenum = bitnum / 8;
bitnum %= 8;
// First bit is the high bit!
bytes[bytenum] = (byte) (1 << (7 - bitnum));
}
private void encWith(byte[] key) throws KrbException {
System.arraycopy(plain, 0, cipher, 0, plain.length);
encProvider.encrypt(key, cipher);
}
}
| 274 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/CheckSumTest.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;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.fail;
/**
* Ref. t_cksum.c in MIT krb5 project.
*
* Only used to test for rsa-md4-des and rsa-md5-des
*/
public class CheckSumTest {
static class CksumTest {
CheckSumType cksumType;
String plainText;
String knownChecksum;
CksumTest(CheckSumType cksumType, String plainText, String knownChecksum) {
this.cksumType = cksumType;
this.plainText = plainText;
this.knownChecksum = knownChecksum;
}
}
static CksumTest[] testCases = new CksumTest[] {
new CksumTest(
CheckSumType.RSA_MD4_DES,
"this is a test",
"e3f76a07f3401e3536b43a3f54226c39422c35682c354835"
),
new CksumTest(
CheckSumType.RSA_MD5_DES,
"this is a test",
"e3f76a07f3401e351143ee6f4c09be1edb4264d55015db53"
)
};
static final byte[] TESTKEY = {(byte) 0x45, (byte) 0x01, (byte) 0x49, (byte) 0x61, (byte) 0x58,
(byte) 0x19, (byte) 0x1a, (byte) 0x3d};
@Test
public void testCheckSums() throws Exception {
for (CksumTest tc : testCases) {
testWith(tc);
}
}
private void testWith(CksumTest testCase) throws Exception {
byte[] knownChecksum = HexUtil.hex2bytes(testCase.knownChecksum);
byte[] plainData = testCase.plainText.getBytes();
if (!CheckSumHandler.isImplemented(testCase.cksumType)) {
fail("Checksum type not supported yet: "
+ testCase.cksumType.getName());
return;
}
EncryptionKey key = new EncryptionKey(EncryptionType.DES_CBC_CRC, TESTKEY);
CheckSum newCksum = CheckSumHandler.checksumWithKey(testCase.cksumType,
plainData, key.getKeyData(), KeyUsage.NONE);
if (!CheckSumHandler.verifyWithKey(newCksum, plainData, key.getKeyData(), KeyUsage.NONE)) {
fail("Checksum verifying failed for " + testCase.cksumType.getName());
}
// corrupt and verify again
byte[] cont = newCksum.getChecksum();
cont[0]++;
newCksum.setChecksum(cont);
if (CheckSumHandler.verifyWithKey(newCksum, plainData, key.getKeyData(), KeyUsage.NONE)) {
fail("Checksum verifying failed with corrupt data for " + testCase.cksumType.getName());
}
CheckSum knwnCksum = new CheckSum(testCase.cksumType, knownChecksum);
if (!CheckSumHandler.verifyWithKey(knwnCksum, plainData, key.getKeyData(), KeyUsage.NONE)) {
fail("Checksum verifying failed with known checksum for " + testCase.cksumType.getName());
}
}
}
| 275 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/FastUtilTest.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;
import org.apache.kerby.kerberos.kerb.crypto.fast.FastUtil;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Ref. fast util test codes in MIT krb5 project.
*/
public class FastUtilTest {
static class TestCase {
EncryptionType encType;
String keyData1;
String keyData2;
String pepper1;
String pepper2;
String answer;
TestCase(EncryptionType encType, String keyData1, String keyData2,
String pepper1, String pepper2, String answer) {
this.encType = encType;
this.keyData1 = keyData1;
this.keyData2 = keyData2;
this.pepper1 = pepper1;
this.pepper2 = pepper2;
this.answer = answer;
}
}
@Test
public void testFastUtil_DES_CBC_CRC() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_CRC,
"key1",
"key2",
"a",
"b",
"43bae3738c9467e6"
));
}
@Test
public void testFastUtil_DES_CBC_MD4() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_MD4,
"key1",
"key2",
"a",
"b",
"43bae3738c9467e6"
));
}
@Test
public void testFastUtil_DES_CBC_MD5() throws Exception {
performTest(new TestCase(
EncryptionType.DES_CBC_MD5,
"key1",
"key2",
"a",
"b",
"43bae3738c9467e6"
));
}
@Test
public void testFastUtil_CAMELLIA128_CTS_CMAC() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"key1",
"key2",
"a",
"b",
"403e44c30ee42525b8b4c8c379a4573c"
));
}
@Test
public void testFastUtil_CAMELLIA256_CTS_CMAC() throws Exception {
performTest(new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"key1",
"key2",
"a",
"b",
"e0595b675a8b082b11b28c2ab9a94988fbc7ddc7ea29ecb5637ea25aff5134db"
));
}
@Test
public void testFastUtil_AES128_CTS_HMAC_SHA1() throws Exception {
performTest(new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"key1",
"key2",
"a",
"b",
"97df97e4b798b29eb31ed7280287a92a"
));
}
@Test
public void testFastUtil_AES256_CTS_HMAC_SHA1() throws Exception {
assumeTrue(CryptoUtil.isAES256Enabled());
performTest(new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"key1",
"key2",
"a",
"b",
"4d6ca4e629785c1f01baf55e2e548566b9617ae3a96868c337cb93b5e72b1c7b"
));
}
@Test
public void testFastUtil_DES3_CBC_SHA1() throws Exception {
performTest(new TestCase(
EncryptionType.DES3_CBC_SHA1,
"key1",
"key2",
"a",
"b",
"e58f9eb643862c13ad38e529313462a7f73e62834fe54a01"
));
}
@Test
public void testFastUtil_RC4_HMAC() throws Exception {
performTest(new TestCase(
EncryptionType.RC4_HMAC,
"key1",
"key2",
"a",
"b",
"24d7f6b6bae4e5c00d2082c5ebab3672"
));
}
@Test
public void testFastUtil_RC4_HMAC_EXP() throws Exception {
performTest(new TestCase(
EncryptionType.RC4_HMAC_EXP,
"key1",
"key2",
"a",
"b",
"24d7f6b6bae4e5c00d2082c5ebab3672"
));
}
private static void performTest(TestCase testCase) throws Exception {
EncryptionKey key, key1, key2;
byte[] keyData1, keyData2;
String pepper1, pepper2, answer;
keyData1 = EncryptionHandler.getEncHandler(testCase.encType).str2key(testCase.keyData1,
testCase.keyData1, null);
key1 = new EncryptionKey(testCase.encType, keyData1);
keyData2 = EncryptionHandler.getEncHandler(testCase.encType).str2key(testCase.keyData2,
testCase.keyData2, null);
key2 = new EncryptionKey(testCase.encType, keyData2);
pepper1 = testCase.pepper1;
pepper2 = testCase.pepper2;
answer = testCase.answer;
key = FastUtil.cf2(key1, pepper1, key2, pepper2);
if (!Arrays.equals(key.getKeyData(), HexUtil.hex2bytes(answer))) {
System.err.println("Failed with:");
System.err.println("outKey:" + HexUtil.bytesToHex(key.getKeyData()));
System.err.println("answer:" + testCase.answer);
fail("CF2Test failed for " + testCase.encType.getName());
}
}
}
| 276 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/DecryptionTest.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;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.util.CryptoUtil;
import org.apache.kerby.util.HexUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Ref. t_decrypt.c test in MIT krb5 project.
*
* Decryption test with known ciphertexts.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DecryptionTest {
/**
* The class used to store the test values
*/
private static class TestCase {
EncryptionType encType;
String plainText;
int keyUsage;
String key;
String cipher;
TestCase(EncryptionType encType, String plainText,
int keyUsage, String key, String cipher) {
this.encType = encType;
this.plainText = plainText;
this.keyUsage = keyUsage;
this.key = key;
this.cipher = cipher;
}
}
/**
* Actually do the test
*/
private boolean testDecrypt(TestCase testCase) throws Exception {
KeyUsage ku = KeyUsage.fromValue(testCase.keyUsage);
byte[] cipherBytes = HexUtil.hex2bytes(testCase.cipher);
byte[] keyBytes = HexUtil.hex2bytes(testCase.key);
EncryptionKey encKey = new EncryptionKey(testCase.encType, keyBytes);
byte[] decrypted = EncryptionHandler.decrypt(cipherBytes, encKey, ku);
String plainText = new String(decrypted);
return plainText.startsWith(testCase.plainText);
}
/**
* Perform all the checks for a testcase
*/
private void performTestDecrypt(TestCase testCase) {
//assertThat(EncryptionHandler.isImplemented(testCase.encType)).isTrue();
if (!EncryptionHandler.isImplemented(testCase.encType)) {
System.err.println("Not implemented yet: " + testCase.encType.getDisplayName());
return;
}
try {
assertThat(testDecrypt(testCase)).isTrue();
} catch (Exception e) {
fail(e.getMessage());
}
}
/**
* Test for DES_CBC_CRC encryption type, with 0 byte
*/
@Test
public void testDecryptDES_CBC_CRC_0() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_CRC,
"", 0,
"45E6087CDF138FB5",
"28F6B09A012BCCF72FB05122B2839E6E");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_CRC encryption type, with 1 byte
*/
@Test
public void testDecryptDES_CBC_CRC_1() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_CRC,
"1", 1,
"92A7155810586B2F",
"B4C871C2F3E7BF7605EFD62F2EEEC205");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_CRC encryption type, with 9 bytes
*/
@Test
public void testDecryptDES_CBC_CRC_9() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_CRC,
"9 bytesss", 2,
"A4B9514A61646423",
"5F14C35178D33D7CDE0EC169C623CC83" + "21B7B8BD34EA7EFE");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_CRC encryption type, with 13 bytes
*/
@Test
public void testDecryptDES_CBC_CRC_13() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_CRC,
"13 bytes byte", 3,
"2F16A2A7FDB05768",
"0B588E38D971433C9D86D8BAEBF63E4C" + "1A01666E76D8A54A3293F72679ED88C9");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_CRC encryption type, with 30 bytes
*/
@Test
public void testDecryptDES_CBC_CRC_30() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_CRC,
"30 bytes bytes bytes bytes byt", 4,
"BC8F70FD2097D67C",
"38D632D2C20A7C2EA250FC8ECE42938E"
+ "92A9F5D302502665C1A33729C1050DC2"
+ "056298FBFB1682CEEB65E59204FDA7DF");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD4 encryption type, with 0 byte
*/
@Test
public void testDecryptDES_CBC_MD4_0() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD4,
"", 0,
"13EF45D0D6D9A15D",
"1FB202BF07AF3047FB7801E588568686"
+ "BA63D78BE3E87DC7");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD4 encryption type, with 1 byte
*/
@Test
public void testDecryptDES_CBC_MD4_1() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD4,
"1", 1,
"64688654DC269E67",
"1F6CB9CECB73F755ABFDB3D565BD31D5"
+ "A2E64BFE44C491E20EEBE5BD20E4D2A9");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD4 encryption type, with 9 bytes
*/
@Test
public void testDecryptDES_CBC_MD4_9() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD4,
"9 bytesss", 2,
"6804FB26DF8A4C32",
"08A53D62FEC3338AD1D218E60DBDD3B2"
+ "12940679D125E0621B3BAB4680CE0367"
+ "6A2C420E9BE784EB");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD4 encryption type, with 13 bytes
*/
@Test
public void testDecryptDES_CBC_MD4_13() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD4,
"13 bytes byte", 3,
"234A436EC72FA80B",
"17CD45E14FF06B2840A6036E9AA7A414"
+ "4E29768144A0C1827D8C4BC7C9906E72"
+ "CD4DC328F6648C99");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD4 encryption type, with 30 bytes
*/
@Test
public void testDecryptDES_CBC_MD4_30() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD4,
"30 bytes bytes bytes bytes byt", 4,
"1FD5F74334C4FB8C",
"51134CD8951E9D57C0A36053E04CE03E"
+ "CB8422488FDDC5C074C4D85E60A2AE42"
+ "3C3C701201314F362CB07448091679C6"
+ "A496C11D7B93C71B");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD5 encryption type, with 0 byte
*/
@Test
public void testDecryptDES_CBC_MD5_0() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD5,
"", 0,
"4A545E0BF7A22631",
"784CD81591A034BE82556F56DCA3224B"
+ "62D9956FA90B1B93");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD5 encryption type, with 1 byte
*/
@Test
public void testDecryptDES_CBC_MD5_1() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD5,
"1", 1,
"D5804A269DC4E645",
"FFA25C7BE287596BFE58126E90AAA0F1"
+ "2D9A82A0D86DF6D5F9074B6B399E7FF1");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD5 encryption type, with 9 bytes
*/
@Test
public void testDecryptDES_CBC_MD5_9() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD5,
"9 bytesss", 2,
"C8312F7F83EA4640",
"E7850337F2CC5E3F35CE3D69E2C32986"
+ "38A7AA44B878031E39851E47C15B5D0E"
+ "E7E7AC54DE111D80");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD5 encryption type, with 13 bytes
*/
@Test
public void testDecryptDES_CBC_MD5_13() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD5,
"13 bytes byte", 3,
"7FDA3E62AD8AF18C",
"D7A8032E19994C928777506595FBDA98"
+ "83158A8514548E296E911C29F465C672"
+ "366000558BFC2E88");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_MD5 encryption type, with 30 bytes
*/
@Test
public void testDecryptDES_CBC_MD5_30() {
TestCase testCase = new TestCase(
EncryptionType.DES_CBC_MD5,
"30 bytes bytes bytes bytes byt", 4,
"D3D6832970A73752",
"8A48166A4C6FEAE607A8CF68B381C075"
+ "5E402B19DBC0F81A7D7CA19A25E05223"
+ "F6064409BF5A4F50ACD826639FFA7673"
+ "FD324EC19E429502");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_SHA1 encryption type, with 0 byte
*/
@Test
public void testDecryptDES_CBC_SHA1_0() {
TestCase testCase = new TestCase(
EncryptionType.DES3_CBC_SHA1,
"", 0,
"7A25DF8992296DCEDA0E135BC4046E23"
+ "75B3C14C98FBC162",
"548AF4D504F7D723303F12175FE8386B"
+ "7B5335A967BAD61F3BF0B143");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_SHA1 encryption type, with 1 byte
*/
@Test
public void testDecryptDES_CBC_SHA1_1() {
TestCase testCase = new TestCase(
EncryptionType.DES3_CBC_SHA1,
"1", 1,
"BC0783891513D5CE57BC138FD3C11AE6"
+ "40452385322962B6",
"9C3C1DBA4747D85AF2916E4745F2DCE3"
+ "8046796E5104BCCDFB669A91D44BC356"
+ "660945C7");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_SHA1 encryption type, with 9 bytes
*/
@Test
public void testDecryptDES_CBC_SHA1_9() {
TestCase testCase = new TestCase(
EncryptionType.DES3_CBC_SHA1,
"9 bytesss", 2,
"2FD0F725CE04100D2FC8A18098831F85"
+ "0B45D9EF850BD920",
"CF9144EBC8697981075A8BAD8D74E5D7"
+ "D591EB7D9770C7ADA25EE8C5B3D69444"
+ "DFEC79A5B7A01482D9AF74E6");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_SHA1 encryption type, with 13 bytes
*/
@Test
public void testDecryptDES_CBC_SHA1_13() {
TestCase testCase = new TestCase(
EncryptionType.DES3_CBC_SHA1,
"13 bytes byte", 3,
"0DD52094E0F41CECCB5BE510A764B351"
+ "76E3981332F1E598",
"839A17081ECBAFBCDC91B88C6955DD3C"
+ "4514023CF177B77BF0D0177A16F705E8"
+ "49CB7781D76A316B193F8D30");
performTestDecrypt(testCase);
}
/**
* Test for DES_CBC_SHA1 encryption type, with 30 bytes
*/
@Test
public void testDecryptDES_CBC_SHA1_30() {
TestCase testCase = new TestCase(
EncryptionType.DES3_CBC_SHA1,
"30 bytes bytes bytes bytes byt", 4,
"F11686CBBC9E23EA54FECD2A3DCDFB20"
+ "B6FE98BF2645C4C4",
"89433E83FD0EA3666CFFCD18D8DEEBC5"
+ "3B9A34EDBEB159D9F667C6C2B9A96440"
+ "1D55E7E9C68D648D65C3AA84FFA3790C"
+ "14A864DA8073A9A95C4BA2BC");
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 0 byte
*/
@Test
public void testDecryptARC_FOUR_0() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC,
"", 0,
"F81FEC39255F5784E850C4377C88BD85",
"02C1EB15586144122EC717763DD348BF"
+ "00434DDC6585954C"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 1 byte
*/
@Test
public void testDecryptARC_FOUR_1() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC,
"1", 1,
"67D1300D281223867F9647FF48721273",
"6156E0CC04E0A0874F9FDA008F498A7A"
+ "DBBC80B70B14DDDBC0"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 9 bytes
*/
@Test
public void testDecryptARC_FOUR_9() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC,
"9 bytesss", 2,
"3E40AB6093695281B3AC1A9304224D98",
"0F9AD121D99D4A09448E4F1F718C4F5C"
+ "BE6096262C66F29DF232A87C9F98755D"
+ "55"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 13 bytes
*/
@Test
public void testDecryptARC_FOUR_13() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC,
"13 bytes byte", 3,
"4BA2FBF0379FAED87A254D3B353D5A7E",
"612C57568B17A70352BAE8CF26FB9459"
+ "A6F3353CD35FD439DB3107CBEC765D32"
+ "6DFC04C1DD"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 30 bytes
*/
@Test
public void testDecryptARC_FOUR_30() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC,
"30 bytes bytes bytes bytes byt", 4,
"68F263DB3FCE15D031C9EAB02D67107A",
"95F9047C3AD75891C2E9B04B16566DC8"
+ "B6EB9CE4231AFB2542EF87A7B5A0F260"
+ "A99F0460508DE0CECC632D07C354124E"
+ "46C5D2234EB8"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC_EXP encryption type, with 0 byte
*/
@Test
public void testDecryptARCFOUR_HMAC_EXP_0() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC_EXP,
"", 0,
"F7D3A155AF5E238A0B7A871A96BA2AB2",
"2827F0E90F62E7460C4E2FB39F9657BA"
+ "8BFAA991D7FDADFF"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 1 byte
*/
@Test
public void testDecryptARCFOUR_HMAC_EXP_1() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC_EXP,
"1", 1,
"DEEAA0607DB799E2FDD6DB2986BB8D65",
"3DDA392E2E275A4D75183FA6328A0A4E"
+ "6B752DF6CD2A25FA4E"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 9 bytes
*/
@Test
public void testDecryptARCFOUR_HMAC_EXP_9() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC_EXP,
"9 bytesss", 2,
"33AD7FC2678615569B2B09836E0A3AB6",
"09D136AC485D92644EC6701D6A0D03E8"
+ "982D7A3CA7EFD0F8F4F83660EF4277BB"
+ "81"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 13 bytes
*/
@Test
public void testDecryptARCFOUR_HMAC_EXP_13() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC_EXP,
"13 bytes byte", 3,
"39F25CD4F0D41B2B2D9D300FCB2981CB",
"912388D7C07612819E3B640FF5CECDAF"
+ "72E5A59DF10F1091A6BEC39CAAD748AF"
+ "9BD2D8D546"
);
performTestDecrypt(testCase);
}
/**
* Test for ARCFOUR_HMAC encryption type, with 30 bytes
*/
@Test
public void testDecryptARCFOUR_HMAC_EXP_30() {
TestCase testCase = new TestCase(
EncryptionType.ARCFOUR_HMAC_EXP,
"30 bytes bytes bytes bytes byt", 4,
"9F725542D9F72AA1F386CBE7896984FC",
"78B35A08B08BE265AEB4145F076513B6"
+ "B56EFED3F7526574AF74F7D2F9BAE96E"
+ "ABB76F2D87386D2E93E3A77B99919F1D"
+ "976490E2BD45"
);
performTestDecrypt(testCase);
}
/**
* Test for AES128_CTS_HMAC_SHA1_96 encryption type, with 0 byte
*/
@Test
public void testDecryptAES128_CTS_HMAC_SHA1_96_0() {
TestCase testCase = new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"", 0,
"5A5C0F0BA54F3828B2195E66CA24A289",
"49FF8E11C173D9583A3254FBE7B1F1DF"
+ "36C538E8416784A1672E6676"
);
performTestDecrypt(testCase);
}
/**
* Test for AES128_CTS_HMAC_SHA1_96 encryption type, with 1 byte
*/
@Test
public void testDecryptAES128_CTS_HMAC_SHA1_96_1() {
TestCase testCase = new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"1", 1,
"98450E3F3BAA13F5C99BEB936981B06F",
"F86742F537B35DC2174A4DBAA920FAF9"
+ "042090B065E1EBB1CAD9A65394"
);
performTestDecrypt(testCase);
}
/**
* Test for AES128_CTS_HMAC_SHA1_96 encryption type, with 9 bytes
*/
@Test
public void testDecryptAES128_CTS_HMAC_SHA1_96_9() {
TestCase testCase = new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"9 bytesss", 2,
"9062430C8CDA3388922E6D6A509F5B7A",
"68FB9679601F45C78857B2BF820FD6E5"
+ "3ECA8D42FD4B1D7024A09205ABB7CD2E"
+ "C26C355D2F"
);
performTestDecrypt(testCase);
}
/**
* Test for AES128_CTS_HMAC_SHA1_96 encryption type, with 13 bytes
*/
@Test
public void testDecryptAES128_CTS_HMAC_SHA1_96_13() {
TestCase testCase = new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"13 bytes byte", 3,
"033EE6502C54FD23E27791E987983827",
"EC366D0327A933BF49330E650E49BC6B"
+ "974637FE80BF532FE51795B4809718E6"
+ "194724DB948D1FD637"
);
performTestDecrypt(testCase);
}
/**
* Test for AES128_CTS_HMAC_SHA1_96 encryption type, with 30 bytes
*/
@Test
public void testDecryptAES128_CTS_HMAC_SHA1_96_30() {
TestCase testCase = new TestCase(
EncryptionType.AES128_CTS_HMAC_SHA1_96,
"30 bytes bytes bytes bytes byt", 4,
"DCEEB70B3DE76562E689226C76429148",
"C96081032D5D8EEB7E32B4089F789D0F"
+ "AA481DEA74C0F97CBF3146DDFCF8E800"
+ "156ECB532FC203E30FF600B63B350939"
+ "FECE510F02D7FF1E7BAC"
);
performTestDecrypt(testCase);
}
/**
* Test for AES256_CTS_HMAC_SHA1_96 encryption type, with 0 byte
*/
@Test
public void testDecryptAES256_CTS_HMAC_SHA1_96_0() {
assumeTrue(CryptoUtil.isAES256Enabled());
TestCase testCase = new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"", 0,
"17F275F2954F2ED1F90C377BA7F4D6A3"
+ "69AA0136E0BF0C927AD6133C693759A9",
"E5094C55EE7B38262E2B044280B06937"
+ "9A95BF95BD8376FB3281B435"
);
performTestDecrypt(testCase);
}
/**
* Test for AES256_CTS_HMAC_SHA1_96 encryption type, with 1 byte
*/
@Test
public void testDecryptAES256_CTS_HMAC_SHA1_96_1() {
assumeTrue(CryptoUtil.isAES256Enabled());
TestCase testCase = new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"1", 1,
"B9477E1FF0329C0050E20CE6C72D2DFF"
+ "27E8FE541AB0954429A9CB5B4F7B1E2A",
"406150B97AEB76D43B36B62CC1ECDFBE"
+ "6F40E95755E0BEB5C27825F3A4"
);
performTestDecrypt(testCase);
}
/**
* Test for AES256_CTS_HMAC_SHA1_96 encryption type, with 9 bytes
*/
@Test
public void testDecryptAES256_CTS_HMAC_SHA1_96_9() {
assumeTrue(CryptoUtil.isAES256Enabled());
TestCase testCase = new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"9 bytesss", 2,
"B1AE4CD8462AFF1677053CC9279AAC30"
+ "B796FB81CE21474DD3DDBCFEA4EC76D7",
"09957AA25FCAF88F7B39E4406E633012"
+ "D5FEA21853F6478DA7065CAEF41FD454"
+ "A40824EEC5"
);
performTestDecrypt(testCase);
}
/**
* Test for AES256_CTS_HMAC_SHA1_96 encryption type, with 13 bytes
*/
@Test
public void testDecryptAES256_CTS_HMAC_SHA1_96_13() {
assumeTrue(CryptoUtil.isAES256Enabled());
TestCase testCase = new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"13 bytes byte", 3,
"E5A72BE9B7926C1225BAFEF9C1872E7B"
+ "A4CDB2B17893D84ABD90ACDD8764D966",
"D8F1AAFEEC84587CC3E700A774E56651"
+ "A6D693E174EC4473B5E6D96F80297A65"
+ "3FB818AD893E719F96"
);
performTestDecrypt(testCase);
}
/**
* Test for AES256_CTS_HMAC_SHA1_96 encryption type, with 30 bytes
*/
@Test
public void testDecryptAES256_CTS_HMAC_SHA1_96_30() {
assumeTrue(CryptoUtil.isAES256Enabled());
TestCase testCase = new TestCase(
EncryptionType.AES256_CTS_HMAC_SHA1_96,
"30 bytes bytes bytes bytes byt", 4,
"F1C795E9248A09338D82C3F8D5B56704"
+ "0B0110736845041347235B1404231398",
"D1137A4D634CFECE924DBC3BF6790648"
+ "BD5CFF7DE0E7B99460211D0DAEF3D79A"
+ "295C688858F3B34B9CBD6EEBAE81DAF6"
+ "B734D4D498B6714F1C1D"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA128_CTS_CMAC encryption type, with 0 byte
*/
@Test
public void testDecryptCAMELIA128_CTS_CMAC_0() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"", 0,
"1DC46A8D763F4F93742BCBA3387576C3",
"C466F1871069921EDB7C6FDE244A52DB"
+ "0BA10EDC197BDB8006658CA3CCCE6EB8"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA128_CTS_CMAC encryption type, with 1 byte
*/
@Test
public void testDecryptCAMELIA128_CTS_CMAC_1() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"1", 1,
"5027BC231D0F3A9D23333F1CA6FDBE7C",
"842D21FD950311C0DD464A3F4BE8D6DA"
+ "88A56D559C9B47D3F9A85067AF661559"
+ "B8"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA128_CTS_CMAC encryption type, with 9 bytes
*/
@Test
public void testDecryptCAMELIA128_CTS_CMAC_9() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"9 bytesss", 2,
"A1BB61E805F9BA6DDE8FDBDDC05CDEA0",
"619FF072E36286FF0A28DEB3A352EC0D"
+ "0EDF5C5160D663C901758CCF9D1ED33D"
+ "71DB8F23AABF8348A0"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA128_CTS_CMAC encryption type, with 13 bytes
*/
@Test
public void testDecryptCAMELIA128_CTS_CMAC_13() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"13 bytes byte", 3,
"2CA27A5FAF5532244506434E1CEF6676",
"B8ECA3167AE6315512E59F98A7C50020"
+ "5E5F63FF3BB389AF1C41A21D640D8615"
+ "C9ED3FBEB05AB6ACB67689B5EA"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA128_CTS_CMAC encryption type, with 30 bytes
*/
@Test
public void testDecryptCAMELIA128_CTS_CMAC_30() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA128_CTS_CMAC,
"30 bytes bytes bytes bytes byt", 4,
"7824F8C16F83FF354C6BF7515B973F43",
"A26A3905A4FFD5816B7B1E27380D0809"
+ "0C8EC1F304496E1ABDCD2BDCD1DFFC66"
+ "0989E117A713DDBB57A4146C1587CBA4"
+ "356665591D2240282F5842B105A5"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA256_CTS_CMAC encryption type, with 0 byte
*/
@Test
public void testDecryptCAMELIA256_CTS_CMAC_0() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"", 0,
"B61C86CC4E5D2757545AD423399FB703"
+ "1ECAB913CBB900BD7A3C6DD8BF92015B",
"03886D03310B47A6D8F06D7B94D1DD83"
+ "7ECCE315EF652AFF620859D94A259266"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA256_CTS_CMAC encryption type, with 1 byte
*/
@Test
public void testDecryptCAMELIA256_CTS_CMAC_1() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"1", 1,
"1B97FE0A190E2021EB30753E1B6E1E77"
+ "B0754B1D684610355864104963463833",
"2C9C1570133C99BF6A34BC1B0212002F"
+ "D194338749DB4135497A347CFCD9D18A12"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA256_CTS_CMAC encryption type, with 9 bytes
*/
@Test
public void testDecryptCAMELIA256_CTS_CMAC_9() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"9 bytesss", 2,
"32164C5B434D1D1538E4CFD9BE8040FE"
+ "8C4AC7ACC4B93D3314D2133668147A05",
"9C6DE75F812DE7ED0D28B2963557A115"
+ "640998275B0AF5152709913FF52A2A9C"
+ "8E63B872F92E64C839"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA256_CTS_CMAC encryption type, with 13 bytes
*/
@Test
public void testDecryptCAMELIA256_CTS_CMAC_13() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"13 bytes byte", 3,
"B038B132CD8E06612267FAB7170066D8"
+ "8AECCBA0B744BFC60DC89BCA182D0715",
"EEEC85A9813CDC536772AB9B42DEFC57"
+ "06F726E975DDE05A87EB5406EA324CA1"
+ "85C9986B42AABE794B84821BEE"
);
performTestDecrypt(testCase);
}
/**
* Test for CAMELLIA256_CTS_CMAC encryption type, with 30 bytes
*/
@Test
public void testDecryptCAMELIA256_CTS_CMAC_30() {
TestCase testCase = new TestCase(
EncryptionType.CAMELLIA256_CTS_CMAC,
"30 bytes bytes bytes bytes byt", 4,
"CCFCD349BF4C6677E86E4B02B8EAB924"
+ "A546AC731CF9BF6989B996E7D6BFBBA7",
"0E44680985855F2D1F1812529CA83BFD"
+ "8E349DE6FD9ADA0BAAA048D68E265FEB"
+ "F34AD1255A344999AD37146887A6C684"
+ "5731AC7F46376A0504CD06571474"
);
performTestDecrypt(testCase);
}
}
| 277 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/DesKeyMakerTest.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;
import org.apache.kerby.kerberos.kerb.crypto.key.DesKeyMaker;
import org.apache.kerby.util.HexUtil;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* This is just for my experimental tweaking, so pleas bear it.
*/
public class DesKeyMakerTest {
/**
* The class used to store the test values
*/
private static final class TestCase {
String salt;
String passwd;
String passwdSaltBytes;
String fanFoldedKey;
String intermediateKey;
String finalKey;
private TestCase(String salt, String passwd, String passwdSaltBytes,
String fanFoldedKey, String intermediateKey, String finalKey) {
this.salt = salt;
this.passwd = passwd;
this.passwdSaltBytes = passwdSaltBytes;
this.fanFoldedKey = fanFoldedKey;
this.intermediateKey = intermediateKey;
this.finalKey = finalKey;
}
}
/**
* Actually do the test
*/
private void test(TestCase tc) {
byte[] expectedValue = HexUtil.hex2bytes(tc.passwdSaltBytes);
byte[] value = DesKeyMaker.makePasswdSalt(tc.passwd, tc.salt);
assertThat(value).as("PasswdSalt bytes").isEqualTo(expectedValue);
expectedValue = HexUtil.hex2bytes(tc.fanFoldedKey);
value = DesKeyMaker.fanFold(tc.passwd, tc.salt, null);
assertThat(value).as("FanFold result").isEqualTo(expectedValue);
expectedValue = HexUtil.hex2bytes(tc.intermediateKey);
value = DesKeyMaker.intermediateKey(value);
assertThat(value).as("IntermediateKey result").isEqualTo(expectedValue);
// finalKey check ignored here and it's done in String2keyTest.
}
/**
* This is just for my experimental tweaking, so pleas bear it.
*/
@Test
@org.junit.jupiter.api.Disabled
public void testCase1() {
TestCase tc = new TestCase("ATHENA.MIT.EDUraeburn",
"password", "70617373776f7264415448454e412e4d49542e4544557261656275726e",
"c01e38688ac86c2e", "c11f38688ac86d2f", "cbc22fae235298e3");
test(tc);
}
}
| 278 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/dh/DhGroupTest.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.dh;
import org.junit.jupiter.api.Test;
/**
* "When using the Diffie-Hellman key agreement method, implementations MUST
* support Oakley 1024-bit Modular Exponential (MODP) well-known group 2
* [RFC2412] and Oakley 2048-bit MODP well-known group 14 [RFC3526] and
* SHOULD support Oakley 4096-bit MODP well-known group 16 [RFC3526]."
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class DhGroupTest extends org.junit.jupiter.api.Assertions {
/**
* Tests that the translation of the hex representation of the prime modulus
* resulted in the expected bit length.
*/
@Test
public void testPrimeBitLengths() {
assertEquals(1024, DhGroup.MODP_GROUP2.getP().bitLength());
assertEquals(2048, DhGroup.MODP_GROUP14.getP().bitLength());
assertEquals(4096, DhGroup.MODP_GROUP16.getP().bitLength());
}
/**
* Tests the generator values.
*/
@Test
public void testGeneratorValues() {
assertEquals(2, DhGroup.MODP_GROUP2.getG().intValue());
assertEquals(2, DhGroup.MODP_GROUP14.getG().intValue());
assertEquals(2, DhGroup.MODP_GROUP16.getG().intValue());
}
}
| 279 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/dh/OctetString2KeyTest.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.dh;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* From RFC 4556:
* <p/>
* "Appendix B. Test Vectors
* <p/>
* Function octetstring2key() is defined in Section 3.2.3.1. This section describes
* a few sets of test vectors that would be useful for implementers of octetstring2key()."
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class OctetString2KeyTest extends org.junit.jupiter.api.Assertions {
/**
* Set 1:
* =====
* Input octet string x is:
* <p/>
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* <p/>
* Output of K-truncate() when the key size is 32 octets:
* <p/>
* 5e e5 0d 67 5c 80 9f e5 9e 4a 77 62 c5 4b 65 83
* 75 47 ea fb 15 9b d8 cd c7 5f fc a5 91 1e 4c 41
*/
@Test
public void testSet1() {
byte[] inputOctetString = new byte[16 * 16];
byte[] expectedOutput =
{(byte) 0x5e, (byte) 0xe5, (byte) 0x0d, (byte) 0x67, (byte) 0x5c, (byte) 0x80, (byte) 0x9f,
(byte) 0xe5, (byte) 0x9e, (byte) 0x4a, (byte) 0x77, (byte) 0x62, (byte) 0xc5,
(byte) 0x4b, (byte) 0x65, (byte) 0x83, (byte) 0x75, (byte) 0x47, (byte) 0xea,
(byte) 0xfb, (byte) 0x15, (byte) 0x9b, (byte) 0xd8, (byte) 0xcd, (byte) 0xc7,
(byte) 0x5f, (byte) 0xfc, (byte) 0xa5, (byte) 0x91, (byte) 0x1e, (byte) 0x4c, (byte) 0x41};
int keySize = 32 * 8;
byte[] result = OctetString2Key.kTruncate(keySize, inputOctetString);
assertTrue(Arrays.equals(result, expectedOutput));
}
/**
* Set 2:
* =====
* Input octet string x is:
* <p/>
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
* <p/>
* Output of K-truncate() when the key size is 32 octets:
* <p/>
* ac f7 70 7c 08 97 3d df db 27 cd 36 14 42 cc fb
* a3 55 c8 88 4c b4 72 f3 7d a6 36 d0 7d 56 78 7e
*/
@Test
public void testSet2() {
byte[] inputOctetString = new byte[16 * 8];
byte[] expectedOutput =
{(byte) 0xac, (byte) 0xf7, (byte) 0x70, (byte) 0x7c, (byte) 0x08, (byte) 0x97, (byte) 0x3d,
(byte) 0xdf, (byte) 0xdb, (byte) 0x27, (byte) 0xcd, (byte) 0x36, (byte) 0x14,
(byte) 0x42, (byte) 0xcc, (byte) 0xfb, (byte) 0xa3, (byte) 0x55, (byte) 0xc8,
(byte) 0x88, (byte) 0x4c, (byte) 0xb4, (byte) 0x72, (byte) 0xf3, (byte) 0x7d,
(byte) 0xa6, (byte) 0x36, (byte) 0xd0, (byte) 0x7d, (byte) 0x56, (byte) 0x78, (byte) 0x7e};
int keySize = 32 * 8;
byte[] result = OctetString2Key.kTruncate(keySize, inputOctetString);
assertTrue(Arrays.equals(result, expectedOutput));
}
/**
* Set 3:
* ======
* Input octet string x is:
* <p/>
* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
* 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e
* 0f 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d
* 0e 0f 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c
* 0d 0e 0f 10 00 01 02 03 04 05 06 07 08 09 0a 0b
* 0c 0d 0e 0f 10 00 01 02 03 04 05 06 07 08 09 0a
* 0b 0c 0d 0e 0f 10 00 01 02 03 04 05 06 07 08 09
* 0a 0b 0c 0d 0e 0f 10 00 01 02 03 04 05 06 07 08
* <p/>
* Output of K-truncate() when the key size is 32 octets:
* <p/>
* c4 42 da 58 5f cb 80 e4 3b 47 94 6f 25 40 93 e3
* 73 29 d9 90 01 38 0d b7 83 71 db 3a cf 5c 79 7e
*/
@Test
public void testSet3() {
byte[] inputOctetString =
{(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06,
(byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c,
(byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
(byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d,
(byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02,
(byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08,
(byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e,
(byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
(byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09,
(byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f,
(byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04,
(byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a,
(byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10,
(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05,
(byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b,
(byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00,
(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06,
(byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c,
(byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08};
byte[] expectedOutput =
{(byte) 0xc4, (byte) 0x42, (byte) 0xda, (byte) 0x58, (byte) 0x5f, (byte) 0xcb, (byte) 0x80,
(byte) 0xe4, (byte) 0x3b, (byte) 0x47, (byte) 0x94, (byte) 0x6f, (byte) 0x25,
(byte) 0x40, (byte) 0x93, (byte) 0xe3, (byte) 0x73, (byte) 0x29, (byte) 0xd9,
(byte) 0x90, (byte) 0x01, (byte) 0x38, (byte) 0x0d, (byte) 0xb7, (byte) 0x83,
(byte) 0x71, (byte) 0xdb, (byte) 0x3a, (byte) 0xcf, (byte) 0x5c, (byte) 0x79, (byte) 0x7e};
int keySize = 32 * 8;
byte[] result = OctetString2Key.kTruncate(keySize, inputOctetString);
assertTrue(Arrays.equals(result, expectedOutput));
}
/**
* Set 4:
* =====
* Input octet string x is:
* <p/>
* 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
* 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e
* 0f 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d
* 0e 0f 10 00 01 02 03 04 05 06 07 08 09 0a 0b 0c
* 0d 0e 0f 10 00 01 02 03 04 05 06 07 08
* <p/>
* Output of K-truncate() when the key size is 32 octets:
* <p/>
* 00 53 95 3b 84 c8 96 f4 eb 38 5c 3f 2e 75 1c 4a
* 59 0e d6 ff ad ca 6f f6 4f 47 eb eb 8d 78 0f fc
*/
@Test
public void testSet4() {
byte[] inputOctetString =
{(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06,
(byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c,
(byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
(byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d,
(byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02,
(byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08,
(byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e,
(byte) 0x0f, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03,
(byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09,
(byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f,
(byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04,
(byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08};
byte[] expectedOutput =
{(byte) 0x00, (byte) 0x53, (byte) 0x95, (byte) 0x3b, (byte) 0x84, (byte) 0xc8, (byte) 0x96,
(byte) 0xf4, (byte) 0xeb, (byte) 0x38, (byte) 0x5c, (byte) 0x3f, (byte) 0x2e,
(byte) 0x75, (byte) 0x1c, (byte) 0x4a, (byte) 0x59, (byte) 0x0e, (byte) 0xd6,
(byte) 0xff, (byte) 0xad, (byte) 0xca, (byte) 0x6f, (byte) 0xf6, (byte) 0x4f,
(byte) 0x47, (byte) 0xeb, (byte) 0xeb, (byte) 0x8d, (byte) 0x78, (byte) 0x0f, (byte) 0xfc};
int keySize = 32 * 8;
byte[] result = OctetString2Key.kTruncate(keySize, inputOctetString);
assertTrue(Arrays.equals(result, expectedOutput));
}
}
| 280 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/test/java/org/apache/kerby/kerberos/kerb/crypto/dh/DhKeyAgreementTest.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.dh;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.SecureRandom;
import java.util.Arrays;
/**
* Tests the Diffie-Hellman key agreement protocol between a client and server.
* <p/>
* Generating a Secret Key Using the Diffie-Hellman Key Agreement Algorithm
* <p/>
* Two parties use a key agreement protocol to generate identical secret keys for
* encryption without ever having to transmit the secret key. The protocol works
* by both parties agreeing on a set of values (a prime, a base, and a private
* value) which are used to generate a key pair.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class DhKeyAgreementTest {
private static SecureRandom secureRandom = new SecureRandom();
/**
* Tests Diffie-Hellman using Oakley 1024-bit Modular Exponential (MODP)
* well-known group 2 [RFC2412].
*
* @throws Exception
*/
@Test
public void testPreGeneratedDhParams() throws Exception {
DiffieHellmanClient client = new DiffieHellmanClient();
DiffieHellmanServer server = new DiffieHellmanServer();
byte[] clientPubKeyEnc = client.init(DhGroup.MODP_GROUP2).getEncoded();
byte[] serverPubKeyEnc = server.initAndDoPhase(clientPubKeyEnc).getEncoded();
server.generateKey(null, null, EncryptionType.AES128_CTS_HMAC_SHA1_96);
client.doPhase(serverPubKeyEnc);
client.generateKey(null, null, EncryptionType.AES128_CTS_HMAC_SHA1_96);
byte[] clearText = "This is just an example".getBytes();
byte[] cipherText = server.encrypt(clearText, KeyUsage.UNKNOWN);
byte[] recovered = client.decrypt(cipherText, KeyUsage.UNKNOWN);
Assertions.assertTrue(Arrays.equals(clearText, recovered));
}
/**
* Tests Diffie-Hellman using Oakley 1024-bit Modular Exponential (MODP)
* well-known group 2 [RFC2412], including the optional DH nonce.
* <p/>
* "This nonce string MUST be as long as the longest key length of the symmetric
* key types that the client supports. This nonce MUST be chosen randomly."
*
* @throws Exception
*/
@Test
public void testPreGeneratedDhParamsWithNonce() throws Exception {
byte[] clientDhNonce = new byte[16];
secureRandom.nextBytes(clientDhNonce);
byte[] serverDhNonce = new byte[16];
secureRandom.nextBytes(serverDhNonce);
DiffieHellmanClient client = new DiffieHellmanClient();
DiffieHellmanServer server = new DiffieHellmanServer();
byte[] clientPubKeyEnc = client.init(DhGroup.MODP_GROUP2).getEncoded();
byte[] serverPubKeyEnc = server.initAndDoPhase(clientPubKeyEnc).getEncoded();
server.generateKey(clientDhNonce, serverDhNonce, EncryptionType.AES128_CTS_HMAC_SHA1_96);
client.doPhase(serverPubKeyEnc);
client.generateKey(clientDhNonce, serverDhNonce, EncryptionType.AES128_CTS_HMAC_SHA1_96);
byte[] clearText = "This is just an example".getBytes();
byte[] cipherText = server.encrypt(clearText, KeyUsage.UNKNOWN);
byte[] recovered = client.decrypt(cipherText, KeyUsage.UNKNOWN);
Assertions.assertTrue(Arrays.equals(clearText, recovered));
}
@Test
public void testGeneratedDhParams() throws Exception {
DiffieHellmanClient client = new DiffieHellmanClient();
DiffieHellmanServer server = new DiffieHellmanServer();
DHPublicKey clientPubKey = client.init(DhGroup.MODP_GROUP2);
DHParameterSpec spec = clientPubKey.getParams();
BigInteger y = clientPubKey.getY();
BigInteger p = spec.getP();
BigInteger g = spec.getG();
DHPublicKeySpec dhPublicKeySpec = new DHPublicKeySpec(y, p, g);
KeyFactory keyFactory = KeyFactory.getInstance("DH");
DHPublicKey dhPublicKey =
(DHPublicKey) keyFactory.generatePublic(dhPublicKeySpec);
byte[] serverPubKeyEnc = server.initAndDoPhase(dhPublicKey.getEncoded()).getEncoded();
server.generateKey(null, null, EncryptionType.AES128_CTS_HMAC_SHA1_96);
client.doPhase(serverPubKeyEnc);
client.generateKey(null, null, EncryptionType.AES128_CTS_HMAC_SHA1_96);
byte[] clearText = "This is just an example".getBytes();
byte[] cipherText = server.encrypt(clearText, KeyUsage.UNKNOWN);
byte[] recovered = client.decrypt(cipherText, KeyUsage.UNKNOWN);
Assertions.assertTrue(Arrays.equals(clearText, recovered));
}
}
| 281 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/CryptoTypeHandler.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;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider;
import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider;
public interface CryptoTypeHandler {
String name();
String displayName();
EncryptProvider encProvider();
HashProvider hashProvider();
}
| 282 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/CheckSumHandler.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;
import org.apache.kerby.kerberos.kerb.KrbErrorCode;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.crypto.cksum.CmacCamellia128CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.CmacCamellia256CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.Crc32CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.DesCbcCheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HmacMd5Rc4CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HmacSha1Aes128CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HmacSha1Aes256CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HmacSha1Des3CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.Md5HmacRc4CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.RsaMd4CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.RsaMd4DesCheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.RsaMd5CheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.RsaMd5DesCheckSum;
import org.apache.kerby.kerberos.kerb.crypto.cksum.Sha1CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSum;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
/**
* Checksum handler as the highest level API for checksum stuffs defined in
* Kerberos RFC3961. It supports all the checksum types. New checksum type
* should be added updating this.
*/
public class CheckSumHandler {
public static CheckSumTypeHandler getCheckSumHandler(String cksumType) throws KrbException {
CheckSumType eTypeEnum = CheckSumType.fromName(cksumType);
return getCheckSumHandler(eTypeEnum);
}
public static CheckSumTypeHandler getCheckSumHandler(int cksumType) throws KrbException {
CheckSumType eTypeEnum = CheckSumType.fromValue(cksumType);
return getCheckSumHandler(eTypeEnum);
}
public static boolean isImplemented(CheckSumType cksumType) throws KrbException {
return getCheckSumHandler(cksumType, true) != null;
}
public static CheckSumTypeHandler getCheckSumHandler(
CheckSumType cksumType) throws KrbException {
return getCheckSumHandler(cksumType, false);
}
/**
* Ref. cksumtypes.c in MIT krb5 project.
*/
private static CheckSumTypeHandler getCheckSumHandler(CheckSumType cksumType,
boolean check) throws KrbException {
CheckSumTypeHandler cksumHandler = null;
switch (cksumType) {
case CRC32:
cksumHandler = new Crc32CheckSum();
break;
case DES_MAC:
cksumHandler = new DesCbcCheckSum();
break;
case RSA_MD4:
cksumHandler = new RsaMd4CheckSum();
break;
case RSA_MD5:
cksumHandler = new RsaMd5CheckSum();
break;
case NIST_SHA:
cksumHandler = new Sha1CheckSum();
break;
case RSA_MD4_DES:
cksumHandler = new RsaMd4DesCheckSum();
break;
case RSA_MD5_DES:
cksumHandler = new RsaMd5DesCheckSum();
break;
case HMAC_SHA1_DES3:
case HMAC_SHA1_DES3_KD:
cksumHandler = new HmacSha1Des3CheckSum();
break;
case HMAC_SHA1_96_AES128:
cksumHandler = new HmacSha1Aes128CheckSum();
break;
case HMAC_SHA1_96_AES256:
cksumHandler = new HmacSha1Aes256CheckSum();
break;
case CMAC_CAMELLIA128:
cksumHandler = new CmacCamellia128CheckSum();
break;
case CMAC_CAMELLIA256:
cksumHandler = new CmacCamellia256CheckSum();
break;
case HMAC_MD5_ARCFOUR:
cksumHandler = new HmacMd5Rc4CheckSum();
break;
case MD5_HMAC_ARCFOUR:
cksumHandler = new Md5HmacRc4CheckSum();
break;
default:
break;
}
if (cksumHandler == null && !check) {
String message = "Unsupported checksum type: " + cksumType.name();
throw new KrbException(KrbErrorCode.KDC_ERR_SUMTYPE_NOSUPP, message);
}
return cksumHandler;
}
public static CheckSum checksum(CheckSumType checkSumType,
byte[] bytes) throws KrbException {
CheckSumTypeHandler handler = getCheckSumHandler(checkSumType);
byte[] checksumBytes = handler.checksum(bytes);
CheckSum checkSum = new CheckSum();
checkSum.setCksumtype(checkSumType);
checkSum.setChecksum(checksumBytes);
return checkSum;
}
public static boolean verify(CheckSum checkSum, byte[] bytes) throws KrbException {
CheckSumType checkSumType = checkSum.getCksumtype();
CheckSumTypeHandler handler = getCheckSumHandler(checkSumType);
return handler.verify(bytes, checkSum.getChecksum());
}
public static CheckSum checksumWithKey(CheckSumType checkSumType,
byte[] bytes, byte[] key, KeyUsage usage) throws KrbException {
CheckSumTypeHandler handler = getCheckSumHandler(checkSumType);
byte[] checksumBytes = handler.checksumWithKey(bytes, key, usage.getValue());
CheckSum checkSum = new CheckSum();
checkSum.setCksumtype(checkSumType);
checkSum.setChecksum(checksumBytes);
return checkSum;
}
public static boolean verifyWithKey(CheckSum checkSum, byte[] bytes,
byte[] key, KeyUsage usage) throws KrbException {
CheckSumType checkSumType = checkSum.getCksumtype();
CheckSumTypeHandler handler = getCheckSumHandler(checkSumType);
return handler.verifyWithKey(bytes, key,
usage.getValue(), checkSum.getChecksum());
}
}
| 283 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/EncTypeHandler.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;
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 interface EncTypeHandler extends CryptoTypeHandler {
EncryptionType eType();
int keyInputSize();
int keySize();
int confounderSize();
int checksumSize();
int prfSize();
byte[] prf(byte[] key, byte[] seed) throws KrbException;
int paddingSize();
byte[] str2key(String string,
String salt, byte[] param) throws KrbException;
byte[] random2Key(byte[] randomBits) throws KrbException;
CheckSumType checksumType();
byte[] encrypt(byte[] data, byte[] key, int usage)
throws KrbException;
byte[] encrypt(byte[] data, byte[] key, byte[] ivec,
int usage) throws KrbException;
byte[] encryptRaw(byte[] data, byte[] key, int usage)
throws KrbException;
byte[] encryptRaw(byte[] data, byte[] key, byte[] ivec,
int usage) throws KrbException;
byte[] decrypt(byte[] cipher, byte[] key, int usage)
throws KrbException;
byte[] decrypt(byte[] cipher, byte[] key, byte[] ivec,
int usage) throws KrbException;
byte[] decryptRaw(byte[] data, byte[] key, int usage)
throws KrbException;
byte[] decryptRaw(byte[] cipher, byte[] key, byte[] ivec,
int usage) throws KrbException;
}
| 284 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/EncryptionHandler.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;
import org.apache.kerby.kerberos.kerb.KrbErrorCode;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.crypto.enc.Aes128CtsHmacSha1Enc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Aes256CtsHmacSha1Enc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Camellia128CtsCmacEnc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Camellia256CtsCmacEnc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Des3CbcSha1Enc;
import org.apache.kerby.kerberos.kerb.crypto.enc.DesCbcCrcEnc;
import org.apache.kerby.kerberos.kerb.crypto.enc.DesCbcMd4Enc;
import org.apache.kerby.kerberos.kerb.crypto.enc.DesCbcMd5Enc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Rc4HmacEnc;
import org.apache.kerby.kerberos.kerb.crypto.enc.Rc4HmacExpEnc;
import org.apache.kerby.kerberos.kerb.crypto.util.Random;
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.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
/**
* Encryption handler as the highest level API for encryption stuffs defined in
* Kerberos RFC3961. It supports all the encryption types. New encryption type
* should be added updating this.
*/
public class EncryptionHandler {
/**
* Get the encryption type.
* @param eType The encryption type string.
* @return The EncryptionType
* @throws KrbException e
*/
public static EncryptionType getEncryptionType(String eType) throws KrbException {
return EncryptionType.fromName(eType);
}
/**
* Get the encryption handler.
*
* @param eType The encryption type string
* @return The EncTypeHandler
* @throws KrbException e
*/
public static EncTypeHandler getEncHandler(String eType) throws KrbException {
EncryptionType result = EncryptionType.fromName(eType);
return getEncHandler(result);
}
/**
* Get the encryption handler.
*
* @param eType The encryption type int
* @return The EncTypeHandler
* @throws KrbException e
*/
public static EncTypeHandler getEncHandler(int eType) throws KrbException {
EncryptionType eTypeEnum = EncryptionType.fromValue(eType);
return getEncHandler(eTypeEnum);
}
/**
* Get the encryption handler.
*
* @param eType The encryption type
* @return The EncTypeHandler
* @throws KrbException e
*/
public static EncTypeHandler getEncHandler(EncryptionType eType) throws KrbException {
return getEncHandler(eType, false);
}
/**
* Get the encryption handler.
*
* @param eType The encryption type
* @param check true if check
* @return The EncTypeHandler
* @throws KrbException e
*/
private static EncTypeHandler getEncHandler(EncryptionType eType,
boolean check) throws KrbException {
EncTypeHandler encHandler = null;
/**
* Ref. etypes.c in MIT krb5 project.
*/
switch (eType) {
case DES_CBC_CRC:
encHandler = new DesCbcCrcEnc();
break;
case DES_CBC_MD5:
case DES:
encHandler = new DesCbcMd5Enc();
break;
case DES_CBC_MD4:
encHandler = new DesCbcMd4Enc();
break;
case DES3_CBC_SHA1:
case DES3_CBC_SHA1_KD:
case DES3_HMAC_SHA1:
encHandler = new Des3CbcSha1Enc();
break;
case AES128_CTS_HMAC_SHA1_96:
case AES128_CTS:
encHandler = new Aes128CtsHmacSha1Enc();
break;
case AES256_CTS_HMAC_SHA1_96:
case AES256_CTS:
encHandler = new Aes256CtsHmacSha1Enc();
break;
case CAMELLIA128_CTS_CMAC:
case CAMELLIA128_CTS:
encHandler = new Camellia128CtsCmacEnc();
break;
case CAMELLIA256_CTS_CMAC:
case CAMELLIA256_CTS:
encHandler = new Camellia256CtsCmacEnc();
break;
case RC4_HMAC:
case ARCFOUR_HMAC:
case ARCFOUR_HMAC_MD5:
encHandler = new Rc4HmacEnc();
break;
case RC4_HMAC_EXP:
case ARCFOUR_HMAC_EXP:
case ARCFOUR_HMAC_MD5_EXP:
encHandler = new Rc4HmacExpEnc();
break;
case NONE:
default:
break;
}
if (encHandler == null && !check) {
String message = "Unsupported encryption type: " + eType.name();
throw new KrbException(KrbErrorCode.KDC_ERR_ETYPE_NOSUPP, message);
}
return encHandler;
}
/**
* Encrypt with the encryption key and key usage.
*
* @param plainText The plain test
* @param key The encryption key
* @param usage The key usage
* @return The encrypted data
* @throws KrbException e
*/
public static EncryptedData encrypt(byte[] plainText, EncryptionKey key,
KeyUsage usage) throws KrbException {
EncTypeHandler handler = getEncHandler(key.getKeyType());
byte[] cipher = handler.encrypt(plainText, key.getKeyData(), usage.getValue());
EncryptedData ed = new EncryptedData();
ed.setCipher(cipher);
ed.setEType(key.getKeyType());
if (key.getKvno() > 0) {
ed.setKvno(key.getKvno());
}
return ed;
}
/**
* Decrypt with the encryption key and key usage.
*
* @param data The encrypted data
* @param key The encryption key
* @param usage The key usage
* @return The decrypted data
* @throws KrbException e
*/
public static byte[] decrypt(byte[] data, EncryptionKey key,
KeyUsage usage) throws KrbException {
EncTypeHandler handler = getEncHandler(key.getKeyType());
return handler.decrypt(data, key.getKeyData(), usage.getValue());
}
/**
* Decrypt with the encryption key and key usage.
*
* @param data The encrypted data
* @param key The encryption key
* @param usage The key usage
* @return The decrypted data
* @throws KrbException e
*/
public static byte[] decrypt(EncryptedData data, EncryptionKey key,
KeyUsage usage) throws KrbException {
EncTypeHandler handler = getEncHandler(key.getKeyType());
return handler.decrypt(data.getCipher(),
key.getKeyData(), usage.getValue());
}
/**
* Return true if the the encryption handler is implemented.
*
* @param eType The encryption type
* @return true if the encryption handler is implemented
*/
public static boolean isImplemented(EncryptionType eType) {
EncTypeHandler handler = null;
try {
handler = getEncHandler(eType, true);
} catch (KrbException e) {
return false;
}
return handler != null;
}
/**
* String to key.
*
* @param principalName The principal name
* @param passPhrase The pass phrase
* @param eType The encryption type
* @return The encryption key
* @throws KrbException e
*/
public static EncryptionKey string2Key(String principalName,
String passPhrase, EncryptionType eType) throws KrbException {
PrincipalName principal = new PrincipalName(principalName);
return string2Key(passPhrase,
PrincipalName.makeSalt(principal), null, eType);
}
/**
* String to key.
*
* @param string The string
* @param salt The salt
* @param s2kparams The params
* @param eType The encryption type
* @return The encryption key
* @throws KrbException e
*/
public static EncryptionKey string2Key(String string, String salt,
byte[] s2kparams, EncryptionType eType) throws KrbException {
EncTypeHandler handler = getEncHandler(eType);
byte[] keyBytes = handler.str2key(string, salt, s2kparams);
return new EncryptionKey(eType, keyBytes);
}
/**
* Random to key.
*
* @param eType The encryption type
* @return The encryption key
* @throws KrbException e
*/
public static EncryptionKey random2Key(EncryptionType eType) throws KrbException {
EncTypeHandler handler = getEncHandler(eType);
byte[] randomBytes = Random.makeBytes(handler.keyInputSize());
byte[] keyBytes = handler.random2Key(randomBytes);
return new EncryptionKey(eType, keyBytes);
}
/**
* Random to key.
*
* @param eType The encryption type
* @param randomBytes The random bytes
* @return The encryption key
* @throws KrbException e
*/
public static EncryptionKey random2Key(EncryptionType eType, byte[] randomBytes) throws KrbException {
EncTypeHandler handler = getEncHandler(eType);
byte[] randomBytes1 = randomBytes;
byte[] keyBytes = handler.random2Key(randomBytes1);
return new EncryptionKey(eType, keyBytes);
}
/**
* Generate a secure and random key seeded with an existing encryption key.
* @param encKey The encryption key
* @return encryption key
*/
public static EncryptionKey makeSubkey(EncryptionKey encKey) {
//TODO: to implement.
return encKey;
}
}
| 285 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/CheckSumTypeHandler.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;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.type.base.CheckSumType;
public interface CheckSumTypeHandler extends CryptoTypeHandler {
int confounderSize();
CheckSumType cksumType();
int computeSize(); // allocation size for checksum computation
int outputSize(); // possibly truncated output size
boolean isSafe();
int cksumSize();
int keySize();
byte[] checksum(byte[] data) throws KrbException;
byte[] checksum(byte[] data, int start, int len) throws KrbException;
boolean verify(byte[] data, byte[] checksum) throws KrbException;
boolean verify(byte[] data, int start, int len, byte[] checksum) throws KrbException;
byte[] checksumWithKey(byte[] data,
byte[] key, int usage) throws KrbException;
byte[] checksumWithKey(byte[] data, int start, int len,
byte[] key, int usage) throws KrbException;
boolean verifyWithKey(byte[] data,
byte[] key, int usage, byte[] checksum) throws KrbException;
}
| 286 |
0 | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb | Create_ds/directory-kerby/kerby-kerb/kerb-crypto/src/main/java/org/apache/kerby/kerberos/kerb/crypto/AbstractCryptoTypeHandler.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;
import org.apache.kerby.kerberos.kerb.crypto.cksum.HashProvider;
import org.apache.kerby.kerberos.kerb.crypto.enc.EncryptProvider;
import java.util.Arrays;
public abstract class AbstractCryptoTypeHandler implements CryptoTypeHandler {
private EncryptProvider encProvider;
private HashProvider hashProvider;
public AbstractCryptoTypeHandler(EncryptProvider encProvider,
HashProvider hashProvider) {
this.encProvider = encProvider;
this.hashProvider = hashProvider;
}
@Override
public EncryptProvider encProvider() {
return encProvider;
}
@Override
public HashProvider hashProvider() {
return hashProvider;
}
protected static boolean checksumEqual(byte[] cksum1, byte[] cksum2) {
return Arrays.equals(cksum1, cksum2);
}
protected static boolean checksumEqual(byte[] cksum1,
byte[] cksum2, int cksum2Start, int len) {
if (cksum1 == cksum2) {
return true;
}
if (cksum1 == null || cksum2 == null) {
return false;
}
if (len <= cksum2.length && len <= cksum1.length) {
for (int i = 0; i < len; i++) {
if (cksum1[i] != cksum2[cksum2Start + i]) {
return false;
}
}
} else {
return false;
}
return true;
}
}
| 287 |
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/dh/DhGroup.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.dh;
import javax.crypto.spec.DHParameterSpec;
import java.math.BigInteger;
/**
* "When using the Diffie-Hellman key agreement method, implementations MUST
* support Oakley 1024-bit Modular Exponential (MODP) well-known group 2
* [RFC2412] and Oakley 2048-bit MODP well-known group 14 [RFC3526] and
* SHOULD support Oakley 4096-bit MODP well-known group 16 [RFC3526]."
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DhGroup {
/**
* From:
* The OAKLEY Key Determination Protocol
* http://www.ietf.org/rfc/rfc2412.txt
*
* Well-Known Group 2: A 1024 bit prime
* This group is assigned id 2 (two).
* The prime is 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
* The generator is 2 (decimal)
*/
public static final DHParameterSpec MODP_GROUP2;
static {
StringBuilder sb = new StringBuilder();
sb.append("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1");
sb.append("29024E088A67CC74020BBEA63B139B22514A08798E3404DD");
sb.append("EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245");
sb.append("E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED");
sb.append("EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381");
sb.append("FFFFFFFFFFFFFFFF");
BigInteger prime = new BigInteger(sb.toString(), 16);
BigInteger generator = BigInteger.valueOf(2);
MODP_GROUP2 = new DHParameterSpec(prime, generator);
}
/**
* From:
* More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)
* http://www.ietf.org/rfc/rfc3526.txt
*
* 2048-bit MODP Group
* This group is assigned id 14.
* This prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 }
* The generator is: 2.
*/
public static final DHParameterSpec MODP_GROUP14;
static {
StringBuilder sb = new StringBuilder();
sb.append("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1");
sb.append("29024E088A67CC74020BBEA63B139B22514A08798E3404DD");
sb.append("EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245");
sb.append("E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED");
sb.append("EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D");
sb.append("C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F");
sb.append("83655D23DCA3AD961C62F356208552BB9ED529077096966D");
sb.append("670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B");
sb.append("E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9");
sb.append("DE2BCBF6955817183995497CEA956AE515D2261898FA0510");
sb.append("15728E5A8AACAA68FFFFFFFFFFFFFFFF");
BigInteger prime = new BigInteger(sb.toString(), 16);
BigInteger generator = BigInteger.valueOf(2);
MODP_GROUP14 = new DHParameterSpec(prime, generator);
}
/**
* From:
* More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)
* http://www.ietf.org/rfc/rfc3526.txt
*
* 4096-bit MODP Group
* This group is assigned id 16.
* This prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 }
* The generator is: 2.
*/
public static final DHParameterSpec MODP_GROUP16;
static {
StringBuilder sb = new StringBuilder();
sb.append("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1");
sb.append("29024E088A67CC74020BBEA63B139B22514A08798E3404DD");
sb.append("EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245");
sb.append("E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED");
sb.append("EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D");
sb.append("C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F");
sb.append("83655D23DCA3AD961C62F356208552BB9ED529077096966D");
sb.append("670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B");
sb.append("E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9");
sb.append("DE2BCBF6955817183995497CEA956AE515D2261898FA0510");
sb.append("15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64");
sb.append("ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7");
sb.append("ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B");
sb.append("F12FFA06D98A0864D87602733EC86A64521F2B18177B200C");
sb.append("BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31");
sb.append("43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7");
sb.append("88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA");
sb.append("2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6");
sb.append("287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED");
sb.append("1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9");
sb.append("93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199");
sb.append("FFFFFFFFFFFFFFFF");
BigInteger prime = new BigInteger(sb.toString(), 16);
BigInteger generator = BigInteger.valueOf(2);
MODP_GROUP16 = new DHParameterSpec(prime, generator);
}
}
| 288 |
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/dh/OctetString2Key.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.dh;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* From RFC 4556:
*
* Define the function octetstring2key() as follows:
*
* octetstring2key(x) == random-to-key(K-truncate(
* SHA1(0x00 | x) |
* SHA1(0x01 | x) |
* SHA1(0x02 | x) |
* ...
* ))
*
* where x is an octet string; | is the concatenation operator; 0x00,
* 0x01, 0x02, etc. are each represented as a single octet; random-
* to-key() is an operation that generates a protocol key from a
* bitstring of length K; and K-truncate truncates its input to the
* first K bits. Both K and random-to-key() are as defined in the
* kcrypto profile [RFC3961] for the enctype of the AS reply key.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class OctetString2Key {
/**
* Performs the function K-truncate to generate the AS reply key k.
*
* @param k The k
* @param x The x
* @return The AS reply key value.
*/
public static byte[] kTruncate(int k, byte[] x) {
int numberOfBytes = k / 8;
byte[] result = new byte[numberOfBytes];
int count = 0;
byte[] filler = calculateIntegrity((byte) count, x);
int position = 0;
for (int i = 0; i < numberOfBytes; i++) {
if (position < filler.length) {
result[i] = filler[position];
position++;
} else {
count++;
filler = calculateIntegrity((byte) count, x);
position = 0;
result[i] = filler[position];
position++;
}
}
return result;
}
private static byte[] calculateIntegrity(byte count, byte[] data) {
try {
MessageDigest digester = MessageDigest.getInstance("SHA1");
digester.update(count);
return digester.digest(data);
} catch (NoSuchAlgorithmException nsae) {
return new byte[0];
}
}
}
| 289 |
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/dh/DiffieHellmanServer.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.dh;
import org.apache.kerby.kerberos.kerb.crypto.EncTypeHandler;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
/**
* The server-side of Diffie-Hellman key agreement for Kerberos PKINIT.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DiffieHellmanServer {
private KeyAgreement serverKeyAgree;
private EncryptionKey serverKey;
public PublicKey initAndDoPhase(byte[] clientPubKeyEnc) throws Exception {
/*
* The server has received the client's public key in encoded format. The
* server instantiates a DH public key from the encoded key material.
*/
KeyFactory serverKeyFac = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(clientPubKeyEnc);
PublicKey clientPubKey = serverKeyFac.generatePublic(x509KeySpec);
/*
* The server gets the DH parameters associated with the client's public
* key. The server must use the same parameters when it generates its own key pair.
*/
DHParameterSpec dhParamSpec = ((DHPublicKey) clientPubKey).getParams();
// The server creates its own DH key pair.
KeyPairGenerator serverKpairGen = KeyPairGenerator.getInstance("DH");
serverKpairGen.initialize(dhParamSpec);
KeyPair serverKpair = serverKpairGen.generateKeyPair();
// The server creates and initializes its DH KeyAgreement object.
serverKeyAgree = KeyAgreement.getInstance("DH");
serverKeyAgree.init(serverKpair.getPrivate());
/*
* The server uses the client's public key for the only phase of its
* side of the DH protocol.
*/
serverKeyAgree.doPhase(clientPubKey, true);
// The server encodes its public key, and sends it over to the client.
return serverKpair.getPublic();
}
public EncryptionKey generateKey(byte[] clientDhNonce, byte[] serverDhNonce, EncryptionType type) {
// ZZ length will be same as public key.
byte[] dhSharedSecret = serverKeyAgree.generateSecret();
byte[] x = dhSharedSecret;
if (clientDhNonce != null && clientDhNonce.length > 0
&& serverDhNonce != null && serverDhNonce.length > 0) {
x = concatenateBytes(dhSharedSecret, clientDhNonce);
x = concatenateBytes(x, serverDhNonce);
}
byte[] secret = OctetString2Key.kTruncate(dhSharedSecret.length, x);
serverKey = new EncryptionKey(type, secret);
return serverKey;
}
/**
* Encrypt
*
* @param clearText The clear test
* @return The cipher text.
* @throws Exception e
*/
public byte[] encrypt(byte[] clearText, KeyUsage usage) throws Exception {
// Use the secret key to encrypt/decrypt data.
EncTypeHandler encType = EncryptionHandler.getEncHandler(serverKey.getKeyType());
return encType.encrypt(clearText, serverKey.getKeyData(), usage.getValue());
}
private byte[] concatenateBytes(byte[] array1, byte[] array2) {
byte[] concatenatedBytes = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, concatenatedBytes, 0, array1.length);
for (int j = array1.length; j < concatenatedBytes.length; j++) {
concatenatedBytes[j] = array2[j - array1.length];
}
return concatenatedBytes;
}
}
| 290 |
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/dh/DiffieHellmanClient.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.dh;
import org.apache.kerby.kerberos.kerb.crypto.EncTypeHandler;
import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.KeyUsage;
import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
/**
* The client-side of Diffie-Hellman key agreement for Kerberos PKINIT.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class DiffieHellmanClient {
private KeyAgreement clientKeyAgree;
private EncryptionKey clientKey;
private DHParameterSpec dhParameterSpec;
public DHParameterSpec getDhParam() {
return dhParameterSpec;
}
public DHPublicKey init(DHParameterSpec dhParamSpec) throws Exception {
dhParameterSpec = dhParamSpec;
// The client creates its own DH key pair, using the DH parameters from above.
KeyPairGenerator clientKpairGen = KeyPairGenerator.getInstance("DH");
clientKpairGen.initialize(dhParamSpec);
KeyPair clientKpair = clientKpairGen.generateKeyPair();
// The client creates and initializes its DH KeyAgreement object.
clientKeyAgree = KeyAgreement.getInstance("DH");
clientKeyAgree.init(clientKpair.getPrivate());
// The client encodes its public key, and sends it over to the server.
return (DHPublicKey) clientKpair.getPublic();
}
public void doPhase(byte[] serverPubKeyEnc) throws Exception {
/*
* The client uses the server's public key for the first (and only) phase
* of its version of the DH protocol. Before it can do so, it has to
* instantiate a DH public key from the server's encoded key material.
*/
KeyFactory clientKeyFac = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(serverPubKeyEnc);
PublicKey serverPubKey = clientKeyFac.generatePublic(x509KeySpec);
clientKeyAgree.doPhase(serverPubKey, true);
}
public EncryptionKey generateKey(byte[] clientDhNonce, byte[] serverDhNonce, EncryptionType type) {
// ZZ length will be same as public key.
byte[] dhSharedSecret = clientKeyAgree.generateSecret();
byte[] x = dhSharedSecret;
if (clientDhNonce != null && clientDhNonce.length > 0
&& serverDhNonce != null && serverDhNonce.length > 0) {
x = concatenateBytes(dhSharedSecret, clientDhNonce);
x = concatenateBytes(x, serverDhNonce);
}
byte[] secret = OctetString2Key.kTruncate(dhSharedSecret.length, x);
clientKey = new EncryptionKey(type, secret);
return clientKey;
}
/**
* Decrypt
*
* @param cipherText
* @return The decrypted byte
* @throws Exception e
*/
public byte[] decrypt(byte[] cipherText, KeyUsage usage) throws Exception {
// Use the secret key to encrypt/decrypt data.
EncTypeHandler encType = EncryptionHandler.getEncHandler(clientKey.getKeyType());
return encType.decrypt(cipherText, clientKey.getKeyData(), usage.getValue());
}
private byte[] concatenateBytes(byte[] array1, byte[] array2) {
byte[] concatenatedBytes = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, concatenatedBytes, 0, array1.length);
for (int j = array1.length; j < concatenatedBytes.length; j++) {
concatenatedBytes[j] = array2[j - array1.length];
}
return concatenatedBytes;
}
}
| 291 |
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/Pbkdf.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 javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.GeneralSecurityException;
public class Pbkdf {
public static byte[] pbkdf2(char[] secret, byte[] salt,
int count, int keySize) throws GeneralSecurityException {
PBEKeySpec ks = new PBEKeySpec(secret, salt, count, keySize * 8);
SecretKeyFactory skf =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey key = skf.generateSecret(ks);
return key.getEncoded();
}
}
| 292 |
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/Des.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;
/**
* Ref. MIT krb5 weak_key.c
*/
public class Des {
/*
* The following are the weak DES keys:
*/
static final byte[][] WEAK_KEYS = {
/* weak keys */
{(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01},
{(byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe},
{(byte) 0x1f, (byte) 0x1f, (byte) 0x1f, (byte) 0x1f, (byte) 0x0e, (byte) 0x0e, (byte) 0x0e, (byte) 0x0e},
{(byte) 0xe0, (byte) 0xe0, (byte) 0xe0, (byte) 0xe0, (byte) 0xf1, (byte) 0xf1, (byte) 0xf1, (byte) 0xf1},
/* semi-weak */
{(byte) 0x01, (byte) 0xfe, (byte) 0x01, (byte) 0xfe, (byte) 0x01, (byte) 0xfe, (byte) 0x01, (byte) 0xfe},
{(byte) 0xfe, (byte) 0x01, (byte) 0xfe, (byte) 0x01, (byte) 0xfe, (byte) 0x01, (byte) 0xfe, (byte) 0x01},
{(byte) 0x1f, (byte) 0xe0, (byte) 0x1f, (byte) 0xe0, (byte) 0x0e, (byte) 0xf1, (byte) 0x0e, (byte) 0xf1},
{(byte) 0xe0, (byte) 0x1f, (byte) 0xe0, (byte) 0x1f, (byte) 0xf1, (byte) 0x0e, (byte) 0xf1, (byte) 0x0e},
{(byte) 0x01, (byte) 0xe0, (byte) 0x01, (byte) 0xe0, (byte) 0x01, (byte) 0xf1, (byte) 0x01, (byte) 0xf1},
{(byte) 0xe0, (byte) 0x01, (byte) 0xe0, (byte) 0x01, (byte) 0xf1, (byte) 0x01, (byte) 0xf1, (byte) 0x01},
{(byte) 0x1f, (byte) 0xfe, (byte) 0x1f, (byte) 0xfe, (byte) 0x0e, (byte) 0xfe, (byte) 0x0e, (byte) 0xfe},
{(byte) 0xfe, (byte) 0x1f, (byte) 0xfe, (byte) 0x1f, (byte) 0xfe, (byte) 0x0e, (byte) 0xfe, (byte) 0x0e},
{(byte) 0x01, (byte) 0x1f, (byte) 0x01, (byte) 0x1f, (byte) 0x01, (byte) 0x0e, (byte) 0x01, (byte) 0x0e},
{(byte) 0x1f, (byte) 0x01, (byte) 0x1f, (byte) 0x01, (byte) 0x0e, (byte) 0x01, (byte) 0x0e, (byte) 0x01},
{(byte) 0xe0, (byte) 0xfe, (byte) 0xe0, (byte) 0xfe, (byte) 0xf1, (byte) 0xfe, (byte) 0xf1, (byte) 0xfe},
{(byte) 0xfe, (byte) 0xe0, (byte) 0xfe, (byte) 0xe0, (byte) 0xfe, (byte) 0xf1, (byte) 0xfe, (byte) 0xf1}
};
public static boolean isWeakKey(byte[] key, int offset, int len) {
boolean match;
for (byte[] weakKey : WEAK_KEYS) {
match = true;
if (weakKey.length == len) {
for (int i = 0; i < len; i++) {
if (weakKey[i] != key[i]) {
match = false;
break;
}
}
}
if (match) {
return true;
}
}
return false;
}
/**
* MIT krb5 FIXUP(k) in s2k_des.c
* @param key The key byte
* @param offset The offset
* @param len The length
*/
public static void fixKey(byte[] key, int offset, int len) {
if (isWeakKey(key, offset, len)) {
key[offset + 7] ^= (byte) 0xf0;
}
}
}
| 293 |
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/Md4.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.security.DigestException;
import java.security.MessageDigest;
/**
* MD4.java - An implementation of Ron Rivest's MD4 message digest algorithm.
* The MD4 algorithm is designed to be quite fast on 32-bit machines. In
* addition, the MD4 algorithm does not require any large substitution
* tables.
*
* @see The <a href="http://www.ietf.org/rfc/rfc1320.txt">MD4</a> Message-
* Digest Algorithm by R. Rivest.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
* @since MINA 2.0.0-M3
*/
/**
* Copied from Mina project and modified a bit
*/
@SuppressWarnings("PMD")
public class Md4 extends MessageDigest {
/**
* The MD4 algorithm message digest length is 16 bytes wide.
*/
public static final int BYTE_DIGEST_LENGTH = 16;
/**
* The MD4 algorithm block length is 64 bytes wide.
*/
public static final int BYTE_BLOCK_LENGTH = 64;
/**
* The initial values of the four registers. RFC gives the values
* in LE so we converted it as JAVA uses BE endianness.
*/
private static final int A = 0x67452301;
private static final int B = 0xefcdab89;
private static final int C = 0x98badcfe;
private static final int D = 0x10325476;
/**
* The four registers initialized with the above IVs.
*/
private int a = A;
private int b = B;
private int c = C;
private int d = D;
/**
* Counts the total length of the data being digested.
*/
private long msgLength;
/**
* The internal buffer is {@link BLOCK_LENGTH} wide.
*/
private final byte[] buffer = new byte[BYTE_BLOCK_LENGTH];
/**
* Default constructor.
*/
public Md4() {
super("MD4");
engineReset();
}
/**
* Returns the digest length in bytes.
*
* @return the digest length in bytes.
*/
protected int engineGetDigestLength() {
return BYTE_DIGEST_LENGTH;
}
/**
* {@inheritDoc}
*/
protected void engineUpdate(byte b) {
int pos = (int) (msgLength % BYTE_BLOCK_LENGTH);
buffer[pos] = b;
msgLength++;
// If buffer contains enough data then process it.
if (pos == (BYTE_BLOCK_LENGTH - 1)) {
process(buffer, 0);
}
}
/**
* {@inheritDoc}
*/
protected void engineUpdate(byte[] b, int offset, int len) {
int pos = (int) (msgLength % BYTE_BLOCK_LENGTH);
int nbOfCharsToFillBuf = BYTE_BLOCK_LENGTH - pos;
int blkStart = 0;
msgLength += len;
// Process each full block
if (len >= nbOfCharsToFillBuf) {
System.arraycopy(b, offset, buffer, pos, nbOfCharsToFillBuf);
process(buffer, 0);
for (blkStart = nbOfCharsToFillBuf; blkStart + BYTE_BLOCK_LENGTH - 1 < len; blkStart += BYTE_BLOCK_LENGTH) {
process(b, offset + blkStart);
}
pos = 0;
}
// Fill buffer with the remaining data
if (blkStart < len) {
System.arraycopy(b, offset + blkStart, buffer, pos, len - blkStart);
}
}
/**
* {@inheritDoc}
*/
protected byte[] engineDigest() {
byte[] p = pad();
engineUpdate(p, 0, p.length);
byte[] digest = {(byte) a, (byte) (a >>> 8), (byte) (a >>> 16), (byte) (a >>> 24), (byte) b, (byte) (b >>> 8),
(byte) (b >>> 16), (byte) (b >>> 24), (byte) c, (byte) (c >>> 8), (byte) (c >>> 16), (byte) (c >>> 24),
(byte) d, (byte) (d >>> 8), (byte) (d >>> 16), (byte) (d >>> 24)};
engineReset();
return digest;
}
/**
* {@inheritDoc}
*/
protected int engineDigest(byte[] buf, int offset, int len) throws DigestException {
if (offset < 0 || offset + len >= buf.length) {
throw new DigestException("Wrong offset or not enough space to store the digest");
}
int destLength = Math.min(len, BYTE_DIGEST_LENGTH);
System.arraycopy(engineDigest(), 0, buf, offset, destLength);
return destLength;
}
/**
* {@inheritDoc}
*/
protected void engineReset() {
a = A;
b = B;
c = C;
d = D;
msgLength = 0;
}
/**
* Pads the buffer by appending the byte 0x80, then append as many zero
* bytes as necessary to make the buffer length a multiple of 64 bytes.
* The last 8 bytes will be filled with the length of the buffer in bits.
* If there's no room to store the length in bits in the block i.e the block
* is larger than 56 bytes then an additionnal 64-bytes block is appended.
*
* @see sections 3.1 & 3.2 of the RFC 1320.
*
* @return the pad byte array
*/
private byte[] pad() {
int pos = (int) (msgLength % BYTE_BLOCK_LENGTH);
int padLength = (pos < 56) ? (64 - pos) : (128 - pos);
byte[] pad = new byte[padLength];
// First bit of the padding set to 1
pad[0] = (byte) 0x80;
long bits = msgLength << 3;
int index = padLength - 8;
for (int i = 0; i < 8; i++) {
pad[index++] = (byte) (bits >>> (i << 3));
}
return pad;
}
/**
* Process one 64-byte block. Algorithm is constituted by three rounds.
* Note that F, G and H functions were inlined for improved performance.
*
* @param in the byte array to process
* @param offset the offset at which the 64-byte block is stored
*/
private void process(byte[] in, int offset) {
// Save previous state.
int aa = a;
int bb = b;
int cc = c;
int dd = d;
// Copy the block to process into X array
int[] x = new int[16];
for (int i = 0; i < 16; i++) {
x[i] = (in[offset++] & 0xff) | (in[offset++] & 0xff) << 8 | (in[offset++] & 0xff) << 16
| (in[offset++] & 0xff) << 24;
}
// Round 1
a += ((b & c) | (~b & d)) + x[0];
a = a << 3 | a >>> (32 - 3);
d += ((a & b) | (~a & c)) + x[1];
d = d << 7 | d >>> (32 - 7);
c += ((d & a) | (~d & b)) + x[2];
c = c << 11 | c >>> (32 - 11);
b += ((c & d) | (~c & a)) + x[3];
b = b << 19 | b >>> (32 - 19);
a += ((b & c) | (~b & d)) + x[4];
a = a << 3 | a >>> (32 - 3);
d += ((a & b) | (~a & c)) + x[5];
d = d << 7 | d >>> (32 - 7);
c += ((d & a) | (~d & b)) + x[6];
c = c << 11 | c >>> (32 - 11);
b += ((c & d) | (~c & a)) + x[7];
b = b << 19 | b >>> (32 - 19);
a += ((b & c) | (~b & d)) + x[8];
a = a << 3 | a >>> (32 - 3);
d += ((a & b) | (~a & c)) + x[9];
d = d << 7 | d >>> (32 - 7);
c += ((d & a) | (~d & b)) + x[10];
c = c << 11 | c >>> (32 - 11);
b += ((c & d) | (~c & a)) + x[11];
b = b << 19 | b >>> (32 - 19);
a += ((b & c) | (~b & d)) + x[12];
a = a << 3 | a >>> (32 - 3);
d += ((a & b) | (~a & c)) + x[13];
d = d << 7 | d >>> (32 - 7);
c += ((d & a) | (~d & b)) + x[14];
c = c << 11 | c >>> (32 - 11);
b += ((c & d) | (~c & a)) + x[15];
b = b << 19 | b >>> (32 - 19);
// Round 2
a += ((b & (c | d)) | (c & d)) + x[0] + 0x5a827999;
a = a << 3 | a >>> (32 - 3);
d += ((a & (b | c)) | (b & c)) + x[4] + 0x5a827999;
d = d << 5 | d >>> (32 - 5);
c += ((d & (a | b)) | (a & b)) + x[8] + 0x5a827999;
c = c << 9 | c >>> (32 - 9);
b += ((c & (d | a)) | (d & a)) + x[12] + 0x5a827999;
b = b << 13 | b >>> (32 - 13);
a += ((b & (c | d)) | (c & d)) + x[1] + 0x5a827999;
a = a << 3 | a >>> (32 - 3);
d += ((a & (b | c)) | (b & c)) + x[5] + 0x5a827999;
d = d << 5 | d >>> (32 - 5);
c += ((d & (a | b)) | (a & b)) + x[9] + 0x5a827999;
c = c << 9 | c >>> (32 - 9);
b += ((c & (d | a)) | (d & a)) + x[13] + 0x5a827999;
b = b << 13 | b >>> (32 - 13);
a += ((b & (c | d)) | (c & d)) + x[2] + 0x5a827999;
a = a << 3 | a >>> (32 - 3);
d += ((a & (b | c)) | (b & c)) + x[6] + 0x5a827999;
d = d << 5 | d >>> (32 - 5);
c += ((d & (a | b)) | (a & b)) + x[10] + 0x5a827999;
c = c << 9 | c >>> (32 - 9);
b += ((c & (d | a)) | (d & a)) + x[14] + 0x5a827999;
b = b << 13 | b >>> (32 - 13);
a += ((b & (c | d)) | (c & d)) + x[3] + 0x5a827999;
a = a << 3 | a >>> (32 - 3);
d += ((a & (b | c)) | (b & c)) + x[7] + 0x5a827999;
d = d << 5 | d >>> (32 - 5);
c += ((d & (a | b)) | (a & b)) + x[11] + 0x5a827999;
c = c << 9 | c >>> (32 - 9);
b += ((c & (d | a)) | (d & a)) + x[15] + 0x5a827999;
b = b << 13 | b >>> (32 - 13);
// Round 3
a += (b ^ c ^ d) + x[0] + 0x6ed9eba1;
a = a << 3 | a >>> (32 - 3);
d += (a ^ b ^ c) + x[8] + 0x6ed9eba1;
d = d << 9 | d >>> (32 - 9);
c += (d ^ a ^ b) + x[4] + 0x6ed9eba1;
c = c << 11 | c >>> (32 - 11);
b += (c ^ d ^ a) + x[12] + 0x6ed9eba1;
b = b << 15 | b >>> (32 - 15);
a += (b ^ c ^ d) + x[2] + 0x6ed9eba1;
a = a << 3 | a >>> (32 - 3);
d += (a ^ b ^ c) + x[10] + 0x6ed9eba1;
d = d << 9 | d >>> (32 - 9);
c += (d ^ a ^ b) + x[6] + 0x6ed9eba1;
c = c << 11 | c >>> (32 - 11);
b += (c ^ d ^ a) + x[14] + 0x6ed9eba1;
b = b << 15 | b >>> (32 - 15);
a += (b ^ c ^ d) + x[1] + 0x6ed9eba1;
a = a << 3 | a >>> (32 - 3);
d += (a ^ b ^ c) + x[9] + 0x6ed9eba1;
d = d << 9 | d >>> (32 - 9);
c += (d ^ a ^ b) + x[5] + 0x6ed9eba1;
c = c << 11 | c >>> (32 - 11);
b += (c ^ d ^ a) + x[13] + 0x6ed9eba1;
b = b << 15 | b >>> (32 - 15);
a += (b ^ c ^ d) + x[3] + 0x6ed9eba1;
a = a << 3 | a >>> (32 - 3);
d += (a ^ b ^ c) + x[11] + 0x6ed9eba1;
d = d << 9 | d >>> (32 - 9);
c += (d ^ a ^ b) + x[7] + 0x6ed9eba1;
c = c << 11 | c >>> (32 - 11);
b += (c ^ d ^ a) + x[15] + 0x6ed9eba1;
b = b << 15 | b >>> (32 - 15);
//Update state.
a += aa;
b += bb;
c += cc;
d += dd;
}
}
| 294 |
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/Confounder.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.security.SecureRandom;
public final class Confounder {
private static SecureRandom instance = new SecureRandom();
public static byte[] makeBytes(int size) {
byte[] data = new byte[size];
instance.nextBytes(data);
return data;
}
}
| 295 |
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/Nonce.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.security.SecureRandom;
public class Nonce {
private static SecureRandom srand = new SecureRandom();
public static synchronized int value() {
int value = srand.nextInt();
return value & 0x7fffffff;
}
}
| 296 |
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/Random.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.security.SecureRandom;
public final class Random {
private static SecureRandom instance = new SecureRandom();
public static byte[] makeBytes(int size) {
byte[] data = new byte[size];
instance.nextBytes(data);
return data;
}
}
| 297 |
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/Rc4.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.nio.charset.StandardCharsets;
/**
* Ref. MIT krb5 enc_rc4.c
*/
public class Rc4 {
private static final byte[] L40 = "fortybits".getBytes(StandardCharsets.UTF_8);
public static byte[] getSalt(int usage, boolean exportable) {
int newUsage = convertUsage(usage);
byte[] salt;
if (exportable) {
salt = new byte[14];
System.arraycopy(L40, 0, salt, 0, 9);
BytesUtil.int2bytes(newUsage, salt, 10, false);
} else {
salt = new byte[4];
BytesUtil.int2bytes(newUsage, salt, 0, false);
}
return salt;
}
private static int convertUsage(int usage) {
switch (usage) {
case 1: return 1; /* AS-REQ PA-ENC-TIMESTAMP padata timestamp, */
case 2: return 2; /* ticket from kdc */
case 3: return 8; /* as-rep encrypted part */
case 4: return 4; /* tgs-req authz data */
case 5: return 5; /* tgs-req authz data in subkey */
case 6: return 6; /* tgs-req authenticator cksum */
case 7: return 7; /* tgs-req authenticator */
case 8: return 8;
case 9: return 9; /* tgs-rep encrypted with subkey */
case 10: return 10; /* ap-rep authentication cksum (never used by MS) */
case 11: return 11; /* app-req authenticator */
case 12: return 12; /* app-rep encrypted part */
case 23: return 13; /* sign wrap token*/
default: return usage;
}
}
}
| 298 |
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/CamelliaKey.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 CamelliaKey {
// S-box data
static final byte[] SBOX1 = {
(byte) 112, (byte) 130, (byte) 44, (byte) 236,
(byte) 179, (byte) 39, (byte) 192, (byte) 229,
(byte) 228, (byte) 133, (byte) 87, (byte) 53,
(byte) 234, (byte) 12, (byte) 174, (byte) 65,
(byte) 35, (byte) 239, (byte) 107, (byte) 147,
(byte) 69, (byte) 25, (byte) 165, (byte) 33,
(byte) 237, (byte) 14, (byte) 79, (byte) 78,
(byte) 29, (byte) 101, (byte) 146, (byte) 189,
(byte) 134, (byte) 184, (byte) 175, (byte) 143,
(byte) 124, (byte) 235, (byte) 31, (byte) 206,
(byte) 62, (byte) 48, (byte) 220, (byte) 95,
(byte) 94, (byte) 197, (byte) 11, (byte) 26,
(byte) 166, (byte) 225, (byte) 57, (byte) 202,
(byte) 213, (byte) 71, (byte) 93, (byte) 61,
(byte) 217, (byte) 1, (byte) 90, (byte) 214,
(byte) 81, (byte) 86, (byte) 108, (byte) 77,
(byte) 139, (byte) 13, (byte) 154, (byte) 102,
(byte) 251, (byte) 204, (byte) 176, (byte) 45,
(byte) 116, (byte) 18, (byte) 43, (byte) 32,
(byte) 240, (byte) 177, (byte) 132, (byte) 153,
(byte) 223, (byte) 76, (byte) 203, (byte) 194,
(byte) 52, (byte) 126, (byte) 118, (byte) 5,
(byte) 109, (byte) 183, (byte) 169, (byte) 49,
(byte) 209, (byte) 23, (byte) 4, (byte) 215,
(byte) 20, (byte) 88, (byte) 58, (byte) 97,
(byte) 222, (byte) 27, (byte) 17, (byte) 28,
(byte) 50, (byte) 15, (byte) 156, (byte) 22,
(byte) 83, (byte) 24, (byte) 242, (byte) 34,
(byte) 254, (byte) 68, (byte) 207, (byte) 178,
(byte) 195, (byte) 181, (byte) 122, (byte) 145,
(byte) 36, (byte) 8, (byte) 232, (byte) 168,
(byte) 96, (byte) 252, (byte) 105, (byte) 80,
(byte) 170, (byte) 208, (byte) 160, (byte) 125,
(byte) 161, (byte) 137, (byte) 98, (byte) 151,
(byte) 84, (byte) 91, (byte) 30, (byte) 149,
(byte) 224, (byte) 255, (byte) 100, (byte) 210,
(byte) 16, (byte) 196, (byte) 0, (byte) 72,
(byte) 163, (byte) 247, (byte) 117, (byte) 219,
(byte) 138, (byte) 3, (byte) 230, (byte) 218,
(byte) 9, (byte) 63, (byte) 221, (byte) 148,
(byte) 135, (byte) 92, (byte) 131, (byte) 2,
(byte) 205, (byte) 74, (byte) 144, (byte) 51,
(byte) 115, (byte) 103, (byte) 246, (byte) 243,
(byte) 157, (byte) 127, (byte) 191, (byte) 226,
(byte) 82, (byte) 155, (byte) 216, (byte) 38,
(byte) 200, (byte) 55, (byte) 198, (byte) 59,
(byte) 129, (byte) 150, (byte) 111, (byte) 75,
(byte) 19, (byte) 190, (byte) 99, (byte) 46,
(byte) 233, (byte) 121, (byte) 167, (byte) 140,
(byte) 159, (byte) 110, (byte) 188, (byte) 142,
(byte) 41, (byte) 245, (byte) 249, (byte) 182,
(byte) 47, (byte) 253, (byte) 180, (byte) 89,
(byte) 120, (byte) 152, (byte) 6, (byte) 106,
(byte) 231, (byte) 70, (byte) 113, (byte) 186,
(byte) 212, (byte) 37, (byte) 171, (byte) 66,
(byte) 136, (byte) 162, (byte) 141, (byte) 250,
(byte) 114, (byte) 7, (byte) 185, (byte) 85,
(byte) 248, (byte) 238, (byte) 172, (byte) 10,
(byte) 54, (byte) 73, (byte) 42, (byte) 104,
(byte) 60, (byte) 56, (byte) 241, (byte) 164,
(byte) 64, (byte) 40, (byte) 211, (byte) 123,
(byte) 187, (byte) 201, (byte) 67, (byte) 193,
(byte) 21, (byte) 227, (byte) 173, (byte) 244,
(byte) 119, (byte) 199, (byte) 128, (byte) 158
};
private static final int[] SIGMA = {
0xa09e667f, 0x3bcc908b,
0xb67ae858, 0x4caa73b2,
0xc6ef372f, 0xe94f82be,
0x54ff53a5, 0xf1d36f1c,
0x10e527fa, 0xde682d1d,
0xb05688c2, 0xb3e6c1fd
};
protected int[] subkey = new int[24 * 4];
protected int[] kw = new int[4 * 2]; // for whitening
protected int[] ke = new int[6 * 2]; // for FL and FL^(-1)
private int keySize;
public CamelliaKey(byte[] key, boolean isEncrypt) {
init(key, isEncrypt);
}
private static int rightRotate(int x, int s) {
return (((x) >>> (s)) + ((x) << (32 - s)));
}
private static int leftRotate(int x, int s) {
return ((x) << (s)) + ((x) >>> (32 - s));
}
private static void roldq(int rot, int[] ki, int ioff,
int[] ko, int ooff) {
ko[0 + ooff] = (ki[0 + ioff] << rot) | (ki[1 + ioff] >>> (32 - rot));
ko[1 + ooff] = (ki[1 + ioff] << rot) | (ki[2 + ioff] >>> (32 - rot));
ko[2 + ooff] = (ki[2 + ioff] << rot) | (ki[3 + ioff] >>> (32 - rot));
ko[3 + ooff] = (ki[3 + ioff] << rot) | (ki[0 + ioff] >>> (32 - rot));
ki[0 + ioff] = ko[0 + ooff];
ki[1 + ioff] = ko[1 + ooff];
ki[2 + ioff] = ko[2 + ooff];
ki[3 + ioff] = ko[3 + ooff];
}
private static void decroldq(int rot, int[] ki, int ioff,
int[] ko, int ooff) {
ko[2 + ooff] = (ki[0 + ioff] << rot) | (ki[1 + ioff] >>> (32 - rot));
ko[3 + ooff] = (ki[1 + ioff] << rot) | (ki[2 + ioff] >>> (32 - rot));
ko[0 + ooff] = (ki[2 + ioff] << rot) | (ki[3 + ioff] >>> (32 - rot));
ko[1 + ooff] = (ki[3 + ioff] << rot) | (ki[0 + ioff] >>> (32 - rot));
ki[0 + ioff] = ko[2 + ooff];
ki[1 + ioff] = ko[3 + ooff];
ki[2 + ioff] = ko[0 + ooff];
ki[3 + ioff] = ko[1 + ooff];
}
private static void roldqo32(int rot, int[] ki, int ioff,
int[] ko, int ooff) {
ko[0 + ooff] = (ki[1 + ioff] << (rot - 32)) | (ki[2 + ioff] >>> (64 - rot));
ko[1 + ooff] = (ki[2 + ioff] << (rot - 32)) | (ki[3 + ioff] >>> (64 - rot));
ko[2 + ooff] = (ki[3 + ioff] << (rot - 32)) | (ki[0 + ioff] >>> (64 - rot));
ko[3 + ooff] = (ki[0 + ioff] << (rot - 32)) | (ki[1 + ioff] >>> (64 - rot));
ki[0 + ioff] = ko[0 + ooff];
ki[1 + ioff] = ko[1 + ooff];
ki[2 + ioff] = ko[2 + ooff];
ki[3 + ioff] = ko[3 + ooff];
}
private static void decroldqo32(int rot, int[] ki, int ioff,
int[] ko, int ooff) {
ko[2 + ooff] = (ki[1 + ioff] << (rot - 32)) | (ki[2 + ioff] >>> (64 - rot));
ko[3 + ooff] = (ki[2 + ioff] << (rot - 32)) | (ki[3 + ioff] >>> (64 - rot));
ko[0 + ooff] = (ki[3 + ioff] << (rot - 32)) | (ki[0 + ioff] >>> (64 - rot));
ko[1 + ooff] = (ki[0 + ioff] << (rot - 32)) | (ki[1 + ioff] >>> (64 - rot));
ki[0 + ioff] = ko[2 + ooff];
ki[1 + ioff] = ko[3 + ooff];
ki[2 + ioff] = ko[0 + ooff];
ki[3 + ioff] = ko[1 + ooff];
}
protected boolean is128() {
return keySize == 16;
}
private byte lRot8(byte v, int rot) {
return (byte) ((v << rot) | ((v & 0xff) >>> (8 - rot)));
}
private int sbox2(int x) {
return (lRot8(SBOX1[x], 1) & 0xff);
}
private int sbox3(int x) {
return (lRot8(SBOX1[x], 7) & 0xff);
}
private int sbox4(int x) {
return (SBOX1[((int) lRot8((byte) x, 1) & 0xff)] & 0xff);
}
protected void fls(int[] s, int[] fkey, int keyoff) {
s[1] ^= leftRotate(s[0] & fkey[0 + keyoff], 1);
s[0] ^= fkey[1 + keyoff] | s[1];
s[2] ^= fkey[3 + keyoff] | s[3];
s[3] ^= leftRotate(fkey[2 + keyoff] & s[2], 1);
}
protected void f2(int[] s, int[] skey, int keyoff) {
int t1, t2, u, v;
t1 = s[0] ^ skey[0 + keyoff];
u = sbox4((t1 & 0xff));
u |= (sbox3(((t1 >>> 8) & 0xff)) << 8);
u |= (sbox2(((t1 >>> 16) & 0xff)) << 16);
u |= ((int) (SBOX1[((t1 >>> 24) & 0xff)] & 0xff) << 24);
t2 = s[1] ^ skey[1 + keyoff];
v = (int) SBOX1[(t2 & 0xff)] & 0xff;
v |= (sbox4(((t2 >>> 8) & 0xff)) << 8);
v |= (sbox3(((t2 >>> 16) & 0xff)) << 16);
v |= (sbox2(((t2 >>> 24) & 0xff)) << 24);
v = leftRotate(v, 8);
u ^= v;
v = leftRotate(v, 8) ^ u;
u = rightRotate(u, 8) ^ v;
s[2] ^= leftRotate(v, 16) ^ u;
s[3] ^= leftRotate(u, 8);
t1 = s[2] ^ skey[2 + keyoff];
u = sbox4((t1 & 0xff));
u |= sbox3(((t1 >>> 8) & 0xff)) << 8;
u |= sbox2(((t1 >>> 16) & 0xff)) << 16;
u |= ((int) SBOX1[((t1 >>> 24) & 0xff)] & 0xff) << 24;
t2 = s[3] ^ skey[3 + keyoff];
v = ((int) SBOX1[(t2 & 0xff)] & 0xff);
v |= sbox4(((t2 >>> 8) & 0xff)) << 8;
v |= sbox3(((t2 >>> 16) & 0xff)) << 16;
v |= sbox2(((t2 >>> 24) & 0xff)) << 24;
v = leftRotate(v, 8);
u ^= v;
v = leftRotate(v, 8) ^ u;
u = rightRotate(u, 8) ^ v;
s[0] ^= leftRotate(v, 16) ^ u;
s[1] ^= leftRotate(u, 8);
}
private void init(byte[] key, boolean isEncrypt) {
keySize = key.length;
int[] k = new int[8];
int[] ka = new int[4];
int[] kb = new int[4];
int[] t = new int[4];
switch (key.length) {
case 16:
k[0] = BytesUtil.bytes2int(key, 0, true);
k[1] = BytesUtil.bytes2int(key, 4, true);
k[2] = BytesUtil.bytes2int(key, 8, true);
k[3] = BytesUtil.bytes2int(key, 12, true);
k[4] = k[5] = k[6] = k[7] = 0;
break;
case 24:
k[0] = BytesUtil.bytes2int(key, 0, true);
k[1] = BytesUtil.bytes2int(key, 4, true);
k[2] = BytesUtil.bytes2int(key, 8, true);
k[3] = BytesUtil.bytes2int(key, 12, true);
k[4] = BytesUtil.bytes2int(key, 16, true);
k[5] = BytesUtil.bytes2int(key, 20, true);
k[6] = ~k[4];
k[7] = ~k[5];
break;
case 32:
k[0] = BytesUtil.bytes2int(key, 0, true);
k[1] = BytesUtil.bytes2int(key, 4, true);
k[2] = BytesUtil.bytes2int(key, 8, true);
k[3] = BytesUtil.bytes2int(key, 12, true);
k[4] = BytesUtil.bytes2int(key, 16, true);
k[5] = BytesUtil.bytes2int(key, 20, true);
k[6] = BytesUtil.bytes2int(key, 24, true);
k[7] = BytesUtil.bytes2int(key, 28, true);
break;
default:
throw new
IllegalArgumentException("Invalid key size, only support 16/24/32 bytes");
}
for (int i = 0; i < 4; i++) {
ka[i] = k[i] ^ k[i + 4];
}
/* compute KA */
f2(ka, SIGMA, 0);
for (int i = 0; i < 4; i++) {
ka[i] ^= k[i];
}
f2(ka, SIGMA, 4);
if (keySize == 16) {
if (isEncrypt) {
/* KL dependant keys */
kw[0] = k[0];
kw[1] = k[1];
kw[2] = k[2];
kw[3] = k[3];
roldq(15, k, 0, subkey, 4);
roldq(30, k, 0, subkey, 12);
roldq(15, k, 0, t, 0);
subkey[18] = t[2];
subkey[19] = t[3];
roldq(17, k, 0, ke, 4);
roldq(17, k, 0, subkey, 24);
roldq(17, k, 0, subkey, 32);
/* KA dependant keys */
subkey[0] = ka[0];
subkey[1] = ka[1];
subkey[2] = ka[2];
subkey[3] = ka[3];
roldq(15, ka, 0, subkey, 8);
roldq(15, ka, 0, ke, 0);
roldq(15, ka, 0, t, 0);
subkey[16] = t[0];
subkey[17] = t[1];
roldq(15, ka, 0, subkey, 20);
roldqo32(34, ka, 0, subkey, 28);
roldq(17, ka, 0, kw, 4);
} else { // decryption
/* KL dependant keys */
kw[4] = k[0];
kw[5] = k[1];
kw[6] = k[2];
kw[7] = k[3];
decroldq(15, k, 0, subkey, 28);
decroldq(30, k, 0, subkey, 20);
decroldq(15, k, 0, t, 0);
subkey[16] = t[0];
subkey[17] = t[1];
decroldq(17, k, 0, ke, 0);
decroldq(17, k, 0, subkey, 8);
decroldq(17, k, 0, subkey, 0);
/* KA dependant keys */
subkey[34] = ka[0];
subkey[35] = ka[1];
subkey[32] = ka[2];
subkey[33] = ka[3];
decroldq(15, ka, 0, subkey, 24);
decroldq(15, ka, 0, ke, 4);
decroldq(15, ka, 0, t, 0);
subkey[18] = t[2];
subkey[19] = t[3];
decroldq(15, ka, 0, subkey, 12);
decroldqo32(34, ka, 0, subkey, 4);
roldq(17, ka, 0, kw, 0);
}
} else { // 192bit or 256bit
/* compute KB */
for (int i = 0; i < 4; i++) {
kb[i] = ka[i] ^ k[i + 4];
}
f2(kb, SIGMA, 8);
if (isEncrypt) {
/* KL dependant keys */
kw[0] = k[0];
kw[1] = k[1];
kw[2] = k[2];
kw[3] = k[3];
roldqo32(45, k, 0, subkey, 16);
roldq(15, k, 0, ke, 4);
roldq(17, k, 0, subkey, 32);
roldqo32(34, k, 0, subkey, 44);
/* KR dependant keys */
roldq(15, k, 4, subkey, 4);
roldq(15, k, 4, ke, 0);
roldq(30, k, 4, subkey, 24);
roldqo32(34, k, 4, subkey, 36);
/* KA dependant keys */
roldq(15, ka, 0, subkey, 8);
roldq(30, ka, 0, subkey, 20);
/* 32bit rotation */
ke[8] = ka[1];
ke[9] = ka[2];
ke[10] = ka[3];
ke[11] = ka[0];
roldqo32(49, ka, 0, subkey, 40);
/* KB dependant keys */
subkey[0] = kb[0];
subkey[1] = kb[1];
subkey[2] = kb[2];
subkey[3] = kb[3];
roldq(30, kb, 0, subkey, 12);
roldq(30, kb, 0, subkey, 28);
roldqo32(51, kb, 0, kw, 4);
} else { // decryption
/* KL dependant keys */
kw[4] = k[0];
kw[5] = k[1];
kw[6] = k[2];
kw[7] = k[3];
decroldqo32(45, k, 0, subkey, 28);
decroldq(15, k, 0, ke, 4);
decroldq(17, k, 0, subkey, 12);
decroldqo32(34, k, 0, subkey, 0);
/* KR dependant keys */
decroldq(15, k, 4, subkey, 40);
decroldq(15, k, 4, ke, 8);
decroldq(30, k, 4, subkey, 20);
decroldqo32(34, k, 4, subkey, 8);
/* KA dependant keys */
decroldq(15, ka, 0, subkey, 36);
decroldq(30, ka, 0, subkey, 24);
/* 32bit rotation */
ke[2] = ka[1];
ke[3] = ka[2];
ke[0] = ka[3];
ke[1] = ka[0];
decroldqo32(49, ka, 0, subkey, 4);
/* KB dependant keys */
subkey[46] = kb[0];
subkey[47] = kb[1];
subkey[44] = kb[2];
subkey[45] = kb[3];
decroldq(30, kb, 0, subkey, 32);
decroldq(30, kb, 0, subkey, 16);
roldqo32(51, kb, 0, kw, 0);
}
}
}
}
| 299 |