281. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:26 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.

281.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 ServerHandshaker.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 ServerHandshaker.java Wed Sep 12 17:54:56 2018 UTC

281.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 15 3944
Changed 14 28
Inserted 0 0
Removed 0 0

281.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

281.4 Active regular expressions

No regular expressions were active.

281.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 199 6, 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  
  27   package su n.security .ssl;
  28  
  29   import jav a.io.*;
  30   import jav a.util.*;
  31   import jav a.security .*;
  32   import jav a.security .cert.*;
  33   import jav a.security .interface s.*;
  34   import jav a.security .spec.ECPa rameterSpe c;
  35   import jav a.math.Big Integer;
  36  
  37   import jav ax.crypto. SecretKey;
  38   import jav ax.crypto. spec.Secre tKeySpec;
  39  
  40   import jav ax.net.ssl .*;
  41  
  42   import jav ax.securit y.auth.Sub ject;
  43  
  44   import sun .security. util.KeyUt il;
  45   import sun .security. util.Legac yAlgorithm Constraint s;
  46   import sun .security. action.Get PropertyAc tion;
  47   import sun .security. ssl.Handsh akeMessage .*;
  48   import sun .security. ssl.Cipher Suite.*;
  49   import sun .security. ssl.Signat ureAndHash Algorithm. *;
  50   import sta tic sun.se curity.ssl .CipherSui te.KeyExch ange.*;
  51  
  52   /**
  53    * ServerH andshaker  does the p rotocol ha ndshaking  from the p oint
  54    * of view  of a serv er.  It is  driven as ychronousl y by hands hake messa ges
  55    * as deli vered by t he parent  Handshaker  class, an d also use s
  56    * common  functional ity (e.g.  key genera tion) that  is provid ed there.
  57    *
  58    * @author  David Bro wnell
  59    */
  60   final clas s ServerHa ndshaker e xtends Han dshaker {
  61  
  62       // is  the server  going to  require th e client t o authenti cate?
  63       privat e byte                  doClient Auth;
  64  
  65       // our  authentic ation info
  66       privat e X509Cert ificate[]    certs;
  67       privat e PrivateK ey           privateK ey;
  68  
  69       privat e Object                serviceC reds;
  70  
  71       // fla g to check  for clien tCertifica teVerify m essage
  72       privat e boolean               needClie ntVerify =  false;
  73  
  74       /*
  75        * For  exportabl e ciphersu ites using  non-expor table key  sizes, we  use
  76        * eph emeral RSA  keys. We  could also  do anonym ous RSA in  the same  way
  77        * but  there are  no such c iphersuite s currentl y defined.
  78        */
  79       privat e PrivateK ey           tempPriv ateKey;
  80       privat e PublicKe y            tempPubl icKey;
  81  
  82       /*
  83        * For  anonymous  and ephem eral Diffi e-Hellman  key exchan ge, we use
  84        * eph emeral Dif fie-Hellma n keys.
  85        */
  86       privat e DHCrypt  dh;
  87  
  88       // Hel per for EC DH based k ey exchang es
  89       privat e ECDHCryp t ecdh;
  90  
  91       // ver sion reque st by the  client in  its Client Hello
  92         // we reme mber it fo r the RSA  premaster  PW        version ch eck
  93       privat e Protocol Version cl ientReques tedVersion ;
  94  
  95       // cli ent suppor ted ellipt ic curves
  96       privat e Elliptic CurvesExte nsion requ estedCurve s;
  97  
  98       // the  preferabl e signatur e algorith m used by  ServerKeyE xchange me ssage
  99       Signat ureAndHash Algorithm  preferable SignatureA lgorithm;
  100  
  101       // Fla g to use s mart ephem eral DH ke y which si ze matches  the corre sponding
  102       // aut henticatio n key
  103       privat e static f inal boole an useSmar tEphemeral DHKeys;
  104  
  105       // Fla g to use l egacy ephe meral DH k ey which s ize is 512  bits for
  106       // exp ortable ci pher suite s, and 768  bits for  others
  107       privat e static f inal boole an useLega cyEphemera lDHKeys;
  108  
  109       // The  customize d ephemera l DH key s ize for no n-exportab le cipher  suites.
  110       privat e static f inal int c ustomizedD HKeySize;
  111  
  112       // leg acy algori thm constr aints
  113       privat e static f inal Algor ithmConstr aints lega cyAlgorith mConstrain ts =
  114                new Lega cyAlgorith mConstrain ts(
  115                         LegacyAlgo rithmConst raints.PRO PERTY_TLS_ LEGACY_ALG S,
  116                         new SSLAlg orithmDeco mposer());
  117  
  118       static  {
  119           St ring prope rty = Acce ssControll er.doPrivi leged(
  120                         new GetPro pertyActio n("jdk.tls .ephemeral DHKeySize" ));
  121           if  (property  == null | | property .length()  == 0) {
  122                useLegac yEphemeral DHKeys = f alse;
  123                useSmart EphemeralD HKeys = fa lse;
  124                customiz edDHKeySiz e = -1;
  125           }  else if (" matched".e quals(prop erty)) {
  126                useLegac yEphemeral DHKeys = f alse;
  127                useSmart EphemeralD HKeys = tr ue;
  128                customiz edDHKeySiz e = -1;
  129           }  else if (" legacy".eq uals(prope rty)) {
  130                useLegac yEphemeral DHKeys = t rue;
  131                useSmart EphemeralD HKeys = fa lse;
  132                customiz edDHKeySiz e = -1;
  133           }  else {
  134                useLegac yEphemeral DHKeys = f alse;
  135                useSmart EphemeralD HKeys = fa lse;
  136  
  137                try {
  138                    // D H paramete r generati on can be  extremely  slow, best  to
  139                    // u se one of  the suppor ted pre-co mputed DH  parameters
  140                    // ( see DHCryp t class).
  141                    cust omizedDHKe ySize = In teger.pars eUnsignedI nt(propert y);
  142                    if ( customized DHKeySize  < 1024 ||  customized DHKeySize  > 8192 ||
  143                             (custo mizedDHKey Size & 0x3 f) != 0) {
  144                         throw new  IllegalArg umentExcep tion(
  145                             "Unsup ported cus tomized DH  key size:  " +
  146                             custom izedDHKeyS ize + ". "  +
  147                             "The k ey size mu st be mult iple of 64 , " +
  148                             "and c an only ra nge from 1 024 to 819 2 (inclusi ve)");
  149                    }
  150                } catch  (NumberFor matExcepti on nfe) {
  151                    thro w new Ille galArgumen tException (
  152                             "Inval id system  property j dk.tls.eph emeralDHKe ySize");
  153                }
  154           }
  155       }
  156  
  157       /*
  158        * Con structor . .. use the  keys foun d in the a uth contex t.
  159        */
  160       Server Handshaker (SSLSocket Impl socke t, SSLCont extImpl co ntext,
  161                Protocol List enabl edProtocol s, byte cl ientAuth,
  162                Protocol Version ac tiveProtoc olVersion,  boolean i sInitialHa ndshake,
  163                boolean  secureRene gotiation,
  164                byte[] c lientVerif yData, byt e[] server VerifyData ) {
  165  
  166           su per(socket , context,  enabledPr otocols,
  167                    (cli entAuth !=  SSLEngine Impl.claut h_none), f alse,
  168                    acti veProtocol Version, i sInitialHa ndshake, s ecureReneg otiation,
  169                    clie ntVerifyDa ta, server VerifyData );
  170           do ClientAuth  = clientA uth;
  171       }
  172  
  173       /*
  174        * Con structor . .. use the  keys foun d in the a uth contex t.
  175        */
  176       Server Handshaker (SSLEngine Impl engin e, SSLCont extImpl co ntext,
  177                Protocol List enabl edProtocol s, byte cl ientAuth,
  178                Protocol Version ac tiveProtoc olVersion,
  179                boolean  isInitialH andshake,  boolean se cureRenego tiation,
  180                byte[] c lientVerif yData, byt e[] server VerifyData ) {
  181  
  182           su per(engine , context,  enabledPr otocols,
  183                    (cli entAuth !=  SSLEngine Impl.claut h_none), f alse,
  184                    acti veProtocol Version, i sInitialHa ndshake, s ecureReneg otiation,
  185                    clie ntVerifyDa ta, server VerifyData );
  186           do ClientAuth  = clientA uth;
  187       }
  188  
  189       /*
  190        * As  long as ha ndshaking  has not st arted, we  can change
  191        * whe ther clien t authenti cation is  required.   Otherwise ,
  192        * we  will need  to wait fo r the next  handshake .
  193        */
  194       void s etClientAu th(byte cl ientAuth)  {
  195           do ClientAuth  = clientA uth;
  196       }
  197  
  198       /*
  199        * Thi s routine  handles al l the serv er side ha ndshake me ssages, on e at
  200        * a t ime.  Give n the mess age type ( and in som e cases th e pending  cipher
  201        * spe c) it pars es the typ e-specific  message.   Then it c alls a fun ction
  202        * tha t handles  that speci fic messag e.
  203        *
  204        * It  updates th e state ma chine as e ach messag e is proce ssed, and  writes
  205        * res ponses as  needed usi ng the con nection in  the const ructor.
  206        */
  207       @Overr ide
  208       void p rocessMess age(byte t ype, int m essage_len )
  209                throws I OException  {
  210           //
  211           //  In SSLv3  and TLS, m essages fo llow stric tly increa sing
  212           //  numerical  order _ex cept_ for  one annoyi ng special  case.
  213           //
  214           if  ((state > = type)
  215                    && ( state != H andshakeMe ssage.ht_c lient_key_ exchange
  216                         && type !=  Handshake Message.ht _certifica te_verify) ) {
  217                throw ne w SSLProto colExcepti on(
  218                         "Handshake  message s equence vi olation, s tate = " +  state
  219                         + ", type  = " + type );
  220           }
  221  
  222           sw itch (type ) {
  223                case Han dshakeMess age.ht_cli ent_hello:
  224                    Clie ntHello ch  = new Cli entHello(i nput, mess age_len);
  225                    /*
  226                     * s end it off  for proce ssing.
  227                     */
  228                    this .clientHel lo(ch);
  229                    brea k;
  230  
  231                case Han dshakeMess age.ht_cer tificate:
  232                    if ( doClientAu th == SSLE ngineImpl. clauth_non e) {
  233                         fatalSE(Al erts.alert _unexpecte d_message,
  234                                      "client  sent unsol icited cer t chain");
  235                         // NOTREAC HED
  236                    }
  237                    this .clientCer tificate(n ew Certifi cateMsg(in put));
  238                    brea k;
  239  
  240                case Han dshakeMess age.ht_cli ent_key_ex change:
  241                    Secr etKey preM asterSecre t;
  242                    swit ch (keyExc hange) {
  243                    case  K_RSA:
  244                    case  K_RSA_EXP ORT:
  245                         /*
  246                           * The clie nt's pre-m aster  PW        is decrypt ed using
  247                          * either  the server 's normal  private RS A key, or  the
  248                          * tempora ry one use d for non- export or  signing-on ly
  249                          * certifi cates/keys .
  250                          */
  251                         RSAClientK eyExchange  pms = new  RSAClient KeyExchang e(
  252                                 pr otocolVers ion, clien tRequested Version,
  253                                 ss lContext.g etSecureRa ndom(), in put,
  254                                 me ssage_len,  privateKe y);
  255                         preMasterS ecret = th is.clientK eyExchange (pms);
  256                         break;
  257                    case  K_KRB5:
  258                    case  K_KRB5_EX PORT:
  259                         preMasterS ecret = th is.clientK eyExchange (
  260                             new Ke rberosClie ntKeyExcha nge(protoc olVersion,
  261                                 cl ientReques tedVersion ,
  262                                 ss lContext.g etSecureRa ndom(),
  263                                 in put,
  264                                 th is.getAccS E(),
  265                                 se rviceCreds ));
  266                         break;
  267                    case  K_DHE_RSA :
  268                    case  K_DHE_DSS :
  269                    case  K_DH_ANON :
  270                         /*
  271                           * The pre- master  PW        is derived  using the  normal
  272                          * Diffie- Hellman ca lculation.    Note th at the mai n
  273                          * protoco l differen ce in thes e five fla vors is in  how
  274                          * the Ser verKeyExch ange messa ge was con structed!
  275                          */
  276                         preMasterS ecret = th is.clientK eyExchange (
  277                                 ne w DHClient KeyExchang e(input));
  278                         break;
  279                    case  K_ECDH_RS A:
  280                    case  K_ECDH_EC DSA:
  281                    case  K_ECDHE_R SA:
  282                    case  K_ECDHE_E CDSA:
  283                    case  K_ECDH_AN ON:
  284                         preMasterS ecret = th is.clientK eyExchange
  285                                                   (new E CDHClientK eyExchange (input));
  286                         break;
  287                    defa ult:
  288                         throw new  SSLProtoco lException
  289                             ("Unre cognized k ey exchang e: " + key Exchange);
  290                    }
  291  
  292                    // N eed to add  the hash  for RFC 76 27.
  293                    if ( session.ge tUseExtend edMasterSe cret()) {
  294                         input.dige stNow();
  295                    }
  296  
  297                    //
  298                      // All key s are calc ulated fro m the prem aster  PW     
  299                    // a nd the exc hanged non ces in the  same way.
  300                    //
  301                    calc ulateKeys( preMasterS ecret, cli entRequest edVersion) ;
  302                    brea k;
  303  
  304                case Han dshakeMess age.ht_cer tificate_v erify:
  305                    this .clientCer tificateVe rify(new C ertificate Verify(inp ut,
  306                                 ge tLocalSupp ortedSignA lgs(), pro tocolVersi on));
  307                    brea k;
  308  
  309                case Han dshakeMess age.ht_fin ished:
  310                    // A  ChangeCip herSpec re cord must  have been  received p rior to
  311                    // r eception o f the Fini shed messa ge (RFC 52 46, 7.4.9) .
  312                    if ( !receivedC hangeCiphe rSpec()) {
  313                         fatalSE(Al erts.alert _handshake _failure,
  314                             "Recei ved Finish ed message  before Ch angeCipher Spec");
  315                    }
  316  
  317                    this .clientFin ished(
  318                         new Finish ed(protoco lVersion,  input, cip herSuite)) ;
  319                    brea k;
  320  
  321                default:
  322                    thro w new SSLP rotocolExc eption(
  323                             "Illeg al server  handshake  msg, " + t ype);
  324           }
  325  
  326           //
  327           //  Move stat e machine  forward if  the messa ge handlin g
  328           //  code didn 't already  do so
  329           //
  330           if  (state <  type) {
  331                if(type  == Handsha keMessage. ht_certifi cate_verif y) {
  332                    stat e = type +  2;    //  an annoyin g special  case
  333                } else {
  334                    stat e = type;
  335                }
  336           }
  337       }
  338  
  339  
  340       /*
  341        * Cli entHello p resents th e server w ith a bunc h of optio ns, to whi ch the
  342        * ser ver replie s with a S erverHello  listing t he ones wh ich this s ession
  343        * wil l use.  If  needed, i t also wri tes its Ce rtificate  plus in so me cases
  344        * a S erverKeyEx change mes sage.  It  may also w rite a Cer tificateRe quest,
  345        * to  elicit a c lient cert ificate.
  346        *
  347        * All  these mes sages are  terminated  by a Serv erHelloDon e message.   In
  348        * mos t cases, a ll this ca n be sent  in a singl e Record.
  349        */
  350       privat e void cli entHello(C lientHello  mesg) thr ows IOExce ption {
  351           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  352                mesg.pri nt(System. out);
  353           }
  354  
  355           //  Reject cl ient initi ated reneg otiation?
  356           //
  357           //  If server  side shou ld reject  client-ini tiated ren egotiation ,
  358           //  send an a lert_hands hake_failu re fatal a lert, not  a no_reneg otiation
  359           //  warning a lert (no_r enegotiati on must be  a warning : RFC 2246 ).
  360           //  no_renego tiation mi ght seem m ore natura l at first , but warn ings
  361           //  are not a ppropriate  because t he sending  party doe s not know  how
  362           //  the recei ving party  will beha ve.  This  state must  be treate d as
  363           //  a fatal s erver cond ition.
  364           //
  365           //  This will  not have  any impact  on server  initiated  renegotia tion.
  366           if  (rejectCl ientInitia tedRenego  && !isInit ialHandsha ke &&
  367                    stat e != Hands hakeMessag e.ht_hello _request)  {
  368                fatalSE( Alerts.ale rt_handsha ke_failure ,
  369                    "Cli ent initia ted renego tiation is  not allow ed");
  370           }
  371  
  372           //  check the  server na me indicat ion if req uired
  373           Se rverNameEx tension cl ientHelloS NIExt = (S erverNameE xtension)
  374                         mesg.exten sions.get( ExtensionT ype.EXT_SE RVER_NAME) ;
  375           if  (!sniMatc hers.isEmp ty()) {
  376                // we do  not rejec t client w ithout SNI  extension
  377                if (clie ntHelloSNI Ext != nul l &&
  378                             !clien tHelloSNIE xt.isMatch ed(sniMatc hers)) {
  379                    fata lSE(Alerts .alert_unr ecognized_ name,
  380                         "Unrecogni zed server  name indi cation");
  381                }
  382           }
  383  
  384           //  Does the  message in clude secu rity reneg otiation i ndication?
  385           bo olean rene gotiationI ndicated =  false;
  386  
  387           //  check the  TLS_EMPTY _RENEGOTIA TION_INFO_ SCSV
  388           Ci pherSuiteL ist cipher Suites = m esg.getCip herSuites( );
  389           if  (cipherSu ites.conta ins(Cipher Suite.C_SC SV)) {
  390                renegoti ationIndic ated = tru e;
  391                if (isIn itialHands hake) {
  392                    secu reRenegoti ation = tr ue;
  393                } else {
  394                    // a bort the h andshake w ith a fata l handshak e_failure  alert
  395                    if ( secureRene gotiation)  {
  396                         fatalSE(Al erts.alert _handshake _failure,
  397                             "The S CSV is pre sent in a  secure ren egotiation ");
  398                    } el se {
  399                         fatalSE(Al erts.alert _handshake _failure,
  400                             "The S CSV is pre sent in a  insecure r enegotiati on");
  401                    }
  402                }
  403           }
  404  
  405           //  check the  "renegoti ation_info " extensio n
  406           Re negotiatio nInfoExten sion clien tHelloRI =  (Renegoti ationInfoE xtension)
  407                         mesg.exten sions.get( ExtensionT ype.EXT_RE NEGOTIATIO N_INFO);
  408           if  (clientHe lloRI != n ull) {
  409                renegoti ationIndic ated = tru e;
  410                if (isIn itialHands hake) {
  411                    // v erify the  length of  the "reneg otiated_co nnection"  field
  412                    if ( !clientHel loRI.isEmp ty()) {
  413                         // abort t he handsha ke with a  fatal hand shake_fail ure alert
  414                         fatalSE(Al erts.alert _handshake _failure,
  415                             "The r enegotiati on_info fi eld is not  empty");
  416                    }
  417  
  418                    secu reRenegoti ation = tr ue;
  419                } else {
  420                    if ( !secureRen egotiation ) {
  421                         // unexpec ted RI ext ension for  insecure  renegotiat ion,
  422                         // abort t he handsha ke with a  fatal hand shake_fail ure alert
  423                         fatalSE(Al erts.alert _handshake _failure,
  424                             "The r enegotiati on_info is  present i n a insecu re " +
  425                             "reneg otiation") ;
  426                    }
  427  
  428                    // v erify the  client_ver ify_data v alue
  429                    if ( !MessageDi gest.isEqu al(clientV erifyData,
  430                                      clientHe lloRI.getR enegotiate dConnectio n())) {
  431                         fatalSE(Al erts.alert _handshake _failure,
  432                             "Incor rect verif y data in  ClientHell o " +
  433                             "reneg otiation_i nfo messag e");
  434                    }
  435                }
  436           }  else if (! isInitialH andshake & & secureRe negotiatio n) {
  437               // if the  connectio n's "secur e_renegoti ation" fla g is set t o TRUE
  438               // and th e "renegot iation_inf o" extensi on is not  present, a bort
  439               // the ha ndshake.
  440                fatalSE( Alerts.ale rt_handsha ke_failure ,
  441                             "Incon sistent se cure reneg otiation i ndication" );
  442           }
  443  
  444           //  if there  is no secu rity reneg otiation i ndication  or the pre vious
  445           //  handshake  is insecu re.
  446           if  (!renegot iationIndi cated || ! secureRene gotiation)  {
  447                if (isIn itialHands hake) {
  448                    if ( !allowLega cyHelloMes sages) {
  449                         // abort t he handsha ke with a  fatal hand shake_fail ure alert
  450                         fatalSE(Al erts.alert _handshake _failure,
  451                             "Faile d to negot iate the u se of secu re renegot iation");
  452                    }
  453  
  454                    // c ontinue wi th legacy  ClientHell o
  455                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  456                         System.out .println(" Warning: N o renegoti ation " +
  457                             "indic ation in C lientHello , allow le gacy Clien tHello");
  458                    }
  459                } else i f (!allowU nsafeReneg otiation)  {
  460                    // a bort the h andshake
  461                    if ( activeProt ocolVersio n.v >= Pro tocolVersi on.TLS10.v ) {
  462                         // respond  with a no _renegotia tion warni ng
  463                         warningSE( Alerts.ale rt_no_rene gotiation) ;
  464  
  465                         // invalid ate the ha ndshake so  that the  caller can
  466                         // dispose  this obje ct.
  467                         invalidate d = true;
  468  
  469                         // If ther e is still  unread bl ock in the  handshake
  470                         // input s tream, it  would be t runcated w ith the di sposal
  471                         // and the  next hand shake mess age will b ecome inco mplete.
  472                         //
  473                         // However , accordin g to SSL/T LS specifi cations, n o more
  474                         // handsha ke message  could imm ediately f ollow Clie ntHello
  475                         // or Hell oRequest.  But in cas e of any i mproper me ssages,
  476                         // we'd be tter check  to ensure  there is  no remaini ng bytes
  477                         // in the  handshake  input stre am.
  478                         if (input. available( ) > 0) {
  479                             fatalS E(Alerts.a lert_unexp ected_mess age,
  480                                 "C lientHello  followed  by an unex pected  "  +
  481                                 "h andshake m essage");
  482                         }
  483  
  484                         return;
  485                    } el se {
  486                         // For SSL v3, send t he handsha ke_failure  fatal err or.
  487                         // Note th at SSLv3 d oes not de fine a no_ renegotiat ion
  488                         // alert l ike TLSv1.  However w e cannot i gnore the  message
  489                         // simply,  otherwise  the other  side was  waiting fo r a
  490                         // respons e that wou ld never c ome.
  491                         fatalSE(Al erts.alert _handshake _failure,
  492                             "Reneg otiation i s not allo wed");
  493                    }
  494                } else {    // !isI nitialHand shake && a llowUnsafe Renegotiat ion
  495                    // c ontinue wi th unsafe  renegotiat ion.
  496                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  497                         System.out .println(
  498                                 "W arning: co ntinue wit h insecure  renegotia tion");
  499                    }
  500                }
  501           }
  502  
  503             // check o ut the "ex tended_mas ter_ PW      " extensio n
  504           if  (useExten dedMasterS ecret) {
  505                Extended MasterSecr etExtensio n extended MasterSecr etExtensio n =
  506                         (ExtendedM asterSecre tExtension )mesg.exte nsions.get (
  507                                 Ex tensionTyp e.EXT_EXTE NDED_MASTE R_SECRET);
  508                if (exte ndedMaster SecretExte nsion != n ull) {
  509                    requ estedToUse EMS = true ;
  510                } else i f (mesg.pr otocolVers ion.v >= P rotocolVer sion.TLS10 .v) {
  511                    if ( !allowLega cyMasterSe cret) {
  512                         // For ful l handshak e, if the  server rec eives a Cl ientHello
  513                         // without  the exten sion, it S HOULD abor t the hand shake if
  514                         // it does  not wish  to interop erate with  legacy cl ients.
  515                         //
  516                         // As if e xtended ma ster exten sion is re quired for  full
  517                         // handsha ke, it MUS T be used  in abbrevi ated hands hake too.
  518                         fatalSE(Al erts.alert _handshake _failure,
  519                             "Exten ded Master  Secret ex tension is  required" );
  520                    }
  521                }
  522           }
  523  
  524           /*
  525            *  Always ma ke sure th is entire  record has  been dige sted befor e we
  526            *  start emi tting outp ut, to ens ure correc t digestin g order.
  527            * /
  528           in put.digest Now();
  529  
  530           /*
  531            *  FIRST, co nstruct th e ServerHe llo using  the option s and prio rities
  532            *  from the  ClientHell o.  Update  the (pend ing) ciphe r spec as  we do
  533            *  so, and s ave the cl ient's ver sion to pr otect agai nst rollba ck
  534            *  attacks.
  535            *
  536            *  There are  a bunch o f minor ta sks here,  and one ma jor one: d eciding
  537            *  if the sh ort or the  full hand shake sequ ence will  be used.
  538            * /
  539           Se rverHello  m1 = new S erverHello ();
  540  
  541           cl ientReques tedVersion  = mesg.pr otocolVers ion;
  542  
  543           //  select a  proper pro tocol vers ion.
  544           Pr otocolVers ion select edVersion  =
  545                   selec tProtocolV ersion(cli entRequest edVersion) ;
  546           if  (selected Version ==  null ||
  547                    sele ctedVersio n.v == Pro tocolVersi on.SSL20He llo.v) {
  548                fatalSE( Alerts.ale rt_handsha ke_failure ,
  549                    "Cli ent reques ted protoc ol " + cli entRequest edVersion  +
  550                    " no t enabled  or not sup ported");
  551           }
  552  
  553           ha ndshakeHas h.protocol Determined (selectedV ersion);
  554           se tVersion(s electedVer sion);
  555  
  556           m1 .protocolV ersion = p rotocolVer sion;
  557  
  558           //
  559           //  random .. . save cli ent and se rver value s for late r use
  560             // in comp uting the  master  PW        (from pre- master  PW      )
  561           //  and thenc e the othe r crypto k eys.
  562           //
  563           //  NOTE:  th is use of  three inpu ts to gene rating _ea ch_ set
  564           //  of cipher s slows th ings down,  but it do es increas e the
  565           //  security  since each  connectio n in the s ession can  hold
  566           //  its own a uthenticat ed (and st rong) keys .  One cou ld make
  567           //  creation  of a sessi on a rare  thing...
  568           //
  569           cl nt_random  = mesg.cln t_random;
  570           sv r_random =  new Rando mCookie(ss lContext.g etSecureRa ndom());
  571           m1 .svr_rando m = svr_ra ndom;
  572  
  573           se ssion = nu ll; // for get about  the curren t session
  574           //
  575           //  Here we g o down eit her of two  paths:  ( a) the fas t one, whe re
  576           //  the clien t's asked  to rejoin  an existin g session,  and the s erver
  577           //  permits t his; (b) t he other o ne, where  a new sess ion is cre ated.
  578           //
  579           if  (mesg.ses sionId.len gth() != 0 ) {
  580                // clien t is tryin g to resum e a sessio n, let's s ee...
  581  
  582                SSLSessi onImpl pre vious = (( SSLSession ContextImp l)sslConte xt
  583                             .engin eGetServer SessionCon text())
  584                             .get(m esg.sessio nId.getId( ));
  585                //
  586                // Check  if we can  use the f ast path,  resuming a  session.   We
  587                // can d o so iff w e have a v alid recor d for that  session,  and
  588                // the c ipher suit e for that  session w as on the  list which  the
  589                // clien t requeste d, and if  we're not  forgetting  any neede d
  590                // authe ntication  on the par t of the c lient.
  591                //
  592                if (prev ious != nu ll) {
  593                    resu mingSessio n = previo us.isRejoi nable();
  594  
  595                    if ( resumingSe ssion) {
  596                         ProtocolVe rsion oldV ersion = p revious.ge tProtocolV ersion();
  597                         // cannot  resume ses sion with  different  version
  598                         if (oldVer sion != me sg.protoco lVersion)  {
  599                             resumi ngSession  = false;
  600                         }
  601                    }
  602  
  603                    if ( resumingSe ssion && u seExtended MasterSecr et) {
  604                         if (reques tedToUseEM S &&
  605                                 !p revious.ge tUseExtend edMasterSe cret()) {
  606                             // For  abbreviat ed handsha ke request , If the o riginal
  607                               // session  did not u se the "ex tended_mas ter_ PW      "
  608                             // ext ension but  the new C lientHello  contains  the
  609                             // ext ension, th en the ser ver MUST N OT perform  the
  610                             // abb reviated h andshake.   Instead,  it SHOULD  continue
  611                             // wit h a full h andshake.
  612                             resumi ngSession  = false;
  613                         } else if  (!requeste dToUseEMS  &&
  614                                 pr evious.get UseExtende dMasterSec ret()) {
  615                             // For  abbreviat ed handsha ke request , if the o riginal
  616                               // session  used the  "extended_ master_ PW      " extensio n
  617                             // but  the new C lientHello  does not  contain it , the
  618                             // ser ver MUST a bort the a bbreviated  handshake .
  619                             fatalS E(Alerts.a lert_hands hake_failu re,
  620                                      "Missing  Extended  Master Sec ret extens ion " +
  621                                      "on sess ion resump tion");
  622                         } else if  (!requeste dToUseEMS  &&
  623                                 !p revious.ge tUseExtend edMasterSe cret()) {
  624                             // For  abbreviat ed handsha ke request , if neith er the
  625                             // ori ginal sess ion nor th e new Clie ntHello us es the
  626                             // ext ension, th e server S HOULD abor t the hand shake.
  627                             if (!a llowLegacy Resumption ) {
  628                                 fa talSE(Aler ts.alert_h andshake_f ailure,
  629                                      "Missing  Extended  Master Sec ret extens ion " +
  630                                      "on sess ion resump tion");
  631                             } else  {  // Oth erwise, co ntinue wit h a full h andshake.
  632                                 re sumingSess ion = fals e;
  633                             }
  634                         }
  635                    }
  636  
  637                    // c annot resu me session  with diff erent serv er name in dication
  638                    if ( resumingSe ssion) {
  639                         List<SNISe rverName>  oldServerN ames =
  640                                 pr evious.get RequestedS erverNames ();
  641                         if (client HelloSNIEx t != null)  {
  642                             if (!c lientHello SNIExt.isI dentical(o ldServerNa mes)) {
  643                                 re sumingSess ion = fals e;
  644                             }
  645                         } else if  (!oldServe rNames.isE mpty()) {
  646                             resumi ngSession  = false;
  647                         }
  648  
  649                         if (!resum ingSession  &&
  650                                 de bug != nul l && Debug .isOn("han dshake"))  {
  651                             System .out.print ln(
  652                                 "T he request ed server  name indic ation " +
  653                                 "i s not iden tical to t he previou s one");
  654                         }
  655                    }
  656  
  657                    if ( resumingSe ssion &&
  658                             (doCli entAuth ==  SSLEngine Impl.claut h_required )) {
  659                         try {
  660                             previo us.getPeer Principal( );
  661                         } catch (S SLPeerUnve rifiedExce ption e) {
  662                             resumi ngSession  = false;
  663                         }
  664                    }
  665  
  666                    // v alidate su bject iden tity
  667                    if ( resumingSe ssion) {
  668                         CipherSuit e suite =  previous.g etSuite();
  669                         if (suite. keyExchang e == K_KRB 5 ||
  670                             suite. keyExchang e == K_KRB 5_EXPORT)  {
  671                             Princi pal localP rincipal =  previous. getLocalPr incipal();
  672  
  673                             Subjec t subject  = null;
  674                             try {
  675                                 su bject = Ac cessContro ller.doPri vileged(
  676                                      new Priv ilegedExce ptionActio n<Subject> () {
  677                                      @Overrid e
  678                                      public S ubject run () throws  Exception  {
  679                                          retu rn
  680                                               Krb5Helper .getServer Subject(ge tAccSE());
  681                                 }} );
  682                             } catc h (Privile gedActionE xception e ) {
  683                                 su bject = nu ll;
  684                                 if  (debug !=  null && D ebug.isOn( "session") ) {
  685                                      System.o ut.println ("Attempt  to obtain"  +
  686                                                       "  subject fa iled!");
  687                                 }
  688                             }
  689  
  690                             if (su bject != n ull) {
  691                                 //  Eliminate  dependenc y on Kerbe rosPrincip al
  692                                 if  (Krb5Help er.isRelat ed(subject , localPri ncipal)) {
  693                                      if (debu g != null  && Debug.i sOn("sessi on"))
  694                                          Syst em.out.pri ntln("Subj ect can" +
  695                                                   " prov ide creds  for princ" );
  696                                 }  else {
  697                                      resuming Session =  false;
  698                                      if (debu g != null  && Debug.i sOn("sessi on"))
  699                                          Syst em.out.pri ntln("Subj ect cannot " +
  700                                                   " prov ide creds  for princ" );
  701                                 }
  702                             } else  {
  703                                 re sumingSess ion = fals e;
  704                                 if  (debug !=  null && D ebug.isOn( "session") )
  705                                      System.o ut.println ("Kerberos  credentia ls are" +
  706                                          " no t present  in the cur rent Subje ct;" +
  707                                          " ch eck if " +
  708                                          " ja vax.securi ty.auth.us eSubjectAs Creds" +
  709                                          " sy stem prope rty has be en set to  false");
  710                             }
  711                         }
  712                    }
  713  
  714                    if ( resumingSe ssion) {
  715                         CipherSuit e suite =  previous.g etSuite();
  716                         // verify  that the c iphersuite  from the  cached ses sion
  717                         // is in t he list of  client re quested ci phersuites  and
  718                         // we have  it enable d
  719                         if ((isNeg otiable(su ite) == fa lse) ||
  720                                 (m esg.getCip herSuites( ).contains (suite) ==  false)) {
  721                             resumi ngSession  = false;
  722                         } else {
  723                             // eve rything lo oks ok, se t the ciph ersuite
  724                             // thi s should b e done las t when we  are sure w e
  725                             // wil l resume
  726                             setCip herSuite(s uite);
  727                         }
  728                    }
  729  
  730                    if ( resumingSe ssion) {
  731                         session =  previous;
  732                         if (debug  != null &&
  733                             (Debug .isOn("han dshake") | | Debug.is On("sessio n"))) {
  734                             System .out.print ln("%% Res uming " +  session);
  735                         }
  736                    }
  737                }
  738           }  // else cl ient did n ot try to  resume
  739  
  740           //
  741           //  If client  hasn't sp ecified a  session we  can resum e, start a
  742           //  new one a nd choose  its cipher  suite and  compressi on options .
  743           //  Unless ne w session  creation i s disabled  for this  connection !
  744           //
  745           if  (session  == null) {
  746                if (!ena bleNewSess ion) {
  747                    thro w new SSLE xception(" Client did  not resum e a sessio n");
  748                }
  749  
  750                requeste dCurves =  (EllipticC urvesExten sion)
  751                             mesg.e xtensions. get(Extens ionType.EX T_ELLIPTIC _CURVES);
  752  
  753                // We on ly need to  handle th e "signatu re_algorit hm" extens ion
  754                // for f ull handsh akes and T LS 1.2 or  later.
  755                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  756                    Sign atureAlgor ithmsExten sion signA lgs =
  757                         (Signature Algorithms Extension) mesg.exten sions.get(
  758                                          Exte nsionType. EXT_SIGNAT URE_ALGORI THMS);
  759                    if ( signAlgs ! = null) {
  760                         Collection <Signature AndHashAlg orithm> pe erSignAlgs  =
  761                                                   signAl gs.getSign Algorithms ();
  762                         if (peerSi gnAlgs ==  null || pe erSignAlgs .isEmpty() ) {
  763                             throw  new SSLHan dshakeExce ption(
  764                                 "N o peer sup ported sig nature alg orithms");
  765                         }
  766  
  767                         Collection <Signature AndHashAlg orithm>
  768                             suppor tedPeerSig nAlgs =
  769                                 Si gnatureAnd HashAlgori thm.getSup portedAlgo rithms(
  770                                      algorith mConstrain ts, peerSi gnAlgs);
  771                         if (suppor tedPeerSig nAlgs.isEm pty()) {
  772                             throw  new SSLHan dshakeExce ption(
  773                                 "N o signatur e and hash  algorithm  in common ");
  774                         }
  775  
  776                         setPeerSup portedSign Algs(suppo rtedPeerSi gnAlgs);
  777                    } //  else, nee d to use p eer implic it support ed signatu re algs
  778                }
  779  
  780                session  = new SSLS essionImpl (protocolV ersion, Ci pherSuite. C_NULL,
  781                             getLoc alSupporte dSignAlgs( ),
  782                             sslCon text.getSe cureRandom (),
  783                             getHos tAddressSE (), getPor tSE(),
  784                             (reque stedToUseE MS &&
  785                                      (protoco lVersion.v  >= Protoc olVersion. TLS10.v))) ;
  786  
  787                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  788                    if ( peerSuppor tedSignAlg s != null)  {
  789                         session.se tPeerSuppo rtedSignat ureAlgorit hms(
  790                                 pe erSupporte dSignAlgs) ;
  791                    }    // else, w e will set  the impli cit peer s upported s ignature
  792                         // algorit hms in cho oseCipherS uite()
  793                }
  794  
  795                // set t he server  name indic ation in t he session
  796                List<SNI ServerName > clientHe lloSNI =
  797                         Collection s.<SNIServ erName>emp tyList();
  798                if (clie ntHelloSNI Ext != nul l) {
  799                    clie ntHelloSNI  = clientH elloSNIExt .getServer Names();
  800                }
  801                session. setRequest edServerNa mes(client HelloSNI);
  802  
  803                // set t he handsha ke session
  804                setHands hakeSessio nSE(sessio n);
  805  
  806                // choos e cipher s uite and c orrespondi ng private  key
  807                chooseCi pherSuite( mesg);
  808  
  809                session. setSuite(c ipherSuite );
  810                session. setLocalPr ivateKey(p rivateKey) ;
  811  
  812                // choos eCompressi on(mesg);
  813           }  else {
  814                // set t he handsha ke session
  815                setHands hakeSessio nSE(sessio n);
  816           }
  817  
  818           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  819                handshak eHash.setF inishedAlg (cipherSui te.prfAlg. getPRFHash Alg());
  820           }
  821  
  822           m1 .cipherSui te = ciphe rSuite;
  823           m1 .sessionId  = session .getSessio nId();
  824           m1 .compressi on_method  = session. getCompres sion();
  825  
  826           if  (secureRe negotiatio n) {
  827                // For S erverHello s that are  initial h andshakes,  then the
  828                // "rene gotiated_c onnection"  field in  "renegotia tion_info"
  829                // exten sion is of  zero leng th.
  830                //
  831                // For S erverHello s that are  renegotia ting, this  field con tains
  832                // the c oncatenati on of clie nt_verify_ data and s erver_veri fy_data.
  833                //
  834                // Note  that for i nitial han dshakes, b oth the cl ientVerify Data
  835                // varia ble and se rverVerify Data varia ble are of  zero leng th.
  836                HelloExt ension ser verHelloRI  = new Ren egotiation InfoExtens ion(
  837                                               clientVeri fyData, se rverVerify Data);
  838                m1.exten sions.add( serverHell oRI);
  839           }
  840  
  841           if  (!sniMatc hers.isEmp ty() && cl ientHelloS NIExt != n ull) {
  842                // When  resuming a  session,  the server  MUST NOT  include a
  843                // serve r_name ext ension in  the server  hello.
  844                if (!res umingSessi on) {
  845                    Serv erNameExte nsion serv erHelloSNI  = new Ser verNameExt ension();
  846                    m1.e xtensions. add(server HelloSNI);
  847                }
  848           }
  849  
  850           if  (session. getUseExte ndedMaster Secret())  {
  851                m1.exten sions.add( new Extend edMasterSe cretExtens ion());
  852           }
  853  
  854           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  855                m1.print (System.ou t);
  856                System.o ut.println ("Cipher s uite:  " +  session.g etSuite()) ;
  857           }
  858           m1 .write(out put);
  859  
  860           //
  861           //  If we are  resuming  a session,  we finish  writing h andshake
  862           //  messages  right now  and then f inish.
  863           //
  864           if  (resuming Session) {
  865                calculat eConnectio nKeys(sess ion.getMas terSecret( ));
  866                sendChan geCipherAn dFinish(fa lse);
  867                return;
  868           }
  869  
  870  
  871           /*
  872            *  SECOND, w rite the s erver Cert ificate(s)  if we nee d to.
  873            *
  874            *  NOTE:  wh ile an "an onymous RS A" mode is  explicitl y allowed  by
  875            *  the proto col, we ca n't suppor t it since  all of th e SSL flav ors
  876            *  defined i n the prot ocol spec  are explic itly state d to requi re
  877            *  using RSA  certifica tes.
  878            * /
  879           if  (keyExcha nge == K_K RB5 || key Exchange = = K_KRB5_E XPORT) {
  880                // Serve r certific ates are o mitted for  Kerberos  ciphers
  881  
  882           }  else if (( keyExchang e != K_DH_ ANON) && ( keyExchang e != K_ECD H_ANON)) {
  883                if (cert s == null)  {
  884                    thro w new Runt imeExcepti on("no cer tificates" );
  885                }
  886  
  887                Certific ateMsg m2  = new Cert ificateMsg (certs);
  888  
  889                /*
  890                 * Set l ocal certs  in the SS LSession,  output
  891                 * debug  info, and  then actu ally write  to the cl ient.
  892                 */
  893                session. setLocalCe rtificates (certs);
  894                if (debu g != null  && Debug.i sOn("hands hake")) {
  895                    m2.p rint(Syste m.out);
  896                }
  897                m2.write (output);
  898  
  899                // XXX h as some si de effects  with OS T CP bufferi ng,
  900                // leave  it out fo r now
  901  
  902                // let c lient veri fy chain i n the mean time...
  903                // outpu t.flush();
  904           }  else {
  905                if (cert s != null)  {
  906                    thro w new Runt imeExcepti on("anonym ous keyexc hange with  certs");
  907                }
  908           }
  909  
  910           /*
  911            *  THIRD, th e ServerKe yExchange  message .. . iff it's  needed.
  912            *
  913            *  It's usua lly needed  unless th ere's an e ncryption- capable
  914            *  RSA cert,  or a D-H  cert.  The  notable e xception i s that
  915            *  exportabl e ciphers  used with  big RSA ke ys need to  downgrade
  916            *  to use sh ort RSA ke ys, even w hen the ke y/cert enc rypts OK.
  917            * /
  918  
  919           Se rverKeyExc hange m3;
  920           sw itch (keyE xchange) {
  921           ca se K_RSA:
  922           ca se K_KRB5:
  923           ca se K_KRB5_ EXPORT:
  924                // no se rver key e xchange fo r RSA or K RB5 cipher suites
  925                m3 = nul l;
  926                break;
  927           ca se K_RSA_E XPORT:
  928                if (Jsse Jce.getRSA KeyLength( certs[0].g etPublicKe y()) > 512 ) {
  929                    try  {
  930                         m3 = new R SA_ServerK eyExchange (
  931                             tempPu blicKey, p rivateKey,
  932                             clnt_r andom, svr _random,
  933                             sslCon text.getSe cureRandom ());
  934                         privateKey  = tempPri vateKey;
  935                    } ca tch (Gener alSecurity Exception  e) {
  936                         throwSSLEx ception
  937                             ("Erro r generati ng RSA ser ver key ex change", e );
  938                         m3 = null;  // make c ompiler ha ppy
  939                    }
  940                } else {
  941                    // R SA_EXPORT  with short  key, don' t need Ser verKeyExch ange
  942                    m3 =  null;
  943                }
  944                break;
  945           ca se K_DHE_R SA:
  946           ca se K_DHE_D SS:
  947                try {
  948                    m3 =  new DH_Se rverKeyExc hange(dh,
  949                         privateKey ,
  950                         clnt_rando m.random_b ytes,
  951                         svr_random .random_by tes,
  952                         sslContext .getSecure Random(),
  953                         preferable SignatureA lgorithm,
  954                         protocolVe rsion);
  955                } catch  (GeneralSe curityExce ption e) {
  956                    thro wSSLExcept ion("Error  generatin g DH serve r key exch ange", e);
  957                    m3 =  null; //  make compi ler happy
  958                }
  959                break;
  960           ca se K_DH_AN ON:
  961                m3 = new  DH_Server KeyExchang e(dh, prot ocolVersio n);
  962                break;
  963           ca se K_ECDHE _RSA:
  964           ca se K_ECDHE _ECDSA:
  965           ca se K_ECDH_ ANON:
  966                try {
  967                    m3 =  new ECDH_ ServerKeyE xchange(ec dh,
  968                         privateKey ,
  969                         clnt_rando m.random_b ytes,
  970                         svr_random .random_by tes,
  971                         sslContext .getSecure Random(),
  972                         preferable SignatureA lgorithm,
  973                         protocolVe rsion);
  974                } catch  (GeneralSe curityExce ption e) {
  975                    thro wSSLExcept ion(
  976                         "Error gen erating EC DH server  key exchan ge", e);
  977                    m3 =  null; //  make compi ler happy
  978                }
  979                break;
  980           ca se K_ECDH_ RSA:
  981           ca se K_ECDH_ ECDSA:
  982                // Serve rKeyExchan ge not use d for fixe d ECDH
  983                m3 = nul l;
  984                break;
  985           de fault:
  986                throw ne w RuntimeE xception(" internal e rror: " +  keyExchang e);
  987           }
  988           if  (m3 != nu ll) {
  989                if (debu g != null  && Debug.i sOn("hands hake")) {
  990                    m3.p rint(Syste m.out);
  991                }
  992                m3.write (output);
  993           }
  994  
  995           //
  996           //  FOURTH, t he Certifi cateReques t message.   The deta ils of
  997           //  the messa ge can be  affected b y the key  exchange a lgorithm
  998           //  in use.   For exampl e, certs w ith fixed  Diffie-Hel lman keys
  999           //  are only  useful wit h the DH_D SS and DH_ RSA key ex change
  1000           //  algorithm s.
  1001           //
  1002           //  Needed on ly if serv er require s client t o authenti cate self.
  1003           //  Illegal f or anonymo us flavors , so we ne ed to chec k that.
  1004           //
  1005           //  Certifica teRequest  is omitted  for Kerbe ros cipher s
  1006           if  (doClient Auth != SS LEngineImp l.clauth_n one &&
  1007                    keyE xchange !=  K_DH_ANON  && keyExc hange != K _ECDH_ANON  &&
  1008                    keyE xchange !=  K_KRB5 &&  keyExchan ge != K_KR B5_EXPORT)  {
  1009  
  1010                Certific ateRequest  m4;
  1011                X509Cert ificate ca Certs[];
  1012  
  1013                Collecti on<Signatu reAndHashA lgorithm>  localSignA lgs = null ;
  1014                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1015                    // W e currentl y use all  local uppo rted signa ture and h ash
  1016                    // a lgorithms.  However,  to minimiz e the comp utation co st
  1017                    // o f requeste d hash alg orithms, w e may use  a restrict ed
  1018                    // s et of sign ature algo rithms in  the future .
  1019                    loca lSignAlgs  = getLocal SupportedS ignAlgs();
  1020                    if ( localSignA lgs.isEmpt y()) {
  1021                         throw new  SSLHandsha keExceptio n(
  1022                                 "N o supporte d signatur e algorith m");
  1023                    }
  1024  
  1025                    Set< String> lo calHashAlg s =
  1026                         SignatureA ndHashAlgo rithm.getH ashAlgorit hmNames(
  1027                             localS ignAlgs);
  1028                    if ( localHashA lgs.isEmpt y()) {
  1029                         throw new  SSLHandsha keExceptio n(
  1030                                 "N o supporte d signatur e algorith m");
  1031                    }
  1032                }
  1033  
  1034                caCerts  = sslConte xt.getX509 TrustManag er().getAc ceptedIssu ers();
  1035                m4 = new  Certifica teRequest( caCerts, k eyExchange ,
  1036                                                   localS ignAlgs, p rotocolVer sion);
  1037  
  1038                if (debu g != null  && Debug.i sOn("hands hake")) {
  1039                    m4.p rint(Syste m.out);
  1040                }
  1041                m4.write (output);
  1042           }
  1043  
  1044           /*
  1045            *  FIFTH, sa y ServerHe lloDone.
  1046            * /
  1047           Se rverHelloD one m5 = n ew ServerH elloDone() ;
  1048  
  1049           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1050                m5.print (System.ou t);
  1051           }
  1052           m5 .write(out put);
  1053  
  1054           /*
  1055            *  Flush any  buffered  messages s o the clie nt will se e them.
  1056            *  Ideally,  all the me ssages abo ve go in a  single ne twork leve l
  1057            *  message t o the clie nt.  Witho ut big Cer tificate c hains, it' s
  1058            *  going to  be the com mon case.
  1059            * /
  1060           ou tput.flush ();
  1061       }
  1062  
  1063       /*
  1064        * Cho ose cipher  suite fro m among th ose suppor ted by cli ent. Sets
  1065        * the  cipherSui te and key Exchange v ariables.
  1066        */
  1067       privat e void cho oseCipherS uite(Clien tHello mes g) throws  IOExceptio n {
  1068           Ci pherSuiteL ist prefer ed;
  1069           Ci pherSuiteL ist propos ed;
  1070           if  (preferLo calCipherS uites) {
  1071                prefered  = getActi veCipherSu ites();
  1072                proposed  = mesg.ge tCipherSui tes();
  1073           }  else {
  1074                prefered  = mesg.ge tCipherSui tes();
  1075                proposed  = getActi veCipherSu ites();
  1076           }
  1077  
  1078           Li st<CipherS uite> lega cySuites =  new Array List<>();
  1079           fo r (CipherS uite suite  : prefere d.collecti on()) {
  1080                if (isNe gotiable(p roposed, s uite) == f alse) {
  1081                    cont inue;
  1082                }
  1083  
  1084                if (doCl ientAuth = = SSLEngin eImpl.clau th_require d) {
  1085                    if ( (suite.key Exchange = = K_DH_ANO N) ||
  1086                         (suite.key Exchange = = K_ECDH_A NON)) {
  1087                         continue;
  1088                    }
  1089                }
  1090  
  1091                if (!leg acyAlgorit hmConstrai nts.permit s(null, su ite.name,  null)) {
  1092                    lega cySuites.a dd(suite);
  1093                    cont inue;
  1094                }
  1095  
  1096                if (tryS etCipherSu ite(suite)  == false)  {
  1097                    cont inue;
  1098                }
  1099  
  1100                if (debu g != null  && Debug.i sOn("hands hake")) {
  1101                    Syst em.out.pri ntln("Stan dard ciphe rsuite cho sen: " + s uite);
  1102                }
  1103                return;
  1104           }
  1105  
  1106           fo r (CipherS uite suite  : legacyS uites) {
  1107                if (tryS etCipherSu ite(suite) ) {
  1108                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  1109                         System.out .println(" Legacy cip hersuite c hosen: " +  suite);
  1110                    }
  1111                    retu rn;
  1112                }
  1113           }
  1114  
  1115           fa talSE(Aler ts.alert_h andshake_f ailure, "n o cipher s uites in c ommon");
  1116       }
  1117  
  1118       /**
  1119        * Set  the given  CipherSui te, if pos sible. Ret urn the re sult.
  1120        * The  call succ eeds if th e CipherSu ite is ava ilable and  we have
  1121        * the  necessary  certifica tes to com plete the  handshake.  We don't
  1122        * che ck if the  CipherSuit e is actua lly enable d.
  1123        *
  1124        * If  successful , this met hod also g enerates e phemeral k eys if
  1125        * req uired for  this ciphe rsuite. Th is may tak e some tim e, so this
  1126        * met hod should  only be c alled if y ou really  want to us e the
  1127        * Cip herSuite.
  1128        *
  1129        * Thi s method i s called f rom choose CipherSuit e() in thi s class.
  1130        */
  1131       boolea n trySetCi pherSuite( CipherSuit e suite) {
  1132           /*
  1133            *  If we're  resuming a  session w e know we  can
  1134            *  support t his key ex change alg orithm and  in fact
  1135            *  have alre ady cached  the resul t of it in
  1136            *  the sessi on state.
  1137            * /
  1138           if  (resuming Session) {
  1139                return t rue;
  1140           }
  1141  
  1142           if  (suite.is Negotiable () == fals e) {
  1143                return f alse;
  1144           }
  1145  
  1146           //  must not  negotiate  the obsole ted weak c ipher suit es.
  1147           if  (protocol Version.v  >= suite.o bsoleted)  {
  1148                return f alse;
  1149           }
  1150  
  1151           //  must not  negotiate  unsupporte d cipher s uites.
  1152           if  (protocol Version.v  < suite.su pported) {
  1153                return f alse;
  1154           }
  1155  
  1156           Ke yExchange  keyExchang e = suite. keyExchang e;
  1157  
  1158           //  null out  any existi ng referen ces
  1159           pr ivateKey =  null;
  1160           ce rts = null ;
  1161           dh  = null;
  1162           te mpPrivateK ey = null;
  1163           te mpPublicKe y = null;
  1164  
  1165           Co llection<S ignatureAn dHashAlgor ithm> supp ortedSignA lgs = null ;
  1166           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1167                if (peer SupportedS ignAlgs !=  null) {
  1168                    supp ortedSignA lgs = peer SupportedS ignAlgs;
  1169                } else {
  1170                    Sign atureAndHa shAlgorith m algorith m = null;
  1171  
  1172                    // w e may opti mize the p erformance
  1173                    swit ch (keyExc hange) {
  1174                         // If the  negotiated  key excha nge algori thm is one  of
  1175                         // (RSA, D HE_RSA, DH _RSA, RSA_ PSK, ECDH_ RSA, ECDHE _RSA),
  1176                         // behave  as if clie nt had sen t the valu e {sha1,rs a}.
  1177                         case K_RSA :
  1178                         case K_DHE _RSA:
  1179                         case K_DH_ RSA:
  1180                         // case K_ RSA_PSK:
  1181                         case K_ECD H_RSA:
  1182                         case K_ECD HE_RSA:
  1183                             algori thm = Sign atureAndHa shAlgorith m.valueOf(
  1184                                      HashAlgo rithm.SHA1 .value,
  1185                                      Signatur eAlgorithm .RSA.value , 0);
  1186                             break;
  1187                         // If the  negotiated  key excha nge algori thm is one  of
  1188                         // (DHE_DS S, DH_DSS) , behave a s if the c lient had
  1189                         // sent th e value {s ha1,dsa}.
  1190                         case K_DHE _DSS:
  1191                         case K_DH_ DSS:
  1192                             algori thm = Sign atureAndHa shAlgorith m.valueOf(
  1193                                      HashAlgo rithm.SHA1 .value,
  1194                                      Signatur eAlgorithm .DSA.value , 0);
  1195                             break;
  1196                         // If the  negotiated  key excha nge algori thm is one  of
  1197                         // (ECDH_E CDSA, ECDH E_ECDSA),  behave as  if the cli ent
  1198                         // had sen t value {s ha1,ecdsa} .
  1199                         case K_ECD H_ECDSA:
  1200                         case K_ECD HE_ECDSA:
  1201                             algori thm = Sign atureAndHa shAlgorith m.valueOf(
  1202                                      HashAlgo rithm.SHA1 .value,
  1203                                      Signatur eAlgorithm .ECDSA.val ue, 0);
  1204                             break;
  1205                         default:
  1206                             // no  peer suppo rted signa ture algor ithms
  1207                    }
  1208  
  1209                    if ( algorithm  == null) {
  1210                         supportedS ignAlgs =
  1211                             Collec tions.<Sig natureAndH ashAlgorit hm>emptySe t();
  1212                    } el se {
  1213                         supportedS ignAlgs =
  1214                             new Ar rayList<Si gnatureAnd HashAlgori thm>(1);
  1215                         supportedS ignAlgs.ad d(algorith m);
  1216  
  1217                         supportedS ignAlgs =
  1218                                 Si gnatureAnd HashAlgori thm.getSup portedAlgo rithms(
  1219                                      algorith mConstrain ts, suppor tedSignAlg s);
  1220  
  1221                         // May be  no default  activated  signature  algorithm , but
  1222                         // let the  following  process m ake the fi nal decisi on.
  1223                    }
  1224  
  1225                    // S ets the pe er support ed signatu re algorit hm to use  in KM
  1226                    // t emporarily .
  1227                    sess ion.setPee rSupported SignatureA lgorithms( supportedS ignAlgs);
  1228                }
  1229           }
  1230  
  1231           sw itch (keyE xchange) {
  1232           ca se K_RSA:
  1233                // need  RSA certs  for authen tication
  1234                if (setu pPrivateKe yAndChain( "RSA") ==  false) {
  1235                    retu rn false;
  1236                }
  1237                break;
  1238           ca se K_RSA_E XPORT:
  1239                // need  RSA certs  for authen tication
  1240                if (setu pPrivateKe yAndChain( "RSA") ==  false) {
  1241                    retu rn false;
  1242                }
  1243  
  1244                try {
  1245                   if (J sseJce.get RSAKeyLeng th(certs[0 ].getPubli cKey()) >  512) {
  1246                         if (!setup EphemeralR SAKeys(sui te.exporta ble)) {
  1247                             return  false;
  1248                         }
  1249                   }
  1250                } catch  (RuntimeEx ception e)  {
  1251                    // c ould not d etermine k eylength,  ignore key
  1252                    retu rn false;
  1253                }
  1254                break;
  1255           ca se K_DHE_R SA:
  1256                // need  RSA certs  for authen tication
  1257                if (setu pPrivateKe yAndChain( "RSA") ==  false) {
  1258                    retu rn false;
  1259                }
  1260  
  1261                // get p referable  peer signa ture algor ithm for s erver key  exchange
  1262                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1263                    pref erableSign atureAlgor ithm =
  1264                         SignatureA ndHashAlgo rithm.getP referableA lgorithm(
  1265                                               supportedS ignAlgs, " RSA", priv ateKey);
  1266                    if ( preferable SignatureA lgorithm = = null) {
  1267                         if ((debug  != null)  && Debug.i sOn("hands hake")) {
  1268                             System .out.print ln(
  1269                                      "No sign ature and  hash algor ithm for c ipher " +
  1270                                      suite);
  1271                         }
  1272                         return fal se;
  1273                    }
  1274                }
  1275  
  1276                setupEph emeralDHKe ys(suite.e xportable,  privateKe y);
  1277                break;
  1278           ca se K_ECDHE _RSA:
  1279                // need  RSA certs  for authen tication
  1280                if (setu pPrivateKe yAndChain( "RSA") ==  false) {
  1281                    retu rn false;
  1282                }
  1283  
  1284                // get p referable  peer signa ture algor ithm for s erver key  exchange
  1285                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1286                    pref erableSign atureAlgor ithm =
  1287                         SignatureA ndHashAlgo rithm.getP referableA lgorithm(
  1288                                               supportedS ignAlgs, " RSA", priv ateKey);
  1289                    if ( preferable SignatureA lgorithm = = null) {
  1290                         if ((debug  != null)  && Debug.i sOn("hands hake")) {
  1291                             System .out.print ln(
  1292                                      "No sign ature and  hash algor ithm for c ipher " +
  1293                                      suite);
  1294                         }
  1295                         return fal se;
  1296                    }
  1297                }
  1298  
  1299                if (setu pEphemeral ECDHKeys()  == false)  {
  1300                    retu rn false;
  1301                }
  1302                break;
  1303           ca se K_DHE_D SS:
  1304                // get p referable  peer signa ture algor ithm for s erver key  exchange
  1305                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1306                    pref erableSign atureAlgor ithm =
  1307                         SignatureA ndHashAlgo rithm.getP referableA lgorithm(
  1308                                                       su pportedSig nAlgs, "DS A");
  1309                    if ( preferable SignatureA lgorithm = = null) {
  1310                         if ((debug  != null)  && Debug.i sOn("hands hake")) {
  1311                             System .out.print ln(
  1312                                      "No sign ature and  hash algor ithm for c ipher " +
  1313                                      suite);
  1314                         }
  1315                         return fal se;
  1316                    }
  1317                }
  1318  
  1319                // need  DSS certs  for authen tication
  1320                if (setu pPrivateKe yAndChain( "DSA") ==  false) {
  1321                    retu rn false;
  1322                }
  1323  
  1324                setupEph emeralDHKe ys(suite.e xportable,  privateKe y);
  1325                break;
  1326           ca se K_ECDHE _ECDSA:
  1327                // get p referable  peer signa ture algor ithm for s erver key  exchange
  1328                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1329                    pref erableSign atureAlgor ithm =
  1330                         SignatureA ndHashAlgo rithm.getP referableA lgorithm(
  1331                                                   suppor tedSignAlg s, "ECDSA" );
  1332                    if ( preferable SignatureA lgorithm = = null) {
  1333                         if ((debug  != null)  && Debug.i sOn("hands hake")) {
  1334                             System .out.print ln(
  1335                                      "No sign ature and  hash algor ithm for c ipher " +
  1336                                      suite);
  1337                         }
  1338                         return fal se;
  1339                    }
  1340                }
  1341  
  1342                // need  EC cert
  1343                if (setu pPrivateKe yAndChain( "EC") == f alse) {
  1344                    retu rn false;
  1345                }
  1346                if (setu pEphemeral ECDHKeys()  == false)  {
  1347                    retu rn false;
  1348                }
  1349                break;
  1350           ca se K_ECDH_ RSA:
  1351                // need  EC cert
  1352                if (setu pPrivateKe yAndChain( "EC") == f alse) {
  1353                    retu rn false;
  1354                }
  1355                setupSta ticECDHKey s();
  1356                break;
  1357           ca se K_ECDH_ ECDSA:
  1358                // need  EC cert
  1359                if (setu pPrivateKe yAndChain( "EC") == f alse) {
  1360                    retu rn false;
  1361                }
  1362                setupSta ticECDHKey s();
  1363                break;
  1364           ca se K_KRB5:
  1365           ca se K_KRB5_ EXPORT:
  1366                // need  Kerberos K ey
  1367                if (!set upKerberos Keys()) {
  1368                    retu rn false;
  1369                }
  1370                break;
  1371           ca se K_DH_AN ON:
  1372                // no ce rts needed  for anony mous
  1373                setupEph emeralDHKe ys(suite.e xportable,  null);
  1374                break;
  1375           ca se K_ECDH_ ANON:
  1376                // no ce rts needed  for anony mous
  1377                if (setu pEphemeral ECDHKeys()  == false)  {
  1378                    retu rn false;
  1379                }
  1380                break;
  1381           de fault:
  1382                // inter nal error,  unknown k ey exchang e
  1383                throw ne w RuntimeE xception(
  1384                         "Unrecogni zed cipher Suite: " +  suite);
  1385           }
  1386           se tCipherSui te(suite);
  1387  
  1388           //  set the p eer implic it support ed signatu re algorit hms
  1389           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1390                if (peer SupportedS ignAlgs ==  null) {
  1391                    setP eerSupport edSignAlgs (supported SignAlgs);
  1392                    // w e had alre ay update  the sessio n
  1393                }
  1394           }
  1395           re turn true;
  1396       }
  1397  
  1398       /*
  1399        * Get  some "eph emeral" RS A keys for  this cont ext. This  means
  1400        * gen erating th em if it's  not alrea dy been do ne.
  1401        *
  1402        * Not e that we  currently  do not imp lement any  ciphersui tes that u se
  1403        * str ong epheme ral RSA. ( We do not  support th e EXPORT10 24 ciphers uites
  1404        * and  standard  RSA cipher suites pro hibit ephe meral mode  for some  reason)
  1405        * Thi s means th at export  is always  true and 5 12 bit key s are gene rated.
  1406        */
  1407       privat e boolean  setupEphem eralRSAKey s(boolean  export) {
  1408           Ke yPair kp =  sslContex t.getEphem eralKeyMan ager().
  1409                             getRSA KeyPair(ex port, sslC ontext.get SecureRand om());
  1410           if  (kp == nu ll) {
  1411                return f alse;
  1412           }  else {
  1413                tempPubl icKey = kp .getPublic ();
  1414                tempPriv ateKey = k p.getPriva te();
  1415                return t rue;
  1416           }
  1417       }
  1418  
  1419       /*
  1420        * Acq uire some  "ephemeral " Diffie-H ellman  ke ys for thi s handshak e.
  1421        * We  don't reus e these, f or improve d forward  secrecy.
  1422        */
  1423       privat e void set upEphemera lDHKeys(bo olean expo rt, Key ke y) {
  1424           /*
  1425            *  768 bits  ephemeral  DH private  keys were  used to b e used in
  1426            *  ServerKey Exchange e xcept that  exportabl e ciphers  max out at  512
  1427            *  bits modu lus values . We still  adhere to  this beha vior in le gacy
  1428            *  mode (sys tem proper ty "jdk.tl s.ephemera lDHKeySize " is defin ed
  1429            *  as "legac y").
  1430            *
  1431            *  Old JDK ( JDK 7 and  previous)  releases d on't suppo rt DH keys  bigger
  1432            *  than 1024  bits. We  have to co nsider the  compatibi lity requi rement.
  1433            *  1024 bits  DH key is  always us ed for non -exportabl e cipher s uites
  1434            *  in defaul t mode (sy stem prope rty "jdk.t ls.ephemer alDHKeySiz e"
  1435            *  is not de fined).
  1436            *
  1437            *  However,  if applica tions want  more stro nger stren gth, setti ng
  1438            *  system pr operty "jd k.tls.ephe meralDHKey Size" to " matched"
  1439            *  is a work around to  use epheme ral DH key  which siz e matches  the
  1440            *  correspon ding authe ntication  key. For e xample, if  the publi c key
  1441            *  size of a n authenti cation cer tificate i s 2048 bit s, then th e
  1442            *  ephemeral  DH key si ze should  be 2048 bi ts accordi ngly unles s
  1443            *  the ciphe r suite is  exportabl e.  This k ey sizing  scheme kee ps
  1444            *  the crypt ographic s trength co nsistent b etween aut henticatio n
  1445            *  keys and  key-exchan ge keys.
  1446            *
  1447            *  Applicati ons may al so want to  customize  the ephem eral DH ke y size
  1448            *  to a fixe d length f or non-exp ortable ci pher suite s. This ca n be
  1449            *  approache d by setti ng system  property " jdk.tls.ep hemeralDHK eySize"
  1450            *  to a vali d positive  integer b etween 102 4 and 8192  bits, inc lusive.
  1451            *
  1452            *  Note that  the minim um accepta ble key si ze is 1024  bits exce pt
  1453            *  exportabl e cipher s uites or l egacy mode .
  1454            *
  1455            *  Note that  per RFC 2 246, the k ey size li mit of DH  is 512 bit s for
  1456            *  exportabl e cipher s uites.  Be cause of t he weaknes s, exporta ble
  1457            *  cipher su ites are d eprecated  since TLS  v1.1 and t hey are no t
  1458            *  enabled b y default  in Oracle  provider.  The legacy  behavior  is
  1459            *  reserved  and 512 bi ts DH key  is always  used for e xportable
  1460            *  cipher su ites.
  1461            * /
  1462           in t keySize  = export ?  512 : 102 4;            // defa ult mode
  1463           if  (!export)  {
  1464                if (useL egacyEphem eralDHKeys ) {           // lega cy mode
  1465                    keyS ize = 768;
  1466                } else i f (useSmar tEphemeral DHKeys) {     // matc hed mode
  1467                    if ( key != nul l) {
  1468                         int ks = K eyUtil.get KeySize(ke y);
  1469  
  1470                         // DH para meter gene ration can  be extrem ely slow,  make
  1471                         // sure to  use one o f the supp orted pre- computed D H
  1472                         // paramet ers (see D HCrypt cla ss).
  1473                         //
  1474                         // Old dep loyed appl ications m ay not be  ready to s upport
  1475                         // DH key  sizes bigg er than 20 48 bits.   Please DON 'T use
  1476                         // value o ther than  1024 and 2 048 at pre sent.  May  improve
  1477                         // the und erlying pr oviders an d key size  limit in  the
  1478                         // future  when the c ompatibili ty and int eroperabil ity
  1479                         // impact  is limited .
  1480                         //
  1481                         // keySize  = ks <= 1 024 ? 1024  : (ks >=  2048 ? 204 8 : ks);
  1482                         keySize =  ks <= 1024  ? 1024 :  2048;
  1483                    } //  Otherwise , anonymou s cipher s uites, 102 4-bit is u sed.
  1484                } else i f (customi zedDHKeySi ze > 0) {     // cust omized mod e
  1485                    keyS ize = cust omizedDHKe ySize;
  1486                }
  1487           }
  1488  
  1489           dh  = new DHC rypt(keySi ze, sslCon text.getSe cureRandom ());
  1490       }
  1491  
  1492       // Set up the eph emeral ECD H paramete rs.
  1493       // If  we cannot  continue b ecause we  do not sup port any o f the curv es that
  1494       // the  client re quested, r eturn fals e. Otherwi se (all is  well), re turn true.
  1495       privat e boolean  setupEphem eralECDHKe ys() {
  1496           in t index =  (requested Curves !=  null) ?
  1497                    requ estedCurve s.getPrefe rredCurve( algorithmC onstraints ) :
  1498                    Elli pticCurves Extension. getActiveC urves(algo rithmConst raints);
  1499           if  (index <  0) {
  1500                // no ma tch found,  cannot us e this cip hersuite
  1501                return f alse;
  1502           }
  1503  
  1504           ec dh = new E CDHCrypt(i ndex, sslC ontext.get SecureRand om());
  1505           re turn true;
  1506       }
  1507  
  1508       privat e void set upStaticEC DHKeys() {
  1509           //  don't nee d to check  whether t he curve i s supporte d, already  done
  1510           //  in setupP rivateKeyA ndChain().
  1511           ec dh = new E CDHCrypt(p rivateKey,  certs[0]. getPublicK ey());
  1512       }
  1513  
  1514       /**
  1515        * Ret rieve the  server key  and certi ficate for  the speci fied algor ithm
  1516        * fro m the KeyM anager and  set the i nstance va riables.
  1517        *
  1518        * @re turn true  if success ful, false  if not av ailable or  invalid
  1519        */
  1520       privat e boolean  setupPriva teKeyAndCh ain(String  algorithm ) {
  1521           X5 09Extended KeyManager  km = sslC ontext.get X509KeyMan ager();
  1522           St ring alias ;
  1523           if  (conn !=  null) {
  1524                alias =  km.chooseS erverAlias (algorithm , null, co nn);
  1525           }  else {
  1526                alias =  km.chooseE ngineServe rAlias(alg orithm, nu ll, engine );
  1527           }
  1528           if  (alias ==  null) {
  1529                return f alse;
  1530           }
  1531           Pr ivateKey t empPrivate Key = km.g etPrivateK ey(alias);
  1532           if  (tempPriv ateKey ==  null) {
  1533                return f alse;
  1534           }
  1535           X5 09Certific ate[] temp Certs = km .getCertif icateChain (alias);
  1536           if  ((tempCer ts == null ) || (temp Certs.leng th == 0))  {
  1537                return f alse;
  1538           }
  1539           St ring keyAl gorithm =  algorithm. split("_") [0];
  1540           Pu blicKey pu blicKey =  tempCerts[ 0].getPubl icKey();
  1541           if  ((tempPri vateKey.ge tAlgorithm ().equals( keyAlgorit hm) == fal se)
  1542                    || ( publicKey. getAlgorit hm().equal s(keyAlgor ithm) == f alse)) {
  1543                return f alse;
  1544           }
  1545           //  For ECC c erts, chec k whether  we support  the EC do main param eters.
  1546           //  If the cl ient sent  a Supporte dEllipticC urves Clie ntHello ex tension,
  1547           //  check aga inst that  too.
  1548           if  (keyAlgor ithm.equal s("EC")) {
  1549                if (publ icKey inst anceof ECP ublicKey = = false) {
  1550                    retu rn false;
  1551                }
  1552                ECParame terSpec pa rams = ((E CPublicKey )publicKey ).getParam s();
  1553                int id =  EllipticC urvesExten sion.getCu rveIndex(p arams);
  1554                if ((id  <= 0) || ! EllipticCu rvesExtens ion.isSupp orted(id)  ||
  1555                    ((re questedCur ves != nul l) && !req uestedCurv es.contain s(id))) {
  1556                    retu rn false;
  1557                }
  1558           }
  1559           th is.private Key = temp PrivateKey ;
  1560           th is.certs =  tempCerts ;
  1561           re turn true;
  1562       }
  1563  
  1564       /**
  1565        * Ret rieve the  Kerberos k ey for the  specified  server pr incipal
  1566        * fro m the JAAS  configura tion file.
  1567        *
  1568        * @re turn true  if success ful, false  if not av ailable or  invalid
  1569        */
  1570       privat e boolean  setupKerbe rosKeys()  {
  1571           if  (serviceC reds != nu ll) {
  1572                return t rue;
  1573           }
  1574           tr y {
  1575                final Ac cessContro lContext a cc = getAc cSE();
  1576                serviceC reds = Acc essControl ler.doPriv ileged(
  1577                    // E liminate d ependency  on Kerbero sKey
  1578                    new  Privileged ExceptionA ction<Obje ct>() {
  1579                    @Ove rride
  1580                    publ ic Object  run() thro ws Excepti on {
  1581                         // get ker beros key  for the de fault prin cipal
  1582                         return Krb 5Helper.ge tServiceCr eds(acc);
  1583                             }});
  1584  
  1585                  // check p ermission  to access  and use th PW        key of the
  1586                // Kerbe rized "hos t" service
  1587                if (serv iceCreds ! = null) {
  1588                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  1589                         System.out .println(" Using Kerb eros creds ");
  1590                    }
  1591                    Stri ng serverP rincipal =
  1592                             Krb5He lper.getSe rverPrinci palName(se rviceCreds );
  1593                    if ( serverPrin cipal != n ull) {
  1594                         // When se rvice is b ound, we c heck ASAP.  Otherwise ,
  1595                         // will ch eck after  client req uest is re ceived
  1596                         // in in K erberos Cl ientKeyExc hange
  1597                         SecurityMa nager sm =  System.ge tSecurityM anager();
  1598                         try {
  1599                             if (sm  != null)  {
  1600                                 //  Eliminate  dependenc y on Servi cePermissi on
  1601                                 sm .checkPerm ission(Krb 5Helper.ge tServicePe rmission(
  1602                                          serv erPrincipa l, "accept "), acc);
  1603                             }
  1604                         } catch (S ecurityExc eption se)  {
  1605                             servic eCreds = n ull;
  1606                             // Do  not destro y keys. Wi ll affect  Subject
  1607                             if (de bug != nul l && Debug .isOn("han dshake"))  {
  1608                                 Sy stem.out.p rintln("Pe rmission t o access K erberos"
  1609                                            + "  PW        key denied ");
  1610                             }
  1611                             return  false;
  1612                         }
  1613                    }
  1614                }
  1615                return s erviceCred s != null;
  1616           }  catch (Pri vilegedAct ionExcepti on e) {
  1617                // Likel y exceptio n here is  LoginExcep tin
  1618                if (debu g != null  && Debug.i sOn("hands hake")) {
  1619                    Syst em.out.pri ntln("Atte mpt to obt ain Kerber os key fai led: "
  1620                                      + e.toSt ring());
  1621                }
  1622                return f alse;
  1623           }
  1624       }
  1625  
  1626       /*
  1627          * For Kerb eros ciphe rs, the pr emaster  PW        is encrypt ed using
  1628        * the  session k ey. See RF C 2712.
  1629        */
  1630       privat e SecretKe y clientKe yExchange( KerberosCl ientKeyExc hange mesg )
  1631           th rows IOExc eption {
  1632  
  1633           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1634                mesg.pri nt(System. out);
  1635           }
  1636  
  1637           //  Record th e principa ls involve d in excha nge
  1638           se ssion.setP eerPrincip al(mesg.ge tPeerPrinc ipal());
  1639           se ssion.setL ocalPrinci pal(mesg.g etLocalPri ncipal());
  1640  
  1641           by te[] b = m esg.getUne ncryptedPr eMasterSec ret();
  1642           re turn new S ecretKeySp ec(b, "Tls PremasterS ecret");
  1643       }
  1644  
  1645       /*
  1646        * Dif fie Hellma n key exch ange is us ed when th e server p resented
  1647        * D-H  parameter s in its c ertificate  (signed u sing RSA o r DSS/DSA) ,
  1648        * or  else the s erver pres ented no c ertificate  but sent  D-H params
  1649        * in  a ServerKe yExchange  message.   Use of D-H  is specif ied by the
  1650        * cip her suite  chosen.
  1651        *
  1652        * The  message o ptionally  contains t he client' s D-H publ ic key (if
  1653        * it  wasn't not  sent in a  client ce rtificate) .  As alwa ys with D- H,
  1654        * if  a client a nd a serve r have eac h other's  D-H public  keys and
  1655        * the y use comm on algorit hm paramet ers, they  have a sha red key
  1656        * tha t's derive d via the  D-H calcul ation.  Th at key bec omes the
  1657          * pre-mast er  PW      .
  1658        */
  1659       privat e SecretKe y clientKe yExchange( DHClientKe yExchange  mesg)
  1660                throws I OException  {
  1661  
  1662           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1663                mesg.pri nt(System. out);
  1664           }
  1665  
  1666           Bi gInteger p ublicKeyVa lue = mesg .getClient PublicKey( );
  1667  
  1668           //  check alg orithm con straints
  1669           dh .checkCons traints(al gorithmCon straints,  publicKeyV alue);
  1670  
  1671           re turn dh.ge tAgreedSec ret(public KeyValue,  false);
  1672       }
  1673  
  1674       privat e SecretKe y clientKe yExchange( ECDHClient KeyExchang e mesg)
  1675                throws I OException  {
  1676  
  1677           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1678                mesg.pri nt(System. out);
  1679           }
  1680  
  1681           by te[] publi cPoint = m esg.getEnc odedPoint( );
  1682  
  1683           //  check alg orithm con straints
  1684           ec dh.checkCo nstraints( algorithmC onstraints , publicPo int);
  1685  
  1686           re turn ecdh. getAgreedS ecret(publ icPoint);
  1687       }
  1688  
  1689       /*
  1690        * Cli ent wrote  a message  to verify  the certif icate it s ent earlie r.
  1691        *
  1692        * Not e that thi s certific ate isn't  involved i n key exch ange.  Cli ent
  1693        * aut henticatio n messages  are inclu ded in the  checksums  used to
  1694        * val idate the  handshake  (e.g. Fini shed messa ges).  Oth er than th at,
  1695        * the  _exact_ i dentity of  the clien t is less  fundamenta l to proto col
  1696          * security  than its  role in se lecting ke ys via the  pre-maste PW      .
  1697        */
  1698       privat e void cli entCertifi cateVerify (Certifica teVerify m esg)
  1699                throws I OException  {
  1700  
  1701           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1702                mesg.pri nt(System. out);
  1703           }
  1704  
  1705           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1706                Signatur eAndHashAl gorithm si gnAlg =
  1707                    mesg .getPrefer ableSignat ureAlgorit hm();
  1708                if (sign Alg == nul l) {
  1709                    thro w new SSLH andshakeEx ception(
  1710                             "Illeg al Certifi cateVerify  message") ;
  1711                }
  1712  
  1713                String h ashAlg =
  1714                    Sign atureAndHa shAlgorith m.getHashA lgorithmNa me(signAlg );
  1715                if (hash Alg == nul l || hashA lg.length( ) == 0) {
  1716                    thro w new SSLH andshakeEx ception(
  1717                             "No su pported ha sh algorit hm");
  1718                }
  1719           }
  1720  
  1721           tr y {
  1722                PublicKe y publicKe y =
  1723                    sess ion.getPee rCertifica tes()[0].g etPublicKe y();
  1724  
  1725                boolean  valid = me sg.verify( protocolVe rsion, han dshakeHash ,
  1726                                               publicKey,  session.g etMasterSe cret());
  1727                if (vali d == false ) {
  1728                    fata lSE(Alerts .alert_bad _certifica te,
  1729                                 "c ertificate  verify me ssage sign ature erro r");
  1730                }
  1731           }  catch (Gen eralSecuri tyExceptio n e) {
  1732                fatalSE( Alerts.ale rt_bad_cer tificate,
  1733                    "cer tificate v erify form at error",  e);
  1734           }
  1735  
  1736           //  reset the  flag for  clientCert ificateVer ify messag e
  1737           ne edClientVe rify = fal se;
  1738       }
  1739  
  1740  
  1741       /*
  1742        * Cli ent writes  "finished " at the e nd of its  handshake,  after cip her
  1743        * spe c is chang ed.   We v erify it a nd then se nd ours.
  1744        *
  1745        * Whe n we're re suming a s ession, we 'll have a lready sen t our own
  1746        * Fin ished mess age so jus t the veri fication i s needed.
  1747        */
  1748       privat e void cli entFinishe d(Finished  mesg) thr ows IOExce ption {
  1749           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1750                mesg.pri nt(System. out);
  1751           }
  1752  
  1753           /*
  1754            *  Verify if  client di d send the  certifica te when cl ient
  1755            *  authentic ation was  required,  otherwise  server sho uld not pr oceed
  1756            * /
  1757           if  (doClient Auth == SS LEngineImp l.clauth_r equired) {
  1758               // get X5 00Principa l of the e nd-entity  certificat e for X509 -based
  1759               // cipher suites, or  Kerberos  principal  for Kerber os ciphers uites
  1760               session.g etPeerPrin cipal();
  1761           }
  1762  
  1763           /*
  1764            *  Verify if  client di d send cli entCertifi cateVerify  message f ollowing
  1765            *  the clien t Certific ate, other wise serve r should n ot proceed
  1766            * /
  1767           if  (needClie ntVerify)  {
  1768                    fata lSE(Alerts .alert_han dshake_fai lure,
  1769                             "clien t did not  send certi ficate ver ify messag e");
  1770           }
  1771  
  1772           /*
  1773            *  Verify th e client's  message w ith the "b efore" dig est of mes sages,
  1774            *  and forge t about co ntinuing t o use that  digest.
  1775            * /
  1776           bo olean veri fied = mes g.verify(h andshakeHa sh, Finish ed.CLIENT,
  1777                session. getMasterS ecret());
  1778  
  1779           if  (!verifie d) {
  1780                fatalSE( Alerts.ale rt_handsha ke_failure ,
  1781                             "clien t 'finishe d' message  doesn't v erify");
  1782                // NOTRE ACHED
  1783           }
  1784  
  1785           /*
  1786            *  save clie nt verify  data for s ecure rene gotiation
  1787            * /
  1788           if  (secureRe negotiatio n) {
  1789                clientVe rifyData =  mesg.getV erifyData( );
  1790           }
  1791  
  1792           /*
  1793            *  OK, it ve rified.  I f we're do ing the fu ll handsha ke, add th at
  1794            *  "Finished " message  to the has h of hands hake messa ges, then  send
  1795            *  the chang e_cipher_s pec and Fi nished mes sage.
  1796            * /
  1797           if  (!resumin gSession)  {
  1798                input.di gestNow();
  1799                sendChan geCipherAn dFinish(tr ue);
  1800           }
  1801  
  1802           /*
  1803            *  Update th e session  cache only  after the  handshake  completed , else
  1804            *  we're ope n to an at tack again st a parti ally compl eted hands hake.
  1805            * /
  1806           se ssion.setL astAccesse dTime(Syst em.current TimeMillis ());
  1807           if  (!resumin gSession & & session. isRejoinab le()) {
  1808                ((SSLSes sionContex tImpl)sslC ontext.eng ineGetServ erSessionC ontext())
  1809                    .put (session);
  1810                if (debu g != null  && Debug.i sOn("sessi on")) {
  1811                    Syst em.out.pri ntln(
  1812                         "%% Cached  server se ssion: " +  session);
  1813                }
  1814           }  else if (! resumingSe ssion &&
  1815                    debu g != null  && Debug.i sOn("sessi on")) {
  1816                System.o ut.println (
  1817                    "%%  Didn't cac he non-res umable ser ver sessio n: "
  1818                    + se ssion);
  1819           }
  1820       }
  1821  
  1822       /*
  1823        * Com pute finis hed messag e with the  "server"  digest (an d then for get
  1824        * abo ut that di gest, it c an't be us ed again).
  1825        */
  1826       privat e void sen dChangeCip herAndFini sh(boolean  finishedT ag)
  1827                throws I OException  {
  1828  
  1829           ou tput.flush ();
  1830  
  1831           Fi nished mes g = new Fi nished(pro tocolVersi on, handsh akeHash,
  1832                Finished .SERVER, s ession.get MasterSecr et(), ciph erSuite);
  1833  
  1834           /*
  1835            *  Send the  change_cip her_spec r ecord; the n our Fini shed hands hake
  1836            *  message w ill be the  last hand shake mess age.  Flus h, and now  we
  1837            *  are ready  for appli cation dat a!!
  1838            * /
  1839           se ndChangeCi pherSpec(m esg, finis hedTag);
  1840  
  1841           /*
  1842            *  save serv er verify  data for s ecure rene gotiation
  1843            * /
  1844           if  (secureRe negotiatio n) {
  1845                serverVe rifyData =  mesg.getV erifyData( );
  1846           }
  1847  
  1848           /*
  1849            *  Update st ate machin e so clien t MUST sen d 'finishe d' next
  1850            *  The updat e should o nly take p lace if it  is not in  the fast
  1851            *  handshake  mode sinc e the serv er has to  wait for a  finished
  1852            *  message f rom the cl ient.
  1853            * /
  1854           if  (finished Tag) {
  1855                state =  HandshakeM essage.ht_ finished;
  1856           }
  1857       }
  1858  
  1859  
  1860       /*
  1861        * Ret urns a Hel loRequest  message to  kickstart  renegotia tions
  1862        */
  1863       @Overr ide
  1864       Handsh akeMessage  getKickst artMessage () {
  1865           re turn new H elloReques t();
  1866       }
  1867  
  1868  
  1869       /*
  1870        * Fau lt detecte d during h andshake.
  1871        */
  1872       @Overr ide
  1873       void h andshakeAl ert(byte d escription ) throws S SLProtocol Exception  {
  1874  
  1875           St ring messa ge = Alert s.alertDes cription(d escription );
  1876  
  1877           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1878                System.o ut.println ("SSL -- h andshake a lert:  "
  1879                    + me ssage);
  1880           }
  1881  
  1882           /*
  1883            *  It's ok t o get a no _certifica te alert f rom a clie nt of whic h
  1884            *  we *reque sted* auth entication  informati on.
  1885            *  However,  if we *req uired* it,  then this  is not ac ceptable.
  1886            *
  1887            *  Anyone ca lling getP eerCertifi cates() on  the
  1888            *  session w ill get an  SSLPeerUn verifiedEx ception.
  1889            * /
  1890           if  ((descrip tion == Al erts.alert _no_certif icate) &&
  1891                    (doC lientAuth  == SSLEngi neImpl.cla uth_reques ted)) {
  1892                return;
  1893           }
  1894  
  1895           th row new SS LProtocolE xception(" handshake  alert: " +  message);
  1896       }
  1897  
  1898       /*
  1899        * RSA  key excha nge is nor mally used .  The cli ent encryp ts a "pre- master
  1900          PW      " with the  server's  public key , from the  Certifica te (or els e
  1901        * Ser verKeyExch ange) mess age that w as sent to  it by the  server.   That's
  1902        * dec rypted usi ng the pri vate key b efore we g et here.
  1903        */
  1904       privat e SecretKe y clientKe yExchange( RSAClientK eyExchange  mesg)
  1905                throws I OException  {
  1906  
  1907           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1908                mesg.pri nt(System. out);
  1909           }
  1910           re turn mesg. preMaster;
  1911       }
  1912  
  1913       /*
  1914        * Ver ify the ce rtificate  sent by th e client.  We'll only  get one i f we
  1915        * sen t a Certif icateReque st to requ est client  authentic ation. If  we
  1916        * are  in TLS mo de, the cl ient may s end a mess age with n o certific ates
  1917        * to  indicate i t does not  have an a ppropriate  chain. (I n SSLv3 mo de,
  1918        * it  would send  a no cert ificate al ert).
  1919        */
  1920       privat e void cli entCertifi cate(Certi ficateMsg  mesg) thro ws IOExcep tion {
  1921           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1922                mesg.pri nt(System. out);
  1923           }
  1924  
  1925           X5 09Certific ate[] peer Certs = me sg.getCert ificateCha in();
  1926  
  1927           if  (peerCert s.length = = 0) {
  1928                /*
  1929                 * If th e client a uthenticat ion is onl y *REQUEST ED* (e.g.
  1930                 * not * REQUIRED*,  this is a n acceptab le conditi on.)
  1931                 */
  1932                if (doCl ientAuth = = SSLEngin eImpl.clau th_request ed) {
  1933                    retu rn;
  1934                } else {
  1935                    fata lSE(Alerts .alert_bad _certifica te,
  1936                         "null cert  chain");
  1937                }
  1938           }
  1939  
  1940           //  ask the t rust manag er to veri fy the cha in
  1941           X5 09TrustMan ager tm =  sslContext .getX509Tr ustManager ();
  1942  
  1943           tr y {
  1944                // find  out the ty pes of cli ent authen tication u sed
  1945                PublicKe y key = pe erCerts[0] .getPublic Key();
  1946                String k eyAlgorith m = key.ge tAlgorithm ();
  1947                String a uthType;
  1948                if (keyA lgorithm.e quals("RSA ")) {
  1949                    auth Type = "RS A";
  1950                } else i f (keyAlgo rithm.equa ls("DSA"))  {
  1951                    auth Type = "DS A";
  1952                } else i f (keyAlgo rithm.equa ls("EC"))  {
  1953                    auth Type = "EC ";
  1954                } else {
  1955                    // u nknown pub lic key ty pe
  1956                    auth Type = "UN KNOWN";
  1957                }
  1958  
  1959                if (tm i nstanceof  X509Extend edTrustMan ager) {
  1960                    if ( conn != nu ll) {
  1961                         ((X509Exte ndedTrustM anager)tm) .checkClie ntTrusted(
  1962                             peerCe rts.clone( ),
  1963                             authTy pe,
  1964                             conn);
  1965                    } el se {
  1966                         ((X509Exte ndedTrustM anager)tm) .checkClie ntTrusted(
  1967                             peerCe rts.clone( ),
  1968                             authTy pe,
  1969                             engine );
  1970                    }
  1971                } else {
  1972                    // U nlikely to  happen, b ecause we  have wrapp ed the old
  1973                    // X 509TrustMa nager with  the new X 509Extende dTrustMana ger.
  1974                    thro w new Cert ificateExc eption(
  1975                         "Improper  X509TrustM anager imp lementatio n");
  1976                }
  1977           }  catch (Cer tificateEx ception e)  {
  1978                // This  will throw  an except ion, so in clude the  original e rror.
  1979                fatalSE( Alerts.ale rt_certifi cate_unkno wn, e);
  1980           }
  1981           //  set the f lag for cl ientCertif icateVerif y message
  1982           ne edClientVe rify = tru e;
  1983  
  1984           se ssion.setP eerCertifi cates(peer Certs);
  1985       }
  1986   }