285. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:27 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

285.1 Files compared

# Location File Last Modified
1 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl X509KeyManagerImpl.java Mon Jan 22 14:46:54 2018 UTC
2 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl X509KeyManagerImpl.java Wed Sep 12 17:55:01 2018 UTC

285.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 1716
Changed 2 4
Inserted 0 0
Removed 0 0

285.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

285.4 Active regular expressions

No regular expressions were active.

285.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 4, 2017, O racle and/ or its aff iliates. A ll rights  reserved.
  3    * DO NOT  ALTER OR R EMOVE COPY RIGHT NOTI CES OR THI S FILE HEA DER.
  4    *
  5    * This co de is free  software;  you can r edistribut e it and/o r modify i t
  6    * under t he terms o f the GNU  General Pu blic Licen se version  2 only, a s
  7    * publish ed by the  Free Softw are Founda tion.  Ora cle design ates this
  8    * particu lar file a s subject  to the "Cl asspath" e xception a s provided
  9    * by Orac le in the  LICENSE fi le that ac companied  this code.
  10    *
  11    * This co de is dist ributed in  the hope  that it wi ll be usef ul, but WI THOUT
  12    * ANY WAR RANTY; wit hout even  the implie d warranty  of MERCHA NTABILITY  or
  13    * FITNESS  FOR A PAR TICULAR PU RPOSE.  Se e the GNU  General Pu blic Licen se
  14    * version  2 for mor e details  (a copy is  included  in the LIC ENSE file  that
  15    * accompa nied this  code).
  16    *
  17    * You sho uld have r eceived a  copy of th e GNU Gene ral Public  License v ersion
  18    * 2 along  with this  work; if  not, write  to the Fr ee Softwar e Foundati on,
  19    * Inc., 5 1 Franklin  St, Fifth  Floor, Bo ston, MA 0 2110-1301  USA.
  20    *
  21    * Please  contact Or acle, 500  Oracle Par kway, Redw ood Shores , CA 94065  USA
  22    * or visi t www.orac le.com if  you need a dditional  informatio n or have  any
  23    * questio ns.
  24    */
  25  
  26   package su n.security .ssl;
  27  
  28   import jav a.lang.ref .*;
  29   import jav a.util.*;
  30   import sta tic java.u til.Locale .ENGLISH;
  31   import jav a.util.con current.at omic.Atomi cLong;
  32   import jav a.net.Sock et;
  33  
  34   import jav a.security .*;
  35   import jav a.security .KeyStore. *;
  36   import jav a.security .cert.*;
  37   import jav a.security .cert.Cert ificate;
  38  
  39   import jav ax.net.ssl .*;
  40  
  41   import sun .security. provider.c ertpath.Al gorithmChe cker;
  42   import sun .security. validator. Validator;
  43  
  44   /**
  45    * The new  X509 key  manager im plementati on. The ma in differe nces to th e
  46    * old Sun X509 key m anager are :
  47    *  . it i s based ar ound the K eyStore.Bu ilder API.  This allo ws it to u se
  48    *    othe r forms of  KeyStore  protection  or passwo rd input ( e.g. a
  49    *    Call backHandle r) or to h ave keys w ithin one  KeyStore p rotected b y
  50    *    diff erent keys .
  51    *  . it c an use mul tiple KeyS tores at t he same ti me.
  52    *  . it i s explicit ly designe d to accom modate Key Stores tha t change o ver
  53    *    the  lifetime o f the proc ess.
  54    *  . it m akes an ef fort to ch oose the k ey that ma tches best , i.e. one  that
  55    *    is n ot expired  and has t he appropr iate certi ficate ext ensions.
  56    *
  57    * Note th at this co de is not  explicitly  performan ce optimzi ed yet.
  58    *
  59    * @author   Andreas  Sterbenz
  60    */
  61   final clas s X509KeyM anagerImpl  extends X 509Extende dKeyManage r
  62           im plements X 509KeyMana ger {
  63  
  64       privat e static f inal Debug  debug = D ebug.getIn stance("ss l");
  65  
  66       privat e static f inal boole an useDebu g =
  67                                 (d ebug != nu ll) && Deb ug.isOn("k eymanager" );
  68  
  69       // for  unit test ing only,  set via pr ivileged r eflection
  70       privat e static D ate verifi cationDate ;
  71  
  72       // lis t of the b uilders
  73       privat e final Li st<Builder > builders ;
  74  
  75       // cou nter to ge nerate uni que ids fo r the alia ses
  76       privat e final At omicLong u idCounter;
  77  
  78       // cac hed entrie s
  79       privat e final Ma p<String,R eference<P rivateKeyE ntry>> ent ryCacheMap ;
  80  
  81       X509Ke yManagerIm pl(Builder  builder)  {
  82           th is(Collect ions.singl etonList(b uilder));
  83       }
  84  
  85       X509Ke yManagerIm pl(List<Bu ilder> bui lders) {
  86           th is.builder s = builde rs;
  87           ui dCounter =  new Atomi cLong();
  88           en tryCacheMa p = Collec tions.sync hronizedMa p
  89                             (new S izedMap<St ring,Refer ence<Priva teKeyEntry >>());
  90       }
  91  
  92       // Lin kedHashMap  with a ma x size of  10
  93       // see  LinkedHas hMap JavaD ocs
  94       privat e static c lass Sized Map<K,V> e xtends Lin kedHashMap <K,V> {
  95           pr ivate stat ic final l ong serial VersionUID  = -821122 2668790986 062L;
  96  
  97           @O verride pr otected bo olean remo veEldestEn try(Map.En try<K,V> e ldest) {
  98                return s ize() > 10 ;
  99           }
  100       }
  101  
  102       //
  103       // pub lic method s
  104       //
  105  
  106       @Overr ide
  107       public  X509Certi ficate[] g etCertific ateChain(S tring alia s) {
  108           Pr ivateKeyEn try entry  = getEntry (alias);
  109           re turn entry  == null ?  null :
  110                    (X50 9Certifica te[])entry .getCertif icateChain ();
  111       }
  112  
  113       @Overr ide
  114       public  PrivateKe y getPriva teKey(Stri ng alias)  {
  115           Pr ivateKeyEn try entry  = getEntry (alias);
  116           re turn entry  == null ?  null : en try.getPri vateKey();
  117       }
  118  
  119       @Overr ide
  120       public  String ch ooseClient Alias(Stri ng[] keyTy pes, Princ ipal[] iss uers,
  121                Socket s ocket) {
  122           re turn choos eAlias(get KeyTypes(k eyTypes),  issuers, C heckType.C LIENT,
  123                             getAlg orithmCons traints(so cket));
  124       }
  125  
  126       @Overr ide
  127       public  String ch ooseEngine ClientAlia s(String[]  keyTypes,
  128                Principa l[] issuer s, SSLEngi ne engine)  {
  129           re turn choos eAlias(get KeyTypes(k eyTypes),  issuers, C heckType.C LIENT,
  130                             getAlg orithmCons traints(en gine));
  131       }
  132  
  133       @Overr ide
  134       public  String ch ooseServer Alias(Stri ng keyType ,
  135                Principa l[] issuer s, Socket  socket) {
  136           re turn choos eAlias(get KeyTypes(k eyType), i ssuers, Ch eckType.SE RVER,
  137                getAlgor ithmConstr aints(sock et),
  138                X509Trus tManagerIm pl.getRequ estedServe rNames(soc ket),
  139                "HTTPS") ;    // Th e SNI Host Name is a  fully qual ified doma in name.
  140                              // Th e certific ate select ion scheme  for SNI H ostName
  141                              // is  similar t o HTTPS en dpoint ide ntificatio n scheme
  142                              // im plemented  in this pr ovider.
  143                              //
  144                              // Us ing HTTPS  endpoint i dentificat ion scheme  to guide
  145                              // th e selectio n of an ap propriate  authentica tion
  146                              // ce rtificate  according  to request ed SNI ext ension.
  147                              //
  148                              // It  is not a  really HTT PS endpoin t identifi cation.
  149       }
  150  
  151       @Overr ide
  152       public  String ch ooseEngine ServerAlia s(String k eyType,
  153                Principa l[] issuer s, SSLEngi ne engine)  {
  154           re turn choos eAlias(get KeyTypes(k eyType), i ssuers, Ch eckType.SE RVER,
  155                getAlgor ithmConstr aints(engi ne),
  156                X509Trus tManagerIm pl.getRequ estedServe rNames(eng ine),
  157                "HTTPS") ;    // Th e SNI Host Name is a  fully qual ified doma in name.
  158                              // Th e certific ate select ion scheme  for SNI H ostName
  159                              // is  similar t o HTTPS en dpoint ide ntificatio n scheme
  160                              // im plemented  in this pr ovider.
  161                              //
  162                              // Us ing HTTPS  endpoint i dentificat ion scheme  to guide
  163                              // th e selectio n of an ap propriate  authentica tion
  164                              // ce rtificate  according  to request ed SNI ext ension.
  165                              //
  166                              // It  is not a  really HTT PS endpoin t identifi cation.
  167       }
  168  
  169       @Overr ide
  170       public  String[]  getClientA liases(Str ing keyTyp e, Princip al[] issue rs) {
  171           re turn getAl iases(keyT ype, issue rs, CheckT ype.CLIENT , null);
  172       }
  173  
  174       @Overr ide
  175       public  String[]  getServerA liases(Str ing keyTyp e, Princip al[] issue rs) {
  176           re turn getAl iases(keyT ype, issue rs, CheckT ype.SERVER , null);
  177       }
  178  
  179       //
  180       // imp lementatio n private  methods
  181       //
  182  
  183       // Get s algorith m constrai nts of the  socket.
  184       privat e Algorith mConstrain ts getAlgo rithmConst raints(Soc ket socket ) {
  185           if  (socket ! = null &&  socket.isC onnected()  &&
  186                                               socket ins tanceof SS LSocket) {
  187  
  188                SSLSocke t sslSocke t = (SSLSo cket)socke t;
  189                SSLSessi on session  = sslSock et.getHand shakeSessi on();
  190  
  191                if (sess ion != nul l) {
  192                    Prot ocolVersio n protocol Version =
  193                         ProtocolVe rsion.valu eOf(sessio n.getProto col());
  194                    if ( protocolVe rsion.v >=  ProtocolV ersion.TLS 12.v) {
  195                         String[] p eerSupport edSignAlgs  = null;
  196  
  197                         if (sessio n instance of Extende dSSLSessio n) {
  198                             Extend edSSLSessi on extSess ion =
  199                                 (E xtendedSSL Session)se ssion;
  200                             peerSu pportedSig nAlgs =
  201                                 ex tSession.g etPeerSupp ortedSigna tureAlgori thms();
  202                         }
  203  
  204                         return new  SSLAlgori thmConstra ints(
  205                             sslSoc ket, peerS upportedSi gnAlgs, tr ue);
  206                    }
  207                }
  208  
  209                return n ew SSLAlgo rithmConst raints(ssl Socket, tr ue);
  210           }
  211  
  212           re turn new S SLAlgorith mConstrain ts((SSLSoc ket)null,  true);
  213       }
  214  
  215       // Get s algorith m constrai nts of the  engine.
  216       privat e Algorith mConstrain ts getAlgo rithmConst raints(SSL Engine eng ine) {
  217           if  (engine ! = null) {
  218                SSLSessi on session  = engine. getHandsha keSession( );
  219                if (sess ion != nul l) {
  220                    Prot ocolVersio n protocol Version =
  221                         ProtocolVe rsion.valu eOf(sessio n.getProto col());
  222                    if ( protocolVe rsion.v >=  ProtocolV ersion.TLS 12.v) {
  223                         String[] p eerSupport edSignAlgs  = null;
  224  
  225                         if (sessio n instance of Extende dSSLSessio n) {
  226                             Extend edSSLSessi on extSess ion =
  227                                 (E xtendedSSL Session)se ssion;
  228                             peerSu pportedSig nAlgs =
  229                                 ex tSession.g etPeerSupp ortedSigna tureAlgori thms();
  230                         }
  231  
  232                         return new  SSLAlgori thmConstra ints(
  233                             engine , peerSupp ortedSignA lgs, true) ;
  234                    }
  235                }
  236           }
  237  
  238           re turn new S SLAlgorith mConstrain ts(engine,  true);
  239       }
  240  
  241       // we  construct  the alias  we return  to JSSE as  seen in t he code be low
  242       // a u nique id i s included  to allow  us to reli ably cache  entries
  243       // bet ween the c alls to ge tCertifica teChain()  and getPri vateKey()
  244       // eve n if token s are inse rted or re moved
  245       privat e String m akeAlias(E ntryStatus  entry) {
  246           re turn uidCo unter.incr ementAndGe t() + "."  + entry.bu ilderIndex  + "."
  247                    + en try.alias;
  248       }
  249  
  250       privat e PrivateK eyEntry ge tEntry(Str ing alias)  {
  251           //  if the al ias is nul l, return  immediatel y
  252           if  (alias ==  null) {
  253                return n ull;
  254           }
  255  
  256           //  try to ge t the entr y from cac he
  257           Re ference<Pr ivateKeyEn try> ref =  entryCach eMap.get(a lias);
  258           Pr ivateKeyEn try entry  = (ref !=  null) ? re f.get() :  null;
  259           if  (entry !=  null) {
  260                return e ntry;
  261           }
  262  
  263           //  parse the  alias
  264           in t firstDot  = alias.i ndexOf('.' );
  265           in t secondDo t = alias. indexOf('. ', firstDo t + 1);
  266           if  ((firstDo t == -1) | | (secondD ot == firs tDot)) {
  267                // inval id alias
  268                return n ull;
  269           }
  270           tr y {
  271                int buil derIndex =  Integer.p arseInt
  272                                      (alias.s ubstring(f irstDot +  1, secondD ot));
  273                String k eyStoreAli as = alias .substring (secondDot  + 1);
  274                Builder  builder =  builders.g et(builder Index);
  275                KeyStore  ks = buil der.getKey Store();
  276                Entry ne wEntry = k s.getEntry
  277                         (keyStoreA lias, buil der.getPro tectionPar ameter(ali as));
  278                if (newE ntry insta nceof Priv ateKeyEntr y == false ) {
  279                    // u nexpected  type of en try
  280                    retu rn null;
  281                }
  282                entry =  (PrivateKe yEntry)new Entry;
  283                entryCac heMap.put( alias, new  SoftRefer ence<Priva teKeyEntry >(entry));
  284                return e ntry;
  285           }  catch (Exc eption e)  {
  286                // ignor e
  287                return n ull;
  288           }
  289       }
  290  
  291       // Cla ss to help  verify th at the pub lic key al gorithm (a nd optiona lly
  292       // the  signature  algorithm ) of a cer tificate m atches wha t we need.
  293       privat e static c lass KeyTy pe {
  294  
  295           fi nal String  keyAlgori thm;
  296  
  297           //  In TLS 1. 2, the sig nature alg orithm  ha s been obs oleted by  the
  298           //  supported _signature _algorithm s, and the  certifica te type no  longer
  299           //  restricts  the algor ithm used  to sign th e certific ate.
  300           //  However,  because we  don't sup port certi ficate typ e checking  other
  301           //  than rsa_ sign, dss_ sign and e cdsa_sign,  we don't  have to ch eck the
  302           //  protocol  version he re.
  303           fi nal String  sigKeyAlg orithm;
  304  
  305           Ke yType(Stri ng algorit hm) {
  306                int k =  algorithm. indexOf("_ ");
  307                if (k ==  -1) {
  308                    keyA lgorithm =  algorithm ;
  309                    sigK eyAlgorith m = null;
  310                } else {
  311                    keyA lgorithm =  algorithm .substring (0, k);
  312                    sigK eyAlgorith m = algori thm.substr ing(k + 1) ;
  313                }
  314           }
  315  
  316           bo olean matc hes(Certif icate[] ch ain) {
  317                if (!cha in[0].getP ublicKey() .getAlgori thm().equa ls(keyAlgo rithm)) {
  318                    retu rn false;
  319                }
  320                if (sigK eyAlgorith m == null)  {
  321                    retu rn true;
  322                }
  323                if (chai n.length >  1) {
  324                    // i f possible , check th e public k ey in the  issuer cer t
  325                    retu rn sigKeyA lgorithm.e quals(
  326                             chain[ 1].getPubl icKey().ge tAlgorithm ());
  327                } else {
  328                    // C heck the s ignature a lgorithm o f the cert ificate it self.
  329                    // L ook for th e "withRSA " in "SHA1 withRSA",  etc.
  330                    X509 Certificat e issuer =  (X509Cert ificate)ch ain[0];
  331                    Stri ng sigAlgN ame = issu er.getSigA lgName().t oUpperCase (ENGLISH);
  332                    Stri ng pattern  = "WITH"  + sigKeyAl gorithm.to UpperCase( ENGLISH);
  333                    retu rn sigAlgN ame.contai ns(pattern );
  334                }
  335           }
  336       }
  337  
  338       privat e static L ist<KeyTyp e> getKeyT ypes(Strin g ... keyT ypes) {
  339           if  ((keyType s == null)  ||
  340                    (key Types.leng th == 0) | | (keyType s[0] == nu ll)) {
  341                return n ull;
  342           }
  343           Li st<KeyType > list = n ew ArrayLi st<>(keyTy pes.length );
  344           fo r (String  keyType :  keyTypes)  {
  345                list.add (new KeyTy pe(keyType ));
  346           }
  347           re turn list;
  348       }
  349  
  350       /*
  351        * Ret urn the be st alias t hat fits t he given p arameters.
  352        * The  algorithm  we use is :
  353        *   .  scan thro ugh all th e aliases  in all bui lders in o rder
  354        *   .  as soon a s we find  a perfect  match, ret urn
  355        *      (i.e. a m atch with  a cert tha t has appr opriate ke y usage,
  356        *       qualifie d endpoint  identity,  and is no t expired) .
  357        *   .  if we do  not find a  perfect m atch, keep  looping a nd remembe r
  358        *      the imper fect match es
  359        *   .  at the en d, sort th e imperfec t matches.  we prefer  expired c erts
  360        *      with appr opriate ke y usage to  certs wit h the wron g key usag e.
  361        *      return th e first on e of them.
  362        */
  363       privat e String c hooseAlias (List<KeyT ype> keyTy peList, Pr incipal[]  issuers,
  364                CheckTyp e checkTyp e, Algorit hmConstrai nts constr aints) {
  365  
  366           re turn choos eAlias(key TypeList,  issuers,
  367                                          chec kType, con straints,  null, null );
  368       }
  369  
  370       privat e String c hooseAlias (List<KeyT ype> keyTy peList, Pr incipal[]  issuers,
  371                CheckTyp e checkTyp e, Algorit hmConstrai nts constr aints,
  372                List<SNI ServerName > requeste dServerNam es, String  idAlgorit hm) {
  373  
  374           if  (keyTypeL ist == nul l || keyTy peList.isE mpty()) {
  375                return n ull;
  376           }
  377  
  378           Se t<Principa l> issuerS et = getIs suerSet(is suers);
  379           Li st<EntrySt atus> allR esults = n ull;
  380           fo r (int i =  0, n = bu ilders.siz e(); i < n ; i++) {
  381                try {
  382                    List <EntryStat us> result s = getAli ases(i, ke yTypeList,
  383                                 is suerSet, f alse, chec kType, con straints,
  384                                 re questedSer verNames,  idAlgorith m);
  385                    if ( results !=  null) {
  386                         // the res ults will  either be  a single p erfect mat ch
  387                         // or 1 or  more impe rfect matc hes
  388                         // if it's  a perfect  match, re turn immed iately
  389                         EntryStatu s status =  results.g et(0);
  390                         if (status .checkResu lt == Chec kResult.OK ) {
  391                             if (us eDebug) {
  392                                 de bug.printl n("KeyMgr:  choosing  key: " + s tatus);
  393                             }
  394                             return  makeAlias (status);
  395                         }
  396                         if (allRes ults == nu ll) {
  397                             allRes ults = new  ArrayList <EntryStat us>();
  398                         }
  399                         allResults .addAll(re sults);
  400                    }
  401                } catch  (Exception  e) {
  402                    // i gnore
  403                }
  404           }
  405           if  (allResul ts == null ) {
  406                if (useD ebug) {
  407                    debu g.println( "KeyMgr: n o matching  key found ");
  408                }
  409                return n ull;
  410           }
  411           Co llections. sort(allRe sults);
  412           if  (useDebug ) {
  413                debug.pr intln("Key Mgr: no go od matchin g key foun d, "
  414                             + "ret urning bes t match ou t of:");
  415                debug.pr intln(allR esults.toS tring());
  416           }
  417           re turn makeA lias(allRe sults.get( 0));
  418       }
  419  
  420       /*
  421        * Ret urn all al iases that  (approxim ately) fit  the param eters.
  422        * The se are per fect match es plus im perfect ma tches (exp ired certi ficates
  423        * and  certifica tes with t he wrong e xtensions) .
  424        * The  perfect m atches wil l be first  in the ar ray.
  425        */
  426       public  String[]  getAliases (String ke yType, Pri ncipal[] i ssuers,
  427                CheckTyp e checkTyp e, Algorit hmConstrai nts constr aints) {
  428           if  (keyType  == null) {
  429                return n ull;
  430           }
  431  
  432           Se t<Principa l> issuerS et = getIs suerSet(is suers);
  433           Li st<KeyType > keyTypeL ist = getK eyTypes(ke yType);
  434           Li st<EntrySt atus> allR esults = n ull;
  435           fo r (int i =  0, n = bu ilders.siz e(); i < n ; i++) {
  436                try {
  437                    List <EntryStat us> result s = getAli ases(i, ke yTypeList,
  438                                          issu erSet, tru e, checkTy pe, constr aints,
  439                                          null , null);
  440                    if ( results !=  null) {
  441                         if (allRes ults == nu ll) {
  442                             allRes ults = new  ArrayList <EntryStat us>();
  443                         }
  444                         allResults .addAll(re sults);
  445                    }
  446                } catch  (Exception  e) {
  447                    // i gnore
  448                }
  449           }
  450           if  (allResul ts == null  || allRes ults.isEmp ty()) {
  451                if (useD ebug) {
  452                    debu g.println( "KeyMgr: n o matching  alias fou nd");
  453                }
  454                return n ull;
  455           }
  456           Co llections. sort(allRe sults);
  457           if  (useDebug ) {
  458                debug.pr intln("Key Mgr: getti ng aliases : " + allR esults);
  459           }
  460           re turn toAli ases(allRe sults);
  461       }
  462  
  463       // tur n candidat e entries  into uniqu e aliases  we can ret urn to JSS E
  464       privat e String[]  toAliases (List<Entr yStatus> r esults) {
  465           St ring[] s =  new Strin g[results. size()];
  466           in t i = 0;
  467           fo r (EntrySt atus resul t : result s) {
  468                s[i++] =  makeAlias (result);
  469           }
  470           re turn s;
  471       }
  472  
  473       // mak e a Set ou t of the a rray
  474       privat e Set<Prin cipal> get IssuerSet( Principal[ ] issuers)  {
  475           if  ((issuers  != null)  && (issuer s.length ! = 0)) {
  476                return n ew HashSet <>(Arrays. asList(iss uers));
  477           }  else {
  478                return n ull;
  479           }
  480       }
  481  
  482       // a c andidate m atch
  483       // ide ntifies th e entry by  builder a nd alias
  484       // and  includes  the result  of the ce rtificate  check
  485       privat e static c lass Entry Status imp lements Co mparable<E ntryStatus > {
  486  
  487           fi nal int bu ilderIndex ;
  488           fi nal int ke yIndex;
  489           fi nal String  alias;
  490           fi nal CheckR esult chec kResult;
  491  
  492           En tryStatus( int builde rIndex, in t keyIndex , String a lias,
  493                    Cert ificate[]  chain, Che ckResult c heckResult ) {
  494                this.bui lderIndex  = builderI ndex;
  495                this.key Index = ke yIndex;
  496                this.ali as = alias ;
  497                this.che ckResult =  checkResu lt;
  498           }
  499  
  500           @O verride
  501           pu blic int c ompareTo(E ntryStatus  other) {
  502                int resu lt = this. checkResul t.compareT o(other.ch eckResult) ;
  503                return ( result ==  0) ? (this .keyIndex  - other.ke yIndex) :  result;
  504           }
  505  
  506           @O verride
  507           pu blic Strin g toString () {
  508                String s  = alias +  " (verifi ed: " + ch eckResult  + ")";
  509                if (buil derIndex = = 0) {
  510                    retu rn s;
  511                } else {
  512                    retu rn "Builde r #" + bui lderIndex  + ", alias : " + s;
  513                }
  514           }
  515       }
  516  
  517       // enu m for the  type of ce rtificate  check we w ant to per form
  518       // (cl ient or se rver)
  519       // als o includes  the check  code itse lf
  520       privat e static e num CheckT ype {
  521  
  522           //  enum cons tant for " no check"  (currently  not used)
  523           NO NE(Collect ions.<Stri ng>emptySe t()),
  524  
  525           //  enum cons tant for " tls client " check
  526           //  valid EKU  for TLS c lient: any , tls_clie nt
  527           CL IENT(new H ashSet<Str ing>(Array s.asList(n ew String[ ] {
  528                "2.5.29. 37.0", "1. 3.6.1.5.5. 7.3.2" })) ),
  529  
  530           //  enum cons tant for " tls server " check
  531           //  valid EKU  for TLS s erver: any , tls_serv er, ns_sgc , ms_sgc
  532           SE RVER(new H ashSet<Str ing>(Array s.asList(n ew String[ ] {
  533                "2.5.29. 37.0", "1. 3.6.1.5.5. 7.3.1", "2 .16.840.1. 113730.4.1 ",
  534                "1.3.6.1 .4.1.311.1 0.3.3" })) );
  535  
  536           //  set of va lid EKU va lues for t his type
  537           fi nal Set<St ring> vali dEku;
  538  
  539           Ch eckType(Se t<String>  validEku)  {
  540                this.val idEku = va lidEku;
  541           }
  542  
  543           pr ivate stat ic boolean  getBit(bo olean[] ke yUsage, in t bit) {
  544                return ( bit < keyU sage.lengt h) && keyU sage[bit];
  545           }
  546  
  547           //  check if  this certi ficate is  appropriat e for this  type of u se
  548           //  first che ck extensi ons, if th ey match,  check expi ration
  549           //  note: we  may want t o move thi s code int o the sun. security.v alidator
  550           //  package
  551           Ch eckResult  check(X509 Certificat e cert, Da te date,
  552                    List <SNIServer Name> serv erNames, S tring idAl gorithm) {
  553  
  554                if (this  == NONE)  {
  555                    retu rn CheckRe sult.OK;
  556                }
  557  
  558                // check  extension s
  559                try {
  560                    // c heck exten ded key us age
  561                    List <String> c ertEku = c ert.getExt endedKeyUs age();
  562                    if ( (certEku ! = null) &&
  563                             Collec tions.disj oint(valid Eku, certE ku)) {
  564                         // if exte nsion pres ent and it  does not  contain an y of
  565                         // the val id EKU OID s, return  extension_ mismatch
  566                         return Che ckResult.E XTENSION_M ISMATCH;
  567                    }
  568  
  569                    // c heck key u sage
  570                    bool ean[] ku =  cert.getK eyUsage();
  571                    if ( ku != null ) {
  572                         String alg orithm = c ert.getPub licKey().g etAlgorith m();
  573                         boolean ku Signature  = getBit(k u, 0);
  574                         switch (al gorithm) {
  575                             case " RSA":
  576                                 //  require e ither sign ature bit
  577                                 //  or if ser ver also a llow key e nciphermen t bit
  578                                 if  (kuSignat ure == fal se) {
  579                                      if ((thi s == CLIEN T) || (get Bit(ku, 2)  == false) ) {
  580                                          retu rn CheckRe sult.EXTEN SION_MISMA TCH;
  581                                      }
  582                                 }
  583                                 br eak;
  584                             case " DSA":
  585                                 //  require s ignature b it
  586                                 if  (kuSignat ure == fal se) {
  587                                      return C heckResult .EXTENSION _MISMATCH;
  588                                 }
  589                                 br eak;
  590                             case " DH":
  591                                 //  require k eyagreemen t bit
  592                                 if  (getBit(k u, 4) == f alse) {
  593                                      return C heckResult .EXTENSION _MISMATCH;
  594                                 }
  595                                 br eak;
  596                             case " EC":
  597                                 //  require s ignature b it
  598                                 if  (kuSignat ure == fal se) {
  599                                      return C heckResult .EXTENSION _MISMATCH;
  600                                 }
  601                                 //  For serve rs, also r equire key  agreement .
  602                                 //  This is n ot totally  accurate  as the key Agreement
  603                                 //  bit is on ly necessa ry for sta tic ECDH k ey
  604                                 //  exchange  and not ep hemeral EC DH. We lea ve it in
  605                                 //  for now u ntil there  are signs  that this  check
  606                                 //  causes pr oblems for  real worl d EC certi ficates.
  607                                 if  ((this ==  SERVER) & & (getBit( ku, 4) ==  false)) {
  608                                      return C heckResult .EXTENSION _MISMATCH;
  609                                 }
  610                                 br eak;
  611                         }
  612                    }
  613                } catch  (Certifica teExceptio n e) {
  614                    // e xtensions  unparseabl e, return  failure
  615                    retu rn CheckRe sult.EXTEN SION_MISMA TCH;
  616                }
  617  
  618                try {
  619                    cert .checkVali dity(date) ;
  620                } catch  (Certifica teExceptio n e) {
  621                    retu rn CheckRe sult.EXPIR ED;
  622                }
  623  
  624                if (serv erNames !=  null && ! serverName s.isEmpty( )) {
  625                    for  (SNIServer Name serve rName : se rverNames)  {
  626                         if (server Name.getTy pe() ==
  627                                      Standard Constants. SNI_HOST_N AME) {
  628                             if (!( serverName  instanceo f SNIHostN ame)) {
  629                                 tr y {
  630                                      serverNa me =
  631                                          new  SNIHostNam e(serverNa me.getEnco ded());
  632                                 }  catch (Ill egalArgume ntExceptio n iae) {
  633                                      // unlik ely to hap pen, just  in case .. .
  634                                      if (useD ebug) {
  635                                          debu g.println(
  636                                             " Illegal se rver name:  " + serve rName);
  637                                      }
  638  
  639                                      return C heckResult .INSENSITI VE;
  640                                 }
  641                             }
  642                             String  hostname  =
  643                                      ((SNIHos tName)serv erName).ge tAsciiName ();
  644  
  645                             try {
  646                                 X5 09TrustMan agerImpl.c heckIdenti ty(hostnam e,
  647                                                                cert , idAlgori thm);
  648                             } catc h (Certifi cateExcept ion e) {
  649                                 if  (useDebug ) {
  650                                      debug.pr intln(
  651                                         "Cert ificate id entity doe s not matc h " +
  652                                         "Serv er Name In idication  (SNI): " +
  653                                         hostn ame);
  654                                 }
  655                                 re turn Check Result.INS ENSITIVE;
  656                             }
  657  
  658                             break;
  659                         }
  660                    }
  661                }
  662  
  663                return C heckResult .OK;
  664           }
  665  
  666           pu blic Strin g getValid ator() {
  667                if (this  == CLIENT ) {
  668                    retu rn Validat or.VAR_TLS _CLIENT;
  669                } else i f (this ==  SERVER) {
  670                    retu rn Validat or.VAR_TLS _SERVER;
  671                }
  672                return V alidator.V AR_GENERIC ;
  673           }
  674       }
  675  
  676       // enu m for the  result of  the extens ion check
  677       // NOT E: the ord er of the  constants  is importa nt as they  are used
  678       // for  sorting,  i.e. OK is  best, fol lowed by E XPIRED and  EXTENSION _MISMATCH
  679       privat e static e num CheckR esult {
  680           OK ,                       // ok or  not check ed
  681           IN SENSITIVE,              // serve r name ind ication in sensitive
  682           EX PIRED,                  // exten sions vali d but cert  expired
  683           EX TENSION_MI SMATCH,      // exten sions inva lid (expir ation not  checked)
  684       }
  685  
  686       /*
  687        * Ret urn a List  of all ca ndidate ma tches in t he specifi ed builder
  688        * tha t fit the  parameters .
  689        * We  exclude en tries in t he KeyStor e if they  are not:
  690        *  .  private ke y entries
  691        *  .  the certif icates are  not X509  certificat es
  692        *  .  the algori thm of the  key in th e EE cert  doesn't ma tch one of  keyTypes
  693        *  .  none of th e certs is  issued by  a Princip al in issu erSet
  694        * Usi ng those e ntries wou ld not be  possible o r they wou ld almost
  695        * cer tainly be  rejected b y the peer .
  696        *
  697        * In  addition t o those ch ecks, we a lso check  the extens ions in th e EE
  698        * cer t and its  expiration . Even if  there is a  mismatch,  we includ e
  699        * suc h certific ates becau se they te chnically  work and m ight be ac cepted
  700        * by  the peer.  This leads  to more g raceful fa ilure and  better err or
  701        * mes sages if t he cert ex pires from  one day t o the next .
  702        *
  703        * The  return va lues are:
  704        *   .  null, if  there are  no matchin g entries  at all
  705        *   .  if 'findA ll' is 'fa lse' and t here is a  perfect ma tch, a Lis t
  706        *      with a si ngle eleme nt (early  return)
  707        *   .  if 'findA ll' is 'fa lse' and t here is NO  perfect m atch, a Li st
  708        *      with all  the imperf ect matche s (expired , wrong ex tensions)
  709        *   .  if 'findA ll' is 'tr ue', a Lis t with all  perfect a nd imperfe ct
  710        *      matches
  711        */
  712       privat e List<Ent ryStatus>  getAliases (int build erIndex,
  713                List<Key Type> keyT ypes, Set< Principal>  issuerSet ,
  714                boolean  findAll, C heckType c heckType,
  715                Algorith mConstrain ts constra ints,
  716                List<SNI ServerName > requeste dServerNam es,
  717                String i dAlgorithm ) throws E xception {
  718  
  719           Bu ilder buil der = buil ders.get(b uilderInde x);
  720           Ke yStore ks  = builder. getKeyStor e();
  721           Li st<EntrySt atus> resu lts = null ;
  722           Da te date =  verificati onDate;
  723           bo olean pref erred = fa lse;
  724           fo r (Enumera tion<Strin g> e = ks. aliases();  e.hasMore Elements() ; ) {
  725                String a lias = e.n extElement ();
  726                  // check i f it is a  key entry  (private k ey or  PW        key)
  727                if (ks.i sKeyEntry( alias) ==  false) {
  728                    cont inue;
  729                }
  730  
  731                Certific ate[] chai n = ks.get Certificat eChain(ali as);
  732                if ((cha in == null ) || (chai n.length = = 0)) {
  733                      // must be   PW        key entry,  ignore
  734                    cont inue;
  735                }
  736  
  737                boolean  incompatib le = false ;
  738                for (Cer tificate c ert : chai n) {
  739                    if ( cert insta nceof X509 Certificat e == false ) {
  740                         // not an  X509Certif icate, ign ore this a lias
  741                         incompatib le = true;
  742                         break;
  743                    }
  744                }
  745                if (inco mpatible)  {
  746                    cont inue;
  747                }
  748  
  749                // check  keytype
  750                int keyI ndex = -1;
  751                int j =  0;
  752                for (Key Type keyTy pe : keyTy pes) {
  753                    if ( keyType.ma tches(chai n)) {
  754                         keyIndex =  j;
  755                         break;
  756                    }
  757                    j++;
  758                }
  759                if (keyI ndex == -1 ) {
  760                    if ( useDebug)  {
  761                         debug.prin tln("Ignor ing alias  " + alias
  762                                      + ": key  algorithm  does not  match");
  763                    }
  764                    cont inue;
  765                }
  766                // check  issuers
  767                if (issu erSet != n ull) {
  768                    bool ean found  = false;
  769                    for  (Certifica te cert :  chain) {
  770                         X509Certif icate xcer t = (X509C ertificate )cert;
  771                         if (issuer Set.contai ns(xcert.g etIssuerX5 00Principa l())) {
  772                             found  = true;
  773                             break;
  774                         }
  775                    }
  776                    if ( found == f alse) {
  777                         if (useDeb ug) {
  778                             debug. println("I gnoring al ias " + al ias
  779                                          + ":  issuers d o not matc h");
  780                         }
  781                         continue;
  782                    }
  783                }
  784  
  785                // check  the algor ithm const raints
  786                if (cons traints !=  null &&
  787                         !conformsT oAlgorithm Constraint s(constrai nts, chain ,
  788                                 ch eckType.ge tValidator ())) {
  789  
  790                    if ( useDebug)  {
  791                         debug.prin tln("Ignor ing alias  " + alias  +
  792                                 ":  certifica te list do es not con form to "  +
  793                                 "a lgorithm c onstraints ");
  794                    }
  795                    cont inue;
  796                }
  797  
  798                if (date  == null)  {
  799                    date  = new Dat e();
  800                }
  801                CheckRes ult checkR esult =
  802                         checkType. check((X50 9Certifica te)chain[0 ], date,
  803                                          requ estedServe rNames, id Algorithm) ;
  804                EntrySta tus status  =
  805                         new EntryS tatus(buil derIndex,  keyIndex,
  806                                               alias, cha in, checkR esult);
  807                if (!pre ferred &&  checkResul t == Check Result.OK  && keyInde x == 0) {
  808                    pref erred = tr ue;
  809                }
  810                if (pref erred && ( findAll ==  false)) {
  811                    // i f we have  a good mat ch and do  not need a ll matches ,
  812                    // r eturn imme diately
  813                    retu rn Collect ions.singl etonList(s tatus);
  814                } else {
  815                    if ( results ==  null) {
  816                         results =  new ArrayL ist<EntryS tatus>();
  817                    }
  818                    resu lts.add(st atus);
  819                }
  820           }
  821           re turn resul ts;
  822       }
  823  
  824       privat e static b oolean con formsToAlg orithmCons traints(
  825                Algorith mConstrain ts constra ints, Cert ificate[]  chain,
  826                String v ariant) {
  827  
  828           Al gorithmChe cker check er = new A lgorithmCh ecker(cons traints, n ull, varia nt);
  829           tr y {
  830                checker. init(false );
  831           }  catch (Cer tPathValid atorExcept ion cpve)  {
  832                // unlik ely to hap pen
  833                if (useD ebug) {
  834                    debu g.println(
  835                         "Cannot in itialize a lgorithm c onstraints  checker:  " + cpve);
  836                }
  837  
  838                return f alse;
  839           }
  840  
  841           //  It is a f orward che cker, so w e need to  check from  trust to  target.
  842           fo r (int i =  chain.len gth - 1; i  >= 0; i-- ) {
  843                Certific ate cert =  chain[i];
  844                try {
  845                    // W e don't ca re about t he unresol ved critic al extensi ons.
  846                    chec ker.check( cert, Coll ections.<S tring>empt ySet());
  847                } catch  (CertPathV alidatorEx ception cp ve) {
  848                    if ( useDebug)  {
  849                         debug.prin tln("Certi ficate ("  + cert +
  850                             ") doe s not conf orm to alg orithm con straints:  " + cpve);
  851                    }
  852  
  853                    retu rn false;
  854                }
  855           }
  856  
  857           re turn true;
  858       }
  859  
  860   }