Path: blob/master/src/java.base/share/classes/sun/security/x509/IPAddressName.java
41159 views
/*1* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.x509;2627import java.io.IOException;28import java.lang.Integer;29import java.net.InetAddress;30import java.util.Arrays;31import sun.security.util.HexDumpEncoder;32import sun.security.util.BitArray;33import sun.security.util.DerOutputStream;34import sun.security.util.DerValue;3536/**37* This class implements the IPAddressName as required by the GeneralNames38* ASN.1 object. Both IPv4 and IPv6 addresses are supported using the39* formats specified in IETF PKIX RFC 5280.40* <p>41* [RFC 5280 4.2.1.6 Subject Alternative Name]42* When the subjectAltName extension contains an iPAddress, the address43* MUST be stored in the octet string in "network byte order", as44* specified in [RFC791]. The least significant bit (LSB) of each octet45* is the LSB of the corresponding byte in the network address. For IP46* version 4, as specified in [RFC791], the octet string MUST contain47* exactly four octets. For IP version 6, as specified in48* [RFC 2460], the octet string MUST contain exactly sixteen octets.49* <p>50* [RFC 5280 4.2.1.10 Name Constraints]51* The syntax of iPAddress MUST be as described in Section 4.2.1.6 with52* the following additions specifically for name constraints. For IPv453* addresses, the iPAddress field of GeneralName MUST contain eight (8)54* octets, encoded in the style of RFC 4632 (CIDR) to represent an55* address range [RFC 4632]. For IPv6 addresses, the iPAddress field56* MUST contain 32 octets similarly encoded. For example, a name57* constraint for "class C" subnet 192.0.2.0 is represented as the58* octets C0 00 02 00 FF FF FF 00, representing the CIDR notation59* 192.0.2.0/24 (mask 255.255.255.0).60* <p>61* @see GeneralName62* @see GeneralNameInterface63* @see GeneralNames64*65*66* @author Amit Kapoor67* @author Hemma Prafullchandra68*/69public class IPAddressName implements GeneralNameInterface {70private byte[] address;71private boolean isIPv4;72private String name;7374/**75* Create the IPAddressName object from the passed encoded Der value.76*77* @param derValue the encoded DER IPAddressName.78* @exception IOException on error.79*/80public IPAddressName(DerValue derValue) throws IOException {81this(derValue.getOctetString());82}8384/**85* Create the IPAddressName object with the specified octets.86*87* @param address the IP address88* @throws IOException if address is not a valid IPv4 or IPv6 address89*/90public IPAddressName(byte[] address) throws IOException {91/*92* A valid address must consist of 4 bytes of address and93* optional 4 bytes of 4 bytes of mask, or 16 bytes of address94* and optional 16 bytes of mask.95*/96if (address.length == 4 || address.length == 8) {97isIPv4 = true;98} else if (address.length == 16 || address.length == 32) {99isIPv4 = false;100} else {101throw new IOException("Invalid IPAddressName");102}103this.address = address;104}105106/**107* Create an IPAddressName from a String.108* [IETF RFC1338 Supernetting {@literal &} IETF RFC1519 Classless Inter-Domain109* Routing (CIDR)] For IPv4 addresses, the forms are110* "b1.b2.b3.b4" or "b1.b2.b3.b4/m1.m2.m3.m4", where b1 - b4 are decimal111* byte values 0-255 and m1 - m4 are decimal mask values112* 0 - 255.113* <p>114* [IETF RFC2373 IP Version 6 Addressing Architecture]115* For IPv6 addresses, the forms are "a1:a2:...:a8" or "a1:a2:...:a8/n",116* where a1-a8 are hexadecimal values representing the eight 16-bit pieces117* of the address. If /n is used, n is a decimal number indicating how many118* of the leftmost contiguous bits of the address comprise the prefix for119* this subnet. Internally, a mask value is created using the prefix length.120*121* @param name String form of IPAddressName122* @throws IOException if name can not be converted to a valid IPv4 or IPv6123* address124*/125public IPAddressName(String name) throws IOException {126127if (name == null || name.isEmpty()) {128throw new IOException("IPAddress cannot be null or empty");129}130if (name.charAt(name.length() - 1) == '/') {131throw new IOException("Invalid IPAddress: " + name);132}133134if (name.indexOf(':') >= 0) {135// name is IPv6: uses colons as value separators136// Parse name into byte-value address components and optional137// prefix138parseIPv6(name);139isIPv4 = false;140} else if (name.indexOf('.') >= 0) {141//name is IPv4: uses dots as value separators142parseIPv4(name);143isIPv4 = true;144} else {145throw new IOException("Invalid IPAddress: " + name);146}147}148149/**150* Parse an IPv4 address.151*152* @param name IPv4 address with optional mask values153* @throws IOException on error154*/155private void parseIPv4(String name) throws IOException {156157// Parse name into byte-value address components158int slashNdx = name.indexOf('/');159if (slashNdx == -1) {160address = InetAddress.getByName(name).getAddress();161} else {162address = new byte[8];163164// parse mask165byte[] mask = InetAddress.getByName166(name.substring(slashNdx+1)).getAddress();167168// parse base address169byte[] host = InetAddress.getByName170(name.substring(0, slashNdx)).getAddress();171172System.arraycopy(host, 0, address, 0, 4);173System.arraycopy(mask, 0, address, 4, 4);174}175}176177/**178* Parse an IPv6 address.179*180* @param name String IPv6 address with optional /<prefix length>181* If /<prefix length> is present, address[] array will182* be 32 bytes long, otherwise 16.183* @throws IOException on error184*/185private static final int MASKSIZE = 16;186private void parseIPv6(String name) throws IOException {187188int slashNdx = name.indexOf('/');189if (slashNdx == -1) {190address = InetAddress.getByName(name).getAddress();191} else {192address = new byte[32];193byte[] base = InetAddress.getByName194(name.substring(0, slashNdx)).getAddress();195System.arraycopy(base, 0, address, 0, 16);196197// append a mask corresponding to the num of prefix bits specified198int prefixLen = Integer.parseInt(name.substring(slashNdx+1));199if (prefixLen < 0 || prefixLen > 128) {200throw new IOException("IPv6Address prefix length (" +201prefixLen + ") in out of valid range [0,128]");202}203204// create new bit array initialized to zeros205BitArray bitArray = new BitArray(MASKSIZE * 8);206207// set all most significant bits up to prefix length208for (int i = 0; i < prefixLen; i++)209bitArray.set(i, true);210byte[] maskArray = bitArray.toByteArray();211212// copy mask bytes into mask portion of address213for (int i = 0; i < MASKSIZE; i++)214address[MASKSIZE+i] = maskArray[i];215}216}217218/**219* Return the type of the GeneralName.220*/221public int getType() {222return NAME_IP;223}224225/**226* Encode the IPAddress name into the DerOutputStream.227*228* @param out the DER stream to encode the IPAddressName to.229* @exception IOException on encoding errors.230*/231public void encode(DerOutputStream out) throws IOException {232out.putOctetString(address);233}234235/**236* Return a printable string of IPaddress237*/238public String toString() {239try {240return "IPAddress: " + getName();241} catch (IOException ioe) {242// dump out hex rep for debugging purposes243HexDumpEncoder enc = new HexDumpEncoder();244return "IPAddress: " + enc.encodeBuffer(address);245}246}247248/**249* Return a standard String representation of IPAddress.250* See IPAddressName(String) for the formats used for IPv4251* and IPv6 addresses.252*253* @throws IOException if the IPAddress cannot be converted to a String254*/255public String getName() throws IOException {256if (name != null)257return name;258259if (isIPv4) {260//IPv4 address or subdomain261byte[] host = new byte[4];262System.arraycopy(address, 0, host, 0, 4);263name = InetAddress.getByAddress(host).getHostAddress();264if (address.length == 8) {265byte[] mask = new byte[4];266System.arraycopy(address, 4, mask, 0, 4);267name = name + '/' +268InetAddress.getByAddress(mask).getHostAddress();269}270} else {271//IPv6 address or subdomain272byte[] host = new byte[16];273System.arraycopy(address, 0, host, 0, 16);274name = InetAddress.getByAddress(host).getHostAddress();275if (address.length == 32) {276// IPv6 subdomain: display prefix length277278// copy subdomain into new array and convert to BitArray279byte[] maskBytes = new byte[16];280for (int i=16; i < 32; i++)281maskBytes[i-16] = address[i];282BitArray ba = new BitArray(16*8, maskBytes);283// Find first zero bit284int i=0;285for (; i < 16*8; i++) {286if (!ba.get(i))287break;288}289name = name + '/' + i;290// Verify remaining bits 0291for (; i < 16*8; i++) {292if (ba.get(i)) {293throw new IOException("Invalid IPv6 subdomain - set " +294"bit " + i + " not contiguous");295}296}297}298}299return name;300}301302/**303* Returns this IPAddress name as a byte array.304*/305public byte[] getBytes() {306return address.clone();307}308309/**310* Compares this name with another, for equality.311*312* @return true iff the names are identical.313*/314public boolean equals(Object obj) {315if (this == obj)316return true;317318if (!(obj instanceof IPAddressName))319return false;320321IPAddressName otherName = (IPAddressName)obj;322byte[] other = otherName.address;323324if (other.length != address.length)325return false;326327if (address.length == 8 || address.length == 32) {328// Two subnet addresses329// Mask each and compare masked values330int maskLen = address.length/2;331for (int i=0; i < maskLen; i++) {332byte maskedThis = (byte)(address[i] & address[i+maskLen]);333byte maskedOther = (byte)(other[i] & other[i+maskLen]);334if (maskedThis != maskedOther) {335return false;336}337}338// Now compare masks339for (int i=maskLen; i < address.length; i++)340if (address[i] != other[i])341return false;342return true;343} else {344// Two IPv4 host addresses or two IPv6 host addresses345// Compare bytes346return Arrays.equals(other, address);347}348}349350/**351* Returns the hash code value for this object.352*353* @return a hash code value for this object.354*/355public int hashCode() {356int retval = 0;357358for (int i=0; i<address.length; i++)359retval += address[i] * i;360361return retval;362}363364/**365* Return type of constraint inputName places on this name:<ul>366* <li>NAME_DIFF_TYPE = -1: input name is different type from name367* (i.e. does not constrain).368* <li>NAME_MATCH = 0: input name matches name.369* <li>NAME_NARROWS = 1: input name narrows name (is lower in the naming370* subtree)371* <li>NAME_WIDENS = 2: input name widens name (is higher in the naming372* subtree)373* <li>NAME_SAME_TYPE = 3: input name does not match or narrow name, but374* is same type.375* </ul>. These results are used in checking NameConstraints during376* certification path verification.377* <p>378* [RFC 5280 4.2.1.10 Name Constraints]379* The syntax of iPAddress MUST be as described in Section 4.2.1.6 with380* the following additions specifically for name constraints. For IPv4381* addresses, the iPAddress field of GeneralName MUST contain eight (8)382* octets, encoded in the style of RFC 4632 (CIDR) to represent an383* address range [RFC 4632]. For IPv6 addresses, the iPAddress field384* MUST contain 32 octets similarly encoded. For example, a name385* constraint for "class C" subnet 192.0.2.0 is represented as the386* octets C0 00 02 00 FF FF FF 00, representing the CIDR notation387* 192.0.2.0/24 (mask 255.255.255.0).388*389* @param inputName to be checked for being constrained390* @return constraint type above391* @throws UnsupportedOperationException if name is not exact match, but392* narrowing and widening are not supported for this name type.393*/394public int constrains(GeneralNameInterface inputName)395throws UnsupportedOperationException {396int constraintType;397if (inputName == null)398constraintType = NAME_DIFF_TYPE;399else if (inputName.getType() != NAME_IP)400constraintType = NAME_DIFF_TYPE;401else if (((IPAddressName)inputName).equals(this))402constraintType = NAME_MATCH;403else {404IPAddressName otherName = (IPAddressName)inputName;405byte[] otherAddress = otherName.address;406if (otherAddress.length == 4 && address.length == 4)407// Two host addresses408constraintType = NAME_SAME_TYPE;409else if ((otherAddress.length == 8 && address.length == 8) ||410(otherAddress.length == 32 && address.length == 32)) {411// Two subnet addresses412// See if one address fully encloses the other address413boolean otherSubsetOfThis = true;414boolean thisSubsetOfOther = true;415boolean thisEmpty = false;416boolean otherEmpty = false;417int maskOffset = address.length/2;418for (int i=0; i < maskOffset; i++) {419if ((byte)(address[i] & address[i+maskOffset]) != address[i])420thisEmpty=true;421if ((byte)(otherAddress[i] & otherAddress[i+maskOffset]) != otherAddress[i])422otherEmpty=true;423if (!(((byte)(address[i+maskOffset] & otherAddress[i+maskOffset]) == address[i+maskOffset]) &&424((byte)(address[i] & address[i+maskOffset]) == (byte)(otherAddress[i] & address[i+maskOffset])))) {425otherSubsetOfThis = false;426}427if (!(((byte)(otherAddress[i+maskOffset] & address[i+maskOffset]) == otherAddress[i+maskOffset]) &&428((byte)(otherAddress[i] & otherAddress[i+maskOffset]) == (byte)(address[i] & otherAddress[i+maskOffset])))) {429thisSubsetOfOther = false;430}431}432if (thisEmpty || otherEmpty) {433if (thisEmpty && otherEmpty)434constraintType = NAME_MATCH;435else if (thisEmpty)436constraintType = NAME_WIDENS;437else438constraintType = NAME_NARROWS;439} else if (otherSubsetOfThis)440constraintType = NAME_NARROWS;441else if (thisSubsetOfOther)442constraintType = NAME_WIDENS;443else444constraintType = NAME_SAME_TYPE;445} else if (otherAddress.length == 8 || otherAddress.length == 32) {446//Other is a subnet, this is a host address447int i = 0;448int maskOffset = otherAddress.length/2;449for (; i < maskOffset; i++) {450// Mask this address by other address mask and compare to other address451// If all match, then this address is in other address subnet452if ((address[i] & otherAddress[i+maskOffset]) != otherAddress[i])453break;454}455if (i == maskOffset)456constraintType = NAME_WIDENS;457else458constraintType = NAME_SAME_TYPE;459} else if (address.length == 8 || address.length == 32) {460//This is a subnet, other is a host address461int i = 0;462int maskOffset = address.length/2;463for (; i < maskOffset; i++) {464// Mask other address by this address mask and compare to this address465if ((otherAddress[i] & address[i+maskOffset]) != address[i])466break;467}468if (i == maskOffset)469constraintType = NAME_NARROWS;470else471constraintType = NAME_SAME_TYPE;472} else {473constraintType = NAME_SAME_TYPE;474}475}476return constraintType;477}478479/**480* Return subtree depth of this name for purposes of determining481* NameConstraints minimum and maximum bounds and for calculating482* path lengths in name subtrees.483*484* @return distance of name from root485* @throws UnsupportedOperationException if not supported for this name type486*/487public int subtreeDepth() throws UnsupportedOperationException {488throw new UnsupportedOperationException489("subtreeDepth() not defined for IPAddressName");490}491}492493494