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

278.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 Handshaker.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 Handshaker.java Wed Sep 12 17:54:39 2018 UTC

278.2 Comparison summary

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

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

278.4 Active regular expressions

No regular expressions were active.

278.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 199 6, 2016, 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  
  33   import jav ax.crypto. *;
  34   import jav ax.crypto. spec.*;
  35  
  36   import jav ax.net.ssl .*;
  37   import sun .misc.HexD umpEncoder ;
  38  
  39   import sun .security. internal.s pec.*;
  40   import sun .security. internal.i nterfaces. TlsMasterS ecret;
  41  
  42   import sun .security. ssl.Handsh akeMessage .*;
  43   import sun .security. ssl.Cipher Suite.*;
  44  
  45   import sta tic sun.se curity.ssl .CipherSui te.PRF.*;
  46   import sta tic sun.se curity.ssl .CipherSui te.CipherT ype.*;
  47  
  48   /**
  49    * Handsha ker ... pr ocesses ha ndshake re cords from  an SSL V3 .0
  50    * data st ream, hand ling all t he details  of the ha ndshake pr otocol.
  51    *
  52    * Note th at the rea l protocol  work is d one in two  subclasse s, the  ba se
  53    * class j ust provid es the con trol flow  and key ge neration f ramework.
  54    *
  55    * @author  David Bro wnell
  56    */
  57   abstract c lass Hands haker {
  58  
  59       // pro tocol vers ion being  establishe d using th is Handsha ker
  60       Protoc olVersion  protocolVe rsion;
  61  
  62       // the  currently  active pr otocol ver sion durin g a renego tiation
  63       Protoc olVersion  activeProt ocolVersio n;
  64  
  65       // sec urity para meters for  secure re negotiatio n.
  66       boolea n secureRe negotiatio n;
  67       byte[]  clientVer ifyData;
  68       byte[]  serverVer ifyData;
  69  
  70       // Is  it an init ial negoti ation  or  a renegoti ation?
  71       boolea n isInitia lHandshake ;
  72  
  73       // Lis t of enabl ed protoco ls
  74       privat e Protocol List enabl edProtocol s;
  75  
  76       // Lis t of enabl ed CipherS uites
  77       privat e CipherSu iteList en abledCiphe rSuites;
  78  
  79       // The  endpoint  identifica tion proto col
  80       String  identific ationProto col;
  81  
  82       // The  cryptogra phic algor ithm const raints
  83       Algori thmConstra ints algor ithmConstr aints = nu ll;
  84  
  85       // Loc al support ed signatu re and alg orithms
  86       privat e Collecti on<Signatu reAndHashA lgorithm>  localSuppo rtedSignAl gs;
  87  
  88       // Pee r supporte d signatur e and algo rithms
  89       Collec tion<Signa tureAndHas hAlgorithm > peerSupp ortedSignA lgs;
  90  
  91       /*
  92        * Lis t of activ e protocol s
  93        *
  94        * Act ive protoc ols is a s ubset of e nabled pro tocols, an d will
  95        * con tain only  those prot ocols that  have vail d cipher s uites
  96        * ena bled.
  97        */
  98       privat e Protocol List activ eProtocols ;
  99  
  100       /*
  101        * Lis t of activ e cipher s uites
  102        *
  103        * Act ive cipher  suites is  a subset  of enabled  cipher su ites, and  will
  104        * con tain only  those ciph er suites  available  for the ac tive proto cols.
  105        */
  106       privat e CipherSu iteList ac tiveCipher Suites;
  107  
  108       // The  server na me indicat ion and ma tchers
  109       List<S NIServerNa me> server Names = Co llections. <SNIServer Name>empty List();
  110       Collec tion<SNIMa tcher> sni Matchers =  Collectio ns.<SNIMat cher>empty List();
  111  
  112       privat e boolean  isClient;
  113       privat e boolean  needCertVe rify;
  114  
  115       SSLSoc ketImpl co nn = null;
  116       SSLEng ineImpl en gine = nul l;
  117  
  118       Handsh akeHash ha ndshakeHas h;
  119       Handsh akeInStrea m input;
  120       Handsh akeOutStre am output;
  121       int st ate;
  122       SSLCon textImpl s slContext;
  123       Random Cookie cln t_random,  svr_random ;
  124       SSLSes sionImpl s ession;
  125  
  126       // cur rent Ciphe rSuite. Ne ver null,  initially  SSL_NULL_W ITH_NULL_N ULL
  127       Cipher Suite ciph erSuite;
  128  
  129       // cur rent key e xchange. N ever null,  initially  K_NULL
  130       KeyExc hange keyE xchange;
  131  
  132       // Tru e if this  session is  being res umed (fast  handshake )
  133       boolea n resuming Session;
  134  
  135       // Tru e if it's  OK to star t a new SS L session
  136       boolea n enableNe wSession;
  137  
  138       // Tru e if sessi on keys ha ve been ca lculated a nd the cal ler may re ceive
  139       // and  process a  ChangeCip herSpec me ssage
  140       privat e boolean  sessKeysCa lculated;
  141  
  142       // Whe ther local  cipher su ites prefe rence shou ld be hono red during
  143       // han dshaking?
  144       //
  145       // Not e that in  this provi der, this  option onl y applies  to server  side.
  146       // Loc al cipher  suites pre ference is  always ho nored in c lient side  in
  147       // thi s provider .
  148       boolea n preferLo calCipherS uites = fa lse;
  149  
  150       // Tem porary sto rage for t he individ ual keys.  Set by
  151       // cal culateConn ectionKeys () and cle ared once  the cipher s are
  152       // act ivated.
  153       privat e SecretKe y clntWrit eKey, svrW riteKey;
  154       privat e IvParame terSpec cl ntWriteIV,  svrWriteI V;
  155       privat e SecretKe y clntMacS ecret, svr MacSecret;
  156  
  157       /*
  158        * Del egated tas k subsyste m data str uctures.
  159        *
  160        * If  thrown is  set, we ne ed to prop agate this  back imme diately
  161        * on  entry into  processMe ssage().
  162        *
  163        * Dat a is prote cted by th e SSLEngin e.this loc k.
  164        */
  165       privat e volatile  boolean t askDelegat ed = false ;
  166       privat e volatile  Delegated Task<?> de legatedTas k = null;
  167       privat e volatile  Exception  thrown =  null;
  168  
  169       // Cou ld probabl y use a ja va.util.co ncurrent.a tomic.Atom icReferenc e
  170       // her e instead  of using t his lock.   Consider  changing.
  171       privat e Object t hrownLock  = new Obje ct();
  172  
  173       // Cla ss and sub class dyna mic debugg ing suppor t
  174       static  final Deb ug debug =  Debug.get Instance(" ssl");
  175  
  176       // By  default, d isable the  unsafe le gacy sessi on renegot iation
  177       static  final boo lean allow UnsafeRene gotiation  = Debug.ge tBooleanPr operty(
  178                         "sun.secur ity.ssl.al lowUnsafeR enegotiati on", false );
  179  
  180       // For  maximum i nteroperab ility and  backward c ompatibili ty, RFC 57 46
  181       // all ows server  (or clien t) to acce pt ClientH ello (or S erverHello )
  182       // mes sage witho ut the sec ure renego tiation_in fo extensi on or SCSV .
  183       //
  184       // For  maximum s ecurity, R FC 5746 al so allows  server (or  client) t o
  185       // rej ect such m essage wit h a fatal  "handshake _failure"  alert.
  186       //
  187       // By  default, a llow such  legacy hel lo message s.
  188       static  final boo lean allow LegacyHell oMessages  = Debug.ge tBooleanPr operty(
  189                         "sun.secur ity.ssl.al lowLegacyH elloMessag es", true) ;
  190  
  191       // To  prevent th e TLS rene gotiation  issues, by  setting s ystem prop erty
  192       // "jd k.tls.reje ctClientIn itiatedRen egotiation " to true,  applicati ons in
  193       // ser ver side c an disable  all clien t initiate d SSL rene gotiations
  194       // reg ardless of  the suppo rt of TLS  protocols.
  195       //
  196       // By  default, a llow clien t initiate d renegoti ations.
  197       static  final boo lean rejec tClientIni tiatedRene go =
  198                Debug.ge tBooleanPr operty(
  199                    "jdk .tls.rejec tClientIni tiatedRene gotiation" , false);
  200  
  201         // To swit ch off the  extended_ master_ PW        extension.
  202       static  final boo lean useEx tendedMast erSecret;
  203  
  204       // All ow session  resumptio n without  Extended M aster Secr et extensi on.
  205       static  final boo lean allow LegacyResu mption =
  206                Debug.ge tBooleanPr operty("jd k.tls.allo wLegacyRes umption",  true);
  207  
  208       // All ow full ha ndshake wi thout Exte nded Maste r Secret e xtension.
  209       static  final boo lean allow LegacyMast erSecret =
  210                Debug.ge tBooleanPr operty("jd k.tls.allo wLegacyMas terSecret" , true);
  211  
  212         // Is it r equested t o use exte nded maste PW        extension?
  213       boolea n requeste dToUseEMS  = false;
  214  
  215       // nee d to dispo se the obj ect when i t is inval idated
  216       boolea n invalida ted;
  217  
  218         // Is the  extended_m aster_ PW        extension  supported?
  219       static  {
  220           bo olean supp ortExtende dMasterSec ret = true ;
  221           tr y {
  222                KeyGener ator kg =
  223                    Jsse Jce.getKey Generator( "SunTlsExt endedMaste rSecret");
  224           }  catch (NoS uchAlgorit hmExceptio n nae) {
  225                supportE xtendedMas terSecret  = false;
  226           }
  227  
  228           if  (supportE xtendedMas terSecret)  {
  229                useExten dedMasterS ecret = De bug.getBoo leanProper ty(
  230                         "jdk.tls.u seExtended MasterSecr et", true) ;
  231           }  else {
  232                useExten dedMasterS ecret = fa lse;
  233           }
  234       }
  235  
  236       Handsh aker(SSLSo cketImpl c , SSLConte xtImpl con text,
  237                Protocol List enabl edProtocol s, boolean  needCertV erify,
  238                boolean  isClient,  ProtocolVe rsion acti veProtocol Version,
  239                boolean  isInitialH andshake,  boolean se cureRenego tiation,
  240                byte[] c lientVerif yData, byt e[] server VerifyData ) {
  241           th is.conn =  c;
  242           in it(context , enabledP rotocols,  needCertVe rify, isCl ient,
  243                activePr otocolVers ion, isIni tialHandsh ake, secur eRenegotia tion,
  244                clientVe rifyData,  serverVeri fyData);
  245      }
  246  
  247       Handsh aker(SSLEn gineImpl e ngine, SSL ContextImp l context,
  248                Protocol List enabl edProtocol s, boolean  needCertV erify,
  249                boolean  isClient,  ProtocolVe rsion acti veProtocol Version,
  250                boolean  isInitialH andshake,  boolean se cureRenego tiation,
  251                byte[] c lientVerif yData, byt e[] server VerifyData ) {
  252           th is.engine  = engine;
  253           in it(context , enabledP rotocols,  needCertVe rify, isCl ient,
  254                activePr otocolVers ion, isIni tialHandsh ake, secur eRenegotia tion,
  255                clientVe rifyData,  serverVeri fyData);
  256       }
  257  
  258       privat e void ini t(SSLConte xtImpl con text, Prot ocolList e nabledProt ocols,
  259                boolean  needCertVe rify, bool ean isClie nt,
  260                Protocol Version ac tiveProtoc olVersion,
  261                boolean  isInitialH andshake,  boolean se cureRenego tiation,
  262                byte[] c lientVerif yData, byt e[] server VerifyData ) {
  263  
  264           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  265                System.o ut.println (
  266                    "All ow unsafe  renegotiat ion: " + a llowUnsafe Renegotiat ion +
  267                    "\nA llow legac y hello me ssages: "  + allowLeg acyHelloMe ssages +
  268                    "\nI s initial  handshake:  " + isIni tialHandsh ake +
  269                    "\nI s secure r enegotiati on: " + se cureRenego tiation);
  270           }
  271  
  272           th is.sslCont ext = cont ext;
  273           th is.isClien t = isClie nt;
  274           th is.needCer tVerify =  needCertVe rify;
  275           th is.activeP rotocolVer sion = act iveProtoco lVersion;
  276           th is.isIniti alHandshak e = isInit ialHandsha ke;
  277           th is.secureR enegotiati on = secur eRenegotia tion;
  278           th is.clientV erifyData  = clientVe rifyData;
  279           th is.serverV erifyData  = serverVe rifyData;
  280           en ableNewSes sion = tru e;
  281           in validated  = false;
  282           se ssKeysCalc ulated = f alse;
  283  
  284           se tCipherSui te(CipherS uite.C_NUL L);
  285           se tEnabledPr otocols(en abledProto cols);
  286  
  287           if  (conn !=  null) {
  288                algorith mConstrain ts = new S SLAlgorith mConstrain ts(conn, t rue);
  289           }  else {         // eng ine != nul l
  290                algorith mConstrain ts = new S SLAlgorith mConstrain ts(engine,  true);
  291           }
  292  
  293  
  294           //
  295           //  In additi on to the  connection  state mac hine, cont rolling
  296           //  how the c onnection  deals with  the diffe rent sorts  of record s
  297           //  that get  sent (nota bly handsh ake transi tions!), t here's
  298           //  also a ha ndshaking  state mach ine that c ontrols me ssage
  299           //  sequencin g.
  300           //
  301           //  It's a co nvenient a rtifact of  the proto col that t his can,
  302           //  with only  a couple  of minor e xceptions,  be driven  by the
  303           //  type cons tant for t he last me ssage seen :  except  for the
  304           //  client's  cert verif y, those c onstants a re in a co nvenient
  305           //  order to  drasticall y simplify  state mac hine check ing.
  306           //
  307           st ate = -2;   // initia lized but  not activa ted
  308       }
  309  
  310       /*
  311        * Rer outes call s to the S SLSocket o r SSLEngin e (*SE).
  312        *
  313        * We  could have  also done  it by ext ra classes
  314        * and  letting t hem overri de, but th is seemed  much
  315        * les s involved .
  316        */
  317       void f atalSE(byt e b, Strin g diagnost ic) throws  IOExcepti on {
  318           fa talSE(b, d iagnostic,  null);
  319       }
  320  
  321       void f atalSE(byt e b, Throw able cause ) throws I OException  {
  322           fa talSE(b, n ull, cause );
  323       }
  324  
  325       void f atalSE(byt e b, Strin g diagnost ic, Throwa ble cause)
  326                throws I OException  {
  327           if  (conn !=  null) {
  328                conn.fat al(b, diag nostic, ca use);
  329           }  else {
  330                engine.f atal(b, di agnostic,  cause);
  331           }
  332       }
  333  
  334       void w arningSE(b yte b) {
  335           if  (conn !=  null) {
  336                conn.war ning(b);
  337           }  else {
  338                engine.w arning(b);
  339           }
  340       }
  341  
  342       // ONL Y used by  ClientHand shaker to  setup the  peer host  in SSLSess ion.
  343       String  getHostSE () {
  344           if  (conn !=  null) {
  345                return c onn.getHos t();
  346           }  else {
  347                return e ngine.getP eerHost();
  348           }
  349       }
  350  
  351       // ONL Y used by  ServerHand shaker to  setup the  peer host  in SSLSess ion.
  352       String  getHostAd dressSE()  {
  353           if  (conn !=  null) {
  354                return c onn.getIne tAddress() .getHostAd dress();
  355           }  else {
  356                /*
  357                 * This  is for cac hing only,  doesn't m atter that 's is real ly
  358                 * a hos tname.  Th e main thi ng is that  it doesn' t do
  359                 * a rev erse DNS l ookup, pot entially s lowing thi ngs down.
  360                 */
  361                return e ngine.getP eerHost();
  362           }
  363       }
  364  
  365       int ge tPortSE()  {
  366           if  (conn !=  null) {
  367                return c onn.getPor t();
  368           }  else {
  369                return e ngine.getP eerPort();
  370           }
  371       }
  372  
  373       int ge tLocalPort SE() {
  374           if  (conn !=  null) {
  375                return c onn.getLoc alPort();
  376           }  else {
  377                return - 1;
  378           }
  379       }
  380  
  381       Access ControlCon text getAc cSE() {
  382           if  (conn !=  null) {
  383                return c onn.getAcc ();
  384           }  else {
  385                return e ngine.getA cc();
  386           }
  387       }
  388  
  389       final  boolean re ceivedChan geCipherSp ec() {
  390           if  (conn !=  null) {
  391                return c onn.receiv edChangeCi pherSpec() ;
  392           }  else {
  393                return e ngine.rece ivedChange CipherSpec ();
  394           }
  395       }
  396  
  397       String  getEndpoi ntIdentifi cationAlgo rithmSE()  {
  398           SS LParameter s paras;
  399           if  (conn !=  null) {
  400                paras =  conn.getSS LParameter s();
  401           }  else {
  402                paras =  engine.get SSLParamet ers();
  403           }
  404  
  405           re turn paras .getEndpoi ntIdentifi cationAlgo rithm();
  406       }
  407  
  408       privat e void set VersionSE( ProtocolVe rsion prot ocolVersio n) {
  409           if  (conn !=  null) {
  410                conn.set Version(pr otocolVers ion);
  411           }  else {
  412                engine.s etVersion( protocolVe rsion);
  413           }
  414       }
  415  
  416       /**
  417        * Set  the activ e protocol  version a nd propaga te it to t he SSLSock et
  418        * and  our hands hake strea ms. Called  from Clie ntHandshak er
  419        * and  ServerHan dshaker wi th the neg otiated pr otocol ver sion.
  420        */
  421       void s etVersion( ProtocolVe rsion prot ocolVersio n) {
  422           th is.protoco lVersion =  protocolV ersion;
  423           se tVersionSE (protocolV ersion);
  424  
  425           ou tput.r.set Version(pr otocolVers ion);
  426       }
  427  
  428       /**
  429        * Set  the enabl ed protoco ls. Called  from the  constructo r or
  430        * SSL SocketImpl /SSLEngine Impl.setEn abledProto cols() (if  the
  431        * han dshake is  not yet in  progress) .
  432        */
  433       void s etEnabledP rotocols(P rotocolLis t enabledP rotocols)  {
  434           ac tiveCipher Suites = n ull;
  435           ac tiveProtoc ols = null ;
  436  
  437           th is.enabled Protocols  = enabledP rotocols;
  438       }
  439  
  440       /**
  441        * Set  the enabl ed cipher  suites. Ca lled from
  442        * SSL SocketImpl /SSLEngine Impl.setEn abledCiphe rSuites()  (if the
  443        * han dshake is  not yet in  progress) .
  444        */
  445       void s etEnabledC ipherSuite s(CipherSu iteList en abledCiphe rSuites) {
  446           ac tiveCipher Suites = n ull;
  447           ac tiveProtoc ols = null ;
  448           th is.enabled CipherSuit es = enabl edCipherSu ites;
  449       }
  450  
  451       /**
  452        * Set  the algor ithm const raints. Ca lled from  the constr uctor or
  453        * SSL SocketImpl /SSLEngine Impl.setAl gorithmCon straints()  (if the
  454        * han dshake is  not yet in  progress) .
  455        */
  456       void s etAlgorith mConstrain ts(Algorit hmConstrai nts algori thmConstra ints) {
  457           ac tiveCipher Suites = n ull;
  458           ac tiveProtoc ols = null ;
  459  
  460           th is.algorit hmConstrai nts =
  461                new SSLA lgorithmCo nstraints( algorithmC onstraints );
  462           th is.localSu pportedSig nAlgs = nu ll;
  463       }
  464  
  465       Collec tion<Signa tureAndHas hAlgorithm > getLocal SupportedS ignAlgs()  {
  466           if  (localSup portedSign Algs == nu ll) {
  467                localSup portedSign Algs =
  468                    Sign atureAndHa shAlgorith m.getSuppo rtedAlgori thms(
  469                                                            algorith mConstrain ts);
  470           }
  471  
  472           re turn local SupportedS ignAlgs;
  473       }
  474  
  475       void s etPeerSupp ortedSignA lgs(
  476                Collecti on<Signatu reAndHashA lgorithm>  algorithms ) {
  477           pe erSupporte dSignAlgs  =
  478                new Arra yList<Sign atureAndHa shAlgorith m>(algorit hms);
  479       }
  480  
  481       Collec tion<Signa tureAndHas hAlgorithm > getPeerS upportedSi gnAlgs() {
  482           re turn peerS upportedSi gnAlgs;
  483       }
  484  
  485  
  486       /**
  487        * Set  the ident ification  protocol.  Called fro m the cons tructor or
  488        * SSL SocketImpl /SSLEngine Impl.setId entificati onProtocol () (if the
  489        * han dshake is  not yet in  progress) .
  490        */
  491       void s etIdentifi cationProt ocol(Strin g protocol ) {
  492           th is.identif icationPro tocol = pr otocol;
  493       }
  494  
  495       /**
  496        * Set s the serv er name in dication o f the hand shake.
  497        */
  498       void s etSNIServe rNames(Lis t<SNIServe rName> ser verNames)  {
  499           //  The serve rNames par ameter is  unmodifiab le.
  500           th is.serverN ames = ser verNames;
  501       }
  502  
  503       /**
  504        * Set s the serv er name ma tchers of  the handsh aking.
  505        */
  506       void s etSNIMatch ers(Collec tion<SNIMa tcher> sni Matchers)  {
  507           //  The sniMa tchers par ameter is  unmodifiab le.
  508           th is.sniMatc hers = sni Matchers;
  509       }
  510  
  511       /**
  512        * Set s the ciph er suites  preference .
  513        */
  514       void s etUseCiphe rSuitesOrd er(boolean  on) {
  515           th is.preferL ocalCipher Suites = o n;
  516       }
  517  
  518       /**
  519        * Pri or to hand shaking, a ctivate th e handshak e and init ialize the  version,
  520        * inp ut stream  and output  stream.
  521        */
  522       void a ctivate(Pr otocolVers ion helloV ersion) th rows IOExc eption {
  523           if  (activePr otocols ==  null) {
  524                activePr otocols =  getActiveP rotocols() ;
  525           }
  526  
  527           if  (activePr otocols.co llection() .isEmpty()  ||
  528                    acti veProtocol s.max.v ==  ProtocolV ersion.NON E.v) {
  529                throw ne w SSLHands hakeExcept ion(
  530                         "No approp riate prot ocol (prot ocol is di sabled or  " +
  531                         "cipher su ites are i nappropria te)");
  532           }
  533  
  534           if  (activeCi pherSuites  == null)  {
  535                activeCi pherSuites  = getActi veCipherSu ites();
  536           }
  537  
  538           if  (activeCi pherSuites .collectio n().isEmpt y()) {
  539                throw ne w SSLHands hakeExcept ion("No ap propriate  cipher sui te");
  540           }
  541  
  542           //  temporary  protocol  version un til the ac tual proto col versio n
  543           //  is negoti ated in th e Hello ex change. Th is affects  the recor d
  544           //  version w e sent wit h the Clie ntHello.
  545           if  (!isIniti alHandshak e) {
  546                protocol Version =  activeProt ocolVersio n;
  547           }  else {
  548                protocol Version =  activeProt ocols.max;
  549           }
  550  
  551           if  (helloVer sion == nu ll || hell oVersion.v  == Protoc olVersion. NONE.v) {
  552                helloVer sion = act iveProtoco ls.helloVe rsion;
  553           }
  554  
  555           //  We accumu late diges ts of the  handshake  messages s o that
  556           //  we can re ad/write C ertificate Verify and  Finished  messages,
  557           //  getting a ssurance a gainst som e particul ar active  attacks.
  558           ha ndshakeHas h = new Ha ndshakeHas h(needCert Verify);
  559  
  560           //  Generate  handshake  input/outp ut stream.
  561           in put = new  HandshakeI nStream(ha ndshakeHas h);
  562           if  (conn !=  null) {
  563                output =  new Hands hakeOutStr eam(protoc olVersion,  helloVers ion,
  564                                               handshakeH ash, conn) ;
  565                conn.get AppInputSt ream().r.s etHandshak eHash(hand shakeHash) ;
  566                conn.get AppInputSt ream().r.s etHelloVer sion(hello Version);
  567                conn.get AppOutputS tream().r. setHelloVe rsion(hell oVersion);
  568           }  else {
  569                output =  new Hands hakeOutStr eam(protoc olVersion,  helloVers ion,
  570                                               handshakeH ash, engin e);
  571                engine.i nputRecord .setHandsh akeHash(ha ndshakeHas h);
  572                engine.i nputRecord .setHelloV ersion(hel loVersion) ;
  573                engine.o utputRecor d.setHello Version(he lloVersion );
  574           }
  575  
  576           //  move stat e to activ ated
  577           st ate = -1;
  578       }
  579  
  580       /**
  581        * Set  cipherSui te and key Exchange t o the give n CipherSu ite.
  582        * Doe s not perf orm any ve rification  that this  is a vali d selectio n,
  583        * thi s must be  done befor e calling  this metho d.
  584        */
  585       void s etCipherSu ite(Cipher Suite s) {
  586           th is.cipherS uite = s;
  587           th is.keyExch ange = s.k eyExchange ;
  588       }
  589  
  590       /**
  591        * Che ck if the  given ciph ersuite is  enabled a nd availab le within  the
  592        * cur rent activ e cipher s uites.
  593        *
  594        * Doe s not chec k if the r equired se rver certi ficates ar e availabl e.
  595        */
  596       boolea n isNegoti able(Ciphe rSuite s)  {
  597           if  (activeCi pherSuites  == null)  {
  598                activeCi pherSuites  = getActi veCipherSu ites();
  599           }
  600  
  601           re turn isNeg otiable(ac tiveCipher Suites, s) ;
  602       }
  603  
  604       /**
  605        * Che ck if the  given ciph ersuite is  enabled a nd availab le within  the
  606        * pro posed ciph er suite l ist.
  607        *
  608        * Doe s not chec k if the r equired se rver certi ficates ar e availabl e.
  609        */
  610       final  static boo lean isNeg otiable(Ci pherSuiteL ist propos ed, Cipher Suite s) {
  611           re turn propo sed.contai ns(s) && s .isNegotia ble();
  612       }
  613  
  614       /**
  615        * Che ck if the  given prot ocol versi on is enab led and av ailable.
  616        */
  617       boolea n isNegoti able(Proto colVersion  protocolV ersion) {
  618           if  (activePr otocols ==  null) {
  619                activePr otocols =  getActiveP rotocols() ;
  620           }
  621  
  622           re turn activ eProtocols .contains( protocolVe rsion);
  623       }
  624  
  625       /**
  626        * Sel ect a prot ocol versi on from th e list. Ca lled from
  627        * Ser verHandsha ker to neg otiate pro tocol vers ion.
  628        *
  629        * Ret urn the lo wer of the  protocol  version su ggested in  the
  630        * cli en hello a nd the hig hest suppo rted by th e server.
  631        */
  632       Protoc olVersion  selectProt ocolVersio n(Protocol Version pr otocolVers ion) {
  633           if  (activePr otocols ==  null) {
  634                activePr otocols =  getActiveP rotocols() ;
  635           }
  636  
  637           re turn activ eProtocols .selectPro tocolVersi on(protoco lVersion);
  638       }
  639  
  640       /**
  641        * Get  the activ e cipher s uites.
  642        *
  643        * In  TLS 1.1, m any weak o r vulnerab le cipher  suites wer e obsolete d,
  644        * suc h as TLS_R SA_EXPORT_ WITH_RC4_4 0_MD5. The  implement ation MUST  NOT
  645        * neg otiate the se cipher  suites in  TLS 1.1 or  later mod e.
  646        *
  647        * The refore, wh en the act ive protoc ols only i nclude TLS  1.1 or la ter,
  648        * the  client ca nnot reque st to nego tiate thos e obsolete d cipher
  649        * sui tes.  That  is, the o bsoleted s uites shou ld not be  included i n the
  650        * cli ent hello.  So we nee d to creat e a subset  of the en abled ciph er
  651        * sui tes, the a ctive ciph er suites,  which doe s not cont ain obsole ted
  652        * cip her suites  of the mi nimum acti ve protoco l.
  653        *
  654        * Ret urn empty  list inste ad of null  if no act ive cipher  suites.
  655        */
  656       Cipher SuiteList  getActiveC ipherSuite s() {
  657           if  (activeCi pherSuites  == null)  {
  658                if (acti veProtocol s == null)  {
  659                    acti veProtocol s = getAct iveProtoco ls();
  660                }
  661  
  662                ArrayLis t<CipherSu ite> suite s = new Ar rayList<>( );
  663                if (!(ac tiveProtoc ols.collec tion().isE mpty()) &&
  664                         activeProt ocols.min. v != Proto colVersion .NONE.v) {
  665                    bool ean checke dCurves =  false;
  666                    bool ean hasCur ves = fals e;
  667                    for  (CipherSui te suite :  enabledCi pherSuites .collectio n()) {
  668                         if (suite. obsoleted  > activePr otocols.mi n.v &&
  669                                 su ite.suppor ted <= act iveProtoco ls.max.v)  {
  670                             if (al gorithmCon straints.p ermits(
  671                                      EnumSet. of(CryptoP rimitive.K EY_AGREEME NT),
  672                                      suite.na me, null))  {
  673                                 bo olean avai lable = tr ue;
  674                                 if  (suite.ke yExchange. isEC) {
  675                                      if (!che ckedCurves ) {
  676                                          hasC urves = El lipticCurv esExtensio n
  677                                               .hasActive Curves(alg orithmCons traints);
  678                                          chec kedCurves  = true;
  679  
  680                                          if ( !hasCurves  && debug  != null &&
  681                                                       De bug.isOn(" verbose"))  {
  682                                               System.out .println(
  683                                                  "No ava ilable ell iptic curv es");
  684                                          }
  685                                      }
  686  
  687                                      availabl e = hasCur ves;
  688  
  689                                     if (!avai lable && d ebug != nu ll &&
  690                                               Debug.isOn ("verbose" )) {
  691                                          Syst em.out.pri ntln(
  692                                               "No active  elliptic  curves, ig nore " +
  693                                             s uite);
  694                                      }
  695                                 }
  696  
  697                                 if  (availabl e) {
  698                                      suites.a dd(suite);
  699                                 }
  700                             }
  701                         } else if  (debug !=  null && De bug.isOn(" verbose"))  {
  702                             if (su ite.obsole ted <= act iveProtoco ls.min.v)  {
  703                                 Sy stem.out.p rintln(
  704                                      "Ignorin g obsolete d cipher s uite: " +  suite);
  705                             } else  {
  706                                 Sy stem.out.p rintln(
  707                                      "Ignorin g unsuppor ted cipher  suite: "  + suite);
  708                             }
  709                         }
  710                    }
  711                }
  712                activeCi pherSuites  = new Cip herSuiteLi st(suites) ;
  713           }
  714  
  715           re turn activ eCipherSui tes;
  716       }
  717  
  718       /*
  719        * Get  the activ e protocol  versions.
  720        *
  721        * In  TLS 1.1, m any weak o r vulnerab le cipher  suites wer e obsolete d,
  722        * suc h as TLS_R SA_EXPORT_ WITH_RC4_4 0_MD5. The  implement ation MUST  NOT
  723        * neg otiate the se cipher  suites in  TLS 1.1 or  later mod e.
  724        *
  725        * For  example,  if "TLS_RS A_EXPORT_W ITH_RC4_40 _MD5" is t he
  726        * onl y enabled  cipher sui te, the cl ient canno t request  TLS 1.1 or
  727        * lat er, even t hough TLS  1.1 or lat er is enab led.  We n eed to cre ate a
  728        * sub set of the  enabled p rotocols,  called the  active pr otocols, w hich
  729        * con tains prot ocols appr opriate to  the list  of enabled  Ciphersui tes.
  730        *
  731        * Ret urn empty  list inste ad of null  if no act ive protoc ol version s.
  732        */
  733       Protoc olList get ActiveProt ocols() {
  734           if  (activePr otocols ==  null) {
  735                boolean  enabledSSL 20Hello =  false;
  736                boolean  checkedCur ves = fals e;
  737                boolean  hasCurves  = false;
  738                ArrayLis t<Protocol Version> p rotocols =  new Array List<>(4);
  739                for (Pro tocolVersi on protoco l : enable dProtocols .collectio n()) {
  740                    // N eed not to  check the  SSL20Hell o protocol .
  741                    if ( protocol.v  == Protoc olVersion. SSL20Hello .v) {
  742                         enabledSSL 20Hello =  true;
  743                         continue;
  744                    }
  745  
  746                    if ( !algorithm Constraint s.permits(
  747                             EnumSe t.of(Crypt oPrimitive .KEY_AGREE MENT),
  748                             protoc ol.name, n ull)) {
  749                         if (debug  != null &&  Debug.isO n("verbose ")) {
  750                             System .out.print ln(
  751                                 "I gnoring di sabled pro tocol: " +  protocol) ;
  752                         }
  753  
  754                         continue;
  755                    }
  756                    bool ean found  = false;
  757                    for  (CipherSui te suite :  enabledCi pherSuites .collectio n()) {
  758                         if (suite. isAvailabl e() && sui te.obsolet ed > proto col.v &&
  759                                                      sui te.support ed <= prot ocol.v) {
  760                             if (al gorithmCon straints.p ermits(
  761                                      EnumSet. of(CryptoP rimitive.K EY_AGREEME NT),
  762                                      suite.na me, null))  {
  763  
  764                                 bo olean avai lable = tr ue;
  765                                 if  (suite.ke yExchange. isEC) {
  766                                      if (!che ckedCurves ) {
  767                                          hasC urves = El lipticCurv esExtensio n
  768                                               .hasActive Curves(alg orithmCons traints);
  769                                          chec kedCurves  = true;
  770  
  771                                          if ( !hasCurves  && debug  != null &&
  772                                                       De bug.isOn(" verbose"))  {
  773                                               System.out .println(
  774                                                   "No ac tivated el liptic cur ves");
  775                                          }
  776                                      }
  777  
  778                                      availabl e = hasCur ves;
  779  
  780                                      if (!ava ilable &&  debug != n ull &&
  781                                               Debug.isOn ("verbose" )) {
  782                                          Syst em.out.pri ntln(
  783                                               "No active  elliptic  curves, ig nore " +
  784                                               suite + "  for " + pr otocol);
  785                                      }
  786                                 }
  787  
  788                                 if  (availabl e) {
  789                                      protocol s.add(prot ocol);
  790                                      found =  true;
  791                                      break;
  792                                 }
  793                             } else  if (debug  != null & & Debug.is On("verbos e")) {
  794                                 Sy stem.out.p rintln(
  795                                      "Ignorin g disabled  cipher su ite: " + s uite +
  796                                       " for "  + protoco l);
  797                             }
  798                         } else if  (debug !=  null && De bug.isOn(" verbose"))  {
  799                             System .out.print ln(
  800                                 "I gnoring un supported  cipher sui te: " + su ite +
  801                                       " for "  + protoco l);
  802                         }
  803                    }
  804                    if ( !found &&  (debug !=  null) && D ebug.isOn( "handshake ")) {
  805                         System.out .println(
  806                             "No av ailable ci pher suite  for " + p rotocol);
  807                    }
  808                }
  809  
  810                if (!pro tocols.isE mpty() &&  enabledSSL 20Hello) {
  811                    prot ocols.add( ProtocolVe rsion.SSL2 0Hello);
  812                }
  813  
  814                activePr otocols =  new Protoc olList(pro tocols);
  815           }
  816  
  817           re turn activ eProtocols ;
  818       }
  819  
  820       /**
  821        * As  long as ha ndshaking  has not ac tivated, w e can
  822        * cha nge whethe r session  creations  are allowe d.
  823        *
  824        * Cal lers shoul d do their  own check ing if han dshaking
  825        * has  activated .
  826        */
  827       void s etEnableSe ssionCreat ion(boolea n newSessi ons) {
  828           en ableNewSes sion = new Sessions;
  829       }
  830  
  831       /**
  832        * Cre ate a new  read ciphe r and retu rn it to c aller.
  833        */
  834       Cipher Box newRea dCipher()  throws NoS uchAlgorit hmExceptio n {
  835           Bu lkCipher c ipher = ci pherSuite. cipher;
  836           Ci pherBox bo x;
  837           if  (isClient ) {
  838                box = ci pher.newCi pher(proto colVersion , svrWrite Key, svrWr iteIV,
  839                                         sslCo ntext.getS ecureRando m(), false );
  840                svrWrite Key = null ;
  841                svrWrite IV = null;
  842           }  else {
  843                box = ci pher.newCi pher(proto colVersion , clntWrit eKey, clnt WriteIV,
  844                                         sslCo ntext.getS ecureRando m(), false );
  845                clntWrit eKey = nul l;
  846                clntWrit eIV = null ;
  847           }
  848           re turn box;
  849       }
  850  
  851       /**
  852        * Cre ate a new  write ciph er and ret urn it to  caller.
  853        */
  854       Cipher Box newWri teCipher()  throws No SuchAlgori thmExcepti on {
  855           Bu lkCipher c ipher = ci pherSuite. cipher;
  856           Ci pherBox bo x;
  857           if  (isClient ) {
  858                box = ci pher.newCi pher(proto colVersion , clntWrit eKey, clnt WriteIV,
  859                                         sslCo ntext.getS ecureRando m(), true) ;
  860                clntWrit eKey = nul l;
  861                clntWrit eIV = null ;
  862           }  else {
  863                box = ci pher.newCi pher(proto colVersion , svrWrite Key, svrWr iteIV,
  864                                         sslCo ntext.getS ecureRando m(), true) ;
  865                svrWrite Key = null ;
  866                svrWrite IV = null;
  867           }
  868           re turn box;
  869       }
  870  
  871       /**
  872        * Cre ate a new  read MAC a nd return  it to call er.
  873        */
  874       Authen ticator ne wReadAuthe nticator()
  875                throws N oSuchAlgor ithmExcept ion, Inval idKeyExcep tion {
  876  
  877           Au thenticato r authenti cator = nu ll;
  878           if  (cipherSu ite.cipher .cipherTyp e == AEAD_ CIPHER) {
  879                authenti cator = ne w Authenti cator(prot ocolVersio n);
  880           }  else {
  881                MacAlg m acAlg = ci pherSuite. macAlg;
  882                if (isCl ient) {
  883                    auth enticator  = macAlg.n ewMac(prot ocolVersio n, svrMacS ecret);
  884                    svrM acSecret =  null;
  885                } else {
  886                    auth enticator  = macAlg.n ewMac(prot ocolVersio n, clntMac Secret);
  887                    clnt MacSecret  = null;
  888                }
  889           }
  890  
  891           re turn authe nticator;
  892       }
  893  
  894       /**
  895        * Cre ate a new  write MAC  and return  it to cal ler.
  896        */
  897       Authen ticator ne wWriteAuth enticator( )
  898                throws N oSuchAlgor ithmExcept ion, Inval idKeyExcep tion {
  899  
  900           Au thenticato r authenti cator = nu ll;
  901           if  (cipherSu ite.cipher .cipherTyp e == AEAD_ CIPHER) {
  902                authenti cator = ne w Authenti cator(prot ocolVersio n);
  903           }  else {
  904                MacAlg m acAlg = ci pherSuite. macAlg;
  905                if (isCl ient) {
  906                    auth enticator  = macAlg.n ewMac(prot ocolVersio n, clntMac Secret);
  907                    clnt MacSecret  = null;
  908                } else {
  909                    auth enticator  = macAlg.n ewMac(prot ocolVersio n, svrMacS ecret);
  910                    svrM acSecret =  null;
  911                }
  912           }
  913  
  914           re turn authe nticator;
  915       }
  916  
  917       /*
  918        * Ret urns true  iff the ha ndshake se quence is  done, so t hat
  919        * thi s freshly  created se ssion can  become the  current o ne.
  920        */
  921       boolea n isDone()  {
  922           re turn state  == Handsh akeMessage .ht_finish ed;
  923       }
  924  
  925  
  926       /*
  927        * Ret urns the s ession whi ch was cre ated throu gh this
  928        * han dshake seq uence ...  should be  called aft er isDone( )
  929        * ret urns true.
  930        */
  931       SSLSes sionImpl g etSession( ) {
  932           re turn sessi on;
  933       }
  934  
  935       /*
  936        * Set  the hands hake sessi on
  937        */
  938       void s etHandshak eSessionSE (SSLSessio nImpl hand shakeSessi on) {
  939           if  (conn !=  null) {
  940                conn.set HandshakeS ession(han dshakeSess ion);
  941           }  else {
  942                engine.s etHandshak eSession(h andshakeSe ssion);
  943           }
  944       }
  945  
  946       /*
  947        * Ret urns true  if renegot iation is  in use for  this conn ection.
  948        */
  949       boolea n isSecure Renegotiat ion() {
  950           re turn secur eRenegotia tion;
  951       }
  952  
  953       /*
  954        * Ret urns the v erify_data  from the  Finished m essage sen t by the c lient.
  955        */
  956       byte[]  getClient VerifyData () {
  957           re turn clien tVerifyDat a;
  958       }
  959  
  960       /*
  961        * Ret urns the v erify_data  from the  Finished m essage sen t by the s erver.
  962        */
  963       byte[]  getServer VerifyData () {
  964           re turn serve rVerifyDat a;
  965       }
  966  
  967       /*
  968        * Thi s routine  is fed SSL  handshake  records w hen they b ecome avai lable,
  969        * and  processes  messages  found ther ein.
  970        */
  971       void p rocess_rec ord(InputR ecord r, b oolean exp ectingFini shed)
  972                throws I OException  {
  973  
  974           ch eckThrown( );
  975  
  976           /*
  977            *  Store the  incoming  handshake  data, then  see if we  can
  978            *  now proce ss any com pleted han dshake mes sages
  979            * /
  980           in put.incomi ngRecord(r );
  981  
  982           /*
  983            *  We don't  need to cr eate a sep arate dele gatable ta sk
  984            *  for finis hed messag es.
  985            * /
  986           if  ((conn !=  null) ||  expectingF inished) {
  987                processL oop();
  988           }  else {
  989                delegate Task(new P rivilegedE xceptionAc tion<Void> () {
  990                    @Ove rride
  991                    publ ic Void ru n() throws  Exception  {
  992                         processLoo p();
  993                         return nul l;
  994                    }
  995                });
  996           }
  997       }
  998  
  999       /*
  1000        * On  input, we  hash messa ges one at  a time si nce server s may need
  1001        * to  access an  intermedia te hash to  validate  a Certific ateVerify
  1002        * mes sage.
  1003        *
  1004        * Not e that man y handshak e messages  can come  in one rec ord (and o ften
  1005        * do,  to reduce  network r esource ut ilization) , and one  message ca n also
  1006        * req uire multi ple record s (e.g. ve ry large C ertificate  messages) .
  1007        */
  1008       void p rocessLoop () throws  IOExceptio n {
  1009  
  1010           //  need to r ead off 4  bytes at l east to ge t the hand shake
  1011           //  message t ype and le ngth.
  1012           wh ile (input .available () >= 4) {
  1013                byte mes sageType;
  1014                int mess ageLen;
  1015  
  1016                /*
  1017                 * See i f we can r ead the ha ndshake me ssage head er, and
  1018                 * then  the entire  handshake  message.   If not, w ait till
  1019                 * we ca n read and  process a n entire m essage.
  1020                 */
  1021                input.ma rk(4);
  1022  
  1023                messageT ype = (byt e)input.ge tInt8();
  1024                messageL en = input .getInt24( );
  1025  
  1026                if (inpu t.availabl e() < mess ageLen) {
  1027                    inpu t.reset();
  1028                    retu rn;
  1029                }
  1030  
  1031                /*
  1032                 * Proce ss the mes sage.  We  require
  1033                 * that  processMes sage() con sumes the  entire mes sage.  In
  1034                 * lieu  of explici t error ch ecks (how? !) we assu me that th e
  1035                 * data  will look  like garba ge on enco ding/proce ssing erro rs,
  1036                 * and t hat other  protocol c ode will d etect such  errors.
  1037                 *
  1038                 * Note  that diges ting is no rmally def erred till  after the
  1039                 * messa ge has bee n processe d, though  to process  at least  the
  1040                 * clien t's Finish ed message  (i.e. sen d the serv er's) we n eed
  1041                 * to ac ccelerate  that diges ting.
  1042                 *
  1043                 * Also,  note that  hello req uest messa ges are ne ver hashed ;
  1044                 * that  includes t he hello r equest hea der, too.
  1045                 */
  1046                if (mess ageType ==  Handshake Message.ht _hello_req uest) {
  1047                    inpu t.reset();
  1048                    proc essMessage (messageTy pe, messag eLen);
  1049                    inpu t.ignore(4  + message Len);
  1050                } else {
  1051                    inpu t.mark(mes sageLen);
  1052                    proc essMessage (messageTy pe, messag eLen);
  1053                    inpu t.digestNo w();
  1054                }
  1055           }
  1056       }
  1057  
  1058  
  1059       /**
  1060        * Ret urns true  iff the ha ndshaker h as been ac tivated.
  1061        *
  1062        * In  activated  state, the  handshake r may not  send any m essages ou t.
  1063        */
  1064       boolea n activate d() {
  1065           re turn state  >= -1;
  1066       }
  1067  
  1068       /**
  1069        * Ret urns true  iff the ha ndshaker h as sent an y messages .
  1070        */
  1071       boolea n started( ) {
  1072           re turn state  >= 0;  //  0: Handsh akeMessage .ht_hello_ request
  1073                                 //  1: Handsh akeMessage .ht_client _hello
  1074       }
  1075  
  1076  
  1077       /*
  1078        * Use d to kicks tart the n egotiation  ... eithe r writing  a
  1079        * Cli entHello o r a HelloR equest as  appropriat e, whichev er
  1080        * the  subclass  returns.   NOP if han dshaking's  already s tarted.
  1081        */
  1082       void k ickstart()  throws IO Exception  {
  1083           if  (state >=  0) {
  1084                return;
  1085           }
  1086  
  1087           Ha ndshakeMes sage m = g etKickstar tMessage() ;
  1088  
  1089           if  (debug !=  null && D ebug.isOn( "handshake ")) {
  1090                m.print( System.out );
  1091           }
  1092           m. write(outp ut);
  1093           ou tput.flush ();
  1094  
  1095           st ate = m.me ssageType( );
  1096       }
  1097  
  1098       /**
  1099        * Bot h client a nd server  modes can  start hand shaking; b ut the
  1100        * mes sage they  send to do  so is dif ferent.
  1101        */
  1102       abstra ct Handsha keMessage  getKicksta rtMessage( ) throws S SLExceptio n;
  1103  
  1104       /*
  1105        * Cli ent and Se rver side  protocols  are each d riven thou gh this
  1106        * cal l, which p rocesses a  single me ssage and  drives the  appropria te
  1107        * sid e of the p rotocol st ate machin e (dependi ng on the  subclass).
  1108        */
  1109       abstra ct void pr ocessMessa ge(byte me ssageType,  int messa geLen)
  1110           th rows IOExc eption;
  1111  
  1112       /*
  1113        * Mos t alerts i n the prot ocol relat e to hands haking pro blems.
  1114        * Ale rts are de tected as  the connec tion reads  data.
  1115        */
  1116       abstra ct void ha ndshakeAle rt(byte de scription)  throws SS LProtocolE xception;
  1117  
  1118       /*
  1119        * Sen ds a chang e cipher s pec messag e and upda tes the wr ite side
  1120        * cip her state  so that fu ture messa ges use th e just-neg otiated sp ec.
  1121        */
  1122       void s endChangeC ipherSpec( Finished m esg, boole an lastMes sage)
  1123                throws I OException  {
  1124  
  1125           ou tput.flush (); // i.e . handshak e data
  1126  
  1127           /*
  1128            *  The write  cipher st ate is pro tected by  the connec tion write  lock
  1129            *  so we mus t grab it  while maki ng the cha nge. We al so
  1130            *  make sure  no writes  occur bet ween sendi ng the Cha ngeCipherS pec
  1131            *  message,  installing  the new c ipher stat e, and sen ding the
  1132            *  Finished  message.
  1133            *
  1134            *  We alread y hold SSL Engine/SSL Socket "th is" by vir tue
  1135            *  of this b eing calle d from the  readRecor d code.
  1136            * /
  1137           Ou tputRecord  r;
  1138           if  (conn !=  null) {
  1139                r = new  OutputReco rd(Record. ct_change_ cipher_spe c);
  1140           }  else {
  1141                r = new  EngineOutp utRecord(R ecord.ct_c hange_ciph er_spec, e ngine);
  1142           }
  1143  
  1144           r. setVersion (protocolV ersion);
  1145           r. write(1);      // sin gle byte o f data
  1146  
  1147           if  (conn !=  null) {
  1148                conn.wri teLock.loc k();
  1149                try {
  1150                    conn .writeReco rd(r);
  1151                    conn .changeWri teCiphers( );
  1152                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  1153                         mesg.print (System.ou t);
  1154                    }
  1155                    mesg .write(out put);
  1156                    outp ut.flush() ;
  1157                } finall y {
  1158                    conn .writeLock .unlock();
  1159                }
  1160           }  else {
  1161                synchron ized (engi ne.writeLo ck) {
  1162                    engi ne.writeRe cord((Engi neOutputRe cord)r);
  1163                    engi ne.changeW riteCipher s();
  1164                    if ( debug != n ull && Deb ug.isOn("h andshake") ) {
  1165                         mesg.print (System.ou t);
  1166                    }
  1167                    mesg .write(out put);
  1168  
  1169                    if ( lastMessag e) {
  1170                         output.set FinishedMs g();
  1171                    }
  1172                    outp ut.flush() ;
  1173                }
  1174           }
  1175       }
  1176  
  1177       /*
  1178        * Sin gle access  point to  key calcul ation logi c.  Given  the
  1179          * pre-mast er  PW        and the no nces from  client and  server,
  1180        * pro duce all t he keying  material t o be used.
  1181        */
  1182       void c alculateKe ys(SecretK ey preMast erSecret,  ProtocolVe rsion vers ion) {
  1183           Se cretKey ma ster = cal culateMast erSecret(p reMasterSe cret, vers ion);
  1184           se ssion.setM asterSecre t(master);
  1185           ca lculateCon nectionKey s(master);
  1186       }
  1187  
  1188  
  1189       /*
  1190          * Calculat e the mast er  PW        from its v arious com ponents.    This is
  1191        * use d for key  exchange b y all ciph er suites.
  1192        *
  1193          * The mast er  PW        is the cat enation of  three MD5  hashes, e ach
  1194          * consisti ng of the  pre-master   PW        and a SHA1  hash.    Those thre e
  1195        * SHA 1 hashes a re of (dif ferent) co nstant str ings, the  pre-master
  1196          PW      , and the  nonces pro vided by t he client  and the se rver.
  1197        */
  1198       @Suppr essWarning s("depreca tion")
  1199       privat e SecretKe y calculat eMasterSec ret(Secret Key preMas terSecret,
  1200                Protocol Version re questedVer sion) {
  1201  
  1202           if  (debug !=  null && D ebug.isOn( "keygen"))  {
  1203                HexDumpE ncoder       dump = n ew HexDump Encoder();
  1204  
  1205                System.o ut.println ("SESSION  KEYGEN:");
  1206  
  1207                System.o ut.println ("PreMaste r Secret:" );
  1208                printHex (dump, pre MasterSecr et.getEnco ded());
  1209  
  1210                // Nonce s are dump ed with co nnection k eygen, no
  1211                // benef it to doin g it twice
  1212           }
  1213  
  1214           //  What algs /params do  we need t o use?
  1215           St ring maste rAlg;
  1216           PR F prf;
  1217  
  1218           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1219                masterAl g = "SunTl s12MasterS ecret";
  1220                prf = ci pherSuite. prfAlg;
  1221           }  else {
  1222                masterAl g = "SunTl sMasterSec ret";
  1223                prf = P_ NONE;
  1224           }
  1225  
  1226           St ring prfHa shAlg = pr f.getPRFHa shAlg();
  1227           in t prfHashL ength = pr f.getPRFHa shLength() ;
  1228           in t prfBlock Size = prf .getPRFBlo ckSize();
  1229  
  1230           Tl sMasterSec retParamet erSpec spe c;
  1231           if  (session. getUseExte ndedMaster Secret())  {
  1232                  // reset t o use the  extended m aster  PW        algorithm
  1233                masterAl g = "SunTl sExtendedM asterSecre t";
  1234  
  1235                byte[] s essionHash  = null;
  1236                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1237                    sess ionHash =  handshakeH ash.getFin ishedHash( );
  1238                } else {
  1239                    // T LS 1.0/1.1
  1240                    sess ionHash =  new byte[3 6];
  1241                    try  {
  1242                         handshakeH ash.getMD5 Clone().di gest(sessi onHash, 0,  16);
  1243                         handshakeH ash.getSHA Clone().di gest(sessi onHash, 16 , 20);
  1244                    } ca tch (Diges tException  de) {
  1245                         throw new  ProviderEx ception(de );
  1246                    }
  1247                }
  1248  
  1249                spec = n ew TlsMast erSecretPa rameterSpe c(
  1250                         preMasterS ecret, pro tocolVersi on.major,  protocolVe rsion.mino r,
  1251                         sessionHas h, prfHash Alg, prfHa shLength,  prfBlockSi ze);
  1252           }  else {
  1253                spec = n ew TlsMast erSecretPa rameterSpe c(
  1254                         preMasterS ecret, pro tocolVersi on.major,  protocolVe rsion.mino r,
  1255                         clnt_rando m.random_b ytes, svr_ random.ran dom_bytes,
  1256                         prfHashAlg , prfHashL ength, prf BlockSize) ;
  1257           }
  1258  
  1259           tr y {
  1260                KeyGener ator kg =  JsseJce.ge tKeyGenera tor(master Alg);
  1261                kg.init( spec);
  1262                return k g.generate Key();
  1263           }  catch (Inv alidAlgori thmParamet erExceptio n |
  1264                    NoSu chAlgorith mException  iae) {
  1265                // unlik ely to hap pen, other wise, must  be a prov ider excep tion
  1266                //
  1267                  // For RSA  premaster   PW      s, do not  signal a p rotocol er ror
  1268                // due t o the Blei chenbacher  attack. S ee comment s further  down.
  1269                if (debu g != null  && Debug.i sOn("hands hake")) {
  1270                      System.out .println(" RSA master   PW        generation  error:");
  1271                    iae. printStack Trace(Syst em.out);
  1272                }
  1273                throw ne w Provider Exception( iae);
  1274  
  1275           }
  1276       }
  1277  
  1278       /*
  1279        * Cal culate the  keys need ed for thi s connecti on, once t he session 's
  1280          * master  PW        has been c alculated.     Uses the m aster key  and nonces ;
  1281        * the  amount of  keying ma terial gen erated is  a function  of the ci pher
  1282        * sui te that's  been negot iated.
  1283        *
  1284        * Thi s gets cal led both o n the "ful l handshak e" (where  we exchang ed
  1285          * a premas ter  PW        and starte d a new se ssion) as  well as on  the
  1286        * "fa st handsha ke" (where  we just r esumed a p re-existin g session) .
  1287        */
  1288       void c alculateCo nnectionKe ys(SecretK ey masterK ey) {
  1289           /*
  1290            *  For both  the read a nd write s ides of th e protocol , we use t he
  1291              * master t o generate  MAC  PW      s and ciph er keying  material.    Block
  1292            *  ciphers n eed initia lization v ectors, wh ich we als o generate .
  1293            *
  1294            *  First we  figure out  how much  keying mat erial is n eeded.
  1295            * /
  1296           in t hashSize  = cipherS uite.macAl g.size;
  1297           bo olean is_e xportable  = cipherSu ite.export able;
  1298           Bu lkCipher c ipher = ci pherSuite. cipher;
  1299           in t expanded KeySize =  is_exporta ble ? ciph er.expande dKeySize :  0;
  1300  
  1301           //  Which alg s/params d o we need  to use?
  1302           St ring keyMa terialAlg;
  1303           PR F prf;
  1304  
  1305           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1306                keyMater ialAlg = " SunTls12Ke yMaterial" ;
  1307                prf = ci pherSuite. prfAlg;
  1308           }  else {
  1309                keyMater ialAlg = " SunTlsKeyM aterial";
  1310                prf = P_ NONE;
  1311           }
  1312  
  1313           St ring prfHa shAlg = pr f.getPRFHa shAlg();
  1314           in t prfHashL ength = pr f.getPRFHa shLength() ;
  1315           in t prfBlock Size = prf .getPRFBlo ckSize();
  1316  
  1317           //  TLS v1.1  or later u ses an exp licit IV i n CBC ciph er suites  to
  1318           //  protect a gainst the  CBC attac ks.  AEAD/ GCM cipher  suites in  TLS
  1319           //  v1.2 or l ater use a  fixed IV  as the imp licit part  of the pa rtially
  1320           //  implicit  nonce tech nique desc ribed in R FC 5116.
  1321           in t ivSize =  cipher.iv Size;
  1322           if  (cipher.c ipherType  == AEAD_CI PHER) {
  1323                ivSize =  cipher.fi xedIvSize;
  1324           }  else if (p rotocolVer sion.v >=  ProtocolVe rsion.TLS1 1.v &&
  1325                    ciph er.cipherT ype == BLO CK_CIPHER)  {
  1326                ivSize =  0;
  1327           }
  1328  
  1329           Tl sKeyMateri alParamete rSpec spec  = new Tls KeyMateria lParameter Spec(
  1330                masterKe y, protoco lVersion.m ajor, prot ocolVersio n.minor,
  1331                clnt_ran dom.random _bytes, sv r_random.r andom_byte s,
  1332                cipher.a lgorithm,  cipher.key Size, expa ndedKeySiz e,
  1333                ivSize,  hashSize,
  1334                prfHashA lg, prfHas hLength, p rfBlockSiz e);
  1335  
  1336           tr y {
  1337                KeyGener ator kg =  JsseJce.ge tKeyGenera tor(keyMat erialAlg);
  1338                kg.init( spec);
  1339                TlsKeyMa terialSpec  keySpec =  (TlsKeyMa terialSpec )kg.genera teKey();
  1340  
  1341                // Retur n null if  cipher key s are not  supposed t o be gener ated.
  1342                clntWrit eKey = key Spec.getCl ientCipher Key();
  1343                svrWrite Key = keyS pec.getSer verCipherK ey();
  1344  
  1345                // Retur n null if  IVs are no t supposed  to be gen erated.
  1346                clntWrit eIV = keyS pec.getCli entIv();
  1347                svrWrite IV = keySp ec.getServ erIv();
  1348  
  1349                // Retur n null if  MAC keys a re not sup posed to b e generate d.
  1350                clntMacS ecret = ke ySpec.getC lientMacKe y();
  1351                svrMacSe cret = key Spec.getSe rverMacKey ();
  1352           }  catch (Gen eralSecuri tyExceptio n e) {
  1353                throw ne w Provider Exception( e);
  1354           }
  1355  
  1356           //  Mark a fl ag that al lows outsi de entitie s (like SS LSocket/SS LEngine)
  1357           //  determine  if a Chan geCipherSp ec message  could be  processed.
  1358           se ssKeysCalc ulated = t rue;
  1359  
  1360           //
  1361           //  Dump the  connection  keys as t hey're gen erated.
  1362           //
  1363           if  (debug !=  null && D ebug.isOn( "keygen"))  {
  1364                synchron ized (Syst em.out) {
  1365                    HexD umpEncoder   dump = n ew HexDump Encoder();
  1366  
  1367                    Syst em.out.pri ntln("CONN ECTION KEY GEN:");
  1368  
  1369                    // I nputs:
  1370                    Syst em.out.pri ntln("Clie nt Nonce:" );
  1371                    prin tHex(dump,  clnt_rand om.random_ bytes);
  1372                    Syst em.out.pri ntln("Serv er Nonce:" );
  1373                    prin tHex(dump,  svr_rando m.random_b ytes);
  1374                    Syst em.out.pri ntln("Mast er Secret: ");
  1375                    prin tHex(dump,  masterKey .getEncode d());
  1376  
  1377                    // O utputs:
  1378                    if ( clntMacSec ret != nul l) {
  1379                         System.out .println(" Client MAC  write Sec ret:");
  1380                         printHex(d ump, clntM acSecret.g etEncoded( ));
  1381                         System.out .println(" Server MAC  write Sec ret:");
  1382                         printHex(d ump, svrMa cSecret.ge tEncoded() );
  1383                    } el se {
  1384                         System.out .println(" ... no MAC  keys used  for this  cipher");
  1385                    }
  1386  
  1387                    if ( clntWriteK ey != null ) {
  1388                         System.out .println(" Client wri te key:");
  1389                         printHex(d ump, clntW riteKey.ge tEncoded() );
  1390                         System.out .println(" Server wri te key:");
  1391                         printHex(d ump, svrWr iteKey.get Encoded()) ;
  1392                    } el se {
  1393                         System.out .println(" ... no enc ryption ke ys used");
  1394                    }
  1395  
  1396                    if ( clntWriteI V != null)  {
  1397                         System.out .println(" Client wri te IV:");
  1398                         printHex(d ump, clntW riteIV.get IV());
  1399                         System.out .println(" Server wri te IV:");
  1400                         printHex(d ump, svrWr iteIV.getI V());
  1401                    } el se {
  1402                         if (protoc olVersion. v >= Proto colVersion .TLS11.v)  {
  1403                             System .out.print ln(
  1404                                      "... no  IV derived  for this  protocol") ;
  1405                         } else {
  1406                             System .out.print ln("... no  IV used f or this ci pher");
  1407                         }
  1408                    }
  1409                    Syst em.out.flu sh();
  1410                }
  1411           }
  1412       }
  1413  
  1414       /**
  1415        * Ret urn whethe r or not t he Handsha ker has de rived sess ion keys f or
  1416        * thi s handshak e.  This i s used for  determini ng readine ss to proc ess
  1417        * an  incoming C hangeCiphe rSpec mess age.
  1418        */
  1419       boolea n sessionK eysCalcula ted() {
  1420           re turn sessK eysCalcula ted;
  1421       }
  1422  
  1423       privat e static v oid printH ex(HexDump Encoder du mp, byte[]  bytes) {
  1424           if  (bytes ==  null) {
  1425                System.o ut.println ("(key byt es not ava ilable)");
  1426           }  else {
  1427                try {
  1428                    dump .encodeBuf fer(bytes,  System.ou t);
  1429                } catch  (IOExcepti on e) {
  1430                    // j ust for de bugging, i gnore this
  1431                }
  1432           }
  1433       }
  1434  
  1435       /**
  1436        * Thr ow an SSLE xception w ith the sp ecified me ssage and  cause.
  1437        * Sho rthand unt il a new S SLExceptio n construc tor is add ed.
  1438        * Thi s method n ever retur ns.
  1439        */
  1440       static  void thro wSSLExcept ion(String  msg, Thro wable caus e)
  1441                throws S SLExceptio n {
  1442           SS LException  e = new S SLExceptio n(msg);
  1443           e. initCause( cause);
  1444           th row e;
  1445       }
  1446  
  1447  
  1448       /*
  1449        * Imp lement a s imple task  delegator .
  1450        *
  1451        * We  are curren tly implem enting thi s as a sin gle delega tor, may
  1452        * try  for paral lel tasks  later.  Cl ient Authe ntication  could
  1453        * ben efit from  this, wher e ClientKe yExchange/ Certificat eVerify
  1454        * cou ld be carr ied out in  parallel.
  1455        */
  1456       class  DelegatedT ask<E> imp lements Ru nnable {
  1457  
  1458           pr ivate Priv ilegedExce ptionActio n<E> pea;
  1459  
  1460           De legatedTas k(Privileg edExceptio nAction<E>  pea) {
  1461                this.pea  = pea;
  1462           }
  1463  
  1464           pu blic void  run() {
  1465                synchron ized (engi ne) {
  1466                    try  {
  1467                         AccessCont roller.doP rivileged( pea, engin e.getAcc() );
  1468                    } ca tch (Privi legedActio nException  pae) {
  1469                         thrown = p ae.getExce ption();
  1470                    } ca tch (Runti meExceptio n rte) {
  1471                         thrown = r te;
  1472                    }
  1473                    dele gatedTask  = null;
  1474                    task Delegated  = false;
  1475                }
  1476           }
  1477       }
  1478  
  1479       privat e <T> void  delegateT ask(Privil egedExcept ionAction< T> pea) {
  1480           de legatedTas k = new De legatedTas k<T>(pea);
  1481           ta skDelegate d = false;
  1482           th rown = nul l;
  1483       }
  1484  
  1485       Delega tedTask<?>  getTask()  {
  1486           if  (!taskDel egated) {
  1487                taskDele gated = tr ue;
  1488                return d elegatedTa sk;
  1489           }  else {
  1490                return n ull;
  1491           }
  1492       }
  1493  
  1494       /*
  1495        * See  if there  are any ta sks which  need to be  delegated
  1496        *
  1497        * Loc ked by SSL Engine.thi s.
  1498        */
  1499       boolea n taskOuts tanding()  {
  1500           re turn (dele gatedTask  != null);
  1501       }
  1502  
  1503       /*
  1504        * The  previous  caller fai led for so me reason,  report ba ck the
  1505        * Exc eption.  W e won't wo rry about  Error's.
  1506        *
  1507        * Loc ked by SSL Engine.thi s.
  1508        */
  1509       void c heckThrown () throws  SSLExcepti on {
  1510           sy nchronized  (thrownLo ck) {
  1511                if (thro wn != null ) {
  1512  
  1513                    Stri ng msg = t hrown.getM essage();
  1514  
  1515                    if ( msg == nul l) {
  1516                         msg = "Del egated tas k threw Ex ception/Er ror";
  1517                    }
  1518  
  1519                    /*
  1520                     * S ee what th e underlyi ng type of  exception  is.  We s hould
  1521                     * t hrow the s ame thing.   Chain th rown to th e new exce ption.
  1522                     */
  1523                    Exce ption e =  thrown;
  1524                    thro wn = null;
  1525  
  1526                    if ( e instance of Runtime Exception)  {
  1527                         throw new  RuntimeExc eption(msg , e);
  1528                    } el se if (e i nstanceof  SSLHandsha keExceptio n) {
  1529                         throw (SSL HandshakeE xception)
  1530                             new SS LHandshake Exception( msg).initC ause(e);
  1531                    } el se if (e i nstanceof  SSLKeyExce ption) {
  1532                         throw (SSL KeyExcepti on)
  1533                             new SS LKeyExcept ion(msg).i nitCause(e );
  1534                    } el se if (e i nstanceof  SSLPeerUnv erifiedExc eption) {
  1535                         throw (SSL PeerUnveri fiedExcept ion)
  1536                             new SS LPeerUnver ifiedExcep tion(msg). initCause( e);
  1537                    } el se if (e i nstanceof  SSLProtoco lException ) {
  1538                         throw (SSL ProtocolEx ception)
  1539                             new SS LProtocolE xception(m sg).initCa use(e);
  1540                    } el se {
  1541                         /*
  1542                          * If it's  SSLExcept ion or any  other Exc eption,
  1543                          * we'll w rap it in  an SSLExce ption.
  1544                          */
  1545                         throw new  SSLExcepti on(msg, e) ;
  1546                    }
  1547                }
  1548           }
  1549       }
  1550   }