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-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/pkinit/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.server.preauth.pkinit; import org.apache.kerby.asn1.Asn1; import org.apache.kerby.asn1.parse.Asn1Container; import org.apache.kerby.asn1.parse.Asn1ParseResult; import org.apache.kerby.asn1.type.Asn1Integer; 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.EncapsulatedContentInfo; 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.common.CheckSumUtil; import org.apache.kerby.kerberos.kerb.common.KrbUtil; import org.apache.kerby.kerberos.kerb.crypto.dh.DiffieHellmanServer; 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.PkinitPlgCryptoContext; import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitPreauthMeta; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.preauth.AbstractPreauthPlugin; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.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.PrincipalName; import org.apache.kerby.kerberos.kerb.type.kdc.KdcOption; 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.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 java.io.IOException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class PkinitPreauth extends AbstractPreauthPlugin { private static final Logger LOG = LoggerFactory.getLogger(PkinitPreauth.class); private final Map<String, PkinitKdcContext> pkinitContexts; public PkinitPreauth() { super(new PkinitPreauthMeta()); pkinitContexts = new HashMap<>(1); } @Override public void initWith(KdcContext kdcContext) { super.initWith(kdcContext); PkinitKdcContext tmp = new PkinitKdcContext(); tmp.realm = kdcContext.getKdcRealm(); String pkinitIdentity = kdcContext.getConfig().getPkinitIdentity(); tmp.identityOpts.setIdentity(pkinitIdentity); pkinitContexts.put(kdcContext.getKdcRealm(), tmp); } @Override public PluginRequestContext initRequestContext(KdcRequest kdcRequest) { PkinitRequestContext reqCtx = new PkinitRequestContext(); //reqCtx.updateRequestOpts(pkinitContext.pluginOpts); return reqCtx; } @Override public boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException { LOG.info("pkinit verify padata: entered!"); PkinitRequestContext reqCtx = (PkinitRequestContext) requestContext; PrincipalName serverPrincipal = kdcRequest.getServerEntry().getPrincipal(); kdcRequest.setServerPrincipal(serverPrincipal); PkinitKdcContext pkinitContext = findContext(serverPrincipal); if (pkinitContext == null) { return false; } reqCtx.paType = paData.getPaDataType(); if (paData.getPaDataType() == PaDataType.PK_AS_REQ) { LOG.info("processing PK_AS_REQ"); PaPkAsReq paPkAsReq = KrbCodec.decode(paData.getPaDataValue(), PaPkAsReq.class); byte[] signedAuthPack = paPkAsReq.getSignedAuthPack(); AuthPack authPack = null; if (kdcRequest.isAnonymous()) { EncapsulatedContentInfo eContentInfo = new EncapsulatedContentInfo(); try { eContentInfo.decode(signedAuthPack); } catch (IOException e) { LOG.error("Fail to decode signedAuthPack. " + e); } authPack = KrbCodec.decode(eContentInfo.getContent(), AuthPack.class); } else { ContentInfo contentInfo = new ContentInfo(); try { contentInfo.decode(signedAuthPack); } catch (IOException e) { LOG.error("Fail to decode signedAuthPack"); } SignedData signedData = contentInfo.getContentAs(SignedData.class); PkinitCrypto.verifyCmsSignedData(CmsMessageType.CMS_SIGN_CLIENT, signedData); boolean isSigned = signedData.isSigned(); if (isSigned) { //TODO LOG.info("Signed data."); } else { PrincipalName clientPrincial = kdcRequest.getClientEntry().getPrincipal(); PrincipalName anonymousPrincipal = KrbUtil.makeAnonymousPrincipal(); /* If anonymous requests are being used, adjust the realm of the client principal. */ if (kdcRequest.getKdcOptions().isFlagSet(KdcOption.REQUEST_ANONYMOUS) && !KrbUtil.pricipalCompareIgnoreRealm(clientPrincial, anonymousPrincipal)) { String errMsg = "Pkinit request not signed, but client not anonymous."; LOG.error(errMsg); throw new KrbException(KrbErrorCode.KDC_ERR_PREAUTH_FAILED, errMsg); } } authPack = KrbCodec.decode( signedData.getEncapContentInfo().getContent(), AuthPack.class); } PkAuthenticator pkAuthenticator = authPack.getPkAuthenticator(); checkClockskew(kdcRequest, pkAuthenticator.getCtime()); byte[] reqBodyBytes = null; if (kdcRequest.getReqPackage() == null) { LOG.error("ReqBodyBytes isn't available"); return false; } else { Asn1ParseResult parseResult = null; try { parseResult = Asn1.parse(kdcRequest.getReqPackage()); } catch (IOException e) { LOG.error("Fail to parse reqPackage. " + e); } /**Get REQ_BODY in KDC_REQ for checksum*/ Asn1Container container = (Asn1Container) parseResult; List<Asn1ParseResult> parseResults = container.getChildren(); Asn1Container parsingItem = (Asn1Container) parseResults.get(0); List<Asn1ParseResult> items = parsingItem.getChildren(); if (items.size() > 3) { ByteBuffer bodyBuffer = items.get(3).getBodyBuffer(); reqBodyBytes = new byte[bodyBuffer.remaining()]; bodyBuffer.get(reqBodyBytes); } } CheckSum expectedCheckSum = null; try { expectedCheckSum = CheckSumUtil.makeCheckSum(CheckSumType.NIST_SHA, reqBodyBytes); } catch (KrbException e) { LOG.error("Unable to calculate AS REQ checksum. {}", e.getMessage()); } byte[] receivedCheckSumByte = pkAuthenticator.getPaChecksum(); if (expectedCheckSum.getChecksum().length != receivedCheckSumByte.length || !Arrays.equals(expectedCheckSum.getChecksum(), receivedCheckSumByte)) { LOG.debug("received checksum length: " + receivedCheckSumByte.length + ", expected checksum type: " + expectedCheckSum.getCksumtype() + ", expected checksum length: " + expectedCheckSum.encodingLength()); String errorMessage = "Failed to match the checksum."; LOG.error(errorMessage); throw new KrbException(KrbErrorCode.KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED, errorMessage); } SubjectPublicKeyInfo publicKeyInfo = authPack.getClientPublicValue(); DhParameter dhParameter; if (publicKeyInfo.getSubjectPubKey() != null) { dhParameter = authPack.getClientPublicValue().getAlgorithm().getParametersAs(DhParameter.class); PkinitCrypto.serverCheckDH(pkinitContext.pluginOpts, pkinitContext.cryptoctx, dhParameter); byte[] clientSubjectPubKey = publicKeyInfo.getSubjectPubKey().getValue(); Asn1Integer clientPubKey = KrbCodec.decode(clientSubjectPubKey, Asn1Integer.class); BigInteger y = clientPubKey.getValue(); BigInteger p = dhParameter.getP(); BigInteger g = dhParameter.getG(); DHPublicKey dhPublicKey = PkinitCrypto.createDHPublicKey(p, g, y); DiffieHellmanServer server = new DiffieHellmanServer(); DHPublicKey serverPubKey = null; try { serverPubKey = (DHPublicKey) server.initAndDoPhase(dhPublicKey.getEncoded()); } catch (Exception e) { LOG.error("Fail to create server public key.", e); } EncryptionKey secretKey = server.generateKey(null, null, kdcRequest.getEncryptionType()); // Set the DH shared key as the client key kdcRequest.setClientKey(secretKey); String identity = pkinitContext.identityOpts.getIdentity(); PaPkAsRep paPkAsRep = makePaPkAsRep(serverPubKey, identity); PaDataEntry paDataEntry = makeEntry(paPkAsRep); kdcRequest.getPreauthContext().getOutputPaData().add(paDataEntry); } else { if (!kdcRequest.isAnonymous()) { /*Anonymous pkinit requires DH*/ String errMessage = "Anonymous pkinit without DH public value not supported."; LOG.error(errMessage); throw new KrbException(KrbErrorCode.KDC_ERR_PREAUTH_FAILED, errMessage); } else { // rsa System.out.println("rsa"); } } } return true; } private PkinitKdcContext findContext(PrincipalName principal) { String realm = principal.getRealm(); if (pkinitContexts.containsKey(realm)) { return pkinitContexts.get(realm); } return null; } /** * Make padata entry. * * @param paPkAsRep The PaPkAsRep * @return PaDataEntry to be made. */ private PaDataEntry makeEntry(PaPkAsRep paPkAsRep) throws KrbException { PaDataEntry paDataEntry = new PaDataEntry(); paDataEntry.setPaDataType(PaDataType.PK_AS_REP); //TODO CHOICE try { paDataEntry.setPaDataValue(paPkAsRep.encode()); } catch (IOException e) { LOG.error("Fail to encode PaDataEntry. " + e); } return paDataEntry; } private PaPkAsRep makePaPkAsRep(DHPublicKey severPubKey, String identityString) throws KrbException { List<X509Certificate> certificates = new ArrayList<>(); if (identityString != null) { List<String> identityList = Arrays.asList(identityString.split(",")); for (String identity : identityList) { try { List<java.security.cert.Certificate> loadedCerts = CertificateHelper.loadCerts(identity); if (!loadedCerts.isEmpty()) { certificates.add((X509Certificate) loadedCerts.iterator().next()); } } catch (KrbException e) { LOG.warn("Error loading X.509 Certificate", e); } } } else { LOG.warn("No PKINIT identity keys specified"); } PaPkAsRep paPkAsRep = new PaPkAsRep(); DhRepInfo dhRepInfo = new DhRepInfo(); KdcDhKeyInfo kdcDhKeyInfo = new KdcDhKeyInfo(); Asn1Integer publickey = new Asn1Integer(severPubKey.getY()); byte[] pubKeyData = KrbCodec.encode(publickey); kdcDhKeyInfo.setSubjectPublicKey(pubKeyData); kdcDhKeyInfo.setNonce(0); kdcDhKeyInfo.setDHKeyExpiration( new KerberosTime(System.currentTimeMillis() + KerberosTime.DAY)); byte[] signedDataBytes = null; CertificateSet certificateSet = new CertificateSet(); for (X509Certificate x509Certificate : certificates) { Certificate certificate = PkinitCrypto.changeToCertificate(x509Certificate); CertificateChoices certificateChoices = new CertificateChoices(); certificateChoices.setCertificate(certificate); certificateSet.addElement(certificateChoices); } String oid = PkinitPlgCryptoContext.getIdPkinitDHKeyDataOID(); signedDataBytes = PkinitCrypto.cmsSignedDataCreate(KrbCodec.encode(kdcDhKeyInfo), oid, 3, null, certificateSet, null, null); dhRepInfo.setDHSignedData(signedDataBytes); paPkAsRep.setDHRepInfo(dhRepInfo); return paPkAsRep; } private boolean checkClockskew(KdcRequest kdcRequest, KerberosTime time) throws KrbException { long clockSkew = kdcRequest.getKdcContext().getConfig().getAllowableClockSkew() * 1000; if (!time.isInClockSkew(clockSkew)) { throw new KrbException(KrbErrorCode.KDC_ERR_PREAUTH_FAILED); } else { return true; } } }
400
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/pkinit/PkinitKdcContext.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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.kerby.kerberos.kerb.server.preauth.pkinit; import org.apache.kerby.kerberos.kerb.preauth.pkinit.IdentityOpts; import org.apache.kerby.kerberos.kerb.preauth.pkinit.PkinitPlgCryptoContext; import org.apache.kerby.kerberos.kerb.preauth.pkinit.PluginOpts; public class PkinitKdcContext { public PkinitPlgCryptoContext cryptoctx = new PkinitPlgCryptoContext(); public PluginOpts pluginOpts = new PluginOpts(); public IdentityOpts identityOpts = new IdentityOpts(); public String realm; }
401
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/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.server.preauth.builtin; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.builtin.TgtPreauthMeta; import org.apache.kerby.kerberos.kerb.server.preauth.AbstractPreauthPlugin; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.server.request.TgsRequest; import org.apache.kerby.kerberos.kerb.type.pa.PaDataEntry; public class TgtPreauth extends AbstractPreauthPlugin { public TgtPreauth() { super(new TgtPreauthMeta()); } @Override public boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException { TgsRequest tgsRequest = (TgsRequest) kdcRequest; tgsRequest.verifyAuthenticator(paData); return true; } }
402
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/preauth/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.server.preauth.builtin; 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.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.preauth.PluginRequestContext; import org.apache.kerby.kerberos.kerb.preauth.builtin.EncTsPreauthMeta; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.preauth.AbstractPreauthPlugin; import org.apache.kerby.kerberos.kerb.server.request.KdcRequest; import org.apache.kerby.kerberos.kerb.type.base.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.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.pa.PaEncTsEnc; public class EncTsPreauth extends AbstractPreauthPlugin { public EncTsPreauth() { super(new EncTsPreauthMeta()); } @Override public boolean verify(KdcRequest kdcRequest, PluginRequestContext requestContext, PaDataEntry paData) throws KrbException { EncryptedData encData = KrbCodec.decode(paData.getPaDataValue(), EncryptedData.class); EncryptionKey clientKey = kdcRequest.getClientKey(encData.getEType()); if (clientKey == null) { throw new KrbException(KrbErrorCode.KDC_ERR_ETYPE_NOSUPP); } PaEncTsEnc timestamp = EncryptionUtil.unseal(encData, clientKey, KeyUsage.AS_REQ_PA_ENC_TS, PaEncTsEnc.class); KdcContext kdcContext = kdcRequest.getKdcContext(); long clockSkew = kdcContext.getConfig().getAllowableClockSkew() * 1000; if (!timestamp.getAllTime().isInClockSkew(clockSkew)) { throw new KrbException(KrbErrorCode.KDC_ERR_PREAUTH_FAILED); } return true; } }
403
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/request/TicketIssuer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.request; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler; import org.apache.kerby.kerberos.kerb.request.KdcClientRequest; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.type.KerberosTime; import org.apache.kerby.kerberos.kerb.type.ad.AuthorizationData; 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.HostAddresses; import org.apache.kerby.kerberos.kerb.type.base.KeyUsage; import org.apache.kerby.kerberos.kerb.type.base.KrbMessageType; 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.base.TransitedEncoding; import org.apache.kerby.kerberos.kerb.type.base.TransitedEncodingType; 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.KdcReq; import org.apache.kerby.kerberos.kerb.type.ticket.EncTicketPart; import org.apache.kerby.kerberos.kerb.type.ticket.Ticket; import org.apache.kerby.kerberos.kerb.type.ticket.TicketFlag; import org.apache.kerby.kerberos.kerb.type.ticket.TicketFlags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handling ticket constructing, filling, and issuing. */ public abstract class TicketIssuer { private static final Logger LOG = LoggerFactory.getLogger(TicketIssuer.class); private final KdcRequest kdcRequest; public TicketIssuer(KdcRequest kdcRequest) { this.kdcRequest = kdcRequest; } protected KdcRequest getKdcRequest() { return kdcRequest; } public Ticket issueTicket() throws KrbException { KdcReq request = kdcRequest.getKdcReq(); Ticket issuedTicket = new Ticket(); PrincipalName serverPrincipal = getServerPrincipal(); issuedTicket.setSname(serverPrincipal); String serverRealm = request.getReqBody().getRealm(); issuedTicket.setRealm(serverRealm); EncTicketPart encTicketPart = makeEncTicketPart(); EncryptionKey encryptionKey = getTicketEncryptionKey(); EncryptedData encryptedData = EncryptionUtil.seal(encTicketPart, encryptionKey, KeyUsage.KDC_REP_TICKET); issuedTicket.setEncryptedEncPart(encryptedData); issuedTicket.setEncPart(encTicketPart); return issuedTicket; } public EncTicketPart makeEncTicketPart() throws KrbException { KdcReq request = kdcRequest.getKdcReq(); EncTicketPart encTicketPart = new EncTicketPart(); KdcConfig config = kdcRequest.getKdcContext().getConfig(); TicketFlags ticketFlags = new TicketFlags(); encTicketPart.setFlags(ticketFlags); ticketFlags.setFlag(TicketFlag.INITIAL); if (kdcRequest.isPreAuthenticated()) { ticketFlags.setFlag(TicketFlag.PRE_AUTH); } if (request.getReqBody().getKdcOptions().isFlagSet(KdcOption.FORWARDABLE)) { if (!config.isForwardableAllowed()) { LOG.warn("Forward is not allowed."); throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } ticketFlags.setFlag(TicketFlag.FORWARDABLE); } if (request.getReqBody().getKdcOptions().isFlagSet(KdcOption.PROXIABLE)) { if (!config.isProxiableAllowed()) { LOG.warn("Proxy is not allowed."); throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } ticketFlags.setFlag(TicketFlag.PROXIABLE); } if (request.getReqBody().getKdcOptions().isFlagSet(KdcOption.ALLOW_POSTDATE)) { if (!config.isPostdatedAllowed()) { LOG.warn("Post date is not allowed."); throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } ticketFlags.setFlag(TicketFlag.MAY_POSTDATE); } EncryptionKey sessionKey = EncryptionHandler.random2Key( kdcRequest.getEncryptionType()); encTicketPart.setKey(sessionKey); PrincipalName clientPrincipal = getclientPrincipal(); encTicketPart.setCname(getclientPrincipal()); if (clientPrincipal.getRealm() != null) { encTicketPart.setCrealm(clientPrincipal.getRealm()); } else { encTicketPart.setCrealm(request.getReqBody().getRealm()); } TransitedEncoding transEnc = getTransitedEncoding(); encTicketPart.setTransited(transEnc); KdcOptions kdcOptions = request.getReqBody().getKdcOptions(); KerberosTime now = KerberosTime.now(); encTicketPart.setAuthTime(now); KerberosTime krbStartTime = request.getReqBody().getFrom(); if (krbStartTime == null || krbStartTime.lessThan(now) || krbStartTime.isInClockSkew(config.getAllowableClockSkew())) { krbStartTime = now; } if (krbStartTime.greaterThan(now) && !krbStartTime.isInClockSkew(config.getAllowableClockSkew()) && !kdcOptions.isFlagSet(KdcOption.POSTDATED)) { throw new KrbException(KrbErrorCode.KDC_ERR_CANNOT_POSTDATE); } if (kdcOptions.isFlagSet(KdcOption.POSTDATED)) { if (!config.isPostdatedAllowed()) { throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } ticketFlags.setFlag(TicketFlag.POSTDATED); encTicketPart.setStartTime(krbStartTime); } KerberosTime krbEndTime = request.getReqBody().getTill(); KerberosTime maxEndTime = krbStartTime.extend(config.getMaximumTicketLifetime() * 1000); if (krbEndTime == null || krbEndTime.getTime() == 0 || krbEndTime.greaterThan(maxEndTime)) { krbEndTime = maxEndTime; } else if (krbStartTime.greaterThan(krbEndTime)) { throw new KrbException(KrbErrorCode.KDC_ERR_NEVER_VALID); } encTicketPart.setEndTime(krbEndTime); long ticketLifeTime = Math.abs(krbEndTime.diff(krbStartTime)); if (ticketLifeTime < config.getMinimumTicketLifetime()) { throw new KrbException(KrbErrorCode.KDC_ERR_NEVER_VALID); } KerberosTime krbRtime = request.getReqBody().getRtime(); if (kdcOptions.isFlagSet(KdcOption.RENEWABLE_OK)) { kdcOptions.setFlag(KdcOption.RENEWABLE); } if (kdcOptions.isFlagSet(KdcOption.RENEWABLE)) { if (!config.isRenewableAllowed()) { throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } ticketFlags.setFlag(TicketFlag.RENEWABLE); if (krbRtime == null || krbRtime.getTime() == 0) { krbRtime = krbEndTime; } KerberosTime allowedMaximumRenewableTime = krbStartTime; allowedMaximumRenewableTime = allowedMaximumRenewableTime .extend(config.getMaximumRenewableLifetime() * 1000); if (krbRtime.greaterThan(allowedMaximumRenewableTime)) { krbRtime = allowedMaximumRenewableTime; } encTicketPart.setRenewtill(krbRtime); } HostAddresses hostAddresses = request.getReqBody().getAddresses(); if (hostAddresses == null || hostAddresses.isEmpty()) { if (!config.isEmptyAddressesAllowed()) { throw new KrbException(KrbErrorCode.KDC_ERR_POLICY); } } else { encTicketPart.setClientAddresses(hostAddresses); } AuthorizationData authData = makeAuthorizationData(kdcRequest, encTicketPart); if (authData != null) { encTicketPart.setAuthorizationData(authData); } return encTicketPart; } protected AuthorizationData makeAuthorizationData(KdcRequest kdcRequest, EncTicketPart encTicketPart) throws KrbException { // Convert KdcRequest into KdcClientRequest KdcClientRequest clientRequest = new KdcClientRequest(); clientRequest.setAnonymous(kdcRequest.isAnonymous()); clientRequest.setClientAddress(kdcRequest.getClientAddress()); clientRequest.setClientKey(kdcRequest.getClientKey()); clientRequest.setClientPrincipal(kdcRequest.getClientPrincipal()); clientRequest.setClientEntry(kdcRequest.getClientEntry()); clientRequest.setServerPrincipal(kdcRequest.getServerPrincipal()); clientRequest.setServerEntry(kdcRequest.getServerEntry()); clientRequest.setKdcRealm(kdcRequest.getKdcContext().getKdcRealm()); clientRequest.setEncryptionType(kdcRequest.getEncryptionType()); clientRequest.setPkinit(kdcRequest.isPkinit()); clientRequest.setPreAuthenticated(kdcRequest.isPreAuthenticated()); clientRequest.setToken(kdcRequest.getToken()); clientRequest.setIsToken(kdcRequest.isToken()); KrbMessageType msgType = kdcRequest.getKdcReq().getMsgType(); clientRequest.setMsgType(msgType); if (msgType == KrbMessageType.TGS_REQ) { TgsRequest tgsRequest = (TgsRequest) kdcRequest; clientRequest.setTgt(tgsRequest.getTgtTicket()); clientRequest.setTgsName(tgsRequest.getTgsPrincipal()); clientRequest.setTgsKeyType(tgsRequest.getEncryptionType()); clientRequest.setTgsKey(tgsRequest.getTgsEntry().getKey(tgsRequest.getEncryptionType())); clientRequest.setTgsSessionKey(tgsRequest.getTgtSessionKey()); clientRequest.setTgsServerKey(tgsRequest.getServerKey()); } return getKdcContext().getIdentityService() .getIdentityAuthorizationData(clientRequest, encTicketPart); } protected KdcContext getKdcContext() { return kdcRequest.getKdcContext(); } protected KdcReq getKdcReq() { return kdcRequest.getKdcReq(); } protected PrincipalName getclientPrincipal() { if (kdcRequest.isToken()) { return new PrincipalName(kdcRequest.getToken().getSubject()); } else { PrincipalName principalName = getKdcReq().getReqBody().getCname(); if (getKdcRequest().isAnonymous()) { principalName.setNameType(NameType.NT_WELLKNOWN); } return principalName; } } protected PrincipalName getServerPrincipal() { return getKdcReq().getReqBody().getSname(); } protected EncryptionType getTicketEncryptionType() throws KrbException { EncryptionType encryptionType = kdcRequest.getEncryptionType(); return encryptionType; } protected EncryptionKey getTicketEncryptionKey() throws KrbException { EncryptionType encryptionType = getTicketEncryptionType(); EncryptionKey serverKey = kdcRequest.getServerEntry().getKeys().get(encryptionType); return serverKey; } protected TransitedEncoding getTransitedEncoding() { TransitedEncoding transEnc = new TransitedEncoding(); transEnc.setTrType(TransitedEncodingType.DOMAIN_X500_COMPRESS); byte[] empty = new byte[0]; transEnc.setContents(empty); return transEnc; } }
404
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/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.server.request; import org.apache.kerby.kerberos.kerb.KrbCodec; import org.apache.kerby.kerberos.kerb.KrbConstant; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.common.KrbUtil; import org.apache.kerby.kerberos.kerb.crypto.CheckSumHandler; import org.apache.kerby.kerberos.kerb.crypto.EncryptionHandler; import org.apache.kerby.kerberos.kerb.crypto.fast.FastUtil; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.server.KdcRecoverableException; import org.apache.kerby.kerberos.kerb.server.preauth.KdcFastContext; import org.apache.kerby.kerberos.kerb.server.preauth.PreauthContext; import org.apache.kerby.kerberos.kerb.server.preauth.PreauthHandler; 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.AuthToken; 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.EncryptionType; import org.apache.kerby.kerberos.kerb.type.base.EtypeInfo; 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.EtypeInfoEntry; import org.apache.kerby.kerberos.kerb.type.base.KeyUsage; 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.MethodData; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; 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.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.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.ticket.EncTicketPart; import org.apache.kerby.kerberos.kerb.type.ticket.Ticket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.Date; import java.util.List; public abstract class KdcRequest { private static final Logger LOG = LoggerFactory.getLogger(KdcRequest.class); private final KdcReq kdcReq; private final KdcContext kdcContext; private Ticket ticket; private boolean isPreAuthenticated; private KdcRep reply; private InetAddress clientAddress; private boolean isTcp = true; private EncryptionType encryptionType; private EncryptionKey clientKey; private KrbIdentity clientEntry; private KrbIdentity serverEntry; private EncryptionKey serverKey; private KrbIdentity tgsEntry; private PreauthContext preauthContext; private KdcFastContext fastContext; private PrincipalName clientPrincipal; private PrincipalName serverPrincipal; private byte[] innerBodyout; private AuthToken token; private boolean isToken = false; private boolean isPkinit = false; private boolean isAnonymous = false; private EncryptionKey sessionKey; private ByteBuffer reqPackage; private boolean isHttps = false; private boolean isCrossRealm = false; private String remoteRealm = null; /** * Get session key. * * @return session key */ public EncryptionKey getSessionKey() { return sessionKey; } /** * Set session key. * @param sessionKey The session key */ public void setSessionKey(EncryptionKey sessionKey) { this.sessionKey = sessionKey; } /** * kdc request constructor * @param kdcReq kdc request * @param kdcContext kdc context */ public KdcRequest(KdcReq kdcReq, KdcContext kdcContext) { this.kdcReq = kdcReq; this.kdcContext = kdcContext; this.preauthContext = kdcContext.getPreauthHandler() .preparePreauthContext(this); this.fastContext = new KdcFastContext(); } /** * Get kdc context. * * @return kdc context */ public KdcContext getKdcContext() { return kdcContext; } /** * Get KdcReq. * * @return kdc request */ public KdcReq getKdcReq() { return kdcReq; } /** * Get preauth context. * * @return preauthentication context. */ public PreauthContext getPreauthContext() { return preauthContext; } /** * Process the kdcrequest from client and issue the ticket. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ public void process() throws KrbException { checkVersion(); checkTgsEntry(); kdcFindFast(); checkEncryptionType(); if (PreauthHandler.isToken(getKdcReq().getPaData())) { isToken = true; preauth(); checkClient(); checkServer(); } else { if (PreauthHandler.isPkinit(getKdcReq().getPaData())) { isPkinit = true; } checkClient(); checkServer(); preauth(); } checkPolicy(); issueTicket(); makeReply(); } /** * Check the tgs entry. * * @throws org.apache.kerby.kerberos.kerb.KrbException e. */ private void checkTgsEntry() throws KrbException { KrbIdentity tgsEntry = getEntry(getTgsPrincipal().getName()); setTgsEntry(tgsEntry); } /** * Find the fast from padata. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ private void kdcFindFast() throws KrbException { PaData paData = getKdcReq().getPaData(); if (paData != null) { for (PaDataEntry paEntry : paData.getElements()) { if (paEntry.getPaDataType() == PaDataType.FX_FAST) { LOG.info("Found fast padata and starting to process it."); PaFxFastRequest paFxFastRequest = null; try { paFxFastRequest = KrbCodec.decode(paEntry.getPaDataValue(), PaFxFastRequest.class); } catch (KrbException e) { String errMessage = "Decode PaFxFastRequest failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } KrbFastArmoredReq fastArmoredReq = paFxFastRequest.getFastArmoredReq(); if (fastArmoredReq == null) { return; } KrbFastArmor fastArmor = fastArmoredReq.getArmor(); if (fastArmor == null) { return; } try { armorApRequest(fastArmor); } catch (KrbException e) { String errMessage = "Get armor key failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } if (getArmorKey() == null) { return; } EncryptedData encryptedData = fastArmoredReq.getEncryptedFastReq(); KrbFastReq fastReq; try { fastReq = KrbCodec.decode( EncryptionHandler.decrypt(encryptedData, getArmorKey(), KeyUsage.FAST_ENC), KrbFastReq.class); } catch (KrbException e) { String errMessage = "Decode KrbFastReq failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } try { innerBodyout = KrbCodec.encode(fastReq.getKdcReqBody()); } catch (KrbException e) { String errMessage = "Encode KdcReqBody failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } // TODO: get checksumed data in stream CheckSum checkSum = fastArmoredReq.getReqChecksum(); if (checkSum == null) { LOG.warn("Checksum is empty."); throw new KrbException(KrbErrorCode.KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED); } byte[] reqBody; try { reqBody = KrbCodec.encode(getKdcReq().getReqBody()); } catch (KrbException e) { String errMessage = "Encode the ReqBody failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } boolean success; try { success = CheckSumHandler.verifyWithKey(checkSum, reqBody, getArmorKey().getKeyData(), KeyUsage.FAST_REQ_CHKSUM); } catch (KrbException e) { String errMessage = "Verify the KdcReqBody failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } if (!success) { LOG.error("Verify the KdcReqBody failed."); throw new KrbException("Verify the KdcReqBody failed. "); } } } } } /** * Get the armor key. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param fastArmor krb fast armor */ private void armorApRequest(KrbFastArmor fastArmor) throws KrbException { if (fastArmor.getArmorType() == ArmorType.ARMOR_AP_REQUEST) { ApReq apReq; try { apReq = KrbCodec.decode(fastArmor.getArmorValue(), ApReq.class); } catch (KrbException e) { String errMessage = "Decode ApReq failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } Ticket ticket = apReq.getTicket(); EncryptionType encType = ticket.getEncryptedEncPart().getEType(); EncryptionKey tgsKey = getTgsEntry().getKeys().get(encType); if (ticket.getTktvno() != KrbConstant.KRB_V5) { LOG.error(KrbErrorCode.KRB_AP_ERR_BADVERSION.getMessage()); throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADVERSION); } EncTicketPart encPart = null; try { encPart = EncryptionUtil.unseal(ticket.getEncryptedEncPart(), tgsKey, KeyUsage.KDC_REP_TICKET, EncTicketPart.class); } catch (KrbException e) { String errMessage = "Unseal EncTicketPart failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } ticket.setEncPart(encPart); EncryptionKey encKey = ticket.getEncPart().getKey(); setSessionKey(encKey); Authenticator authenticator = null; try { authenticator = EncryptionUtil.unseal(apReq.getEncryptedAuthenticator(), encKey, KeyUsage.AP_REQ_AUTH, Authenticator.class); } catch (KrbException e) { String errMessage = "Unseal Authenticator failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } EncryptionKey armorKey = null; try { armorKey = FastUtil.cf2(authenticator.getSubKey(), "subkeyarmor", encKey, "ticketarmor"); } catch (KrbException e) { String errMessage = "Create armor key failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } setArmorKey(armorKey); } } /** * Get tgs entry. * * @return TGS entry */ public KrbIdentity getTgsEntry() { return tgsEntry; } /** * Set tgs entry . * * @param tgsEntry TGS entry */ public void setTgsEntry(KrbIdentity tgsEntry) { this.tgsEntry = tgsEntry; } /** * Get whether is tcp. * * @return whether is tcp */ public boolean isTcp() { return isTcp; } /** * Set use tcp. * * @param isTcp set kdc request though TCP protocol or not */ public void isTcp(boolean isTcp) { this.isTcp = isTcp; } /** * Get the reply message. * * @return reply */ public KrbMessage getReply() { return reply; } /** * Set kdc reply. * * @param reply reply */ public void setReply(KdcRep reply) { this.reply = reply; } /** * Get client address. * * @return client address */ public InetAddress getClientAddress() { return clientAddress; } /** * Set client address. * * @param clientAddress client address */ public void setClientAddress(InetAddress clientAddress) { this.clientAddress = clientAddress; } /** * Get encryption type. * * @return encryption type */ public EncryptionType getEncryptionType() { return encryptionType; } /** * Set encryption type. * * @param encryptionType encryption type */ public void setEncryptionType(EncryptionType encryptionType) { this.encryptionType = encryptionType; } /** * Get ticket. * * @return ticket */ public Ticket getTicket() { return ticket; } /** * Set ticket. * * @param ticket ticket */ public void setTicket(Ticket ticket) { this.ticket = ticket; } /** * Get whether pre-authenticated. * * @return whether preauthenticated */ public boolean isPreAuthenticated() { return isPreAuthenticated; } /** * Set whether pre-authenticated. * * @param isPreAuthenticated whether is preauthenticated */ public void setPreAuthenticated(boolean isPreAuthenticated) { this.isPreAuthenticated = isPreAuthenticated; } /** * Get server entry. * * @return server entry */ public KrbIdentity getServerEntry() { return serverEntry; } /** * Set server entry. * * @param serverEntry server entry */ public void setServerEntry(KrbIdentity serverEntry) { this.serverEntry = serverEntry; } /** * Get client entry. * * @return client entry */ public KrbIdentity getClientEntry() { return clientEntry; } /** * Set client entry. * * @param clientEntry client entry */ public void setClientEntry(KrbIdentity clientEntry) { this.clientEntry = clientEntry; } /** * Get client key with entryption type. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param encType encryption type * @return encryption key */ public EncryptionKey getClientKey(EncryptionType encType) throws KrbException { return getClientEntry().getKey(encType); } /** * Get client key. * * @return client key */ public EncryptionKey getClientKey() { return clientKey; } /** * Set client key. * * @param clientKey client key */ public void setClientKey(EncryptionKey clientKey) { this.clientKey = clientKey; } /** * Get server key. * @return The server key */ public EncryptionKey getServerKey() { return serverKey; } /** * Set server key. * * @param serverKey server key */ public void setServerKey(EncryptionKey serverKey) { this.serverKey = serverKey; } /** * Get tgs principal name. * * @return principal name */ public PrincipalName getTgsPrincipal() { return KrbUtil.makeTgsPrincipal(kdcContext.getKdcRealm()); } public PrincipalName getCrossRealmTgsPrincipal(String remoteRealm) { return KrbUtil.makeCrossRealmPrincipal(kdcContext.getKdcRealm(), remoteRealm); } public KrbIdentity getCrossRealmTgsEntry(String remoteRealm) throws KrbException { PrincipalName tgsPrincipal = getCrossRealmTgsPrincipal(remoteRealm); KrbIdentity tgsEntry = null; if (tgsPrincipal != null) { tgsEntry = getEntry(tgsPrincipal.getName()); } return tgsEntry; } public boolean checkCrossRealm(String remoteRealm) throws KrbException { if (remoteRealm != null && kdcContext.getKdcRealm() != null) { isCrossRealm = !(kdcContext.getKdcRealm().equals(remoteRealm)); this.remoteRealm = remoteRealm; return isCrossRealm; } else { throw new KrbException("Missing the realm."); } } public boolean isCrossRealm() { return isCrossRealm; } public String getRemoteRealm() { return this.remoteRealm; } /** * Make reply. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected abstract void makeReply() throws KrbException; /** * Check Version. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected void checkVersion() throws KrbException { KdcReq request = getKdcReq(); int kerberosVersion = request.getPvno(); if (kerberosVersion != KrbConstant.KRB_V5) { LOG.warn("Kerberos version: " + kerberosVersion + " should equal to " + KrbConstant.KRB_V5); throw new KrbException(KrbErrorCode.KDC_ERR_BAD_PVNO); } } /** * Check policy. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected void checkPolicy() throws KrbException { KrbIdentity entry = getClientEntry(); // if we can not get the client entry, maybe it is token preauth, ignore it. if (entry != null) { if (entry.isDisabled()) { LOG.warn("Client entry " + entry.getPrincipalName() + " is disabled."); throw new KrbException(KrbErrorCode.KDC_ERR_CLIENT_REVOKED); } if (entry.isLocked()) { LOG.warn("Client entry " + entry.getPrincipalName() + " is expired."); throw new KrbException(KrbErrorCode.KDC_ERR_CLIENT_REVOKED); } if (entry.getExpireTime().lessThan(new Date().getTime())) { throw new KrbException(KrbErrorCode.KDC_ERR_CLIENT_REVOKED); } } else { LOG.info("Client entry is empty, token preauth or cross realm."); } } /** * Check client. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected abstract void checkClient() throws KrbException; /** * Do the preauth. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected void preauth() throws KrbException { KdcReq request = getKdcReq(); if (isAnonymous && !isPkinit) { LOG.info("Need PKINIT."); KrbError krbError = makePreAuthenticationError(kdcContext, request, KrbErrorCode.KDC_ERR_PREAUTH_REQUIRED, true); throw new KdcRecoverableException(krbError); } PaData preAuthData = request.getPaData(); if (preAuthData == null || preAuthData.isEmpty()) { if (isPreauthRequired()) { LOG.info("The preauth data is empty."); KrbError krbError = makePreAuthenticationError(kdcContext, request, KrbErrorCode.KDC_ERR_PREAUTH_REQUIRED, false); throw new KdcRecoverableException(krbError); } } else { getPreauthHandler().verify(this, preAuthData); } setPreAuthenticated(true); } /** * Set whether preauth required. * @param preauthRequired whether preauthentication required */ protected void setPreauthRequired(boolean preauthRequired) { preauthContext.setPreauthRequired(preauthRequired); } /** * Get whether preauth required. * @return whether preauthentication is required */ protected boolean isPreauthRequired() { return preauthContext.isPreauthRequired(); } /** * Get preauth handler. * @return preauthencation handler */ protected PreauthHandler getPreauthHandler() { return kdcContext.getPreauthHandler(); } /** * Check encryption type. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected void checkEncryptionType() throws KrbException { List<EncryptionType> requestedTypes = getKdcReq().getReqBody().getEtypes(); EncryptionType bestType = EncryptionUtil.getBestEncryptionType(requestedTypes, kdcContext.getConfig().getEncryptionTypes()); if (bestType == null) { LOG.error("Can't get the best encryption type."); throw new KrbException(KrbErrorCode.KDC_ERR_ETYPE_NOSUPP); } setEncryptionType(bestType); } /** * Do some authenticate. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected void authenticate() throws KrbException { checkEncryptionType(); checkPolicy(); } /** * Issue ticket. * @throws org.apache.kerby.kerberos.kerb.KrbException e */ protected abstract void issueTicket() throws KrbException; /** * Check server. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ private void checkServer() throws KrbException { KdcReq request = getKdcReq(); PrincipalName principal = request.getReqBody().getSname(); String serverRealm = request.getReqBody().getRealm(); if (serverRealm == null || serverRealm.isEmpty()) { LOG.info("Can't get the server realm from request, and try to get from kdcContext."); serverRealm = kdcContext.getKdcRealm(); } principal.setRealm(serverRealm); KrbIdentity serverEntry = getEntry(principal.getName()); if (serverEntry == null) { LOG.error("Principal: " + principal.getName() + " is not known"); throw new KrbException(KrbErrorCode.KDC_ERR_S_PRINCIPAL_UNKNOWN); } setServerEntry(serverEntry); for (EncryptionType encType : request.getReqBody().getEtypes()) { if (serverEntry.getKeys().containsKey(encType)) { EncryptionKey serverKey = serverEntry.getKeys().get(encType); setServerKey(serverKey); break; } } } /** * Make preauthentication error. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param kdcContext kdc context * @param request kdc request * @param errorCode krb error code * @return The krb error reply to client */ protected KrbError makePreAuthenticationError(KdcContext kdcContext, KdcReq request, KrbErrorCode errorCode, boolean pkinit) throws KrbException { List<EncryptionType> encryptionTypes = kdcContext.getConfig().getEncryptionTypes(); List<EncryptionType> clientEtypes = request.getReqBody().getEtypes(); boolean isNewEtype = true; EtypeInfo2 eTypeInfo2 = new EtypeInfo2(); EtypeInfo eTypeInfo = new EtypeInfo(); for (EncryptionType encryptionType : encryptionTypes) { if (clientEtypes.contains(encryptionType)) { if (!isNewEtype) { EtypeInfoEntry etypeInfoEntry = new EtypeInfoEntry(); etypeInfoEntry.setEtype(encryptionType); etypeInfoEntry.setSalt(null); eTypeInfo.add(etypeInfoEntry); } EtypeInfo2Entry etypeInfo2Entry = new EtypeInfo2Entry(); etypeInfo2Entry.setEtype(encryptionType); eTypeInfo2.add(etypeInfo2Entry); } } byte[] encTypeInfo = null; byte[] encTypeInfo2 = null; if (!isNewEtype) { encTypeInfo = KrbCodec.encode(eTypeInfo); } encTypeInfo2 = KrbCodec.encode(eTypeInfo2); MethodData methodData = new MethodData(); //methodData.add(new PaDataEntry(PaDataType.ENC_TIMESTAMP, null)); if (!isNewEtype) { methodData.add(new PaDataEntry(PaDataType.ETYPE_INFO, encTypeInfo)); } methodData.add(new PaDataEntry(PaDataType.ETYPE_INFO2, encTypeInfo2)); if (pkinit) { methodData.add(new PaDataEntry(PaDataType.PK_AS_REQ, "empty".getBytes())); methodData.add(new PaDataEntry(PaDataType.PK_AS_REP, "empty".getBytes())); } KrbError krbError = new KrbError(); krbError.setErrorCode(errorCode); byte[] encodedData = KrbCodec.encode(methodData); krbError.setEdata(encodedData); return krbError; } /** * Get identity entry with principal name. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principal Principal * @return krb identity entry */ protected KrbIdentity getEntry(String principal) throws KrbException { return kdcContext.getIdentityService().getIdentity(principal); } /** * Get request body. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @return request body */ protected ByteBuffer getRequestBody() throws KrbException { return null; } /** * Get armor key. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @return armor key */ public EncryptionKey getArmorKey() throws KrbException { return fastContext.getArmorKey(); } /** * Set armor key. * * @param armorKey armor key */ protected void setArmorKey(EncryptionKey armorKey) { fastContext.setArmorKey(armorKey); } /** * Get client principal. * @return client principal */ public PrincipalName getClientPrincipal() { return clientPrincipal; } /** * Set client principal. * @param clientPrincipal client principal */ public void setClientPrincipal(PrincipalName clientPrincipal) { this.clientPrincipal = clientPrincipal; } /** * Get server principal. * @return server principal */ public PrincipalName getServerPrincipal() { return serverPrincipal; } /** * Set server principal. * @param serverPrincipal server principal */ public void setServerPrincipal(PrincipalName serverPrincipal) { this.serverPrincipal = serverPrincipal; } /** * Get innerbodyout. * @return inner body out */ protected byte[] getInnerBodyout() { return innerBodyout; } /** * Get whether kdc request with token. * @return whether isToken */ protected boolean isToken() { return isToken; } public boolean isHttps() { return isHttps; } public void setHttps(boolean https) { isHttps = https; } /** * Set auth token. * @param authToken The auth token */ public void setToken(AuthToken authToken) { this.token = authToken; } /** * Get auth token. * @return token */ protected AuthToken getToken() { return token; } protected boolean isPkinit() { return isPkinit; } public boolean isAnonymous() { return getKdcOptions().isFlagSet(KdcOption.REQUEST_ANONYMOUS); } public KdcOptions getKdcOptions() { return kdcReq.getReqBody().getKdcOptions(); } public void setReqPackage(ByteBuffer reqPackage) { this.reqPackage = reqPackage; } public ByteBuffer getReqPackage() { return this.reqPackage; } }
405
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/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.server.request; import org.apache.kerby.kerberos.kerb.KrbCodec; import org.apache.kerby.kerberos.kerb.KrbConstant; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.crypto.CheckSumHandler; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.server.KdcContext; import org.apache.kerby.kerberos.kerb.type.KerberosTime; import org.apache.kerby.kerberos.kerb.type.ap.ApOption; 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.EncryptionType; 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.KrbMessageType; import org.apache.kerby.kerberos.kerb.type.base.LastReq; import org.apache.kerby.kerberos.kerb.type.base.LastReqEntry; import org.apache.kerby.kerberos.kerb.type.base.LastReqType; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; import org.apache.kerby.kerberos.kerb.type.kdc.EncKdcRepPart; import org.apache.kerby.kerberos.kerb.type.kdc.EncTgsRepPart; import org.apache.kerby.kerberos.kerb.type.kdc.KdcReq; 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.pa.PaDataEntry; import org.apache.kerby.kerberos.kerb.type.ticket.EncTicketPart; import org.apache.kerby.kerberos.kerb.type.ticket.Ticket; import org.apache.kerby.kerberos.kerb.type.ticket.TicketFlag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; public class TgsRequest extends KdcRequest { private static final Logger LOG = LoggerFactory.getLogger(TgsRequest.class); private EncryptionKey tgtSessionKey; private Ticket tgtTicket; /** * @param tgsReq TGS request * @param kdcContext kdc context */ public TgsRequest(TgsReq tgsReq, KdcContext kdcContext) { super(tgsReq, kdcContext); setPreauthRequired(true); } /** * Get tgt session key. * * @return The tgt session key */ public EncryptionKey getTgtSessionKey() { return tgtSessionKey; } /** * Set tgt session key. * * @param tgtSessionKey The tgt session key */ public void setTgtSessionKey(EncryptionKey tgtSessionKey) { this.tgtSessionKey = tgtSessionKey; } /** * {@inheritDoc} */ @Override protected void checkClient() throws KrbException { // Nothing to do at this phase because client couldn't be checked out yet. } /** * Get tgt ticket. * * @return The tgt ticket. */ public Ticket getTgtTicket() { return tgtTicket; } /** * {@inheritDoc} */ @Override protected void issueTicket() throws KrbException { TicketIssuer issuer = new ServiceTicketIssuer(this); Ticket newTicket = issuer.issueTicket(); LOG.info("TGS_REQ ISSUE: authtime " + newTicket.getEncPart().getAuthTime().getTime() + "," + newTicket.getEncPart().getCname() + " for " + newTicket.getSname()); setTicket(newTicket); } /** * Verify authenticator. * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param paDataEntry preauthentication data entry */ public void verifyAuthenticator(PaDataEntry paDataEntry) throws KrbException { ApReq apReq = KrbCodec.decode(paDataEntry.getPaDataValue(), ApReq.class); if (apReq.getPvno() != KrbConstant.KRB_V5) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADVERSION); } if (apReq.getMsgType() != KrbMessageType.AP_REQ) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_MSG_TYPE); } tgtTicket = apReq.getTicket(); EncryptionKey tgsKey; EncryptionType encType = tgtTicket.getEncryptedEncPart().getEType(); String remoteRealm = tgtTicket.getRealm(); if (checkCrossRealm(remoteRealm)) { KrbIdentity tgs = getCrossRealmTgsEntry(remoteRealm); if (tgs != null) { tgsKey = tgs.getKey(encType); } else { throw new KrbException("Failed to get the tgs entry for remote realm: " + remoteRealm); } } else { tgsKey = getTgsEntry().getKeys().get(encType); } if (tgsKey == null) { throw new KrbException("Failed to get the tgs key for the type: " + encType); } if (tgtTicket.getTktvno() != KrbConstant.KRB_V5) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADVERSION); } EncTicketPart encPart = EncryptionUtil.unseal(tgtTicket.getEncryptedEncPart(), tgsKey, KeyUsage.KDC_REP_TICKET, EncTicketPart.class); tgtTicket.setEncPart(encPart); EncryptionKey encKey = null; //if (apReq.getApOptions().isFlagSet(ApOptions.USE_SESSION_KEY)) { encKey = tgtTicket.getEncPart().getKey(); if (encKey == null) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_NOKEY); } Authenticator authenticator = EncryptionUtil.unseal(apReq.getEncryptedAuthenticator(), encKey, KeyUsage.TGS_REQ_AUTH, Authenticator.class); if (!authenticator.getCname().equals(tgtTicket.getEncPart().getCname())) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADMATCH); } HostAddresses hostAddresses = tgtTicket.getEncPart().getClientAddresses(); if (hostAddresses == null || hostAddresses.isEmpty()) { if (!getKdcContext().getConfig().isEmptyAddressesAllowed()) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADADDR); } } else if (!hostAddresses.contains(getClientAddress())) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_BADADDR); } PrincipalName serverPrincipal = tgtTicket.getSname(); serverPrincipal.setRealm(tgtTicket.getRealm()); /* The client principal does not exist in backend when it's a cross realm request */ if (authenticator.getCrealm() != null && authenticator.getCrealm().equals(getKdcContext().getKdcRealm())) { PrincipalName clientPrincipal = authenticator.getCname(); clientPrincipal.setRealm(authenticator.getCrealm()); KrbIdentity clientEntry = getEntry(clientPrincipal.getName()); setClientEntry(clientEntry); } if (!authenticator.getCtime().isInClockSkew( getKdcContext().getConfig().getAllowableClockSkew() * 1000)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_SKEW); } KerberosTime now = KerberosTime.now(); KerberosTime startTime = tgtTicket.getEncPart().getStartTime(); if (startTime == null) { startTime = tgtTicket.getEncPart().getAuthTime(); } if (!startTime.lessThan(now)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_TKT_NYV); } KerberosTime endTime = tgtTicket.getEncPart().getEndTime(); if (!endTime.greaterThan(now)) { throw new KrbException(KrbErrorCode.KRB_AP_ERR_TKT_EXPIRED); } apReq.getApOptions().setFlag(ApOption.MUTUAL_REQUIRED); setTgtSessionKey(tgtTicket.getEncPart().getKey()); CheckSum checkSum = authenticator.getCksum(); if (checkSum != null) { byte[] reqBody; try { reqBody = KrbCodec.encode(getKdcReq().getReqBody()); } catch (KrbException e) { String errMessage = "Encode the ReqBody failed. " + e.getMessage(); LOG.error(errMessage); throw new KrbException(errMessage); } boolean success; switch (checkSum.getCksumtype()) { case RSA_MD5_DES: case RSA_MD4_DES: case DES_MAC: case DES_CBC: case HMAC_SHA1_DES3: case HMAC_SHA1_96_AES256: case HMAC_SHA1_96_AES128: case CMAC_CAMELLIA128: case CMAC_CAMELLIA256: case MD5_HMAC_ARCFOUR: case HMAC_MD5_ARCFOUR: success = CheckSumHandler.verifyWithKey(checkSum, reqBody, getTgtSessionKey().getKeyData(), KeyUsage.TGS_REQ_AUTH_CKSUM); break; case RSA_MD5: case NIST_SHA: case CRC32: case RSA_MD4: default: success = CheckSumHandler.verify(checkSum, reqBody); } if (!success) { LOG.error("Verify the KdcReqBody failed."); throw new KrbException("Verify the KdcReqBody failed."); } } } /** * {@inheritDoc} */ @Override protected void makeReply() throws KrbException { Ticket ticket = getTicket(); TgsRep reply = new TgsRep(); if (getClientEntry() == null) { reply.setCname(ticket.getEncPart().getCname()); reply.setCrealm(ticket.getEncPart().getCrealm()); } else { reply.setCname(getClientEntry().getPrincipal()); reply.setCrealm(getKdcContext().getKdcRealm()); } reply.setTicket(ticket); EncKdcRepPart encKdcRepPart = makeEncKdcRepPart(); reply.setEncPart(encKdcRepPart); EncryptionKey sessionKey; if (getToken() != null) { sessionKey = getSessionKey(); } else { sessionKey = getTgtSessionKey(); } EncryptedData encryptedData = EncryptionUtil.seal(encKdcRepPart, sessionKey, KeyUsage.TGS_REP_ENCPART_SESSKEY); reply.setEncryptedEncPart(encryptedData); setReply(reply); } /** * Make EncKdcRepPart. * @return encryption kdc response part */ private EncKdcRepPart makeEncKdcRepPart() { KdcReq request = getKdcReq(); Ticket ticket = getTicket(); EncKdcRepPart encKdcRepPart = new EncTgsRepPart(); //session key encKdcRepPart.setKey(ticket.getEncPart().getKey()); LastReq lastReq = new LastReq(); LastReqEntry entry = new LastReqEntry(); entry.setLrType(LastReqType.THE_LAST_INITIAL); entry.setLrValue(new KerberosTime()); lastReq.add(entry); encKdcRepPart.setLastReq(lastReq); encKdcRepPart.setNonce(request.getReqBody().getNonce()); encKdcRepPart.setFlags(ticket.getEncPart().getFlags()); encKdcRepPart.setAuthTime(ticket.getEncPart().getAuthTime()); encKdcRepPart.setStartTime(ticket.getEncPart().getStartTime()); encKdcRepPart.setEndTime(ticket.getEncPart().getEndTime()); if (ticket.getEncPart().getFlags().isFlagSet(TicketFlag.RENEWABLE)) { encKdcRepPart.setRenewTill(ticket.getEncPart().getRenewtill()); } encKdcRepPart.setSname(ticket.getSname()); encKdcRepPart.setSrealm(ticket.getRealm()); encKdcRepPart.setCaddr(ticket.getEncPart().getClientAddresses()); return encKdcRepPart; } /** * @return request body * @throws KrbException e */ public ByteBuffer getRequestBody() throws KrbException { return null; } }
406
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/request/ServiceTicketIssuer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.request; 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.base.TransitedEncoding; import org.apache.kerby.kerberos.kerb.type.ticket.Ticket; /** * Issuing service ticket. */ public class ServiceTicketIssuer extends TicketIssuer { private final Ticket tgtTicket; private final AuthToken token; public ServiceTicketIssuer(TgsRequest kdcRequest) { super(kdcRequest); tgtTicket = kdcRequest.getTgtTicket(); token = kdcRequest.getToken(); } protected KdcRequest getTgsRequest() { return getKdcRequest(); } @Override protected PrincipalName getclientPrincipal() { PrincipalName clientPrincipal; if (token != null) { clientPrincipal = new PrincipalName(token.getSubject()); } else { clientPrincipal = tgtTicket.getEncPart().getCname(); clientPrincipal.setRealm(tgtTicket.getEncPart().getCrealm()); } return clientPrincipal; } @Override protected TransitedEncoding getTransitedEncoding() { if (token != null) { return super.getTransitedEncoding(); } return tgtTicket.getEncPart().getTransited(); } }
407
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/request/TgtTicketIssuer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.request; import org.apache.kerby.kerberos.kerb.type.base.TransitedEncoding; import org.apache.kerby.kerberos.kerb.type.base.TransitedEncodingType; /** * Issuing TGT ticket. */ public class TgtTicketIssuer extends TicketIssuer { public TgtTicketIssuer(AsRequest kdcRequest) { super(kdcRequest); } @Override protected TransitedEncoding getTransitedEncoding() { TransitedEncoding transEnc = new TransitedEncoding(); transEnc.setTrType(TransitedEncodingType.DOMAIN_X500_COMPRESS); byte[] empty = new byte[0]; transEnc.setContents(empty); return transEnc; } }
408
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/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.server.request; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.common.EncryptionUtil; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.server.KdcContext; 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.KeyUsage; import org.apache.kerby.kerberos.kerb.type.base.LastReq; import org.apache.kerby.kerberos.kerb.type.base.LastReqEntry; import org.apache.kerby.kerberos.kerb.type.base.LastReqType; 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.kdc.AsRep; 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.KdcReq; import org.apache.kerby.kerberos.kerb.type.ticket.Ticket; import org.apache.kerby.kerberos.kerb.type.ticket.TicketFlag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AsRequest extends KdcRequest { private static final Logger LOG = LoggerFactory.getLogger(AsRequest.class); public AsRequest(AsReq asReq, KdcContext kdcContext) { super(asReq, kdcContext); } /** * {@inheritDoc} */ @Override protected void checkClient() throws KrbException { KdcReq request = getKdcReq(); PrincipalName clientPrincipal; if (isToken()) { LOG.info("The request has a token with subject: " + getToken().getSubject()); clientPrincipal = new PrincipalName(getToken().getSubject()); } else { clientPrincipal = request.getReqBody().getCname(); } if (clientPrincipal == null) { LOG.warn("Client principal name is null."); throw new KrbException(KrbErrorCode.KDC_ERR_C_PRINCIPAL_UNKNOWN); } String clientRealm = request.getReqBody().getRealm(); if (clientRealm == null || clientRealm.isEmpty()) { clientRealm = getKdcContext().getKdcRealm(); } clientPrincipal.setRealm(clientRealm); setClientPrincipal(clientPrincipal); KrbIdentity clientEntry; if (isToken()) { clientEntry = new KrbIdentity(clientPrincipal.getName()); clientEntry.setExpireTime(new KerberosTime(getToken().getExpiredTime().getTime())); } else { clientEntry = getEntry(clientPrincipal.getName()); } if (clientEntry == null) { LOG.warn("Can't get the client entry."); throw new KrbException(KrbErrorCode.KDC_ERR_C_PRINCIPAL_UNKNOWN); } if (isAnonymous()) { clientEntry.setPrincipal(new PrincipalName(clientPrincipal.getName(), NameType.NT_WELLKNOWN)); } setClientEntry(clientEntry); for (EncryptionType encType : request.getReqBody().getEtypes()) { if (clientEntry.getKeys().containsKey(encType)) { EncryptionKey clientKey = clientEntry.getKeys().get(encType); setClientKey(clientKey); break; } } } /** * {@inheritDoc} */ @Override protected void issueTicket() throws KrbException { TicketIssuer issuer = new TgtTicketIssuer(this); Ticket newTicket = issuer.issueTicket(); LOG.info("AS_REQ ISSUE: authtime " + newTicket.getEncPart().getAuthTime().getTime() + "," + newTicket.getEncPart().getCname() + " for " + newTicket.getSname()); setTicket(newTicket); } /** * {@inheritDoc} */ @Override protected void makeReply() throws KrbException { Ticket ticket = getTicket(); AsRep reply = new AsRep(); reply.setTicket(ticket); reply.setCname(getClientEntry().getPrincipal()); reply.setCrealm(getKdcContext().getKdcRealm()); EncKdcRepPart encKdcRepPart = makeEncKdcRepPart(); reply.setEncPart(encKdcRepPart); EncryptionKey clientKey = getClientKey(); if (clientKey != null) { EncryptedData encryptedData = EncryptionUtil.seal(encKdcRepPart, clientKey, KeyUsage.AS_REP_ENCPART); reply.setEncryptedEncPart(encryptedData); } else { throw new KrbException("Cant't get the client key to encrypt the kdc rep part."); } if (isPkinit()) { reply.setPaData(getPreauthContext().getOutputPaData()); } setReply(reply); } /** * Make EncKdcRepPart. * @return encryption kdc request part */ protected EncKdcRepPart makeEncKdcRepPart() { KdcReq request = getKdcReq(); Ticket ticket = getTicket(); EncKdcRepPart encKdcRepPart = new EncAsRepPart(); //session key encKdcRepPart.setKey(ticket.getEncPart().getKey()); LastReq lastReq = new LastReq(); LastReqEntry entry = new LastReqEntry(); entry.setLrType(LastReqType.THE_LAST_INITIAL); entry.setLrValue(new KerberosTime()); lastReq.add(entry); encKdcRepPart.setLastReq(lastReq); encKdcRepPart.setNonce(request.getReqBody().getNonce()); encKdcRepPart.setFlags(ticket.getEncPart().getFlags()); encKdcRepPart.setAuthTime(ticket.getEncPart().getAuthTime()); encKdcRepPart.setStartTime(ticket.getEncPart().getStartTime()); encKdcRepPart.setEndTime(ticket.getEncPart().getEndTime()); if (ticket.getEncPart().getFlags().isFlagSet(TicketFlag.RENEWABLE)) { encKdcRepPart.setRenewTill(ticket.getEncPart().getRenewtill()); } encKdcRepPart.setSname(ticket.getSname()); encKdcRepPart.setSrealm(ticket.getRealm()); encKdcRepPart.setCaddr(ticket.getEncPart().getClientAddresses()); return encKdcRepPart; } }
409
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/replay/RequestRecord.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.replay; public class RequestRecord { private String clientPrincipal; private String serverPrincipal; private long requestTime; private int microseconds; public RequestRecord(String clientPrincipal, String serverPrincipal, long requestTime, int microseconds) { this.clientPrincipal = clientPrincipal; this.serverPrincipal = serverPrincipal; this.requestTime = requestTime; this.microseconds = microseconds; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RequestRecord that = (RequestRecord) o; if (microseconds != that.microseconds) { return false; } if (requestTime != that.requestTime) { return false; } if (!clientPrincipal.equals(that.clientPrincipal)) { return false; } if (!serverPrincipal.equals(that.serverPrincipal)) { return false; } return true; } @Override public int hashCode() { int result = clientPrincipal.hashCode(); result = 31 * result + serverPrincipal.hashCode(); result = 31 * result + (int) (requestTime ^ (requestTime >>> 32)); result = 31 * result + microseconds; return result; } }
410
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/replay/CacheService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.replay; public interface CacheService { boolean checkAndCache(RequestRecord request); void clear(); }
411
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/replay/ReplayCheckServiceImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.replay; public class ReplayCheckServiceImpl implements ReplayCheckService { private CacheService cacheService; public ReplayCheckServiceImpl(CacheService cacheService) { this.cacheService = cacheService; } public ReplayCheckServiceImpl() { this(new SimpleCacheService()); } @Override public boolean checkReplay(String clientPrincipal, String serverPrincipal, long requestTime, int microseconds) { RequestRecord record = new RequestRecord(clientPrincipal, serverPrincipal, requestTime, microseconds); return cacheService.checkAndCache(record); } }
412
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/replay/ReplayCheckService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.replay; public interface ReplayCheckService { boolean checkReplay(String clientPrincipal, String serverPrincipal, long requestTime, int microseconds); }
413
0
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server
Create_ds/directory-kerby/kerby-kerb/kerb-server/src/main/java/org/apache/kerby/kerberos/kerb/server/replay/SimpleCacheService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server.replay; import java.util.HashSet; import java.util.Set; public class SimpleCacheService implements CacheService { private final Set<RequestRecord> requests; public SimpleCacheService() { requests = new HashSet<>(); } @Override public boolean checkAndCache(RequestRecord request) { if (requests.contains(request)) { return true; } else { requests.add(request); } return false; } @Override public void clear() { requests.clear(); } }
414
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/test/java/org/apache/kerby/kerberos/kerb/admin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/test/java/org/apache/kerby/kerberos/kerb/admin/server/RemoteKadminTest.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.admin.server; import org.apache.commons.io.FileUtils; import org.apache.kerby.kerberos.kerb.admin.AuthUtil; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadminImpl; import org.apache.kerby.kerberos.kerb.admin.kadmin.remote.AdminClient; import org.apache.kerby.kerberos.kerb.admin.kadmin.remote.AdminConfig; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServer; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerConfig; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.keytab.Keytab; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.server.KdcServer; import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; import org.apache.kerby.util.NetworkUtil; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import java.io.File; import java.util.List; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertEquals; public class RemoteKadminTest { private static final Logger LOG = LoggerFactory.getLogger(RemoteKadminTest.class); protected static File testDir = new File(System.getProperty("test.dir", "target")); private static File testClassDir = new File(testDir, "test-classes"); private static File confDir = new File(testClassDir, "conf"); private static File workDir = new File(testDir, "work-dir"); private static final String SERVER_HOST = "localhost"; private static final String ADMIN_PRINCIPAL = "kadmin/[email protected]"; private static final String PROTOCOL_PRINCIPAL = "adminprotocol/[email protected]"; private static KdcServer kdcServer; private static LocalKadminImpl localKadmin; private static AdminServer adminServer; private static SimpleKdcServer buildMiniKdc() throws Exception { KdcConfig config = new KdcConfig(); BackendConfig backendConfig = new BackendConfig(); backendConfig.addIniConfig(new File(confDir, "backend.conf")); SimpleKdcServer kdc = new SimpleKdcServer(config, backendConfig); kdc.setWorkDir(workDir); kdc.setKdcHost(SERVER_HOST); int kdcPort = NetworkUtil.getServerPort(); kdc.setAllowTcp(true); kdc.setAllowUdp(false); kdc.setKdcTcpPort(kdcPort); LOG.info("Starting KDC server at " + SERVER_HOST + ":" + kdcPort); kdc.init(); return kdc; } private static void buildLocalKadmin() throws Exception { localKadmin = new LocalKadminImpl(kdcServer.getKdcSetting(), kdcServer.getIdentityService()); localKadmin.addPrincipal(PROTOCOL_PRINCIPAL); localKadmin.exportKeytab(new File(workDir, "protocol.keytab"), PROTOCOL_PRINCIPAL); localKadmin.exportKeytab(new File(workDir, "admin.keytab"), ADMIN_PRINCIPAL); } private static AdminServer buildAdminServer() throws Exception { AdminServer server = new AdminServer(confDir); AdminServerConfig config = server.getAdminServerConfig(); server.setAdminHost(config.getAdminHost()); server.setAllowTcp(true); server.setAllowUdp(false); server.setAdminServerPort(config.getAdminPort()); server.init(); return server; } private AdminClient buildKadminRemoteClient() throws Exception { final AdminConfig config = new AdminConfig(); config.addKrb5Config(new File(confDir, "adminClient.conf")); AdminClient adminClient = new AdminClient(config); adminClient.setAdminRealm(config.getAdminRealm()); adminClient.setAllowTcp(true); adminClient.setAllowUdp(false); adminClient.setAdminTcpPort(config.getAdminPort()); adminClient.init(); doSaslHandShake(adminClient, config); return adminClient; } @BeforeAll public static void setUpBeforeAll() throws Exception { workDir.mkdirs(); kdcServer = buildMiniKdc(); kdcServer.start(); buildLocalKadmin(); adminServer = buildAdminServer(); adminServer.start(); } @AfterAll public static void tearDownAfterAll() throws Exception { adminServer.stop(); kdcServer.stop(); FileUtils.deleteDirectory(workDir); } @Test public void remoteListPrincipalTest() throws Exception { AdminClient adminClient = buildKadminRemoteClient(); List<String> principals = adminClient.requestGetprincs(); assertTrue(principals.contains("kadmin/[email protected]")); assertTrue(principals.contains("krbtgt/[email protected]")); assertTrue(principals.contains("adminprotocol/[email protected]")); principals = adminClient.requestGetprincsWithExp("k*"); assertTrue(principals.contains("kadmin/[email protected]")); assertTrue(principals.contains("krbtgt/[email protected]")); assertFalse(principals.contains("adminprotocol/[email protected]")); } @Test public void remoteModifyPrincipalTest() throws Exception { AdminClient adminClient = buildKadminRemoteClient(); String testPrincipal = "test/EXAMPLE.COM"; String renamePrincipal = "test_rename/EXAMPLE.COM"; adminClient.requestAddPrincipal(testPrincipal); assertTrue(localKadmin.getPrincipals().contains(testPrincipal + "@EXAMPLE.COM"), "Remote kadmin add principal test failed."); adminClient.requestRenamePrincipal(testPrincipal, renamePrincipal); assertTrue(localKadmin.getPrincipals().contains(renamePrincipal + "@EXAMPLE.COM"), "Remote kadmin rename principal test failed, the renamed principal does not exist."); assertFalse(localKadmin.getPrincipals().contains(testPrincipal + "@EXAMPLE.COM"), "Remote kadmin rename principal test failed, the old principal still exists."); adminClient.requestDeletePrincipal(renamePrincipal); assertFalse(localKadmin.getPrincipals().contains(renamePrincipal + "@EXAMPLE.COM"), "Remote kadmin delete principal test failed."); } @Test public void remoteKtaddTest() throws Exception { AdminClient adminClient = buildKadminRemoteClient(); String testPrincipal = "test/EXAMPLE.COM"; File keytabOutput = new File(testDir, "test.keytab"); localKadmin.addPrincipal(testPrincipal); adminClient.requestExportKeytab(keytabOutput, testPrincipal); Keytab localKeytab = Keytab.loadKeytab(keytabOutput); List<String> principalNames = localKeytab.getPrincipals() .stream().map(PrincipalName::getName).collect(Collectors.toList()); assertTrue(principalNames.contains(testPrincipal + "@EXAMPLE.COM")); } @Test public void remoteChangePasswordTest() throws Exception { AdminClient adminClient = buildKadminRemoteClient(); String testPrincipal = "cpw/EXAMPLE.COM"; String oldPassword = "old_pwd"; String newPassword = "new_pwd"; localKadmin.addPrincipal(testPrincipal, oldPassword); adminClient.requestChangePassword(testPrincipal, newPassword); try { AuthUtil.loginUsingPassword(testPrincipal, new PasswordCallbackHandler(newPassword)); } catch (LoginException e) { Assertions.fail("Login using new password failed: " + e.toString()); } } @Test public void remoteGetPrincipalTest() throws Exception { AdminClient adminClient = buildKadminRemoteClient(); KrbIdentity identity = adminClient.requestGetPrincipal("kadmin/EXAMPLE.COM"); KrbIdentity expectIdentity = new KrbIdentity("kadmin/[email protected]"); assertEquals(identity, expectIdentity); } private void doSaslHandShake(AdminClient adminClient, AdminConfig config) throws Exception { Subject subject = AuthUtil.loginUsingKeytab(ADMIN_PRINCIPAL, new File(config.getKeyTabFile())); adminClient.setSubject(subject); } }
415
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/test/java/org/apache/kerby/kerberos/kerb/admin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/test/java/org/apache/kerby/kerberos/kerb/admin/server/PasswordCallbackHandler.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.admin.server; import sun.security.util.Password; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import java.io.ByteArrayInputStream; import java.io.IOException; public class PasswordCallbackHandler implements CallbackHandler { private final String password; public PasswordCallbackHandler(String password) { this.password = password; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof PasswordCallback) { PasswordCallback pc = (PasswordCallback) callback; pc.setPassword(Password.readPassword(new ByteArrayInputStream(password.getBytes()), pc.isEchoOn())); } else { throw new UnsupportedCallbackException( callback, "Only support PasswordCallback"); } } } }
416
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/KerbyAdminServer.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.admin.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.Krb5Conf; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServer; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerConfig; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.server.KdcUtil; import org.apache.kerby.util.OSUtil; import java.io.File; import java.io.IOException; public class KerbyAdminServer { private static final String USAGE = (OSUtil.isWindows() ? "Usage: bin\\admin-server.cmd" : "Usage: sh bin/admin-server.sh") + " <conf-file>\n" + "\tExample:\n" + "\t\t" + (OSUtil.isWindows() ? "bin\\admin-server.cmd" : "sh bin/admin-server.sh") + " conf\n"; public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println(USAGE); System.exit(1); } String confDirPath = args[0]; AdminServer adminServer = new AdminServer(new File(confDirPath)); AdminServerConfig adminServerConfig = adminServer.getAdminServerConfig(); adminServer.setAdminHost(adminServerConfig.getAdminHost()); adminServer.setAllowTcp(true); adminServer.setAllowUdp(false); adminServer.setAdminServerPort(adminServerConfig.getAdminPort()); KdcConfig kdcConfig = KdcUtil.getKdcConfig(new File(confDirPath)); if (kdcConfig == null) { kdcConfig = new KdcConfig(); } try { Krb5Conf krb5Conf = new Krb5Conf(new File(confDirPath), kdcConfig); krb5Conf.initKrb5conf(); } catch (IOException e) { throw new KrbException("Failed to make krb5.conf", e); } try { adminServer.init(); } catch (KrbException e) { System.err.println("Errors occurred when start admin server: " + e.getMessage()); System.exit(2); } adminServer.start(); System.out.println("Admin server started!"); } }
417
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerConfig.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.admin.server.kadmin; import org.apache.kerby.kerberos.kerb.common.Krb5Conf; /** * Kerb admin server side configuration API. */ public class AdminServerConfig extends Krb5Conf { private static final String KDCDEFAULT = "kdcdefaults"; public boolean enableDebug() { return getBoolean(AdminServerConfigKey.KRB_DEBUG, true, KDCDEFAULT); } public String getAdminServiceName() { return getString(AdminServerConfigKey.ADMIN_SERVICE_NAME, true, KDCDEFAULT); } public String getAdminHost() { return getString(AdminServerConfigKey.ADMIN_HOST, true, KDCDEFAULT); } public int getAdminPort() { Integer kdcPort = getInt(AdminServerConfigKey.ADMIN_PORT, true, KDCDEFAULT); if (kdcPort != null && kdcPort > 0) { return kdcPort.intValue(); } return -1; } public int getAdminTcpPort() { Integer kdcTcpPort = getInt(AdminServerConfigKey.ADMIN_TCP_PORT, true, KDCDEFAULT); if (kdcTcpPort != null && kdcTcpPort > 0) { return kdcTcpPort.intValue(); } return getAdminPort(); } /** * Is to allow TCP for KDC * @return true to allow TCP, false otherwise */ public Boolean allowTcp() { return getBoolean(AdminServerConfigKey.ADMIN_ALLOW_TCP, true, KDCDEFAULT) || getInt(AdminServerConfigKey.ADMIN_TCP_PORT, true, KDCDEFAULT) != null || getInt(AdminServerConfigKey.ADMIN_PORT, false, KDCDEFAULT) != null; } /** * Is to allow UDP for KDC * @return true to allow UDP, false otherwise */ public Boolean allowUdp() { return getBoolean(AdminServerConfigKey.ADMIN_ALLOW_UDP, true, KDCDEFAULT) || getInt(AdminServerConfigKey.ADMIN_UDP_PORT, true, KDCDEFAULT) != null || getInt(AdminServerConfigKey.ADMIN_PORT, false, KDCDEFAULT) != null; } public int getAdminUdpPort() { Integer kdcUdpPort = getInt(AdminServerConfigKey.ADMIN_UDP_PORT, true, KDCDEFAULT); if (kdcUdpPort != null && kdcUdpPort > 0) { return kdcUdpPort.intValue(); } return getAdminPort(); } public String getAdminRealm() { return getString(AdminServerConfigKey.ADMIN_REALM, true, KDCDEFAULT); } public String getAdminDomain() { return getString(AdminServerConfigKey.ADMIN_DOMAIN, true, KDCDEFAULT); } public String getKeyTabFile() { return getString(AdminServerConfigKey.KEYTAB_FILE, true, KDCDEFAULT); } public String getProtocol() { return getString(AdminServerConfigKey.PROTOCOL, true, KDCDEFAULT); } public String getServerName() { return getString(AdminServerConfigKey.SERVER_NAME, true, KDCDEFAULT); } }
418
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerConfigKey.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.admin.server.kadmin; import org.apache.kerby.config.ConfigKey; public enum AdminServerConfigKey implements ConfigKey { KRB_DEBUG(true), ADMIN_SERVICE_NAME("Kadmin-Server"), KDC_IDENTITY_BACKEND, ADMIN_HOST("localhost"), ADMIN_PORT, ADMIN_ALLOW_TCP(true), ADMIN_ALLOW_UDP(true), ADMIN_UDP_PORT, ADMIN_TCP_PORT, ADMIN_DOMAIN("example.com"), ADMIN_REALM("EXAMPLE.COM"), KEYTAB_FILE, PROTOCOL, SERVER_NAME("localhost"); private Object defaultValue; AdminServerConfigKey() { this.defaultValue = null; } AdminServerConfigKey(Object defaultValue) { this.defaultValue = defaultValue; } @Override public String getPropertyKey() { return name().toLowerCase(); } @Override public Object getDefaultValue() { return this.defaultValue; } }
419
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerSetting.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.admin.server.kadmin; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.server.ServerSetting; /** * Admin Server setting that combines startup options and admin config. */ public class AdminServerSetting implements ServerSetting { private final KOptions startupOptions; private final AdminServerConfig adminServerConfig; private final KdcConfig kdcConfig; private final BackendConfig backendConfig; /** * AdminServerSetting constructor * @param startupOptions startup options * @param adminServerConfig admin configuration * @param kdcConfig kdc configuration * @param backendConfig backend configuration */ public AdminServerSetting(KOptions startupOptions, AdminServerConfig adminServerConfig, KdcConfig kdcConfig, BackendConfig backendConfig) { this.startupOptions = startupOptions; this.adminServerConfig = adminServerConfig; this.kdcConfig = kdcConfig; this.backendConfig = backendConfig; } public AdminServerSetting(AdminServerConfig adminServerConfig, BackendConfig backendConfig, KdcConfig kdcConfig) { this(new KOptions(), adminServerConfig, kdcConfig, backendConfig); } /** * Get the Admin Server config. * @return admin configuration */ public AdminServerConfig getAdminServerConfig() { return adminServerConfig; } /** * Get the realm of KDC of Admin Server. * @return the realm of KDC */ @Override public String getKdcRealm() { return kdcConfig.getKdcRealm(); } /** * Get the KDC config of Admin server. * @return the KDC configuration */ @Override public KdcConfig getKdcConfig() { return kdcConfig; } /** * Get the backend config. * @return backend configuration */ public BackendConfig getBackendConfig() { return backendConfig; } public String getAdminHost() { String adminHost = startupOptions.getStringOption( AdminServerOption.ADMIN_HOST); if (adminHost == null) { adminHost = adminServerConfig.getAdminHost(); } return adminHost; } /** * Check admin tcp setting and see if any bad. * @return valid tcp port or -1 if not allowTcp * @throws KrbException e */ public int checkGetAdminTcpPort() throws KrbException { if (allowTcp()) { int adminPort = getAdminTcpPort(); if (adminPort < 1) { throw new KrbException("Admin Server tcp port isn't set or configured"); } return adminPort; } return -1; } /** * Check admin udp setting and see if any bad. * @return valid udp port or -1 if not allowUdp * @throws KrbException e */ public int checkGetAdminUdpPort() throws KrbException { if (allowUdp()) { int adminPort = getAdminUdpPort(); if (adminPort < 1) { throw new KrbException("Admin Server udp port isn't set or configured"); } return adminPort; } return -1; } /** * Get admin tcp port * * @return admin tcp port */ public int getAdminTcpPort() { int tcpPort = startupOptions.getIntegerOption(AdminServerOption.ADMIN_TCP_PORT); if (tcpPort < 1) { tcpPort = adminServerConfig.getAdminTcpPort(); } if (tcpPort < 1) { tcpPort = getAdminPort(); } return tcpPort; } /** * Get admin port * * @return admin port */ public int getAdminPort() { int adminPort = startupOptions.getIntegerOption(AdminServerOption.ADMIN_PORT); if (adminPort < 1) { adminPort = adminServerConfig.getAdminPort(); } return adminPort; } /** * Get whether tcp protocol is allowed * @return tcp protocol is allowed or not */ public boolean allowTcp() { return startupOptions.getBooleanOption( AdminServerOption.ALLOW_TCP, adminServerConfig.allowTcp()); } /** * Get whether udp protocol is allowed * @return udp protocol is allowed or not */ public boolean allowUdp() { return startupOptions.getBooleanOption( AdminServerOption.ALLOW_UDP, adminServerConfig.allowUdp()); } /** * Get admin udp port * * @return udp port */ public int getAdminUdpPort() { int udpPort = startupOptions.getIntegerOption(AdminServerOption.ADMIN_UDP_PORT); if (udpPort < 1) { udpPort = adminServerConfig.getAdminUdpPort(); } if (udpPort < 1) { udpPort = getAdminPort(); } return udpPort; } /** * Get Admin Server realm. * @return Admin Server realm */ public String getAdminRealm() { String adminRealm = startupOptions.getStringOption(AdminServerOption.ADMIN_REALM); if (adminRealm == null || adminRealm.isEmpty()) { adminRealm = adminServerConfig.getAdminRealm(); } return adminRealm; } }
420
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServer.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.admin.server.kadmin; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.impl.DefaultInternalAdminServerImpl; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.impl.InternalAdminServer; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import java.io.File; /** * The implemented Kerberos remote admin server API. * We add the KdcConfig as a member variable to AdminServer, * In order to make it easy to use LocalKadminImpl. * The Kdc Config of corresponding KDC can be read from ConfDir. */ public class AdminServer { private final AdminServerConfig adminServerConfig; private final BackendConfig backendConfig; private final KdcConfig kdcConfig; private final AdminServerSetting adminServerSetting; private final KOptions startupOptions; private InternalAdminServer innerAdminServer; /** * Constructor passing adminServerConfig, kdcConfig and backendConfig. * @param adminServerConfig The admin server config * @param backendConfig The backend config * @param kdcConfig The kdc config * @throws KrbException e */ public AdminServer(AdminServerConfig adminServerConfig, BackendConfig backendConfig, KdcConfig kdcConfig) throws KrbException { this.adminServerConfig = adminServerConfig; this.kdcConfig = kdcConfig; this.backendConfig = backendConfig; startupOptions = new KOptions(); adminServerSetting = new AdminServerSetting(startupOptions, adminServerConfig, kdcConfig, backendConfig); } /** * Constructor given confDir where 'adminServer.conf', 'kdc.conf' and * 'backend.conf' should be available. * adminServer.conf that contains adminServer related items. * kdc.conf, that contains kdc related items. * backend.conf, that contains identity backend related items. * * @param confDir The conf dir * @throws KrbException e */ public AdminServer(File confDir) throws KrbException { AdminServerConfig tmpAdminServerConfig = AdminServerUtil.getAdminServerConfig(confDir); if (tmpAdminServerConfig == null) { tmpAdminServerConfig = new AdminServerConfig(); } this.adminServerConfig = tmpAdminServerConfig; KdcConfig tmpKdcConfig = AdminServerUtil.getKdcConfig(confDir); if (tmpKdcConfig == null) { tmpKdcConfig = new KdcConfig(); } this.kdcConfig = tmpKdcConfig; BackendConfig tmpBackendConfig = AdminServerUtil.getBackendConfig(confDir); if (tmpBackendConfig == null) { tmpBackendConfig = new BackendConfig(); } tmpBackendConfig.setConfDir(confDir); this.backendConfig = tmpBackendConfig; startupOptions = new KOptions(); adminServerSetting = new AdminServerSetting(startupOptions, adminServerConfig, kdcConfig, backendConfig); } /** * Default constructor. */ public AdminServer() { adminServerConfig = new AdminServerConfig(); backendConfig = new BackendConfig(); kdcConfig = new KdcConfig(); startupOptions = new KOptions(); adminServerSetting = new AdminServerSetting(startupOptions, adminServerConfig, kdcConfig, backendConfig); } /** * Set Admin realm for ticket request * @param realm The kdc realm */ public void setAdminServerRealm(String realm) { startupOptions.add(AdminServerOption.ADMIN_REALM, realm); } /** * Set Admin host. * @param adminHost The kdc host */ public void setAdminHost(String adminHost) { startupOptions.add(AdminServerOption.ADMIN_HOST, adminHost); } /** * Set Admin port. * @param adminPort The admin port */ public void setAdminServerPort(int adminPort) { startupOptions.add(AdminServerOption.ADMIN_PORT, adminPort); } /** * Set Admin tcp port. * @param adminTcpPort The admin tcp port */ public void setAdminTcpPort(int adminTcpPort) { startupOptions.add(AdminServerOption.ADMIN_TCP_PORT, adminTcpPort); } /** * Set to allow UDP or not. * @param allowUdp true if allow udp */ public void setAllowUdp(boolean allowUdp) { startupOptions.add(AdminServerOption.ALLOW_UDP, allowUdp); } /** * Set to allow TCP or not. * @param allowTcp true if allow tcp */ public void setAllowTcp(boolean allowTcp) { startupOptions.add(AdminServerOption.ALLOW_TCP, allowTcp); } /** * Set Admin udp port. Only makes sense when allowUdp is set. * @param adminUdpPort The admin udp port */ public void setAdminUdpPort(int adminUdpPort) { startupOptions.add(AdminServerOption.ADMIN_UDP_PORT, adminUdpPort); } /** * Set runtime folder. * @param workDir The work dir */ public void setWorkDir(File workDir) { startupOptions.add(AdminServerOption.WORK_DIR, workDir); } /** * Allow to debug so have more logs. */ public void enableDebug() { startupOptions.add(AdminServerOption.ENABLE_DEBUG); } /** * Allow to hook customized admin implementation. * * @param innerAdminServerImpl The inner admin implementation */ public void setInnerAdminServerImpl(InternalAdminServer innerAdminServerImpl) { startupOptions.add(AdminServerOption.INNER_ADMIN_IMPL, innerAdminServerImpl); } /** * Get Admin setting from startup options and configs. * @return setting */ public AdminServerSetting getAdminServerSetting() { return adminServerSetting; } /** * Get the Admin config. * @return AdminServerConfig */ public AdminServerConfig getAdminServerConfig() { return adminServerConfig; } /** * Get backend config. * * @return backend configuration */ public BackendConfig getBackendConfig() { return backendConfig; } /** * Get identity service. * @return IdentityService */ public IdentityBackend getIdentityService() { if (innerAdminServer == null) { throw new RuntimeException("Not init yet"); } return innerAdminServer.getIdentityBackend(); } /** * Initialize. * * @throws KrbException e. */ public void init() throws KrbException { if (startupOptions.contains(AdminServerOption.INNER_ADMIN_IMPL)) { innerAdminServer = (InternalAdminServer) startupOptions.getOptionValue( AdminServerOption.INNER_ADMIN_IMPL); } else { innerAdminServer = new DefaultInternalAdminServerImpl(adminServerSetting); } innerAdminServer.init(); } /** * Start the Admin admin. * * @throws KrbException e. */ public void start() throws KrbException { if (innerAdminServer == null) { throw new RuntimeException("Not init yet"); } innerAdminServer.start(); } /** * Stop the Admin admin. * * @throws KrbException e. */ public void stop() throws KrbException { if (innerAdminServer != null) { innerAdminServer.stop(); } } }
421
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerContext.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.admin.server.kadmin; import org.apache.kerby.kerberos.kerb.identity.IdentityService; public class AdminServerContext { private final AdminServerSetting adminServerSetting; private IdentityService identityService; public AdminServerContext(AdminServerSetting adminServerSetting) { this.adminServerSetting = adminServerSetting; } public AdminServerSetting getAdminServerSetting() { return adminServerSetting; } public AdminServerConfig getConfig() { return adminServerSetting.getAdminServerConfig(); } public void setIdentityService(IdentityService identityService) { this.identityService = identityService; } public IdentityService getIdentityService() { return identityService; } public String getAdminRealm() { return adminServerSetting.getAdminRealm(); } }
422
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerUtil.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.admin.server.kadmin; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.server.KdcConfig; import org.apache.kerby.kerberos.kerb.transport.TransportPair; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; /** * Admin Server utilities. */ public final class AdminServerUtil { /** * Get adminServer configuration * @param confDir configuration directory * @return adminServer configuration * @throws KrbException e. */ public static AdminServerConfig getAdminServerConfig(File confDir) throws KrbException { File adminServerConfFile = new File(confDir, "adminServer.conf"); if (adminServerConfFile.exists()) { AdminServerConfig adminServerConfig = new AdminServerConfig(); try { adminServerConfig.addKrb5Config(adminServerConfFile); } catch (IOException e) { throw new KrbException("Can not load the adminServer configuration file " + adminServerConfFile.getAbsolutePath()); } return adminServerConfig; } return null; } /** * Get kdc configuration * @param confDir configuration directory * @return kdc configuration * @throws KrbException e. */ public static KdcConfig getKdcConfig(File confDir) throws KrbException { File kdcConfFile = new File(confDir, "kdc.conf"); if (kdcConfFile.exists()) { KdcConfig kdcConfig = new KdcConfig(); try { kdcConfig.addKrb5Config(kdcConfFile); } catch (IOException e) { throw new KrbException("Can not load the kdc configuration file " + kdcConfFile.getAbsolutePath()); } return kdcConfig; } return null; } /** * Get backend configuration * @param confDir configuration directory * @return backend configuration * @throws KrbException e. */ public static BackendConfig getBackendConfig(File confDir) throws KrbException { File backendConfigFile = new File(confDir, "backend.conf"); if (backendConfigFile.exists()) { BackendConfig backendConfig = new BackendConfig(); try { backendConfig.addIniConfig(backendConfigFile); } catch (IOException e) { throw new KrbException("Can not load the backend configuration file " + backendConfigFile.getAbsolutePath()); } return backendConfig; } return null; } /** * Get KDC network transport addresses according to KDC setting. * @param setting kdc setting * @return UDP and TCP addresses pair * @throws KrbException e */ public static TransportPair getTransportPair( AdminServerSetting setting) throws KrbException { TransportPair result = new TransportPair(); int tcpPort = setting.checkGetAdminTcpPort(); if (tcpPort > 0) { result.tcpAddress = new InetSocketAddress( setting.getAdminHost(), tcpPort); } int udpPort = setting.checkGetAdminUdpPort(); if (udpPort > 0) { result.udpAddress = new InetSocketAddress( setting.getAdminHost(), udpPort); } return result; } /** * Fix principal name. * * @param principal The principal name * @return The fixed principal */ public static String fixPrincipal(String principal, AdminServerSetting setting) { if (!principal.contains("@")) { principal += "@" + setting.getKdcRealm(); } return principal; } }
423
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerOption.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.admin.server.kadmin; import org.apache.kerby.KOption; import org.apache.kerby.KOptionInfo; import org.apache.kerby.KOptionType; /** * KDC admin startup options */ public enum AdminServerOption implements KOption { NONE(null), INNER_ADMIN_IMPL(new KOptionInfo("inner KDC impl", "inner KDC impl", KOptionType.OBJ)), ADMIN_REALM(new KOptionInfo("kdc realm", "kdc realm", KOptionType.STR)), ADMIN_HOST(new KOptionInfo("kdc host", "kdc host", KOptionType.STR)), ADMIN_PORT(new KOptionInfo("kdc port", "kdc port", KOptionType.INT)), ALLOW_TCP(new KOptionInfo("allow tcp", "allow tcp", KOptionType.BOOL)), ADMIN_TCP_PORT(new KOptionInfo("kdc tcp port", "kdc tcp port", KOptionType.INT)), ALLOW_UDP(new KOptionInfo("allow udp", "allow udp", KOptionType.BOOL)), ADMIN_UDP_PORT(new KOptionInfo("kdc udp port", "kdc udp port", KOptionType.INT)), WORK_DIR(new KOptionInfo("work dir", "work dir", KOptionType.DIR)), ENABLE_DEBUG(new KOptionInfo("enable debug", "enable debug", KOptionType.BOOL)); private final KOptionInfo optionInfo; AdminServerOption(KOptionInfo optionInfo) { this.optionInfo = optionInfo; } @Override public KOptionInfo getOptionInfo() { return optionInfo; } }
424
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/AdminServerHandler.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.admin.server.kadmin; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadmin; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadminImpl; import org.apache.kerby.kerberos.kerb.admin.message.AddPrincipalRep; import org.apache.kerby.kerberos.kerb.admin.message.AdminMessage; import org.apache.kerby.kerberos.kerb.admin.message.AdminMessageCode; import org.apache.kerby.kerberos.kerb.admin.message.AdminMessageType; import org.apache.kerby.kerberos.kerb.admin.message.DeletePrincipalRep; import org.apache.kerby.kerberos.kerb.admin.message.GetprincsRep; import org.apache.kerby.kerberos.kerb.admin.message.KadminCode; import org.apache.kerby.kerberos.kerb.admin.message.RenamePrincipalRep; import org.apache.kerby.kerberos.kerb.admin.message.KeytabMessageCode; import org.apache.kerby.kerberos.kerb.admin.message.ExportKeytabRep; import org.apache.kerby.kerberos.kerb.admin.message.ChangePasswordRep; import org.apache.kerby.kerberos.kerb.admin.message.IdentityInfoCode; import org.apache.kerby.kerberos.kerb.admin.message.GetPrincipalRep; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import org.apache.kerby.xdr.XdrDataType; import org.apache.kerby.xdr.XdrFieldInfo; import org.apache.kerby.xdr.type.XdrStructType; import org.xnio.sasl.SaslWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * admin server handler to process client acmin requests. */ public class AdminServerHandler { private static final Logger LOG = LoggerFactory.getLogger(AdminServerHandler.class); private final AdminServerContext adminServerContext; private SaslWrapper saslServerWrapper; /** * Constructor with admin server context. * * @param adminServerContext admin admin server context */ public AdminServerHandler(AdminServerContext adminServerContext) { this.adminServerContext = adminServerContext; LOG.info("Admin realm: " + this.adminServerContext.getAdminRealm()); } public void setSaslServerWrapper(SaslWrapper saslServerWrapper) { this.saslServerWrapper = saslServerWrapper; } public SaslWrapper getSaslServerWrapper() { return saslServerWrapper; } /** * Process the client request message. * * @throws KrbException e * @param receivedMessage The client request message * @param remoteAddress Address from remote side * @return The response message */ public ByteBuffer handleMessage(ByteBuffer receivedMessage, InetAddress remoteAddress) throws KrbException, IOException { XdrStructType decoded = new AdminMessageCode(); decoded.decode(receivedMessage); XdrFieldInfo[] fieldInfos = decoded.getValue().getXdrFieldInfos(); AdminMessageType type = (AdminMessageType) fieldInfos[0].getValue(); /**Create LocalKadmin here*/ LocalKadmin localKadmin = new LocalKadminImpl(adminServerContext.getAdminServerSetting()); ByteBuffer responseMessage = null; switch (type) { case ADD_PRINCIPAL_REQ: System.out.println("message type: add principal req"); responseMessage = handleAddPrincipalReq(localKadmin, fieldInfos); break; case DELETE_PRINCIPAL_REQ: System.out.println("message type: delete principal req"); responseMessage = handleDeletePrincipalReq(localKadmin, fieldInfos); break; case RENAME_PRINCIPAL_REQ: System.out.println("message type: rename principal req"); responseMessage = handleRenamePrincipalReq(localKadmin, fieldInfos); break; case GET_PRINCS_REQ: System.out.println("message type: get principals req"); responseMessage = handleGetprincsReq(localKadmin, fieldInfos); break; case EXPORT_KEYTAB_REQ: System.out.println("message type: export keytab req"); responseMessage = handleExportKeytabReq(localKadmin, fieldInfos); break; case CHANGE_PWD_REQ: System.out.println("message type: change password req"); responseMessage = handleChangePwdReq(localKadmin, fieldInfos); break; case GET_PRINCIPAL_REQ: System.out.println("message type: get principal req"); responseMessage = handleGetPrincipalRep(localKadmin, fieldInfos); break; default: throw new KrbException("AdminMessageType error, can not handle the type: " + type); } return responseMessage; } private ByteBuffer handleAddPrincipalReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { String principal = (String) fieldInfos[2].getValue(); int paramNum = (int) fieldInfos[1].getValue(); if (paramNum == 1) { /** Add principal with only principal name*/ LOG.info("handle nokey principal " + principal); String[] temp = principal.split("@"); try { localKadmin.addPrincipal(temp[0]); } catch (KrbException e) { String error = "The principal already exists!"; LOG.error(error); System.err.println(error); ByteBuffer response = infoPackageTool(error, "addPrincipal"); return response; } } else if (paramNum == 2 && fieldInfos[3].getDataType() == XdrDataType.STRING) { /** Add principal with password*/ LOG.info("handle principal with password " + principal); String[] temp = principal.split("@"); String password = (String) fieldInfos[3].getValue(); try { localKadmin.addPrincipal(temp[0], password); } catch (KrbException e) { String error = " The principal already exists.\n" + "Choose update password instead of add principal"; LOG.error(error); ByteBuffer response = infoPackageTool(error, "addPrincipal"); return response; } } String message = "Add principal:" + principal; System.out.println(message); LOG.info(message); ByteBuffer responseMessage = infoPackageTool(message, "addPrincipal"); return responseMessage; } private ByteBuffer handleDeletePrincipalReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { /** message structure: msg_type, para_num(always equals 1), principal_name*/ String principal = (String) fieldInfos[2].getValue(); String[] temp = principal.split("@"); try { localKadmin.deletePrincipal(temp[0]); } catch (KrbException e) { String error = "No such principal exists!"; LOG.error(error); ByteBuffer response = infoPackageTool(error, "deletePrincipal"); return response; } String message = "Delete principal of " + principal; System.out.println(message); LOG.info(message); ByteBuffer responseMessage = infoPackageTool(message, "deletePrincipal"); return responseMessage; } private ByteBuffer handleRenamePrincipalReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { /** message structure: msg_type, para_num(always equals 2), old name, new name*/ String[] oldPrincipalName = ((String) fieldInfos[2].getValue()).split("@"); String[] newPrincipalName = ((String) fieldInfos[3].getValue()).split("@"); try { localKadmin.renamePrincipal(oldPrincipalName[0], newPrincipalName[0]); } catch (KrbException e) { String error = "The old principal name does not exist, or the new principal name" + " already exists, rename failed."; System.err.println(error); ByteBuffer response = infoPackageTool(error, "renamePrincipal"); return response; } String message = "Rename " + oldPrincipalName[0] + " to " + newPrincipalName[0]; System.out.println(message); LOG.info(message); ByteBuffer responseMessage = infoPackageTool(message, "renamePrincipal"); return responseMessage; } private ByteBuffer handleGetprincsReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { int paramNum = (int) fieldInfos[1].getValue(); String globString = paramNum != 0 ? (String) fieldInfos[2].getValue() : null; List<String> princsList = null; try { if (globString == null || globString.isEmpty()) { princsList = localKadmin.getPrincipals(); } else { princsList = localKadmin.getPrincipals(globString); } ByteBuffer responseMessage = infoPackageTool(listToString(princsList), "getPrincs"); return responseMessage; } catch (KrbException e) { String error = "The principal does not exist."; LOG.error(error + e); ByteBuffer responseError = infoPackageTool(error, "getPrincs"); return responseError; } } private ByteBuffer handleExportKeytabReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { String principals = (String) fieldInfos[2].getValue(); if (principals != null) { List<String> princList = stringToList(principals); if (princList.size() != 0) { LOG.info("Exporting keytab file for " + principals + "..."); File tempDir = Files.createTempDirectory("ktadd").toFile(); File keytabFile = new File(tempDir, princList.get(0) .replace('/', '-') .replace('*', '-') .replace('?', '-') + ".keytab"); try { localKadmin.exportKeytab(keytabFile, princList); LOG.info("Create keytab file for principals successfully."); ByteBuffer responseMessage = infoPackageTool(keytabFile, "exportKeytab"); return responseMessage; } catch (KrbException e) { String error = "Failed to export keytab. " + e.toString(); ByteBuffer responseError = infoPackageTool(error, "exportKeytab"); return responseError; } } else { String error = "No matched principals."; ByteBuffer responseError = infoPackageTool(error, "exportKeytab"); return responseError; } } String error = "Failed to export keytab."; ByteBuffer responseError = infoPackageTool(error, "exportKeytab"); return responseError; } private ByteBuffer handleChangePwdReq(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { String principal = (String) fieldInfos[2].getValue(); String newPassword = (String) fieldInfos[3].getValue(); if (principal == null || principal.isEmpty() || newPassword == null || newPassword.isEmpty()) { String error = "Value of principal or new password is null."; ByteBuffer responseError = infoPackageTool(error, "changePwd"); return responseError; } try { localKadmin.changePassword(principal, newPassword); } catch (KrbException e) { String error = String.format("Failed to change password of principal %s. ", principal) + e.toString(); ByteBuffer responseError = infoPackageTool(error, "changePwd"); return responseError; } String message = String.format("Change password of principal %s.", principal); System.out.println(message); LOG.info(message); ByteBuffer responseMessage = infoPackageTool(message, "changePwd"); return responseMessage; } private ByteBuffer handleGetPrincipalRep(LocalKadmin localKadmin, XdrFieldInfo[] fieldInfos) throws IOException { String principal = fixPrincipal((String) fieldInfos[2].getValue()); try { KrbIdentity identity = localKadmin.getPrincipal(principal); ByteBuffer responseMessage = infoPackageTool(identity, "getPrincipal"); return responseMessage; } catch (KrbException e) { String error = String.format("Failed to get principal %s. ", principal) + e.toString(); ByteBuffer responseError = infoPackageTool(error, "getPrincipal"); return responseError; } } private ByteBuffer infoPackageTool(String message, String dealType) throws IOException { AdminMessage adminMessage = null; XdrFieldInfo[] xdrFieldInfos = new XdrFieldInfo[3]; if ("getPrincs".equals(dealType)) { adminMessage = new GetprincsRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.GET_PRINCS_REP); } else if ("renamePrincipal".equals(dealType)) { adminMessage = new RenamePrincipalRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.RENAME_PRINCIPAL_REP); } else if ("deletePrincipal".equals(dealType)) { adminMessage = new DeletePrincipalRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.DELETE_PRINCIPAL_REP); } else if ("addPrincipal".equals(dealType)) { adminMessage = new AddPrincipalRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.ADD_PRINCIPAL_REP); } else if ("changePwd".equals(dealType)) { adminMessage = new ChangePasswordRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.CHANGE_PWD_REP); } xdrFieldInfos[1] = new XdrFieldInfo(1, XdrDataType.INTEGER, 1); xdrFieldInfos[2] = new XdrFieldInfo(2, XdrDataType.STRING, message); AdminMessageCode value = new AdminMessageCode(xdrFieldInfos); adminMessage.setMessageBuffer(ByteBuffer.wrap(value.encode())); return KadminCode.encodeWrapMessage(adminMessage, getSaslServerWrapper()); } private ByteBuffer infoPackageTool(File keytabFile, String dealType) throws IOException { AdminMessage adminMessage = null; XdrFieldInfo[] xdrFieldInfos = new XdrFieldInfo[3]; if ("exportKeytab".equals(dealType)) { adminMessage = new ExportKeytabRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.EXPORT_KEYTAB_REP); } xdrFieldInfos[1] = new XdrFieldInfo(1, XdrDataType.INTEGER, 1); xdrFieldInfos[2] = new XdrFieldInfo(2, XdrDataType.BYTES, Files.readAllBytes(keytabFile.toPath())); KeytabMessageCode value = new KeytabMessageCode(xdrFieldInfos); adminMessage.setMessageBuffer(ByteBuffer.wrap(value.encode())); return KadminCode.encodeWrapMessage(adminMessage, getSaslServerWrapper()); } private ByteBuffer infoPackageTool(KrbIdentity identity, String dealType) throws IOException { AdminMessage adminMessage = null; XdrFieldInfo[] xdrFieldInfos = new XdrFieldInfo[9]; if ("getPrincipal".equals(dealType)) { adminMessage = new GetPrincipalRep(); xdrFieldInfos[0] = new XdrFieldInfo(0, XdrDataType.ENUM, AdminMessageType.GET_PRINCIPAL_REP); } Map<EncryptionType, EncryptionKey> key = identity.getKeys(); // Join key EncryptionType with comma delimiter String keySet = key.keySet().stream().map(EncryptionType::getName).collect(Collectors.joining(",")); xdrFieldInfos[1] = new XdrFieldInfo(1, XdrDataType.INTEGER, 7); xdrFieldInfos[2] = new XdrFieldInfo(2, XdrDataType.STRING, identity.getPrincipalName()); xdrFieldInfos[3] = new XdrFieldInfo(3, XdrDataType.LONG, identity.getExpireTime().getTime()); xdrFieldInfos[4] = new XdrFieldInfo(4, XdrDataType.LONG, identity.getCreatedTime().getTime()); xdrFieldInfos[5] = new XdrFieldInfo(5, XdrDataType.INTEGER, identity.getKdcFlags()); xdrFieldInfos[6] = new XdrFieldInfo(6, XdrDataType.INTEGER, identity.getKeyVersion()); xdrFieldInfos[7] = new XdrFieldInfo(7, XdrDataType.INTEGER, key.size()); xdrFieldInfos[8] = new XdrFieldInfo(8, XdrDataType.STRING, keySet.toString()); IdentityInfoCode value = new IdentityInfoCode(xdrFieldInfos); adminMessage.setMessageBuffer(ByteBuffer.wrap(value.encode())); return KadminCode.encodeWrapMessage(adminMessage, getSaslServerWrapper()); } private String listToString(List<String> list) { if (list.isEmpty()) { return null; } //Both speed and safety,so use StringBuilder StringBuilder result = new StringBuilder(); for (String item : list) { result.append(item).append(" "); } return result.toString(); } private List<String> stringToList(String str) { if (str == null || str.isEmpty()) { return null; } String[] principals = str.split(" "); for (int i = 0; i < principals.length; i++) { principals[i] = fixPrincipal(principals[i]); } return Arrays.asList(principals); } private String fixPrincipal(String principal) { if (!principal.contains("@")) { principal += "@" + adminServerContext.getAdminRealm(); } return principal; } }
425
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/impl/AbstractInternalAdminServer.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.admin.server.kadmin.impl; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerConfig; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerSetting; import org.apache.kerby.kerberos.kerb.identity.CacheableIdentityService; import org.apache.kerby.kerberos.kerb.identity.IdentityService; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.identity.backend.MemoryIdentityBackend; import org.apache.kerby.kerberos.kerb.server.KdcUtil; /** * Abstract Kadmin admin implementation. */ public class AbstractInternalAdminServer implements InternalAdminServer { private boolean started; private final AdminServerConfig adminServerConfig; private final BackendConfig backendConfig; private final AdminServerSetting adminServerSetting; private IdentityBackend backend; private IdentityService identityService; public AbstractInternalAdminServer(AdminServerSetting adminServerSetting) { this.adminServerSetting = adminServerSetting; this.adminServerConfig = adminServerSetting.getAdminServerConfig(); this.backendConfig = adminServerSetting.getBackendConfig(); } @Override public AdminServerSetting getSetting() { return adminServerSetting; } public boolean isStarted() { return started; } protected String getServiceName() { return adminServerConfig.getAdminServiceName(); } protected IdentityService getIdentityService() { if (identityService == null) { if (backend instanceof MemoryIdentityBackend) { // Already in memory identityService = backend; } else { identityService = new CacheableIdentityService( backendConfig, backend); } } return identityService; } @Override public void init() throws KrbException { backend = KdcUtil.getBackend(backendConfig); } @Override public void start() throws KrbException { try { doStart(); } catch (Exception e) { throw new KrbException("Failed to start " + getServiceName(), e); } started = true; } public boolean enableDebug() { return adminServerConfig.enableDebug(); } @Override public IdentityBackend getIdentityBackend() { return backend; } protected void doStart() throws Exception { backend.start(); } public void stop() throws KrbException { try { doStop(); } catch (Exception e) { throw new KrbException("Failed to stop " + getServiceName(), e); } started = false; } protected void doStop() throws Exception { backend.stop(); } }
426
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/impl/InternalAdminServer.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.admin.server.kadmin.impl; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerSetting; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; /** * An internal KDC admin interface. */ public interface InternalAdminServer { /** * Initialize. * @throws KrbException e */ void init() throws KrbException; /** * Start the KDC admin. * @throws KrbException e */ void start() throws KrbException; /** * Stop the KDC admin. * @throws KrbException e */ void stop() throws KrbException; /** * Get admin admin setting. * @return setting */ AdminServerSetting getSetting(); /** * Get identity backend. * @return IdentityBackend */ IdentityBackend getIdentityBackend(); }
427
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/impl/DefaultAdminServerHandler.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.admin.server.kadmin.impl; import org.apache.kerby.kerberos.kerb.admin.AuthUtil; import org.apache.kerby.kerberos.kerb.admin.kadmin.remote.NegotiationStatus; import org.apache.kerby.kerberos.kerb.admin.message.KadminCode; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerContext; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerHandler; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerUtil; import org.apache.kerby.kerberos.kerb.common.KrbUtil; import org.apache.kerby.kerberos.kerb.transport.KrbTcpTransport; import org.apache.kerby.kerberos.kerb.transport.KrbTransport; import org.xnio.sasl.SaslUtils; import org.xnio.sasl.SaslWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.Subject; 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.File; import java.io.IOException; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Map; public class DefaultAdminServerHandler extends AdminServerHandler implements Runnable { private static Logger logger = LoggerFactory.getLogger(DefaultAdminServerHandler.class); private static final String MECHANISM = "GSSAPI"; private final KrbTransport transport; private AdminServerContext adminServerContext; public DefaultAdminServerHandler(AdminServerContext adminServerContext, KrbTransport transport) { super(adminServerContext); this.transport = transport; this.adminServerContext = adminServerContext; } @Override public void run() { try { doSaslHandshake(); } catch (Exception e) { logger.error("With exception when SASL negotiation." + e); return; } do { try { ByteBuffer message = transport.receiveMessage(); if (message == null) { logger.debug("No valid request recved. Disconnect actively"); transport.release(); break; } // unwrap SASL message ByteBuffer unwrapMessage = ByteBuffer.wrap(getSaslServerWrapper().unwrap(message)); handleMessage(unwrapMessage); } catch (IOException e) { transport.release(); logger.debug("Transport or decoding error occurred, " + "disconnecting abnormally", e); break; } } while (!((KrbTcpTransport) transport).isClosed()); } protected void handleMessage(ByteBuffer message) { InetAddress clientAddress = transport.getRemoteAddress(); try { ByteBuffer adminResponse = handleMessage(message, clientAddress); transport.sendMessage(adminResponse); } catch (Exception e) { transport.release(); logger.error("Error occured while processing request:", e); } } private void doSaslHandshake() throws Exception { File keytabFile = new File(adminServerContext.getConfig().getKeyTabFile()); String principal = adminServerContext.getConfig().getProtocol() + "/" + adminServerContext.getConfig().getAdminHost(); String fixedPrincipal = AdminServerUtil.fixPrincipal(principal, adminServerContext.getAdminServerSetting()); String adminPrincipal = KrbUtil.makeKadminPrincipal( adminServerContext.getAdminServerSetting().getKdcRealm()).getName(); Subject subject = AuthUtil.loginUsingKeytab(fixedPrincipal, keytabFile); Subject.doAs(subject, (PrivilegedExceptionAction<Object>) () -> { boolean success = false; try { ByteBuffer message; try { message = transport.receiveMessage(); } catch (SocketTimeoutException ignore) { // Ignore time out, wake up to see if should continue to run. // When client create a new tpc transport, socket always timeout, // because the first connection will not send message to the server. // SASL handshake is not performed until the connection is established. return null; } Map<String, Object> props = new HashMap<>(); props.put(Sasl.QOP, "auth-conf"); props.put(Sasl.SERVER_AUTH, "true"); String protocol = adminServerContext.getConfig().getProtocol(); String serverName = adminServerContext.getConfig().getServerName(); CallbackHandler callbackHandler = new SaslGssCallbackHandler(adminPrincipal); SaslServer saslServer = Sasl.createSaslServer(MECHANISM, protocol, serverName, props, callbackHandler); if (saslServer == null) { throw new Exception("Unable to find server implementation for: GSSAPI"); } setSaslServerWrapper(SaslWrapper.create(saslServer)); while (!saslServer.isComplete()) { int scComplete = message.getInt(); if (scComplete == NegotiationStatus.SUCCESS.getValue()) { logger.info("Sasl Client completed"); } byte[] challenge = null; try { challenge = SaslUtils.evaluateResponse(saslServer, message); } catch (SaslException e) { throw new Exception("Sasl server evaluate challenge failed. " + e); } if (!saslServer.isComplete()) { // Send message to client only when SASL server is not complete sendMessage(challenge, saslServer); logger.info("Waiting receive message"); message = transport.receiveMessage(); } } success = true; } finally { if (!success) { transport.release(); } } return null; }); } private void sendMessage(byte[] challenge, SaslServer saslServer) throws IOException { NegotiationStatus status = saslServer.isComplete() ? NegotiationStatus.SUCCESS : NegotiationStatus.CONTINUE; ByteBuffer buffer = KadminCode.encodeSaslMessage(challenge, status); try { transport.sendMessage(buffer); logger.info("Send message to admin client."); } catch (SaslException e) { logger.error("Failed to send message to client. " + e.toString()); } } private static class SaslGssCallbackHandler implements CallbackHandler { private final String adminPrincipal; SaslGssCallbackHandler(String principal) { this.adminPrincipal = principal; } @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) && authid.equals(adminPrincipal)) { ac.setAuthorized(true); } else { logger.warn("Client try to login using principal " + authid); ac.setAuthorized(false); } if (ac.isAuthorized()) { ac.setAuthorizedID(authzid); } } } } }
428
0
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin
Create_ds/directory-kerby/kerby-kerb/kerb-admin-server/src/main/java/org/apache/kerby/kerberos/kerb/admin/server/kadmin/impl/DefaultInternalAdminServerImpl.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.admin.server.kadmin.impl; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerContext; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerSetting; import org.apache.kerby.kerberos.kerb.admin.server.kadmin.AdminServerUtil; import org.apache.kerby.kerberos.kerb.transport.KdcNetwork; import org.apache.kerby.kerberos.kerb.transport.KrbTransport; import org.apache.kerby.kerberos.kerb.transport.TransportPair; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A default admin admin implementation. */ public class DefaultInternalAdminServerImpl extends AbstractInternalAdminServer { private ExecutorService executor; private AdminServerContext adminContext; private KdcNetwork network; public DefaultInternalAdminServerImpl(AdminServerSetting adminSetting) { super(adminSetting); } @Override protected void doStart() throws Exception { super.doStart(); prepareHandler(); executor = Executors.newCachedThreadPool(); network = new KdcNetwork() { @Override protected void onNewTransport(KrbTransport transport) { DefaultAdminServerHandler kdcHandler = new DefaultAdminServerHandler(adminContext, transport); executor.execute(kdcHandler); } }; network.init(); TransportPair tpair = AdminServerUtil.getTransportPair(getSetting()); network.listen(tpair); network.start(); } private void prepareHandler() { adminContext = new AdminServerContext(getSetting()); adminContext.setIdentityService(getIdentityService()); } @Override protected void doStop() throws Exception { super.doStop(); network.stop(); executor.shutdownNow(); } }
429
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/BatchTrans.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; /** * Batch operations support to create/update/delete principal accounts * in a transaction. */ public interface BatchTrans { /** * Commit this transaction, releasing any associated resources. * @throws KrbException */ void commit() throws KrbException; /** * Give up this transaction, releasing any associated resources. * @throws KrbException */ void rollback() throws KrbException; /** * Add an identity, and return the newly created result. * @param identity The identity * @return BatchTrans * @throws KrbException e */ BatchTrans addIdentity(KrbIdentity identity) throws KrbException; /** * Update an identity, and return the updated result. * @param identity The identity * @return BatchTrans * @throws KrbException e */ BatchTrans updateIdentity(KrbIdentity identity) throws KrbException; /** * Delete the identity specified by principal name * @param principalName The principal name * @return BatchTrans * @throws KrbException e */ BatchTrans deleteIdentity(String principalName) throws KrbException; }
430
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/CacheableIdentityService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity; import org.apache.kerby.config.Config; import org.apache.kerby.config.Configured; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.KdcClientRequest; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.type.ad.AuthorizationData; import org.apache.kerby.kerberos.kerb.type.ticket.EncTicketPart; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A cacheable identity backend that provides a cache with FIFO and size limit. * Note only limited recently active identities are kept in the cache, and other * identities are meant to be loaded from the underlying backend like memory, * file, SQL DB, LDAP, and etc. */ public class CacheableIdentityService extends Configured implements IdentityService { private static final int DEFAULT_CACHE_SIZE = 1000; private Map<String, KrbIdentity> idCache; private int cacheSize = DEFAULT_CACHE_SIZE; private IdentityService underlying; public CacheableIdentityService(Config config, IdentityService underlying) { super(config); this.underlying = underlying; init(); } /** * {@inheritDoc} */ @Override public boolean supportBatchTrans() { return false; } /** * {@inheritDoc} */ @Override public BatchTrans startBatchTrans() throws KrbException { throw new KrbException("Transaction isn't supported"); } private void init() { Map<String, KrbIdentity> tmpMap = new LinkedHashMap<String, KrbIdentity>(cacheSize) { private static final long serialVersionUID = -6911200685333503214L; @Override protected boolean removeEldestEntry(Map.Entry<String, KrbIdentity> eldest) { return size() > cacheSize; } }; idCache = new ConcurrentHashMap<>(tmpMap); } /** * {@inheritDoc} */ @Override public Iterable<String> getIdentities() throws KrbException { return underlying.getIdentities(); } /** * {@inheritDoc} */ @Override public KrbIdentity getIdentity(String principalName) throws KrbException { if (idCache.containsKey(principalName)) { return idCache.get(principalName); } KrbIdentity identity = underlying.getIdentity(principalName); if (identity != null) { idCache.put(principalName, identity); } return identity; } /** * {@inheritDoc} */ @Override public KrbIdentity addIdentity(KrbIdentity identity) throws KrbException { KrbIdentity added = underlying.addIdentity(identity); if (added != null) { idCache.put(added.getPrincipalName(), added); } return added; } /** * {@inheritDoc} */ @Override public KrbIdentity updateIdentity(KrbIdentity identity) throws KrbException { KrbIdentity updated = underlying.updateIdentity(identity); if (updated != null) { idCache.put(updated.getPrincipalName(), updated); } return updated; } /** * {@inheritDoc} */ @Override public void deleteIdentity(String principalName) throws KrbException { if (idCache.containsKey(principalName)) { idCache.remove(principalName); } underlying.deleteIdentity(principalName); } /** * {@inheritDoc} */ @Override public AuthorizationData getIdentityAuthorizationData(KdcClientRequest kdcClientRequest, EncTicketPart encTicketPart) throws KrbException { return underlying.getIdentityAuthorizationData(kdcClientRequest, encTicketPart); } }
431
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/IdentityService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.KdcClientRequest; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import org.apache.kerby.kerberos.kerb.type.ad.AuthorizationData; import org.apache.kerby.kerberos.kerb.type.ticket.EncTicketPart; /** * Identity service for KDC backend to create, get and manage principal accounts. */ public interface IdentityService { /** * Query to know if xtrans is supported or not. * @return true if supported, false otherwise */ boolean supportBatchTrans(); /** * Start a transaction. * @return xtrans The batch trans * @throws KrbException e */ BatchTrans startBatchTrans() throws KrbException; /** * Get all of the identity principal names. * Note it's ordered by principal name. * @return principal names * @throws KrbException e */ Iterable<String> getIdentities() throws KrbException; /** * Get the identity account specified by name. * @param principalName The principal name * @return identity * @throws KrbException e */ KrbIdentity getIdentity(String principalName) throws KrbException; /** * Get an identity's Authorization Data. * @param kdcClientRequest The KdcClientRequest * @param encTicketPart The EncTicketPart being built for the KrbIdentity * @return The Authorization Data * @throws KrbException e */ AuthorizationData getIdentityAuthorizationData(KdcClientRequest kdcClientRequest, EncTicketPart encTicketPart) throws KrbException; /** * Add an identity, and return the newly created result. * @param identity The identity * @return identity * @throws KrbException e */ KrbIdentity addIdentity(KrbIdentity identity) throws KrbException; /** * Update an identity, and return the updated result. * @param identity The identity * @return identity * @throws KrbException e */ KrbIdentity updateIdentity(KrbIdentity identity) throws KrbException; /** * Delete the identity specified by principal name * @param principalName The principal name * @throws KrbException e */ void deleteIdentity(String principalName) throws KrbException; }
432
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/IdentityBackend.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.config.Configurable; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.IdentityService; /** * Identity backend for KDC, either internal embedded or external standalone. */ public interface IdentityBackend extends IdentityService, Configurable { /** * Init work for the backend can be done here. * @throws KrbException e */ void initialize() throws KrbException; /** * Start the backend and return soon after the backend or the connection to * it is well prepared and ready for KDC to use. * * Will be called during KDC startup. */ void start(); /** * Stop the backend. * * Will be called during KDC stop. * @throws KrbException e */ void stop() throws KrbException; /** * Release the backend associated resources like connection. * * Will be called during KDC shutdown. */ void release(); }
433
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/BackendConfig.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.config.Conf; import java.io.File; /** * Backend configuration API. */ public class BackendConfig extends Conf { private File confDir; public void setConfDir(File dir) { this.confDir = dir; } public File getConfDir() { return confDir; } }
434
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/AbstractIdentityBackend.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity.backend; import java.io.IOException; import java.util.Collections; import org.apache.kerby.config.Configured; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.identity.BatchTrans; import org.apache.kerby.kerberos.kerb.request.KdcClientRequest; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; 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.ad.AuthorizationType; 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.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An abstract identity backend that provides default behaviors and a cache * with FIFO and size limit. Note only limited recently active identities are * kept in the cache, and other identities are meant to be loaded from * persistent storage by specific backend, like memory, file, SQL DB, LDAP, * and etc. */ public abstract class AbstractIdentityBackend extends Configured implements IdentityBackend { private static Logger logger = LoggerFactory.getLogger(AbstractIdentityBackend.class); /** * Get the Backend Config. * @return The backend config */ protected BackendConfig getBackendConfig() { return (BackendConfig) getConfig(); } /** * {@inheritDoc} */ @Override public void initialize() throws KrbException { logger.debug("initialize called"); doInitialize(); } /** * {@inheritDoc} */ @Override public boolean supportBatchTrans() { return false; } /** * {@inheritDoc} */ @Override public BatchTrans startBatchTrans() throws KrbException { throw new KrbException("Transaction isn't supported"); } /** * Perform the real initialization work for the backend. * @throws KrbException e */ protected void doInitialize() throws KrbException { } /** * {@inheritDoc} */ @Override public void start() { doStart(); logger.debug("start called"); } /** * Perform the real start work for the backend. */ protected void doStart() { } /** * {@inheritDoc} */ @Override public void stop() throws KrbException { doStop(); logger.debug("stop called"); } /** * Perform the real stop work for the backend. * @throws KrbException e */ protected void doStop() throws KrbException { } /** * {@inheritDoc} */ @Override public void release() { doRelease(); logger.debug("release called"); } /** * Perform the real release work for the backend. */ protected void doRelease() { } /** * {@inheritDoc} */ @Override public Iterable<String> getIdentities() throws KrbException { logger.debug("getIdentities called"); return doGetIdentities(); } /** * Perform the real work to get identities. * @return The identities * @throws KrbException e */ protected abstract Iterable<String> doGetIdentities() throws KrbException; /** * {@inheritDoc} */ @Override public KrbIdentity getIdentity(String principalName) throws KrbException { if (principalName == null || principalName.isEmpty()) { throw new IllegalArgumentException("Invalid principal name"); } logger.debug("getIdentity called, principalName = {}", principalName); KrbIdentity identity = doGetIdentity(principalName); logger.debug("getIdentity {}, principalName = {}", identity != null ? "successful" : "failed", principalName); return identity; } /** * Add an identity, invoked by addIdentity. * @param principalName The principal name * @return The added identity * @throws KrbException e */ protected abstract KrbIdentity doGetIdentity(String principalName) throws KrbException; /** * {@inheritDoc} */ @Override public AuthorizationData getIdentityAuthorizationData(KdcClientRequest kdcClientRequest, EncTicketPart encTicketPart) throws KrbException { if (kdcClientRequest == null) { throw new IllegalArgumentException("Invalid identity"); } logger.debug("getIdentityAuthorizationData called, krbIdentity = {}", kdcClientRequest.getClientPrincipal()); AuthorizationData authData = doGetIdentityAuthorizationData(kdcClientRequest, encTicketPart); logger.debug("getIdentityAuthorizationData {}, authData = {}", authData != null ? "successful" : "failed", authData); return authData; } /** * Get an identity's Authorization Data, invoked by getIdentityAuthorizationData. * @param kdcClientRequest The KdcClientRequest * @param encTicketPart The EncTicketPart being built for the KrbIdentity * @return The Authorization Data * @throws KrbException e */ protected AuthorizationData doGetIdentityAuthorizationData( KdcClientRequest kdcClientRequest, EncTicketPart encTicketPart) throws KrbException { if (kdcClientRequest.isToken()) { KrbToken krbToken = new KrbToken(kdcClientRequest.getToken(), TokenFormat.JWT); AdToken adToken = new AdToken(); adToken.setToken(krbToken); AuthorizationData authzData = new AuthorizationData(); AuthorizationDataEntry authzDataEntry = new AuthorizationDataEntry(); try { authzDataEntry.setAuthzData(adToken.encode()); } catch (IOException e) { throw new KrbException("Error encoding AdToken", e); } authzDataEntry.setAuthzType(AuthorizationType.AD_TOKEN); authzData.setElements(Collections.singletonList(authzDataEntry)); return authzData; } return null; } /** {@inheritDoc} */ @Override public KrbIdentity addIdentity(KrbIdentity identity) throws KrbException { if (identity == null) { throw new IllegalArgumentException("null identity to add"); } if (doGetIdentity(identity.getPrincipalName()) != null) { throw new KrbException("Principal already exists: " + identity.getPrincipalName()); } KrbIdentity added = doAddIdentity(identity); logger.debug("addIdentity {}, principalName = {}", added != null ? "successful" : "failed", identity.getPrincipalName()); return added; } /** * Add an identity, invoked by addIdentity, and return added identity. * @param identity The identity to be added * @return The added identity * @throws KrbException e */ protected abstract KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException; /** * {@inheritDoc} */ @Override public KrbIdentity updateIdentity(KrbIdentity identity) throws KrbException { if (identity == null) { throw new IllegalArgumentException("null identity to update"); } if (doGetIdentity(identity.getPrincipalName()) == null) { logger.error("Error occurred while updating identity, principal " + identity.getPrincipalName() + " does not exists."); throw new KrbException("Principal does not exist."); } KrbIdentity updated = doUpdateIdentity(identity); logger.debug("updateIdentity {}, principalName = {}", updated != null ? "successful" : "failed", identity.getPrincipalName()); return updated; } /** * Update an identity, invoked by updateIdentity, and return updated identity. * @param identity The origin identity * @return The updated identity * @throws KrbException e */ protected abstract KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException; /** * {@inheritDoc} */ @Override public void deleteIdentity(String principalName) throws KrbException { logger.debug("deleteIdentity called, principalName = {}", principalName); if (principalName == null) { throw new IllegalArgumentException("null identity to remove"); } if (doGetIdentity(principalName) == null) { logger.error("Error occurred while deleting identity, principal " + principalName + " does not exist."); throw new KrbException("Principal does not exist."); } doDeleteIdentity(principalName); } /** * Delete an identity, invoked by deleteIndentity. * @param principalName The principal name * @throws KrbException e */ protected abstract void doDeleteIdentity(String principalName) throws KrbException; }
435
0
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity
Create_ds/directory-kerby/kerby-kerb/kerb-identity/src/main/java/org/apache/kerby/kerberos/kerb/identity/backend/MemoryIdentityBackend.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.identity.backend; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.KrbIdentity; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A memory map based identity backend. */ public class MemoryIdentityBackend extends AbstractIdentityBackend { // TODO: configurable private static final int DEFAULT_STORAGE_SIZE = 10000000; private Map<String, KrbIdentity> storage; private int storageSize = DEFAULT_STORAGE_SIZE; protected void doInitialize() { Map<String, KrbIdentity> tmpMap = new LinkedHashMap<String, KrbIdentity>(storageSize) { private static final long serialVersionUID = 714064587685837472L; @Override protected boolean removeEldestEntry(Map.Entry<String, KrbIdentity> eldest) { return size() > storageSize; } }; storage = new ConcurrentHashMap<>(tmpMap); } /** * {@inheritDoc} */ @Override protected KrbIdentity doGetIdentity(String principalName) { return storage.get(principalName); } /** * {@inheritDoc} */ @Override protected KrbIdentity doAddIdentity(KrbIdentity identity) { storage.put(identity.getPrincipalName(), identity); // return the same identity, cause Map.put() will return null // when a new element was added return identity; } /** * {@inheritDoc} */ @Override protected KrbIdentity doUpdateIdentity(KrbIdentity identity) { return storage.put(identity.getPrincipalName(), identity); } /** * {@inheritDoc} */ @Override protected void doDeleteIdentity(String principalName) { storage.remove(principalName); } /** * {@inheritDoc} */ @Override protected Iterable<String> doGetIdentities() throws KrbException { List<String> identities = new ArrayList<>(storage.keySet()); Collections.sort(identities); return identities; } }
436
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/BadCredentialsTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbErrorCode; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Send some unknown principals, bad passwords etc. to the KDC to check that it is handled correctly. */ public class BadCredentialsTest extends KdcTestBase { @Test public void testUnknownClientPrincipal() { String principal = "unknown@" + TestKdcServer.KDC_REALM; try { getKrbClient().requestTgt(principal, getClientPassword()); } catch (KrbException ex) { Assertions.assertEquals(KrbErrorCode.KDC_ERR_C_PRINCIPAL_UNKNOWN, ex.getKrbErrorCode()); } } @Test public void testUnknownClientPassword() { try { getKrbClient().requestTgt(getClientPrincipal(), "badpass"); } catch (KrbException ex) { Assertions.assertEquals(KrbErrorCode.KRB_AP_ERR_BAD_INTEGRITY, ex.getKrbErrorCode()); } } @Test public void testUnknownServicePrincipal() { try { TgtTicket tgtTicket = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); String serverPrincipal = "unknown/" + getHostname() + "@" + TestKdcServer.KDC_REALM; getKrbClient().requestSgt(tgtTicket, serverPrincipal); } catch (KrbException ex) { Assertions.assertEquals(KrbErrorCode.KDC_ERR_S_PRINCIPAL_UNKNOWN, ex.getKrbErrorCode()); } } }
437
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KeytabLoginTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class KeytabLoginTest extends LoginTestBase { @Test public void testLogin() throws Exception { checkSubject(super.loginServiceUsingKeytab()); } }
438
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KerberosClientExceptionAction.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import java.security.Principal; import java.security.PrivilegedExceptionAction; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; /** * This class represents a PrivilegedExceptionAction implementation to * a service ticket from a Kerberos Key Distribution Center. */ public class KerberosClientExceptionAction implements PrivilegedExceptionAction<byte[]> { private static final String JGSS_KERBEROS_TICKET_OID = "1.2.840.113554.1.2.2"; private Principal clientPrincipal; private String serviceName; public KerberosClientExceptionAction(Principal clientPrincipal, String serviceName) { this.clientPrincipal = clientPrincipal; this.serviceName = serviceName; } public byte[] run() throws GSSException { GSSManager gssManager = GSSManager.getInstance(); GSSName gssService = gssManager.createName(serviceName, GSSName.NT_USER_NAME); Oid oid = new Oid(JGSS_KERBEROS_TICKET_OID); GSSName gssClient = gssManager.createName(clientPrincipal.getName(), GSSName.NT_USER_NAME); GSSCredential credentials = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); GSSContext secContext = gssManager.createContext(gssService, oid, credentials, GSSContext.DEFAULT_LIFETIME); secContext.requestMutualAuth(false); secContext.requestCredDeleg(false); try { byte[] token = new byte[0]; byte[] returnedToken = secContext.initSecContext(token, 0, token.length); return returnedToken; } finally { secContext.dispose(); } } }
439
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/TcpAndUdpKdcTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class TcpAndUdpKdcTest extends KdcTest { @Override protected boolean allowUdp() { return true; } @Override protected boolean allowTcp() { return true; } @Test public void testKdc() throws Exception { performKdcTest(); } }
440
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/RepeatLoginWithDefaultKdcNetworkTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class RepeatLoginWithDefaultKdcNetworkTest extends LoginTestBase { @Test public void testLogin() throws Exception { checkSubject(super.loginServiceUsingKeytab()); } @Test public void testLoginSecondTime() throws Exception { checkSubject(super.loginServiceUsingKeytab()); } }
441
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/GssUdpInteropTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; /** * This is an interop test using the Java GSS APIs against the Kerby KDC (using UDP) */ public class GssUdpInteropTest extends GssInteropTest { @Override protected boolean allowUdp() { return true; } @Override protected boolean allowTcp() { return false; } }
442
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/OnlyUdpKdcTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class OnlyUdpKdcTest extends KdcTest { @Override protected boolean allowTcp() { return false; } @Override protected boolean allowUdp() { return true; } @Test public void testKdc() throws Exception { performKdcTest(); } }
443
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KdcSettingTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class KdcSettingTest { @Test public void testKdcServerMannualSetting() throws KrbException { KdcServer kerbServer = new KdcServer(); kerbServer.setKdcHost("localhost"); kerbServer.setKdcRealm("TEST2.COM"); kerbServer.setKdcTcpPort(12345); kerbServer.init(); KdcSetting kdcSetting = kerbServer.getKdcSetting(); assertThat(kdcSetting.getKdcHost()).isEqualTo("localhost"); assertThat(kdcSetting.getKdcTcpPort()).isEqualTo(12345); assertThat(kdcSetting.getKdcRealm()).isEqualTo("TEST2.COM"); } }
444
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KdcTestBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.client.KrbClient; import org.apache.kerby.kerberos.kerb.client.KrbPkinitClient; import org.apache.kerby.kerberos.kerb.client.KrbTokenClient; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; public abstract class KdcTestBase { private static File testDir; private final String clientPassword = "123456"; private String hostname; private final String clientPrincipalName = "drankye"; private final String clientPrincipal = clientPrincipalName + "@" + TestKdcServer.KDC_REALM; private final String serverPassword = "654321"; private final String serverPrincipalName = "test-service"; private final String serverPrincipal; private SimpleKdcServer kdcServer; public KdcTestBase() { try { hostname = InetAddress.getByName("127.0.0.1").getHostName(); } catch (UnknownHostException e) { hostname = "localhost"; } serverPrincipal = serverPrincipalName + "/" + hostname + "@" + TestKdcServer.KDC_REALM; } @BeforeAll public static void createTestDir() throws IOException { String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = new File(".").getCanonicalPath(); } File targetdir = new File(basedir, "target"); testDir = new File(targetdir, "tmp"); testDir.mkdirs(); } @AfterAll public static void deleteTestDir() throws IOException { testDir.delete(); } protected File getTestDir() { return testDir; } protected SimpleKdcServer getKdcServer() { return kdcServer; } protected void setKdcServer(SimpleKdcServer kdcServer) { this.kdcServer = kdcServer; } protected KrbClient getKrbClient() { return kdcServer.getKrbClient(); } protected KrbPkinitClient getPkinitClient() { return kdcServer.getPkinitClient(); } protected KrbTokenClient getTokenClient() { return kdcServer.getTokenClient(); } protected String getClientPrincipalName() { return clientPrincipalName; } protected String getClientPrincipal() { return clientPrincipal; } protected String getServerPrincipalName() { return serverPrincipalName; } protected String getClientPassword() { return clientPassword; } protected String getServerPassword() { return serverPassword; } protected String getServerPrincipal() { return serverPrincipal; } protected String getHostname() { return hostname; } protected boolean allowUdp() { return true; } protected boolean allowTcp() { return true; } @BeforeEach public void setUp() throws Exception { setUpKdcServer(); createPrincipals(); setUpClient(); } protected void prepareKdc() throws KrbException { kdcServer.init(); } protected void configKdcSeverAndClient() { kdcServer.setWorkDir(testDir); } protected void setUpKdcServer() throws Exception { kdcServer = new TestKdcServer(allowTcp(), allowUdp()); configKdcSeverAndClient(); prepareKdc(); kdcServer.start(); } protected void setUpClient() throws Exception { } protected void createPrincipals() throws KrbException { kdcServer.createPrincipal(serverPrincipal, serverPassword); kdcServer.createPrincipal(clientPrincipal, clientPassword); } protected void deletePrincipals() throws KrbException { kdcServer.getKadmin().deleteBuiltinPrincipals(); kdcServer.deletePrincipals(serverPrincipal); kdcServer.deletePrincipal(clientPrincipal); } @AfterEach public void tearDown() throws Exception { deletePrincipals(); kdcServer.stop(); } }
445
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/LoginTestBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.client.JaasKrbUtil; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import java.io.File; import java.security.Principal; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; public class LoginTestBase extends KdcTestBase { protected File ticketCacheFile; protected File serviceKeytabFile; @BeforeEach @Override public void setUp() throws Exception { super.setUp(); ticketCacheFile = new File(getTestDir(), "test-tkt.cc"); serviceKeytabFile = new File(getTestDir(), "test-service.keytab"); } protected Subject loginClientUsingPassword() throws LoginException { return JaasKrbUtil.loginUsingPassword(getClientPrincipal(), getClientPassword()); } protected Subject loginClientUsingTicketCache() throws Exception { TgtTicket tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); getKrbClient().storeTicket(tgt, ticketCacheFile); return JaasKrbUtil.loginUsingTicketCache(getClientPrincipal(), ticketCacheFile); } protected Subject loginServiceUsingKeytab() throws Exception { getKdcServer().exportPrincipal(getServerPrincipal(), serviceKeytabFile); return JaasKrbUtil.loginUsingKeytab(getServerPrincipal(), serviceKeytabFile); } protected void checkSubject(Subject subject) { Set<Principal> clientPrincipals = subject.getPrincipals(); assertThat(clientPrincipals).isNotEmpty(); } @AfterEach @Override public void tearDown() throws Exception { ticketCacheFile.delete(); serviceKeytabFile.delete(); super.tearDown(); } }
446
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/ApRequestTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.request.ApRequest; import org.apache.kerby.kerberos.kerb.response.ApResponse; import org.apache.kerby.kerberos.kerb.type.ap.ApRep; import org.apache.kerby.kerberos.kerb.type.ap.ApReq; import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.KrbMessageType; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class ApRequestTest extends KdcTestBase { @Test public void test() throws IOException, KrbException { TgtTicket tgt = null; SgtTicket tkt = null; try { tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); assertThat(tgt).isNotNull(); assertThat(tgt.getClientPrincipal().getName()).isEqualTo(getClientPrincipal()); tkt = getKrbClient().requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); } catch (Exception e) { Assertions.fail("Exception occurred with good password. " + e.toString()); } ApRequest apRequest = new ApRequest(new PrincipalName(getClientPrincipal()), tkt); ApReq apReq = apRequest.getApReq(); assertThat(apReq.getPvno()).isEqualTo(5); assertThat(apReq.getMsgType()).isEqualTo(KrbMessageType.AP_REQ); assertThat(apReq.getAuthenticator().getCname()).isEqualTo(tgt.getClientPrincipal()); assertThat(apReq.getAuthenticator().getCrealm()).isEqualTo(tgt.getRealm()); EncryptionKey encryptedKey = getKdcServer().getKadmin().getPrincipal( getServerPrincipal()).getKey(tkt.getTicket().getEncryptedEncPart().getEType()); ApResponse apResponse = new ApResponse(apReq, encryptedKey); ApRep apRep = apResponse.getApRep(); assertThat(apRep.getPvno()).isEqualTo(5); assertThat(apRep.getMsgType()).isEqualTo(KrbMessageType.AP_REP); } }
447
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KeytabArcFourMd5LoginTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.client.KrbClient; import org.apache.kerby.kerberos.kerb.client.KrbConfigKey; import org.apache.kerby.kerberos.kerb.client.KrbOption; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Test; public class KeytabArcFourMd5LoginTest extends LoginTestBase { @Override protected void setUpKdcServer() throws Exception { KdcConfig config = new KdcConfig(); config.setString(KdcConfigKey.ENCRYPTION_TYPES, "arcfour-hmac rc4-hmac"); SimpleKdcServer kdcServer = new TestKdcServer(allowTcp(), allowUdp(), config, new BackendConfig()); super.setKdcServer(kdcServer); configKdcSeverAndClient(); prepareKdc(); kdcServer.start(); } @Test public void testLoginARCFOURHMAC() throws Exception { KrbClient client = super.getKrbClient(); client.getKrbConfig().setString(KrbConfigKey.PERMITTED_ENCTYPES, "arcfour-hmac"); KOptions requestOptions = new KOptions(); requestOptions.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); requestOptions.add(KrbOption.USE_KEYTAB, true); File keytab = new File(getTestDir(), "test-client.keytab"); requestOptions.add(KrbOption.KEYTAB_FILE, keytab); getKdcServer().exportPrincipal(getClientPrincipal(), keytab); TgtTicket tgt = client.requestTgt(requestOptions); assertThat(tgt).isNotNull(); SgtTicket tkt = client.requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); keytab.delete(); } @Test public void testLoginRC4HMAC() throws Exception { KrbClient client = super.getKrbClient(); client.getKrbConfig().setString(KrbConfigKey.PERMITTED_ENCTYPES, "rc4-hmac"); KOptions requestOptions = new KOptions(); requestOptions.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); requestOptions.add(KrbOption.USE_KEYTAB, true); File keytab = new File(getTestDir(), "test-client.keytab"); requestOptions.add(KrbOption.KEYTAB_FILE, keytab); getKdcServer().exportPrincipal(getClientPrincipal(), keytab); TgtTicket tgt = client.requestTgt(requestOptions); assertThat(tgt).isNotNull(); SgtTicket tkt = client.requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); keytab.delete(); } }
448
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/PreAuthNotRequiredTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.client.KrbClient; import org.apache.kerby.kerberos.kerb.client.KrbConfigKey; import org.apache.kerby.kerberos.kerb.client.KrbOption; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Test; /** * Test client connection when pre-auth is not required by the AS */ public class PreAuthNotRequiredTest extends LoginTestBase { @Override protected void setUpKdcServer() throws Exception { KdcConfig config = new KdcConfig(); config.setString(KdcConfigKey.PREAUTH_REQUIRED, "false"); SimpleKdcServer kdcServer = new TestKdcServer(allowTcp(), allowUdp(), config, new BackendConfig()); super.setKdcServer(kdcServer); configKdcSeverAndClient(); prepareKdc(); kdcServer.start(); } @Test public void testPreAuthTrue() throws Exception { KrbClient client = super.getKrbClient(); client.getKrbConfig().setString(KrbConfigKey.PREAUTH_REQUIRED, "true"); KOptions requestOptions = new KOptions(); requestOptions.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); requestOptions.add(KrbOption.USE_KEYTAB, true); File keytab = new File(getTestDir(), "test-client.keytab"); requestOptions.add(KrbOption.KEYTAB_FILE, keytab); getKdcServer().exportPrincipal(getClientPrincipal(), keytab); TgtTicket tgt = client.requestTgt(requestOptions); assertThat(tgt).isNotNull(); SgtTicket tkt = client.requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); keytab.delete(); } @Test public void testPreAuthFalse() throws Exception { KrbClient client = super.getKrbClient(); client.getKrbConfig().setString(KrbConfigKey.PREAUTH_REQUIRED, "false"); KOptions requestOptions = new KOptions(); requestOptions.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); requestOptions.add(KrbOption.USE_KEYTAB, true); File keytab = new File(getTestDir(), "test-client.keytab"); requestOptions.add(KrbOption.KEYTAB_FILE, keytab); getKdcServer().exportPrincipal(getClientPrincipal(), keytab); TgtTicket tgt = client.requestTgt(requestOptions); assertThat(tgt).isNotNull(); SgtTicket tkt = client.requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); keytab.delete(); } }
449
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/GssTcpInteropTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; /** * This is an interop test using the Java GSS APIs against the Kerby KDC (using TCP) */ public class GssTcpInteropTest extends GssInteropTest { @Override protected boolean allowUdp() { return false; } @Override protected boolean allowTcp() { return true; } }
450
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/TestKdcServer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.client.KrbClient; import org.apache.kerby.kerberos.kerb.client.KrbConfig; import org.apache.kerby.kerberos.kerb.client.KrbConfigKey; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.util.NetworkUtil; import java.io.File; public class TestKdcServer extends SimpleKdcServer { public static final String KDC_REALM = "TEST.COM"; public static final String HOSTNAME = "localhost"; public TestKdcServer(boolean allowTcp, boolean allowUdp) throws KrbException { super(); setKdcRealm(KDC_REALM); setKdcHost(HOSTNAME); setAllowTcp(allowTcp); setAllowUdp(allowUdp); if (allowTcp) { setKdcTcpPort(NetworkUtil.getServerPort()); } if (allowUdp) { setKdcUdpPort(NetworkUtil.getServerPort()); } setClient(); } public TestKdcServer(boolean allowTcp, boolean allowUdp, KdcConfig kdcConfig, BackendConfig backendConfig) throws KrbException { super(kdcConfig, backendConfig); setKdcRealm(KDC_REALM); setKdcHost(HOSTNAME); setAllowTcp(allowTcp); setAllowUdp(allowUdp); if (allowTcp) { setKdcTcpPort(NetworkUtil.getServerPort()); } if (allowUdp) { setKdcUdpPort(NetworkUtil.getServerPort()); } setClient(); } public TestKdcServer(File confDir, KrbConfig krbConfig) throws KrbException { super(confDir, krbConfig); setClient(); } private void setClient() { KrbClient krbClnt = getKrbClient(); KrbConfig krbConfig = krbClnt.getKrbConfig(); krbConfig.setString(KrbConfigKey.PERMITTED_ENCTYPES, "aes128-cts-hmac-sha1-96 des-cbc-crc des-cbc-md5 des3-cbc-sha1"); krbClnt.setTimeout(10 * 1000); } }
451
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/OnlyTcpKdcTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class OnlyTcpKdcTest extends KdcTest { @Override protected boolean allowTcp() { return true; } @Override protected boolean allowUdp() { return false; } @Test public void testKdc() throws Exception { performKdcTest(); } }
452
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/PrincipalNameTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import java.io.IOException; import org.apache.kerby.KOptions; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.client.KrbOption; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class PrincipalNameTest extends KdcTestBase { @Test public void testNTPrincipal() throws IOException, KrbException { KOptions options = new KOptions(); options.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); options.add(KrbOption.USER_PASSWD, getClientPassword()); options.add(KrbOption.USE_PASSWD, true); TgtTicket tgt = getKrbClient().requestTgt(options); assertThat(tgt.getClientPrincipal().getName()).isEqualTo(getClientPrincipal()); } @Test @org.junit.jupiter.api.Disabled // See https://issues.apache.org/jira/browse/DIRKRB-659 public void testNTEnterprisePrincipal() throws IOException, KrbException { KOptions options = new KOptions(); options.add(KrbOption.CLIENT_PRINCIPAL, getClientPrincipal()); options.add(KrbOption.USER_PASSWD, getClientPassword()); options.add(KrbOption.USE_PASSWD, true); options.add(KrbOption.AS_ENTERPRISE_PN, true); TgtTicket tgt = getKrbClient().requestTgt(options); assertThat(tgt.getClientPrincipal().getName()).isEqualTo(getClientPrincipal()); } }
453
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/KdcTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Assertions; import static org.assertj.core.api.Assertions.assertThat; public abstract class KdcTest extends KdcTestBase { protected void performKdcTest() throws Exception { TgtTicket tgt; SgtTicket tkt; try { tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); assertThat(tgt).isNotNull(); tkt = getKrbClient().requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); } catch (Exception e) { Assertions.fail("Exception occurred with good password. " + e.toString()); } } }
454
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/PasswordLoginTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class PasswordLoginTest extends LoginTestBase { @Test public void testLogin() throws Exception { checkSubject(super.loginClientUsingPassword()); } }
455
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/GssInteropTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import java.security.Principal; import java.security.PrivilegedExceptionAction; import java.util.Set; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosTicket; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * This is an interop test using the Java GSS APIs against the Kerby KDC */ public class GssInteropTest extends LoginTestBase { @Test public void testGss() throws Exception { Subject clientSubject = loginClientUsingTicketCache(); Set<Principal> clientPrincipals = clientSubject.getPrincipals(); Assertions.assertFalse(clientPrincipals.isEmpty()); // Get the TGT Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); Assertions.assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); Assertions.assertNotNull(tgt); // Get the service ticket KerberosClientExceptionAction action = new KerberosClientExceptionAction(clientPrincipals.iterator().next(), getServerPrincipal()); byte[] kerberosToken = (byte[]) Subject.doAs(clientSubject, action); Assertions.assertNotNull(kerberosToken); validateServiceTicket(kerberosToken); } private void validateServiceTicket(byte[] ticket) throws Exception { Subject serviceSubject = loginServiceUsingKeytab(); Set<Principal> servicePrincipals = serviceSubject.getPrincipals(); Assertions.assertFalse(servicePrincipals.isEmpty()); // Handle the service ticket KerberosServiceExceptionAction serviceAction = new KerberosServiceExceptionAction(ticket, getServerPrincipal()); Subject.doAs(serviceSubject, serviceAction); } private static class KerberosServiceExceptionAction implements PrivilegedExceptionAction<byte[]> { private static final String JGSS_KERBEROS_TICKET_OID = "1.2.840.113554.1.2.2"; private byte[] ticket; private String serviceName; KerberosServiceExceptionAction(byte[] ticket, String serviceName) { this.ticket = ticket; this.serviceName = serviceName; } public byte[] run() throws GSSException { GSSManager gssManager = GSSManager.getInstance(); GSSContext secContext; GSSName gssService = gssManager.createName(serviceName, GSSName.NT_USER_NAME); Oid oid = new Oid(JGSS_KERBEROS_TICKET_OID); GSSCredential credentials = gssManager.createCredential( gssService, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.ACCEPT_ONLY); secContext = gssManager.createContext(credentials); try { return secContext.acceptSecContext(ticket, 0, ticket.length); } finally { if (null != secContext) { secContext.dispose(); } } } } }
456
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/MultiRequestsKdcTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class MultiRequestsKdcTest extends KdcTestBase { private String serverPrincipal; @Test public void multiRequestsTest() throws Exception { TgtTicket tgt; SgtTicket tkt; // With good password try { tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); assertThat(tgt).isNotNull(); serverPrincipal = getServerPrincipal(); tkt = getKrbClient().requestSgt(tgt, serverPrincipal); assertThat(tkt).isNotNull(); } catch (Exception e) { Assertions.fail("Exception occurred with good password. " + e.toString()); } // With bad password /* try { tgt = krbClnt.requestTgt(clientPrincipal, "badpassword"); } catch (Exception e) { System.out.println("Exception occurred with bad password"); }*/ // With good password again try { tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); assertThat(tgt).isNotNull(); tkt = getKrbClient().requestSgt(tgt, serverPrincipal); assertThat(tkt).isNotNull(); } catch (Exception e) { Assertions.fail("Exception occurred with good password again. " + e.toString()); } } }
457
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/TicketCacheLoginTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.junit.jupiter.api.Test; public class TicketCacheLoginTest extends LoginTestBase { @Test public void testLogin() throws Exception { checkSubject(super.loginClientUsingTicketCache()); } }
458
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/CacheFileTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.junit.jupiter.api.Test; public class CacheFileTest extends KdcTestBase { @Test public void testStoringSGT() throws Exception { TgtTicket tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword()); assertThat(tgt).isNotNull(); SgtTicket tkt = getKrbClient().requestSgt(tgt, getServerPrincipal()); assertThat(tkt).isNotNull(); File ccFile = new File("target/cache.cc"); if (ccFile.exists()) { ccFile.delete(); } try { // Test storing the SGT and not the TGT getKrbClient().storeTicket(tkt, ccFile); } catch (Throwable t) { t.printStackTrace(); } } }
459
0
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-kdc-test/src/test/java/org/apache/kerby/kerberos/kerb/server/RepeatLoginWithNettyKdcNetworkTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kdc.impl.NettyKdcServerImpl; import org.apache.kerby.kerberos.kerb.KrbException; import org.junit.jupiter.api.Test; public class RepeatLoginWithNettyKdcNetworkTest extends LoginTestBase { @Override protected void prepareKdc() throws KrbException { getKdcServer().setInnerKdcImpl( new NettyKdcServerImpl(getKdcServer().getKdcSetting())); super.prepareKdc(); } @Test public void testLogin() throws Exception { checkSubject(super.loginServiceUsingKeytab()); } @Test public void testLoginSecondTime() throws Exception { checkSubject(super.loginServiceUsingKeytab()); } }
460
0
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/test/java/org/apache/kerby/kerberos
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/test/java/org/apache/kerby/kerberos/kerb/SimpleKdcServerTest.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; import org.apache.kerby.kerberos.kerb.server.KdcServer; import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; import org.apache.kerby.util.NetworkUtil; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class SimpleKdcServerTest { private String serverHost = "localhost"; private int serverPort = -1; private KdcServer kdcServer; @BeforeEach public void setUp() throws Exception { kdcServer = new SimpleKdcServer(); kdcServer.setKdcHost(serverHost); kdcServer.setAllowUdp(false); kdcServer.setAllowTcp(true); serverPort = NetworkUtil.getServerPort(); kdcServer.setKdcTcpPort(serverPort); kdcServer.init(); kdcServer.start(); } @Test public void testKdc() throws IOException, InterruptedException { try (SocketChannel socketChannel = SocketChannel.open()) { socketChannel.configureBlocking(true); SocketAddress sa = new InetSocketAddress(serverHost, serverPort); socketChannel.connect(sa); String badKrbMessage = "Hello World!"; ByteBuffer writeBuffer = ByteBuffer.allocate(4 + badKrbMessage.getBytes().length); writeBuffer.putInt(badKrbMessage.getBytes().length); writeBuffer.put(badKrbMessage.getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); socketChannel.close(); } } @AfterEach public void tearDown() throws Exception { kdcServer.stop(); } }
461
0
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb/server/SimpleKdcServer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.kerby.kerberos.kerb.server; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadmin; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadminImpl; import org.apache.kerby.kerberos.kerb.client.Krb5Conf; import org.apache.kerby.kerberos.kerb.client.KrbClient; import org.apache.kerby.kerberos.kerb.client.KrbConfig; import org.apache.kerby.kerberos.kerb.client.KrbPkinitClient; import org.apache.kerby.kerberos.kerb.client.KrbTokenClient; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.util.NetworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; /** * A simple KDC server mainly for test usage. It also integrates krb client and * kadmin sides for convenience. */ public class SimpleKdcServer extends KdcServer { private static final Logger LOG = LoggerFactory.getLogger(SimpleKdcServer.class); private final KrbClient krbClnt; private LocalKadmin kadmin; private Krb5Conf krb5Conf; private File workDir; private KrbPkinitClient pkinitClient; private KrbTokenClient tokenClient; /** * Default constructor. * * @throws org.apache.kerby.kerberos.kerb.KrbException e */ public SimpleKdcServer() throws KrbException { this(new KrbConfig()); setKdcRealm("EXAMPLE.COM"); setKdcHost("localhost"); setKdcPort(NetworkUtil.getServerPort()); } public SimpleKdcServer(KdcConfig kdcConfig, BackendConfig backendConfig) throws KrbException { super(kdcConfig, backendConfig); this.krbClnt = new KrbClient(new KrbConfig()); setKdcRealm("EXAMPLE.COM"); setKdcHost("localhost"); setKdcPort(NetworkUtil.getServerPort()); } public SimpleKdcServer(KrbConfig krbConfig) { super(); this.krbClnt = new KrbClient(krbConfig); } public SimpleKdcServer(File confDir, KrbConfig krbConfig) throws KrbException { super(confDir); this.krbClnt = new KrbClient(krbConfig); } public synchronized void setWorkDir(File workDir) { this.workDir = workDir; } public synchronized File getWorkDir() { return workDir; } /** * {@inheritDoc} */ @Override public synchronized void setKdcRealm(String realm) { super.setKdcRealm(realm); krbClnt.setKdcRealm(realm); } /** * {@inheritDoc} */ @Override public synchronized void setKdcHost(String kdcHost) { super.setKdcHost(kdcHost); krbClnt.setKdcHost(kdcHost); } /** * {@inheritDoc} */ @Override public synchronized void setKdcTcpPort(int kdcTcpPort) { super.setKdcTcpPort(kdcTcpPort); krbClnt.setKdcTcpPort(kdcTcpPort); setAllowTcp(true); } /** * {@inheritDoc} */ @Override public synchronized void setAllowUdp(boolean allowUdp) { super.setAllowUdp(allowUdp); krbClnt.setAllowUdp(allowUdp); } /** * {@inheritDoc} */ @Override public synchronized void setAllowTcp(boolean allowTcp) { super.setAllowTcp(allowTcp); krbClnt.setAllowTcp(allowTcp); } /** * {@inheritDoc} */ @Override public synchronized void setKdcUdpPort(int kdcUdpPort) { super.setKdcUdpPort(kdcUdpPort); krbClnt.setKdcUdpPort(kdcUdpPort); setAllowUdp(true); } /** * {@inheritDoc} */ @Override public synchronized void init() throws KrbException { super.init(); kadmin = new LocalKadminImpl(getKdcSetting(), getIdentityService()); kadmin.createBuiltinPrincipals(); try { krb5Conf = new Krb5Conf(this); krb5Conf.initKrb5conf(); } catch (IOException e) { throw new KrbException("Failed to make krb5.conf", e); } } /** * {@inheritDoc} */ @Override public synchronized void start() throws KrbException { super.start(); krbClnt.init(); } /** * Get krb client. * @return KrbClient */ public synchronized KrbClient getKrbClient() { return krbClnt; } /** * @return PKINIT client */ public synchronized KrbPkinitClient getPkinitClient() { if (pkinitClient == null) { pkinitClient = new KrbPkinitClient(krbClnt); } return pkinitClient; } /** * @return Token client */ public synchronized KrbTokenClient getTokenClient() { if (tokenClient == null) { tokenClient = new KrbTokenClient(krbClnt); } return tokenClient; } /** * Get Kadmin operation interface. * @return Kadmin */ public synchronized LocalKadmin getKadmin() { return kadmin; } /** * Create principal with principal name. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principal The principal name */ public synchronized void createPrincipal(String principal) throws KrbException { kadmin.addPrincipal(principal); } /** * Create principal with principal name and password. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principal The principal name * @param password The password to create keys */ public synchronized void createPrincipal(String principal, String password) throws KrbException { kadmin.addPrincipal(principal, password); } /** * Create principals. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principals The principal list */ public synchronized void createPrincipals(String... principals) throws KrbException { for (String principal : principals) { kadmin.addPrincipal(principal); } } /** * Creates principals and export their keys to the specified keytab file. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param keytabFile The keytab file to store principal keys * @param principals The principals to be create */ public synchronized void createAndExportPrincipals(File keytabFile, String... principals) throws KrbException { createPrincipals(principals); exportPrincipals(keytabFile); } /** * Delete principals. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principals The principals to be delete */ public synchronized void deletePrincipals(String... principals) throws KrbException { for (String principal : principals) { deletePrincipal(principal); } } /** * Delete principal. * * @throws org.apache.kerby.kerberos.kerb.KrbException e * @param principal The principal to be delete */ public synchronized void deletePrincipal(String principal) throws KrbException { kadmin.deletePrincipal(principal); } /** * Export principals to keytab file. * * @param keytabFile The keytab file * @throws KrbException e */ public synchronized void exportPrincipals(File keytabFile) throws KrbException { kadmin.exportKeytab(keytabFile); } /** * Export the keys of the specified principal into keytab file. * @param principal principal * @param keytabFile keytab file * @throws org.apache.kerby.kerberos.kerb.KrbException e */ public synchronized void exportPrincipal(String principal, File keytabFile) throws KrbException { kadmin.exportKeytab(keytabFile, principal); } /** * @throws KrbException e */ @Override public synchronized void stop() throws KrbException { super.stop(); try { krb5Conf.deleteKrb5conf(); } catch (IOException e) { LOG.info("Fail to delete krb5 conf. " + e); } } }
462
0
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb/client/Krb5Conf.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.server.KdcSetting; import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; import org.apache.kerby.util.IOUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * Generate krb5 file using given kdc server settings. */ public class Krb5Conf { public static final String KRB5_CONF = "java.security.krb5.conf"; private static final String KRB5_CONF_FILE = "krb5.conf"; private SimpleKdcServer kdcServer; private File confFile; public Krb5Conf(SimpleKdcServer kdcServer) { this.kdcServer = kdcServer; } public void initKrb5conf() throws IOException { File confFile = generateConfFile(); System.setProperty(KRB5_CONF, confFile.getAbsolutePath()); } // Read in krb5.conf and substitute in the correct port private File generateConfFile() throws IOException { KdcSetting setting = kdcServer.getKdcSetting(); String resourcePath = setting.allowUdp() ? "/krb5_udp-template.conf" : "/krb5-template.conf"; String templateContent; try (InputStream templateResource = getClass().getResourceAsStream(resourcePath)) { templateContent = IOUtil.readInput(templateResource); } String content = templateContent; content = content.replaceAll("_REALM_", "" + setting.getKdcRealm()); int kdcPort = setting.allowUdp() ? setting.getKdcUdpPort() : setting.getKdcTcpPort(); content = content.replaceAll("_KDC_PORT_", String.valueOf(kdcPort)); if (setting.allowTcp()) { content = content.replaceAll("#_KDC_TCP_PORT_", "kdc_tcp_port = " + setting.getKdcTcpPort()); } if (setting.allowUdp()) { content = content.replaceAll("#_KDC_UDP_PORT_", "kdc_udp_port = " + setting.getKdcUdpPort()); } int udpLimit = setting.allowUdp() ? 4096 : 1; content = content.replaceAll("_UDP_LIMIT_", String.valueOf(udpLimit)); this.confFile = new File(kdcServer.getWorkDir(), KRB5_CONF_FILE); IOUtil.writeFile(content, confFile); return confFile; } public void deleteKrb5conf() throws IOException { if (!this.confFile.delete()) { throw new IOException(); } } }
463
0
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb
Create_ds/directory-kerby/kerby-kerb/kerb-simplekdc/src/main/java/org/apache/kerby/kerberos/kerb/client/JaasKrbUtil.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 javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; 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 static org.apache.kerby.util.SysUtil.IBM_JAVA; import java.io.File; import java.io.IOException; import java.security.Principal; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * JAAS utilities for Kerberos login. */ public final class JaasKrbUtil { public static final boolean ENABLE_DEBUG = false; private JaasKrbUtil() { } public static Subject loginUsingPassword( String principal, String password) 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 = usePassword(principal); String confName = "PasswordConf"; CallbackHandler callback = new KrbCallbackHandler(principal, password); LoginContext loginContext = new LoginContext(confName, subject, callback, conf); loginContext.login(); return loginContext.getSubject(); } public static Subject loginUsingTicketCache( String principal, File cacheFile) 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 = useTicketCache(principal, cacheFile); String confName = "TicketCacheConf"; LoginContext loginContext = new LoginContext(confName, subject, null, conf); loginContext.login(); return loginContext.getSubject(); } public static Subject loginUsingKeytab( String principal, File keytabFile) 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 = useKeytab(principal, keytabFile); String confName = "KeytabConf"; LoginContext loginContext = new LoginContext(confName, subject, null, conf); loginContext.login(); return loginContext.getSubject(); } public static Configuration usePassword(String principal) { return new PasswordJaasConf(principal); } public static Configuration useTicketCache(String principal, File credentialFile) { return new TicketCacheJaasConf(principal, credentialFile); } public static Configuration useKeytab(String principal, File keytabFile) { return new KeytabJaasConf(principal, keytabFile); } private static String getKrb5LoginModuleName() { return IBM_JAVA ? "com.ibm.security.auth.module.Krb5LoginModule" : "com.sun.security.auth.module.Krb5LoginModule"; } static class KeytabJaasConf extends Configuration { private String principal; private File keytabFile; KeytabJaasConf(String principal, File keytab) { this.principal = principal; this.keytabFile = keytab; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<>(); options.put("keyTab", keytabFile.getAbsolutePath()); options.put("principal", principal); options.put("useKeyTab", "true"); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); options.put("renewTGT", "false"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); options.put("debug", String.valueOf(ENABLE_DEBUG)); return new AppConfigurationEntry[]{ new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)}; } } static class TicketCacheJaasConf extends Configuration { private String principal; private File clientCredentialFile; TicketCacheJaasConf(String principal, File clientCredentialFile) { this.principal = principal; this.clientCredentialFile = clientCredentialFile; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<>(); options.put("principal", principal); options.put("storeKey", "false"); options.put("doNotPrompt", "false"); options.put("useTicketCache", "true"); options.put("renewTGT", "true"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); options.put("ticketCache", clientCredentialFile.getAbsolutePath()); options.put("debug", String.valueOf(ENABLE_DEBUG)); return new AppConfigurationEntry[]{ new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)}; } } static class PasswordJaasConf extends Configuration { private String principal; PasswordJaasConf(String principal) { this.principal = principal; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<>(); options.put("principal", principal); options.put("storeKey", "true"); options.put("useTicketCache", "true"); options.put("useKeyTab", "false"); options.put("renewTGT", "true"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); options.put("debug", String.valueOf(ENABLE_DEBUG)); return new AppConfigurationEntry[]{ new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)}; } } public static class KrbCallbackHandler implements CallbackHandler { private String principal; private String password; public KrbCallbackHandler(String principal, String password) { this.principal = principal; this.password = password; } public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof PasswordCallback) { PasswordCallback pc = (PasswordCallback) callback; if (pc.getPrompt().contains(principal)) { pc.setPassword(password.toCharArray()); break; } } } } } }
464
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/EnvelopedDataTest.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.cms; import org.apache.kerby.asn1.Asn1; import org.apache.kerby.cms.type.EnvelopedContentInfo; import org.apache.kerby.cms.type.EnvelopedData; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; /** * Ref. CMSTest test in BouncyCastle library. */ public class EnvelopedDataTest extends CmsTestBase { @Test public void testDecodingKeyTrns() throws IOException { byte[] data = readDataFile("/enveloped-keytrns.txt"); try { Asn1.parseAndDump(data); EnvelopedContentInfo contentInfo = new EnvelopedContentInfo(); contentInfo.decode(data); Asn1.dump(contentInfo); EnvelopedData envelopedData = contentInfo.getEnvelopedData(); Asn1.dump(envelopedData); } catch (Exception e) { Assertions.fail("Failed to decode keyTrn from file:" + " enveloped-keytrns.txt. " + e.toString()); } } @Test public void testDecodingKek() throws IOException { byte[] data = readDataFile("/enveloped-kek.txt"); try { Asn1.parseAndDump(data); EnvelopedContentInfo contentInfo = new EnvelopedContentInfo(); contentInfo.decode(data); Asn1.dump(contentInfo); EnvelopedData envelopedData = contentInfo.getEnvelopedData(); Asn1.dump(envelopedData); } catch (Exception e) { Assertions.fail("Failed to decode kek from file: enveloped-kek.txt. " + e.toString()); } } @Test public void testDecodingNestedNDEF() throws IOException { byte[] data = readDataFile("/enveloped-nested-ndef.txt"); try { Asn1.parseAndDump(data); EnvelopedContentInfo contentInfo = new EnvelopedContentInfo(); contentInfo.decode(data); Asn1.dump(contentInfo); EnvelopedData envelopedData = contentInfo.getEnvelopedData(); Asn1.dump(envelopedData); } catch (Exception e) { Assertions.fail("Failed to decode nestedNDEF from file:" + " enveloped-nested-ndef.txt. " + e.toString()); } } }
465
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/CmsTestBase.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.cms; import org.apache.kerby.asn1.util.HexUtil; import org.apache.kerby.asn1.util.IOUtil; import java.io.IOException; import java.io.InputStream; public class CmsTestBase { static byte[] readDataFile(String resource) throws IOException { try (InputStream is = CmsTestBase.class.getResourceAsStream(resource)) { String hexStr = IOUtil.readInput(is); return HexUtil.hex2bytes(hexStr); } } }
466
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/CertificateTest.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.cms; import org.apache.kerby.asn1.Asn1; import org.apache.kerby.x500.type.Name; import org.apache.kerby.x509.type.Certificate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; public class CertificateTest extends CmsTestBase { @Test public void testDecodingCertificate() throws IOException { byte[] data = readDataFile("/certificate1.txt"); try { Asn1.parseAndDump(data); Certificate certificate = new Certificate(); certificate.decode(data); Asn1.dump(certificate); } catch (Exception e) { Assertions.fail("Failed to decode certificate from file:" + " certificate1.txt. " + e.toString()); } } @Test public void testEncodingCertificate() throws IOException { byte[] data = readDataFile("/certificate1.txt"); Asn1.parseAndDump(data); try { Certificate certificate = new Certificate(); certificate.decode(data); Asn1.dump(certificate); byte[] encodedData = certificate.encode(); Asn1.parseAndDump(encodedData); } catch (Exception e) { Assertions.fail("Failed to encode certificate from file:" + " certificate1.txt. " + e.toString()); } } @Test public void testDecodingName() throws IOException { byte[] data = readDataFile("/name.txt"); try { Asn1.parseAndDump(data); Name name = new Name(); name.decode(data); Asn1.dump(name.getName()); } catch (Exception e) { Assertions.fail("Failed to decode name from file:" + " name.txt. " + e.toString()); } } }
467
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/GeneralNameTest.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.cms; import org.apache.kerby.asn1.Asn1; import org.apache.kerby.asn1.util.HexUtil; import org.apache.kerby.x509.type.GeneralName; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; /** * Ref. GeneralNameTest test in BouncyCastle library. */ public class GeneralNameTest { private static final byte[] IPV4 = HexUtil.hex2bytes("87040a090800"); @Test public void testIpAddress() throws IOException { try { Asn1.parseAndDump(IPV4); GeneralName generalName = new GeneralName(); generalName.decode(IPV4); assertThat(generalName.getIPAddress()).isNotNull(); byte[] addressBytes = generalName.getIPAddress(); // "10.9.8.0" assertThat(addressBytes).isEqualTo(new byte[] {0x0a, 0x09, 0x08, 0x00}); } catch (Exception e) { Assertions.fail("Failed to test IpAddress. " + e.toString()); } } }
468
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/CompressedDataTest.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.cms; import org.apache.kerby.asn1.Asn1; import org.apache.kerby.cms.type.CompressedContentInfo; import org.apache.kerby.cms.type.CompressedData; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; /** * Ref. CMSTest test in BouncyCastle library. */ public class CompressedDataTest extends CmsTestBase { @Test public void testDump1WithCompressedData() throws IOException { byte[] data = readDataFile("/compressed-data.txt"); try { Asn1.parseAndDump(data); CompressedContentInfo contentInfo = new CompressedContentInfo(); contentInfo.decode(data); Asn1.dump(contentInfo); CompressedData compressedData = contentInfo.getCompressedData(); Asn1.dump(compressedData); } catch (Exception e) { Assertions.fail("Failed to dump the compressed data from file: " + "compressed-data.txt. " + e.toString()); } } }
469
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/SignedDataTest.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.cms; import org.apache.kerby.asn1.Asn1; 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.EncapsulatedContentInfo; import org.apache.kerby.cms.type.SignedContentInfo; import org.apache.kerby.cms.type.SignedData; import org.apache.kerby.x509.type.Certificate; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; /** * Ref. CMSTest test in BouncyCastle library. */ public class SignedDataTest extends CmsTestBase { @Test public void testDecoding() throws IOException { byte[] data = readDataFile("/signed-data.txt"); try { Asn1.parseAndDump(data); //Asn1.decodeAndDump(data); SignedContentInfo contentInfo = new SignedContentInfo(); contentInfo.decode(data); //Asn1.dump(contentInfo); SignedData signedData = contentInfo.getSignedData(); Asn1.dump(signedData); Asn1.dump(contentInfo); byte[] encodedData = contentInfo.encode(); Asn1.parseAndDump(encodedData); } catch (Exception e) { Assertions.fail("Failed to test decode from file: signed-data.txt. " + e.toString()); } } @Test public void testEncoding() throws IOException { SignedContentInfo contentInfo = new SignedContentInfo(); contentInfo.setContentType("1.2.840.113549.1.7.2"); SignedData signedData = new SignedData(); EncapsulatedContentInfo eContentInfo = new EncapsulatedContentInfo(); eContentInfo.setContentType("1.3.6.1.5.2.3.1"); eContentInfo.setContent("data".getBytes()); signedData.setEncapContentInfo(eContentInfo); byte[] data = readDataFile("/certificate1.txt"); Certificate certificate = new Certificate(); certificate.decode(data); CertificateChoices certificateChoices = new CertificateChoices(); certificateChoices.setCertificate(certificate); CertificateSet certificateSet = new CertificateSet(); certificateSet.addElement(certificateChoices); signedData.setCertificates(certificateSet); contentInfo.setSignedData(signedData); Asn1.dump(contentInfo); byte[] encodedData = contentInfo.encode(); Asn1.parseAndDump(encodedData); SignedContentInfo decodedContentInfo = new SignedContentInfo(); decodedContentInfo.decode(encodedData); Asn1.dump(decodedContentInfo); SignedData decodedSignedData = decodedContentInfo.getSignedData(); Asn1.dump(decodedSignedData); } @Test public void testContentInfo() throws IOException { byte[] data = readDataFile("/anonymous.txt"); try { Asn1.parseAndDump(data); ContentInfo contentInfo = new ContentInfo(); contentInfo.decode(data); Asn1.dump(contentInfo); SignedData signedData = contentInfo.getContentAs(SignedData.class); Asn1.dump(signedData); } catch (Exception e) { Assertions.fail("Failed to test content info from file: anonymous.txt. " + e.toString()); } } }
470
0
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/test/java/org/apache/kerby/cms/ExtensionTest.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.cms; import org.apache.kerby.asn1.type.Asn1ObjectIdentifier; import org.apache.kerby.x509.type.Extension; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.*; public class ExtensionTest { @Test public void testUnsetCritical() throws IOException { Extension extension = new Extension(); extension.setExtnId(new Asn1ObjectIdentifier("1.3.6.1.5.2.3.1")); extension.setExtnValue("value".getBytes()); extension.setCritical(false); byte[] encodedBytes = extension.encode(); Extension decodedExtension = new Extension(); decodedExtension.decode(encodedBytes); assertThat(decodedExtension.getCritical()).isFalse(); } @Test public void testSetCritical() throws IOException { Extension extension = new Extension(); extension.setCritical(true); extension.setExtnId(new Asn1ObjectIdentifier("1.3.6.1.5.2.3.1")); extension.setExtnValue("value".getBytes()); byte[] encodedBytes = extension.encode(); Extension decodedExtension = new Extension(); decodedExtension.decode(encodedBytes); assertThat(decodedExtension.getCritical()).isTrue(); } }
471
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/pkix/PkiException.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.pkix; /** * The root exception for the module. */ public class PkiException extends Exception { private static final long serialVersionUID = 7305497872367599428L; public PkiException(String message) { super(message); } public PkiException(String message, Throwable cause) { super(message, cause); } }
472
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/pkix/PkiUtil.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.pkix; import org.apache.kerby.cms.type.SignedData; import java.security.PrivateKey; import java.security.cert.X509Certificate; /** * Pki utilities. */ public final class PkiUtil { private PkiUtil() { } public static byte[] getSignedData(PrivateKey privateKey, X509Certificate certificate, byte[] dataToSign, String eContentType) throws PkiException { /** * TO DO */ return null; } /** * Validates a CMS SignedData using the public key corresponding to the private * key used to sign the structure. * * @param signedData The signed Data * @return true if the signature is valid. * @throws PkiException e */ public static boolean validateSignedData(SignedData signedData) throws PkiException { /** * TO DO */ return false; } }
473
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/CertificatePair.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * * <pre> * CertificatePair ::= SEQUENCE { * forward [0] Certificate OPTIONAL, * reverse [1] Certificate OPTIONAL, * -- at least one of the pair shall be present -- * } * </pre> */ public class CertificatePair extends Asn1SequenceType { protected enum CertificatePairField implements EnumType { FORWARD, REVERSE; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ExplicitField(CertificatePairField.FORWARD, Certificate.class), new ExplicitField(CertificatePairField.REVERSE, Certificate.class) }; public CertificatePair() { super(fieldInfos); } public Certificate getForward() { return getFieldAs(CertificatePairField.FORWARD, Certificate.class); } public void setForward(Certificate forward) { setFieldAs(CertificatePairField.FORWARD, forward); } public Certificate getReverse() { return getFieldAs(CertificatePairField.REVERSE, Certificate.class); } public void setReverse(Certificate reverse) { setFieldAs(CertificatePairField.REVERSE, reverse); } }
474
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/TargetCert.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * TargetCert ::= SEQUENCE { * targetCertificate IssuerSerial, * targetName GeneralName OPTIONAL, * certDigestInfo ObjectDigestInfo OPTIONAL * } */ public class TargetCert extends Asn1SequenceType { protected enum TargetCertField implements EnumType { TARGET_CERTIFICATE, TARGET_NAME, CERT_DIGEST_INFO; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(TargetCertField.TARGET_CERTIFICATE, IssuerSerial.class), new Asn1FieldInfo(TargetCertField.TARGET_NAME, GeneralName.class), new Asn1FieldInfo(TargetCertField.CERT_DIGEST_INFO, ObjectDigestInfo.class) }; public TargetCert() { super(fieldInfos); } public IssuerSerial getTargetCertificate() { return getFieldAs(TargetCertField.TARGET_CERTIFICATE, IssuerSerial.class); } public void setTargetCertificate(IssuerSerial targetCertificate) { setFieldAs(TargetCertField.TARGET_CERTIFICATE, targetCertificate); } public GeneralName getTargetName() { return getFieldAs(TargetCertField.TARGET_NAME, GeneralName.class); } public void setTargetName(GeneralName targetName) { setFieldAs(TargetCertField.TARGET_NAME, targetName); } public ObjectDigestInfo getCertDigestInfo() { return getFieldAs(TargetCertField.CERT_DIGEST_INFO, ObjectDigestInfo.class); } public void setCerttDigestInfo(ObjectDigestInfo certDigestInfo) { setFieldAs(TargetCertField.CERT_DIGEST_INFO, certDigestInfo); } }
475
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/BasicConstraints.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Boolean; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; import java.math.BigInteger; /** * <pre> * BasicConstraints := SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL * } * </pre> */ public class BasicConstraints extends Asn1SequenceType { protected enum BasicConstraintsField implements EnumType { CA, PATH_LEN_CONSTRAINT; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(BasicConstraintsField.CA, Asn1Boolean.class), new Asn1FieldInfo(BasicConstraintsField.PATH_LEN_CONSTRAINT, Asn1Integer.class) }; public BasicConstraints() { super(fieldInfos); } public boolean isCA() { return false; } public boolean getCA() { return getFieldAs(BasicConstraintsField.CA, Asn1Boolean.class).getValue(); } public void setCA(Asn1Boolean isCA) { setFieldAs(BasicConstraintsField.CA, isCA); } public BigInteger getPathLenConstraint() { return getFieldAs(BasicConstraintsField.PATH_LEN_CONSTRAINT, Asn1Integer.class).getValue(); } public void setPathLenConstraint(Asn1Integer pathLenConstraint) { setFieldAs(BasicConstraintsField.PATH_LEN_CONSTRAINT, pathLenConstraint); } }
476
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/Attributes.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.x509.type; import org.apache.kerby.asn1.type.Asn1SequenceOf; /** * Ref. RFC 3039 * * <pre> * SubjectDirectoryAttributes ::= Attributes * Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute * Attribute ::= SEQUENCE { * type AttributeType * values SET OF AttributeValue * } * * AttributeType ::= OBJECT IDENTIFIER * AttributeValue ::= ANY DEFINED BY AttributeType * </pre> */ public class Attributes extends Asn1SequenceOf<Attribute> { }
477
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/GeneralSubtrees.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.x509.type; import org.apache.kerby.asn1.type.Asn1SequenceOf; public class GeneralSubtrees extends Asn1SequenceOf<GeneralSubtree> { }
478
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/ObjectDigestInfo.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1BitString; import org.apache.kerby.asn1.type.Asn1ObjectIdentifier; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * * <pre> * ObjectDigestInfo ::= SEQUENCE { * digestedObjectType ENUMERATED { * publicKey (0), * publicKeyCert (1), * otherObjectTypes (2) }, * -- otherObjectTypes MUST NOT * -- be used in this profile * otherObjectTypeID OBJECT IDENTIFIER OPTIONAL, * digestAlgorithm AlgorithmIdentifier, * objectDigest BIT STRING * } * * </pre> * */ public class ObjectDigestInfo extends Asn1SequenceType { protected enum ODInfoField implements EnumType { DIGESTED_OBJECT_TYPE, OTHER_OBJECT_TYPE_ID, DIGEST_ALGORITHM, OBJECT_DIGEST; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(ODInfoField.DIGESTED_OBJECT_TYPE, DigestedObjectType.class), new Asn1FieldInfo(ODInfoField.OTHER_OBJECT_TYPE_ID, Asn1ObjectIdentifier.class), new Asn1FieldInfo(ODInfoField.DIGEST_ALGORITHM, AlgorithmIdentifier.class), new Asn1FieldInfo(ODInfoField.OBJECT_DIGEST, Asn1BitString.class) }; public ObjectDigestInfo() { super(fieldInfos); } public DigestedObjectType getDigestedObjectType() { return getFieldAs(ODInfoField.DIGESTED_OBJECT_TYPE, DigestedObjectType.class); } public void setDigestedObjectType(DigestedObjectType digestedObjectType) { setFieldAs(ODInfoField.DIGESTED_OBJECT_TYPE, digestedObjectType); } public Asn1ObjectIdentifier getOtherObjectTypeID() { return getFieldAs(ODInfoField.OTHER_OBJECT_TYPE_ID, Asn1ObjectIdentifier.class); } public void setOtherObjectTypeId(Asn1ObjectIdentifier otherObjectTypeID) { setFieldAs(ODInfoField.OTHER_OBJECT_TYPE_ID, otherObjectTypeID); } public AlgorithmIdentifier getDigestAlgorithm() { return getFieldAs(ODInfoField.DIGEST_ALGORITHM, AlgorithmIdentifier.class); } public void setDigestAlgorithm(AlgorithmIdentifier digestAlgorithm) { setFieldAs(ODInfoField.DIGEST_ALGORITHM, digestAlgorithm); } public Asn1BitString getObjectDigest() { return getFieldAs(ODInfoField.OBJECT_DIGEST, Asn1BitString.class); } public void setObjectDigest(Asn1BitString objectDigest) { setFieldAs(ODInfoField.OBJECT_DIGEST, objectDigest); } }
479
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/AttCertIssuer.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1Choice; /** * * <pre> * AttCertIssuer ::= CHOICE { * v1Form GeneralNames, -- MUST NOT be used in this profile * v2Form [0] V2Form -- v2 only * } * </pre> */ public class AttCertIssuer extends Asn1Choice { protected enum AttCertIssuerField implements EnumType { V1_FORM, V2_FORM; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(AttCertIssuerField.V1_FORM, GeneralNames.class), new ExplicitField(AttCertIssuerField.V2_FORM, 0, V2Form.class) }; public AttCertIssuer() { super(fieldInfos); } public GeneralNames getV1Form() { return getChoiceValueAs(AttCertIssuerField.V1_FORM, GeneralNames.class); } public void setV1Form(GeneralNames v1Form) { setChoiceValue(AttCertIssuerField.V1_FORM, v1Form); } public V2Form getV2Form() { return getChoiceValueAs(AttCertIssuerField.V2_FORM, V2Form.class); } public void setV2Form(V2Form v2Form) { setChoiceValue(AttCertIssuerField.V2_FORM, v2Form); } }
480
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/PolicyConstraints.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * Ref. RFC 5280 * <pre> * id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } * * PolicyConstraints ::= SEQUENCE { * requireExplicitPolicy [0] SkipCerts OPTIONAL, * inhibitPolicyMapping [1] SkipCerts OPTIONAL } * * SkipCerts ::= INTEGER (0..MAX) * </pre> */ public class PolicyConstraints extends Asn1SequenceType { protected enum PolicyConstraintsField implements EnumType { REQUIRE_EXPLICIT_POLICY, INHIBIT_POLICY_MAPPING; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ExplicitField(PolicyConstraintsField.REQUIRE_EXPLICIT_POLICY, Asn1Integer.class), new ExplicitField(PolicyConstraintsField.INHIBIT_POLICY_MAPPING, Asn1Integer.class) }; public PolicyConstraints() { super(fieldInfos); } public Asn1Integer getRequireExplicitPolicy() { return getFieldAs(PolicyConstraintsField.REQUIRE_EXPLICIT_POLICY, Asn1Integer.class); } public void setRequireExplicitPolicy(Asn1Integer requireExplicitPolicy) { setFieldAs(PolicyConstraintsField.REQUIRE_EXPLICIT_POLICY, requireExplicitPolicy); } public Asn1Integer getInhibitPolicyMapping() { return getFieldAs(PolicyConstraintsField.INHIBIT_POLICY_MAPPING, Asn1Integer.class); } public void setInhibitPolicyMapping(Asn1Integer inhibitPolicyMapping) { setFieldAs(PolicyConstraintsField.INHIBIT_POLICY_MAPPING, inhibitPolicyMapping); } }
481
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/DhParameter.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; import java.math.BigInteger; public class DhParameter extends Asn1SequenceType { protected enum DhParameterField implements EnumType { P, G, Q; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(DhParameterField.P, Asn1Integer.class), new Asn1FieldInfo(DhParameterField.G, Asn1Integer.class), new Asn1FieldInfo(DhParameterField.Q, Asn1Integer.class), }; public DhParameter() { super(fieldInfos); } public void setP(BigInteger p) { setFieldAsInt(DhParameterField.P, p); } public BigInteger getP() { Asn1Integer p = getFieldAs(DhParameterField.P, Asn1Integer.class); return p.getValue(); } public void setG(BigInteger g) { setFieldAsInt(DhParameterField.G, g); } public BigInteger getG() { Asn1Integer g = getFieldAs(DhParameterField.G, Asn1Integer.class); return g.getValue(); } public void setQ(BigInteger q) { setFieldAsInt(DhParameterField.Q, q); } public BigInteger getQ() { Asn1Integer q = getFieldAs(DhParameterField.Q, Asn1Integer.class); return q.getValue(); } }
482
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/DSAParameter.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; import java.math.BigInteger; public class DSAParameter extends Asn1SequenceType { protected enum DSAParameterField implements EnumType { P, Q, G; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(DSAParameterField.P, Asn1Integer.class), new Asn1FieldInfo(DSAParameterField.Q, Asn1Integer.class), new Asn1FieldInfo(DSAParameterField.G, Asn1Integer.class) }; public DSAParameter() { super(fieldInfos); } public BigInteger getP() { return getFieldAs(DSAParameterField.P, Asn1Integer.class).getValue(); } public void setP(BigInteger p) { setFieldAs(DSAParameterField.P, new Asn1Integer(p)); } public BigInteger getQ() { return getFieldAs(DSAParameterField.Q, Asn1Integer.class).getValue(); } public void setQ(BigInteger q) { setFieldAs(DSAParameterField.Q, new Asn1Integer(q)); } public BigInteger getG() { return getFieldAs(DSAParameterField.G, Asn1Integer.class).getValue(); } public void setG(BigInteger g) { setFieldAs(DSAParameterField.G, new Asn1Integer(g)); } }
483
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/Extension.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Boolean; import org.apache.kerby.asn1.type.Asn1ObjectIdentifier; import org.apache.kerby.asn1.type.Asn1OctetString; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * Ref. X.509 V3 extension * <pre> * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension * * Extension ::= SEQUENCE { * extnId EXTENSION.&amp;id ({ExtensionSet}), * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING } * </pre> */ public class Extension extends Asn1SequenceType { protected enum ExtensionField implements EnumType { EXTN_ID, CRITICAL, EXTN_VALUE; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(ExtensionField.EXTN_ID, Asn1ObjectIdentifier.class), new Asn1FieldInfo(ExtensionField.CRITICAL, Asn1Boolean.class), new Asn1FieldInfo(ExtensionField.EXTN_VALUE, Asn1OctetString.class) }; public Extension() { super(fieldInfos); } public Asn1ObjectIdentifier getExtnId() { return getFieldAs(ExtensionField.EXTN_ID, Asn1ObjectIdentifier.class); } public void setExtnId(Asn1ObjectIdentifier extnId) { setFieldAs(ExtensionField.EXTN_ID, extnId); } public boolean getCritical() { return getFieldAs(ExtensionField.CRITICAL, Asn1Boolean.class).getValue(); } public void setCritical(boolean critical) { setFieldAs(ExtensionField.CRITICAL, new Asn1Boolean(critical)); } public byte[] getExtnValue() { return getFieldAsOctets(ExtensionField.EXTN_VALUE); } public void setExtnValue(byte[] value) { setFieldAsOctets(ExtensionField.EXTN_VALUE, value); } }
484
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/UserNotice.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * * <pre> * UserNotice ::= SEQUENCE { * noticeRef NoticeReference OPTIONAL, * explicitText DisplayText OPTIONAL} * * </pre> * */ public class UserNotice extends Asn1SequenceType { protected enum UserNoticeField implements EnumType { NOTICE_REF, EXPLICIT_TEXT; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(UserNoticeField.NOTICE_REF, NoticeReference.class), new Asn1FieldInfo(UserNoticeField.EXPLICIT_TEXT, DisplayText.class) }; public UserNotice() { super(fieldInfos); } public NoticeReference getNoticeRef() { return getFieldAs(UserNoticeField.NOTICE_REF, NoticeReference.class); } public void setNoticeRef(NoticeReference noticeRef) { setFieldAs(UserNoticeField.NOTICE_REF, noticeRef); } public DisplayText getExplicitText() { return getFieldAs(UserNoticeField.EXPLICIT_TEXT, DisplayText.class); } public void setExplicitText(DisplayText explicitText) { setFieldAs(UserNoticeField.EXPLICIT_TEXT, explicitText); } }
485
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/AuthorityInformationAccess.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.x509.type; import org.apache.kerby.asn1.type.Asn1SequenceOf; /** * * <pre> * id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 } * * AuthorityInfoAccessSyntax ::= * SEQUENCE SIZE (1..MAX) OF AccessDescription * AccessDescription ::= SEQUENCE { * accessMethod OBJECT IDENTIFIER, * accessLocation GeneralName * } * * </pre> */ public class AuthorityInformationAccess extends Asn1SequenceOf<AccessDescription> { }
486
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/TBSCertList.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; import org.apache.kerby.x500.type.Name; /** * Ref. RFC-2459 * <pre> * TBSCertList ::= SEQUENCE { * version Version OPTIONAL, * -- if present, shall be v2 * signature AlgorithmIdentifier, * issuer Name, * thisUpdate Time, * nextUpdate Time OPTIONAL, * revokedCertificates SEQUENCE OF SEQUENCE { * userCertificate CertificateSerialNumber, * revocationDate Time, * crlEntryExtensions Extensions OPTIONAL * -- if present, shall be v2 * } OPTIONAL, * crlExtensions [0] EXPLICIT Extensions OPTIONAL * -- if present, shall be v2 * } * </pre> */ public class TBSCertList extends Asn1SequenceType { protected enum TBSCertListField implements EnumType { VERSION, SIGNATURE, ISSUER, THIS_UPDATA, NEXT_UPDATE, REVOKED_CERTIFICATES, CRL_EXTENSIONS; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(TBSCertListField.VERSION, Asn1Integer.class), new Asn1FieldInfo(TBSCertListField.SIGNATURE, AlgorithmIdentifier.class), new Asn1FieldInfo(TBSCertListField.ISSUER, Name.class), new Asn1FieldInfo(TBSCertListField.THIS_UPDATA, Time.class), new Asn1FieldInfo(TBSCertListField.NEXT_UPDATE, Time.class), new Asn1FieldInfo(TBSCertListField.REVOKED_CERTIFICATES, RevokedCertificates.class), new ExplicitField(TBSCertListField.CRL_EXTENSIONS, 0, Extensions.class) }; public TBSCertList() { super(fieldInfos); } public Asn1Integer getVersion() { return getFieldAs(TBSCertListField.VERSION, Asn1Integer.class); } public void setVersion(Asn1Integer version) { setFieldAs(TBSCertListField.VERSION, version); } public AlgorithmIdentifier getSignature() { return getFieldAs(TBSCertListField.SIGNATURE, AlgorithmIdentifier.class); } public void setSignature(AlgorithmIdentifier signature) { setFieldAs(TBSCertListField.SIGNATURE, signature); } public Name getIssuer() { return getFieldAs(TBSCertListField.ISSUER, Name.class); } public void setIssuer(Name issuer) { setFieldAs(TBSCertListField.ISSUER, issuer); } public Time getThisUpdate() { return getFieldAs(TBSCertListField.THIS_UPDATA, Time.class); } public void setThisUpdata(Time thisUpdata) { setFieldAs(TBSCertListField.THIS_UPDATA, thisUpdata); } public Time getNextUpdate() { return getFieldAs(TBSCertListField.NEXT_UPDATE, Time.class); } public void setNextUpdate(Time nextUpdate) { setFieldAs(TBSCertListField.NEXT_UPDATE, nextUpdate); } public RevokedCertificates getRevokedCertificates() { return getFieldAs(TBSCertListField.REVOKED_CERTIFICATES, RevokedCertificates.class); } public void setRevokedCertificates(RevokedCertificates revokedCertificates) { setFieldAs(TBSCertListField.REVOKED_CERTIFICATES, revokedCertificates); } public Extensions getCrlExtensions() { return getFieldAs(TBSCertListField.CRL_EXTENSIONS, Extensions.class); } public void setCrlExtensions(Extensions crlExtensions) { setFieldAs(TBSCertListField.CRL_EXTENSIONS, crlExtensions); } }
487
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/ReasonFlags.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.x509.type; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Flags; /** * * <pre> * ReasonFlags ::= BIT STRING { * unused (0), * keyCompromise (1), * cACompromise (2), * affiliationChanged (3), * superseded (4), * cessationOfOperation (5), * certificateHold (6), * privilegeWithdrawn (7), * aACompromise (8) * } * </pre> */ enum ReasonFlagsEnum implements EnumType { UNUSED, KEY_COMPROMISE, CA_COMPROMISE, AFFILIATION_CHANGED, SUPERSEDED, CESSATION_OF_OPERATION, CERTIFICATE_HOLD, PRIVILEGE_WITH_DRAWN, AA_COMPROMISE; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } public class ReasonFlags extends Asn1Flags { }
488
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/Holder.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * <pre> * Holder ::= SEQUENCE { * baseCertificateID [0] IssuerSerial OPTIONAL, * -- the issuer and serial number of * -- the holder's Public Key Certificate * entityName [1] GeneralNames OPTIONAL, * -- the name of the claimant or role * objectDigestInfo [2] ObjectDigestInfo OPTIONAL * -- used to directly authenticate the holder, * -- for example, an executable * } * </pre> */ public class Holder extends Asn1SequenceType { protected enum HolderField implements EnumType { BASE_CERTIFICATE_ID, ENTITY_NAME, OBJECT_DIGEST_INFO; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ExplicitField(HolderField.BASE_CERTIFICATE_ID, IssuerSerial.class), new ExplicitField(HolderField.ENTITY_NAME, GeneralNames.class), new ExplicitField(HolderField.OBJECT_DIGEST_INFO, ObjectDigestInfo.class) }; public Holder() { super(fieldInfos); } public IssuerSerial getBaseCertificateID() { return getFieldAs(HolderField.BASE_CERTIFICATE_ID, IssuerSerial.class); } public void setBaseCertificateId(IssuerSerial baseCertificateId) { setFieldAs(HolderField.BASE_CERTIFICATE_ID, baseCertificateId); } public GeneralNames getEntityName() { return getFieldAs(HolderField.ENTITY_NAME, GeneralNames.class); } public void setEntityName(GeneralNames entityName) { setFieldAs(HolderField.ENTITY_NAME, entityName); } public ObjectDigestInfo getObjectDigestInfo() { return getFieldAs(HolderField.OBJECT_DIGEST_INFO, ObjectDigestInfo.class); } public void setObjectDigestInfo(ObjectDigestInfo objectDigestInfo) { setFieldAs(HolderField.OBJECT_DIGEST_INFO, objectDigestInfo); } }
489
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/GeneralNames.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.x509.type; import org.apache.kerby.asn1.type.Asn1SequenceOf; /* * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName */ public class GeneralNames extends Asn1SequenceOf<GeneralName> { }
490
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/AuthorityKeyIdentifier.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ImplicitField; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * * <pre> * id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } * * AuthorityKeyIdentifier ::= SEQUENCE { * keyIdentifier [0] IMPLICIT KeyIdentifier OPTIONAL, * authorityCertIssuer [1] IMPLICIT GeneralNames OPTIONAL, * authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL * } * * KeyIdentifier ::= OCTET STRING * </pre> * */ public class AuthorityKeyIdentifier extends Asn1SequenceType { protected enum AKIdentifierField implements EnumType { KEY_IDENTIFIER, AUTHORITY_CERT_ISSUER, AUTHORITY_CERT_SERIAL_NUMBER; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ImplicitField(AKIdentifierField.KEY_IDENTIFIER, KeyIdentifier.class), new ImplicitField(AKIdentifierField.AUTHORITY_CERT_ISSUER, GeneralNames.class), new ImplicitField(AKIdentifierField.AUTHORITY_CERT_SERIAL_NUMBER, CertificateSerialNumber.class) }; public AuthorityKeyIdentifier() { super(fieldInfos); } public KeyIdentifier getKeyIdentifier() { return getFieldAs(AKIdentifierField.KEY_IDENTIFIER, KeyIdentifier.class); } public void setKeyIdentifier(KeyIdentifier keyIdentifier) { setFieldAs(AKIdentifierField.KEY_IDENTIFIER, keyIdentifier); } public GeneralNames getAuthorityCertIssuer() { return getFieldAs(AKIdentifierField.AUTHORITY_CERT_ISSUER, GeneralNames.class); } public void setAuthorityCertIssuer(GeneralNames authorityCertIssuer) { setFieldAs(AKIdentifierField.AUTHORITY_CERT_ISSUER, authorityCertIssuer); } public CertificateSerialNumber getAuthorityCertSerialNumber() { return getFieldAs(AKIdentifierField.AUTHORITY_CERT_SERIAL_NUMBER, CertificateSerialNumber.class); } public void setAuthorityCertSerialNumber(CertificateSerialNumber authorityCertSerialNumber) { setFieldAs(AKIdentifierField.AUTHORITY_CERT_SERIAL_NUMBER, authorityCertSerialNumber); } }
491
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/IetfAttrSyntaxChoice.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Choice; import org.apache.kerby.asn1.type.Asn1ObjectIdentifier; import org.apache.kerby.asn1.type.Asn1OctetString; /** * Ref. RFC3281 * <pre> * IetfAttrSyntax ::= SEQUENCE { * policyAuthority [0] GeneralNames OPTIONAL, * values SEQUENCE OF CHOICE { * octets OCTET STRING, * oid OBJECT IDENTIFIER, * string UTF8String * } * } * </pre> */ public class IetfAttrSyntaxChoice extends Asn1Choice { protected enum IetfAttrSyntaxChoiceField implements EnumType { OCTETS, OID, UTF8; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(IetfAttrSyntaxChoiceField.OCTETS, Asn1OctetString.class), new Asn1FieldInfo(IetfAttrSyntaxChoiceField.OID, Asn1ObjectIdentifier.class), new Asn1FieldInfo(IetfAttrSyntaxChoiceField.UTF8, Asn1ObjectIdentifier.class) }; public IetfAttrSyntaxChoice() { super(fieldInfos); } public Asn1OctetString getOctets() { return getChoiceValueAs(IetfAttrSyntaxChoiceField.OCTETS, Asn1OctetString.class); } public void setOctets(Asn1OctetString octets) { setChoiceValue(IetfAttrSyntaxChoiceField.OCTETS, octets); } public Asn1ObjectIdentifier getOid() { return getChoiceValueAs(IetfAttrSyntaxChoiceField.OID, Asn1ObjectIdentifier.class); } public void setOid(Asn1ObjectIdentifier oid) { setChoiceValue(IetfAttrSyntaxChoiceField.OID, oid); } public Asn1ObjectIdentifier getUtf8() { return getChoiceValueAs(IetfAttrSyntaxChoiceField.UTF8, Asn1ObjectIdentifier.class); } public void setUtf8(Asn1ObjectIdentifier utf8) { setChoiceValue(IetfAttrSyntaxChoiceField.UTF8, utf8); } }
492
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/NoticeReference.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * <pre> * NoticeReference ::= SEQUENCE { * organization DisplayText, * noticeNumbers SEQUENCE OF INTEGER * } * * </pre> * */ public class NoticeReference extends Asn1SequenceType { protected enum NoticeReferenceField implements EnumType { ORGANIZATION, NOTICE_NUMBERS; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(NoticeReferenceField.ORGANIZATION, DisplayText.class), new Asn1FieldInfo(NoticeReferenceField.NOTICE_NUMBERS, NoticeNumbers.class) }; public NoticeReference() { super(fieldInfos); } public DisplayText getOrganization() { return getFieldAs(NoticeReferenceField.ORGANIZATION, DisplayText.class); } public void setOrganization(DisplayText organization) { setFieldAs(NoticeReferenceField.ORGANIZATION, organization); } public NoticeNumbers getNoticeNumbers() { return getFieldAs(NoticeReferenceField.NOTICE_NUMBERS, NoticeNumbers.class); } public void setNoticeNumbers(NoticeNumbers noticeNumbers) { setFieldAs(NoticeReferenceField.NOTICE_NUMBERS, noticeNumbers); } }
493
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/GeneralName.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.ImplicitField; import org.apache.kerby.asn1.type.Asn1Any; import org.apache.kerby.asn1.type.Asn1Choice; import org.apache.kerby.asn1.type.Asn1IA5String; import org.apache.kerby.asn1.type.Asn1ObjectIdentifier; import org.apache.kerby.asn1.type.Asn1OctetString; import org.apache.kerby.x500.type.Name; /** * * <pre> * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER * } * </pre> */ public class GeneralName extends Asn1Choice { protected enum GeneralNameField implements EnumType { OTHER_NAME, RFC822_NAME, DNS_NAME, X400_ADDRESS, DIRECTORY_NAME, EDI_PARTY_NAME, UNIFORM_RESOURCE_IDENTIFIER, IP_ADDRESS, REGISTERED_ID; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ImplicitField(GeneralNameField.OTHER_NAME, OtherName.class), new ImplicitField(GeneralNameField.RFC822_NAME, Asn1IA5String.class), new ImplicitField(GeneralNameField.DNS_NAME, Asn1IA5String.class), // ORAddress is to be defined. new ImplicitField(GeneralNameField.X400_ADDRESS, Asn1Any.class), new ExplicitField(GeneralNameField.DIRECTORY_NAME, Name.class), new ImplicitField(GeneralNameField.EDI_PARTY_NAME, EDIPartyName.class), new ImplicitField(GeneralNameField.UNIFORM_RESOURCE_IDENTIFIER, Asn1IA5String.class), new ImplicitField(GeneralNameField.IP_ADDRESS, Asn1OctetString.class), new ImplicitField(GeneralNameField.REGISTERED_ID, Asn1ObjectIdentifier.class) }; public GeneralName() { super(fieldInfos); } public OtherName getOtherName() { return getChoiceValueAs(GeneralNameField.OTHER_NAME, OtherName.class); } public void setOtherName(OtherName otherName) { setChoiceValue(GeneralNameField.OTHER_NAME, otherName); } public Asn1IA5String getRfc822Name() { return getChoiceValueAs(GeneralNameField.RFC822_NAME, Asn1IA5String.class); } public void setRfc822Name(Asn1IA5String rfc822Name) { setChoiceValue(GeneralNameField.RFC822_NAME, rfc822Name); } public Asn1IA5String getDNSName() { return getChoiceValueAs(GeneralNameField.DNS_NAME, Asn1IA5String.class); } public void setDNSName(Asn1IA5String dnsName) { setChoiceValue(GeneralNameField.DNS_NAME, dnsName); } public Asn1Any getX400Address() { return getChoiceValueAs(GeneralNameField.X400_ADDRESS, Asn1Any.class); } public void setX400Address(Asn1Any x400Address) { setChoiceValue(GeneralNameField.X400_ADDRESS, x400Address); } public Name getDirectoryName() { return getChoiceValueAs(GeneralNameField.DIRECTORY_NAME, Name.class); } public void setDirectoryName(Name directoryName) { setChoiceValue(GeneralNameField.DIRECTORY_NAME, directoryName); } public EDIPartyName getEdiPartyName() { return getChoiceValueAs(GeneralNameField.EDI_PARTY_NAME, EDIPartyName.class); } public void setEdiPartyName(EDIPartyName ediPartyName) { setChoiceValue(GeneralNameField.EDI_PARTY_NAME, ediPartyName); } public Asn1IA5String getUniformResourceIdentifier() { return getChoiceValueAs(GeneralNameField.UNIFORM_RESOURCE_IDENTIFIER, Asn1IA5String.class); } public void setUniformResourceIdentifier(Asn1IA5String uniformResourceIdentifier) { setChoiceValue(GeneralNameField.UNIFORM_RESOURCE_IDENTIFIER, uniformResourceIdentifier); } public byte[] getIPAddress() { return getChoiceValueAsOctets(GeneralNameField.IP_ADDRESS); } public void setIpAddress(byte[] ipAddress) { setChoiceValueAsOctets(GeneralNameField.IP_ADDRESS, ipAddress); } public Asn1ObjectIdentifier getRegisteredID() { return getChoiceValueAs(GeneralNameField.REGISTERED_ID, Asn1ObjectIdentifier.class); } public void setRegisteredID(Asn1ObjectIdentifier registeredID) { setChoiceValue(GeneralNameField.REGISTERED_ID, registeredID); } }
494
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/DirectoryString.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1BmpString; import org.apache.kerby.asn1.type.Asn1Choice; import org.apache.kerby.asn1.type.Asn1PrintableString; import org.apache.kerby.asn1.type.Asn1T61String; import org.apache.kerby.asn1.type.Asn1UniversalString; import org.apache.kerby.asn1.type.Asn1Utf8String; /** * <pre> * DirectoryString ::= CHOICE { * teletexString TeletexString (SIZE (1..MAX)), * printableString PrintableString (SIZE (1..MAX)), * universalString UniversalString (SIZE (1..MAX)), * utf8String UTF8String (SIZE (1..MAX)), * bmpString BMPString (SIZE (1..MAX)) * } * </pre> */ public class DirectoryString extends Asn1Choice { protected enum DirectoryStringField implements EnumType { TELETEX_STRING, PRINTABLE_STRING, UNIVERSAL_STRING, UTF8_STRING, BMP_STRING; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[]{ new Asn1FieldInfo(DirectoryStringField.TELETEX_STRING, Asn1T61String.class), new Asn1FieldInfo(DirectoryStringField.PRINTABLE_STRING, Asn1PrintableString.class), new Asn1FieldInfo(DirectoryStringField.UNIVERSAL_STRING, Asn1UniversalString.class), new Asn1FieldInfo(DirectoryStringField.UTF8_STRING, Asn1Utf8String.class), new Asn1FieldInfo(DirectoryStringField.BMP_STRING, Asn1BmpString.class) }; public DirectoryString() { super(fieldInfos); } public Asn1T61String getTeletexString() { return getChoiceValueAs(DirectoryStringField.TELETEX_STRING, Asn1T61String.class); } public void setTeletexString(Asn1T61String teletexString) { setChoiceValue(DirectoryStringField.TELETEX_STRING, teletexString); } public Asn1PrintableString getPrintableString() { return getChoiceValueAs(DirectoryStringField.PRINTABLE_STRING, Asn1PrintableString.class); } public void setPrintableString(Asn1PrintableString printableString) { setChoiceValue(DirectoryStringField.PRINTABLE_STRING, printableString); } public Asn1UniversalString getUniversalString() { return getChoiceValueAs(DirectoryStringField.UNIVERSAL_STRING, Asn1UniversalString.class); } public void setUniversalString(Asn1UniversalString universalString) { setChoiceValue(DirectoryStringField.UNIVERSAL_STRING, universalString); } public Asn1Utf8String getUtf8String() { return getChoiceValueAs(DirectoryStringField.UTF8_STRING, Asn1Utf8String.class); } public void setUtf8String(Asn1Utf8String utf8String) { setChoiceValue(DirectoryStringField.UTF8_STRING, utf8String); } public Asn1BmpString getBmpString() { return getChoiceValueAs(DirectoryStringField.BMP_STRING, Asn1BmpString.class); } public void setBmpString(Asn1BmpString bmpString) { setChoiceValue(DirectoryStringField.BMP_STRING, bmpString); } }
495
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/DigestedObjectType.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.x509.type; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Enumerated; /** * * <pre> * digestedObjectType ENUMERATED { * publicKey (0), * publicKeyCert (1), * otherObjectTypes (2) * } * * </pre> * */ enum DigestedObjectEnum implements EnumType { PUBLIC_KEY, PUBLIC_KEY_CERT, OTHER_OBJECT_TYPES; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } public class DigestedObjectType extends Asn1Enumerated<DigestedObjectEnum> { @Override public EnumType[] getAllEnumValues() { return DigestedObjectEnum.values(); } }
496
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/PolicyQualifierInfo.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1Any; import org.apache.kerby.asn1.type.Asn1SequenceType; import org.apache.kerby.asn1.type.Asn1Type; /** * * <pre> * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId * } * * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice ) * </pre> */ public class PolicyQualifierInfo extends Asn1SequenceType { protected enum PolicyQualifierInfoField implements EnumType { POLICY_QUALIFIER_ID, QUALIFIER; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(PolicyQualifierInfoField.POLICY_QUALIFIER_ID, PolicyQualifierId.class), new Asn1FieldInfo(PolicyQualifierInfoField.QUALIFIER, Asn1Any.class) }; public PolicyQualifierInfo() { super(fieldInfos); } public PolicyQualifierId getPolicyQualifierId() { return getFieldAs(PolicyQualifierInfoField.POLICY_QUALIFIER_ID, PolicyQualifierId.class); } public void setPolicyQualifierId(PolicyQualifierId policyQualifierId) { setFieldAs(PolicyQualifierInfoField.POLICY_QUALIFIER_ID, policyQualifierId); } public <T extends Asn1Type> T getQualifierAs(Class<T> t) { return getFieldAsAny(PolicyQualifierInfoField.QUALIFIER, t); } public void setQualifier(Asn1Type qualifier) { setFieldAsAny(PolicyQualifierInfoField.QUALIFIER, qualifier); } }
497
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/PrivateKeyUsagePeriod.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.ExplicitField; import org.apache.kerby.asn1.type.Asn1GeneralizedTime; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * <pre> * PrivateKeyUsagePeriod ::= SEQUENCE { * notBefore [0] GeneralizedTime OPTIONAL, * notAfter [1] GeneralizedTime OPTIONAL * } * </pre> */ public class PrivateKeyUsagePeriod extends Asn1SequenceType { protected enum PrivateKeyUsagePeriodField implements EnumType { NOT_BEFORE, NOT_AFTER; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new ExplicitField(PrivateKeyUsagePeriodField.NOT_BEFORE, Asn1GeneralizedTime.class), new ExplicitField(PrivateKeyUsagePeriodField.NOT_AFTER, Asn1GeneralizedTime.class) }; public PrivateKeyUsagePeriod() { super(fieldInfos); } public Asn1GeneralizedTime getNotBeforeTime() { return getFieldAs(PrivateKeyUsagePeriodField.NOT_BEFORE, Asn1GeneralizedTime.class); } public void setNotBeforeTime(Asn1GeneralizedTime notBeforeTime) { setFieldAs(PrivateKeyUsagePeriodField.NOT_BEFORE, notBeforeTime); } public Asn1GeneralizedTime getNotAfterTime() { return getFieldAs(PrivateKeyUsagePeriodField.NOT_AFTER, Asn1GeneralizedTime.class); } public void setNotAfterTime(Asn1GeneralizedTime notAfterTime) { setFieldAs(PrivateKeyUsagePeriodField.NOT_AFTER, notAfterTime); } }
498
0
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509
Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/x509/type/AttributeCertificateInfo.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.x509.type; import org.apache.kerby.asn1.Asn1FieldInfo; import org.apache.kerby.asn1.EnumType; import org.apache.kerby.asn1.type.Asn1BitString; import org.apache.kerby.asn1.type.Asn1Integer; import org.apache.kerby.asn1.type.Asn1SequenceType; /** * * <pre> * AttributeCertificateInfo ::= SEQUENCE { * version AttCertVersion -- version is v2, * holder Holder, * issuer AttCertIssuer, * signature AlgorithmIdentifier, * serialNumber CertificateSerialNumber, * attrCertValidityPeriod AttCertValidityPeriod, * attributes SEQUENCE OF Attribute, * issuerUniqueID UniqueIdentifier OPTIONAL, * extensions Extensions OPTIONAL * } * * AttCertVersion ::= INTEGER { v2(1) } * * UniqueIdentifier ::= BIT STRING * </pre> */ public class AttributeCertificateInfo extends Asn1SequenceType { protected enum ACInfoField implements EnumType { VERSION, HOLDER, ISSUER, SIGNATURE, SERIAL_NUMBER, ATTR_CERT_VALIDITY_PERIOD, ATTRIBUTES, ISSUER_UNIQUE_ID, EXTENSIONS; @Override public int getValue() { return ordinal(); } @Override public String getName() { return name(); } } static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] { new Asn1FieldInfo(ACInfoField.VERSION, Asn1Integer.class), new Asn1FieldInfo(ACInfoField.HOLDER, Holder.class), new Asn1FieldInfo(ACInfoField.ISSUER, AttCertIssuer.class), new Asn1FieldInfo(ACInfoField.SIGNATURE, AlgorithmIdentifier.class), new Asn1FieldInfo(ACInfoField.SERIAL_NUMBER, CertificateSerialNumber.class), new Asn1FieldInfo(ACInfoField.ATTR_CERT_VALIDITY_PERIOD, AttCertValidityPeriod.class), new Asn1FieldInfo(ACInfoField.ATTRIBUTES, Attributes.class), new Asn1FieldInfo(ACInfoField.ISSUER_UNIQUE_ID, Asn1BitString.class), new Asn1FieldInfo(ACInfoField.EXTENSIONS, Extensions.class) }; public AttributeCertificateInfo() { super(fieldInfos); } public int getVersion() { return getFieldAsInteger(ACInfoField.VERSION); } public void setVersion(int version) { setFieldAsInt(ACInfoField.VERSION, version); } public Holder getHolder() { return getFieldAs(ACInfoField.HOLDER, Holder.class); } public void setHolder(Holder holder) { setFieldAs(ACInfoField.HOLDER, holder); } public AttCertIssuer getIssuer() { return getFieldAs(ACInfoField.ISSUER, AttCertIssuer.class); } public void setIssuer(AttCertIssuer attCertIssuer) { setFieldAs(ACInfoField.ISSUER, attCertIssuer); } public AlgorithmIdentifier getSignature() { return getFieldAs(ACInfoField.SIGNATURE, AlgorithmIdentifier.class); } public void setSignature(AlgorithmIdentifier signature) { setFieldAs(ACInfoField.SIGNATURE, signature); } public CertificateSerialNumber getSerialNumber() { return getFieldAs(ACInfoField.SERIAL_NUMBER, CertificateSerialNumber.class); } public void setSerialNumber(CertificateSerialNumber certificateSerialNumber) { setFieldAs(ACInfoField.SERIAL_NUMBER, certificateSerialNumber); } public AttCertValidityPeriod getAttrCertValidityPeriod() { return getFieldAs(ACInfoField.ATTR_CERT_VALIDITY_PERIOD, AttCertValidityPeriod.class); } public void setAttrCertValidityPeriod(AttCertValidityPeriod attrCertValidityPeriod) { setFieldAs(ACInfoField.ATTR_CERT_VALIDITY_PERIOD, attrCertValidityPeriod); } public Attributes getAttributes() { return getFieldAs(ACInfoField.ATTRIBUTES, Attributes.class); } public void setAttributes(Attributes attributes) { setFieldAs(ACInfoField.ATTRIBUTES, attributes); } public byte[] getIssuerUniqueID() { return getFieldAs(ACInfoField.ISSUER_UNIQUE_ID, Asn1BitString.class).getValue(); } public void setIssuerUniqueId(byte[] issuerUniqueId) { setFieldAs(ACInfoField.ISSUER_UNIQUE_ID, new Asn1BitString(issuerUniqueId)); } public Extensions getExtensions() { return getFieldAs(ACInfoField.EXTENSIONS, Extensions.class); } public void setExtensions(Extensions extensions) { setFieldAs(ACInfoField.EXTENSIONS, extensions); } }
499