Let's Encrypt má šest nových certifikátů, přibude plná podpora ECDSA

18. 9. 2020
Doba čtení: 7 minut

Sdílet

Ilustrační obrázek
Autor: Depositphotos – stori
Ilustrační obrázek
Populární certifikační autorita Let's Encrypt během nedávného ceremoniálu vytvořila šest nových certifikátů a připravuje se na plnou podporu ECDSA. Nabídne tak menší certifikáty a rychlejší šifrování.

Ve čtvrtek 3. září vytvořila certifikační autorita Let’s Encrypt šest nových certifikátů: jeden kořenový, čtyři mezilehlé a jeden křížově podepsaný. Tento krok je součástí většího procesu, který má za úkol zlepšit bezpečnost na webu, rozšířit podporu algoritmu ECDSA a zmenšit velikost certifikátů.

Kořen je základ

Každá veřejná důvěryhodná certifikační autorita potřebuje alespoň jeden kořenový certifikát, který je součástí prohlížečů, operačních systémů či jiných úložišť. Tento certifikát je bodem důvěry a umožňuje uživateli automatizovaně ověřit, že certifikát dodaný konkrétním webem vystavila důvěryhodná organizace.

Kořenové certifikáty mají ale z principu velmi dlouhou životnost a autorita musí dobře chránit jejich soukromý klíč. Ideálně tak, aby byl zcela oddělen od infrastruktury a v běžném provozu se vůbec nepoužíval. Proto mají autority na základě tohoto kořenového certifikátu vystaveny další mezilehlé certifikáty, které mají kratší životnost, používají se v produkčním prostředí a v případě problému je lze nahradit.

V průběhu předešlých pěti let používala autorita Let's Encrypt kořenový certifikát ISRG Root X1 s platností do roku 2035, který obsahoval 4096bitový klíč RSA.

V průběhu těchto let vzniklo postupně několik mezilehlých certifikátů: X1, X2, X3 a X4. První dva vznikly hned v roce 2015 a měly platnost pět let. Následující dva pak byly vytvořeny v roce 2016 a také mají platnost pět let. Všechny tyto mezilehlé certifikáty používají 2048bitové RSA klíče. Navíc jsou všechny křížově podepsané také kořenovým certifikátem autority IdenTrust s názvem DST Root CA X3. Tento certifikát patří jiné autoritě a je od začátku běžnou součástí aplikací a úložišť.

Kromě toho vytvořil Let's Encrypt ještě certifikát ISRG Root OCSP X1, který ovšem neslouží jako další autorita, ale používá se k podepisování odpovědí v protokolu OCSP (Online Certificate Status Protocol). Ten umožňuje klientům zjistit, zda nejsou mezilehlé certifikáty předčasně revokované.


Autor: Let's Encrypt

Hierarchie certifikátů v srpnu 2020

Šest nových certifikátů

Nyní byly vytvořeny další dva nové certifikáty obsahující 2048bititové RSA, které se jmenují R3R4. Jsou oba odvozené od kořenového ISRG Root X1 a mají opět životnost nastavenou na pět let. Opět je také podepíše autorita IdenTrust. Jsou vlastně plnohodnotnou náhradou certifikátů X3 a X4, které vyprší už příští rok. Předpokládá se, že autorita na základě R3 začne vystavovat koncové certifikáty ke konci letošního roku. Na uživatele to nebude mít žádný dopad, jde o čistě formální změnu v řetězci důvěry.

Další certifikáty jsou ale zajímavější. Zaprvé vznikl nový kořenový certifikát ISRG Root X2, který místo RSA používá klíče ECDSA P-384 a je platný do roku 2040. Na jeho základě vznikly další dva mezilehlé certifikáty E1E2, které obsahují také ECDSA klíče a jsou platné příštích pět let.

Tyto mezilehlé certifikáty už nejsou křížově podepsány kořenovým certifikátem IdenTrust’s DST Root CA X3 a místo toho je samotný nový kořen ISRG Root X2 také podepsán starším ISRG Root X1.

Nový certifikát pro OCSP založený na ISRG Root X2 nevznikl. Důvody jsou vysvětleny dále.


Autor: Let's Encrypt

Hierarchie certifikátů v září 2020

Proč chceme ECDSA

Algoritmus ECDSA je založen na eliptických křivkách, jejichž použití má řadu praktických výhod. Pro zajištění stejné bezpečnosti stačí menší klíče, práce s nimi je rychlejší a tedy i energeticky méně náročná a v neposlední řadě je díky nim možné vytvořit menší certifikáty.

Každé spojení prováděné pomocí HTTPS musí provést takzvaný TLS handshake. Ten vyžaduje, aby server na začátku odeslal klientovi svůj koncový certifikát a příslušné mezilehlé certifikáty. Ověření platnosti totiž vyžaduje, aby klient znal celý řetězec důvěry od kořene až ke koncovému certifikátu. To znamená, že každé spojení s každou doménou vyžaduje přenesení velkého množství dat obsahujících certifikát. Pokud navštívený web načítá obsah z dalších domén, přenášených certifikátů přibývá. Každý takový certifikát obsahuje veřejný klíč a podpis vystavený autoritou.

Zatímco klasický 2048bitový RSA klíč má 256 bajtů, klíč ECDSA P-384 má pouze 48 bajtů. Podobně podpis pomocí RSA zabere 256 bajtů a pokud k němu použijeme ECDSA, bude nám stačit přenést jen 96 bajtů. Pokud přičteme nějakou další režii, ušetříme při přenosu jediného certifikátu asi 400 bajtů. Musíme to ale vynásobit všemi doménami, se kterými se spojujeme, a tohle číslo může v průběhu dne poměrně rychle narůstat.

Ušetřené bajty jsou výhodné pro obě strany – provozovatelé služby ušetří peníze za přenosovou kapacitu, uživatele zase potěší rychlejší načítání a na mobilu ušetřená data. Nové certifikáty tak budou nejen bezpečnější, ale i efektivnější.

Ze stejného důvodu pak navíc Let's Encrypt přijal některá další opatření. Zkrátilo se například jméno autority (Subject Common Name) z „Let’s Encrypt Authority X3“ na jednoduché „R3“. Informace o organizaci zůstane v položce Organization Name, kde je stále uvedeno „Let’s Encrypt“. Zároveň byly zkráceny položky „Authority Information Access Issuer“ a „CRL Distribution Point URL“, nově se v nich používá krátká doména lencr.org. Zcela byly odstraněny adresy pro CPS a OCSP. Tím se dohromady ušetřilo dalších 120 bajtů, aniž by to mělo nějaký praktický dopad na použití certifikátu.

Proč křížově podepsat kořen ECDSA

Křížové podepisování je důležité pro překonání doby mezi vystavením nového kořenového certifikátu a jeho distribucí do nejrůznějších úložišť. Může to trvat až pět let, než bude nový kořen ISRG Root X2 dostatečně důvěryhodný. Je tedy potřeba jej v řetězci podepsat nějakým už důvěryhodným certifikátem, aby byl mezilehlý E1 pro klienty také důvěryhodný.

Autorita měla v zásadě dvě možnosti: podepsat nový ISRG Root X2 stávajícím kořenem ISRG Root X1 nebo pomocí X1 rovnou podepsat mezilehlé E1 a E2. Každý z postupů má své výhody a nevýhody.

Křížově podepsat kořenový ISRG Root X2 znamená, že pokud jej bude mít uživatel mezi důvěryhodnými, bude možné mít celou cestu složenou z ECDSA certifikátů. V průběhu následujících let, až se nový kořen dostane mezi uživatele, bude ověření rychlejší a uživatel přitom nebude muset nic změnit. Dokud k tomu ale nedojde, budou muset uživatelé ověřovat řetězec se dvěma mezilehlými certifikáty E1 a X2, což bude znamenat zpomalení celého procesu.

Podepsat křížově přímo mezilehlé certifikáty přináší obrácený kompromis: na jedné straně budou mít sice všechny řetězce stejnou délku s jedním mezilehlým certifikátem mezi koncovým a kořenem ISRG Root X1. Na druhou stranu, jakmile se dostatečně rozšíří ISRG Root X2, bude muset autorita znovu projít změnou řetězce, aby bylo možné mít celou cestu složenou z ECDSA.

Nakonec bylo rozhodnuto, že plný ECDSA řetězec je důležitější, takže se autorita vydala první zmíněnou cestou: křížově podepsala samotný kořen ISRG Root X2.

Proč chybí certifikát pro OCSP

Protokol OCSP (Online Certificate Status Protocol) umožňuje klientovi v reálném čase ověřit, že daný certifikát nebyl revokován. Jinými slovy, že autorita nerozhodla o jeho předčasném zneplatnění. Pokud si to přeje prohlížeč ověřit, dotáže se na adresu uvedenou v certifikátu a okamžitě se dozví, jak to s platností vypadá. Tato odpověď je podepsaná dalším certifikátem a její pravost je tak možné snadno ověřit.

To je užitečné pro koncové certifikáty, protože odpovědi jsou velmi rychlé a malé a každý uživatel tak může mít přehled o individuální sadě domén a jejich certifikátů. Podle toho, jaké domény svým prohlížečem navštěvuje.

Jenže mezilehlé certifikáty tvoří jen velmi malou skupinu ze všech certifikátů, které kolují po internetu. Jsou navíc velmi dobře známé a revokují se zřídka. Díky tomu je výrazně efektivnější udržovat seznam obsahující stav všech těchto známých certifikátů. Tomuto seznamu se říká Certificate Revocation List (CRL).

Mezilehlé certifikáty Let's Encrypt proto obsahují adresu (URL), ze které si prohlížeč může tento seznam stáhnout. Tvůrci některých prohlížečů to dokonce dělají automaticky a distribuují seznamy společně s novými verzemi svých programů. Ověření platnosti těchto mezilehlých certifikátů pak tedy nevyžaduje další síťovou komunikaci, což opět vede ke zrychlení.

Nedávná změna pravidel pro certifikační autority (ballot SC31) už nevyžaduje, aby mezilehlé certifikáty obsahovaly URL pro OCSP. Jejich stav tak může být distribuován výhradně pomocí CRL. Proto se autorita Let's Encrypt rozhodla odstranit adresu OCSP ze svých mezilehlých certifikátů. Tím pádem ani není potřeba vytvářet nový certifikát pro OCSP na základě nového kořene ISRG Root X2.

Automatizovaný ceremoniál

Vytvoření nových kořenových a mezilehlých certifikátů je velká událost, protože jejich obsah je přísně regulován a přidružené soukromé klíče musí být zvlášť bedlivě střeženy. Proto se celému procesu také říká vznosně „ceremoniál“. Let’s Encrypt věří v automatizaci, takže i tento proces byl svěřen strojům s minimální lidskou účastí.

Byl proto vytvořen zvláštní ceremoniální nástroj, který dokáže po nastavení automatizovaně vytvořit všechny požadované klíče, certifikáty a žádosti pro podpis. Bylo také vytvořeno demo celého ceremoniálu, které ukazuje obsah konfiguračních souborů a dovoluje komukoliv celý proces spustit a ověřit výsledek.

Lidé z Let's encrypt vytvořili kopii celé sítě včetně HSM (Hardware Security Module) a vyzkoušeli několikrát celý proces. Výsledek byl konzultován s technickým výborem a byl zveřejněn v několika komunitních mailing listech. Na ostro pak byl proces spuštěn 3. září v zabezpečeném datacentru a vše bylo zaznamenáno pro pozdější audity.

zabbix_tip

Autorita už také aktualizovala informační stránku, která nyní obsahuje podrobnosti o všech současných certifikátech a zahájila proces zařazení nového kořenového certifikátu do důvěryhodných úložišť. Koncové certifikáty založené na nových mezilehlých certifikátech by měly začít být vystavovány v průběhu následujících týdnů. Podrobnosti se objeví v komunitním fóru.

(Zdroj: Let's Encrypt)

Autor článku

Petr Krčmář pracuje jako šéfredaktor serveru Root.cz. Studoval počítače a média, takže je rozpolcen mezi dva obory. Snaží se dělat obojí, jak nejlépe umí.

'; document.getElementById('preroll-iframe').onload = function () { setupIframe(); } prerollContainer = document.getElementsByClassName('preroll-container-iframe')[0]; } function setupIframe() { prerollDocument = document.getElementById('preroll-iframe').contentWindow.document; let el = prerollDocument.createElement('style'); prerollDocument.head.appendChild(el); el.innerText = "#adContainer>div:nth-of-type(1),#adContainer>div:nth-of-type(1) > iframe { width: 99% !important;height: 99% !important;max-width: 100%;}#videoContent,body{ width:100vw;height:100vh}body{ font-family:'Helvetica Neue',Arial,sans-serif}#videoContent{ overflow:hidden;background:#000}#adMuteBtn{ width:35px;height:35px;border:0;background:0 0;display:none;position:absolute;fill:rgba(230,230,230,1);bottom:20px;right:25px}"; videoContent = prerollDocument.getElementById('contentElement'); videoContent.style.display = 'none'; videoContent.volume = 1; videoContent.muted = false; const playPromise = videoContent.play(); if (playPromise !== undefined) { playPromise.then(function () { console.log('PREROLL sound allowed'); // setUpIMA(true); videoContent.volume = 1; videoContent.muted = false; setUpIMA(); }).catch(function () { console.log('PREROLL sound forbidden'); videoContent.volume = 0; videoContent.muted = true; setUpIMA(); }); } } function setupDimensions() { prerollWidth = Math.min(iinfoPrerollPosition.offsetWidth, 480); prerollHeight = Math.min(iinfoPrerollPosition.offsetHeight, 320); } function setUpIMA() { google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true); google.ima.settings.setLocale('cs'); google.ima.settings.setNumRedirects(10); // Create the ad display container. createAdDisplayContainer(); // Create ads loader. adsLoader = new google.ima.AdsLoader(adDisplayContainer); // Listen and respond to ads loaded and error events. adsLoader.addEventListener( google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, onAdsManagerLoaded, false); adsLoader.addEventListener( google.ima.AdErrorEvent.Type.AD_ERROR, onAdError, false); // An event listener to tell the SDK that our content video // is completed so the SDK can play any post-roll ads. const contentEndedListener = function () { adsLoader.contentComplete(); }; videoContent.onended = contentEndedListener; // Request video ads. const adsRequest = new google.ima.AdsRequest(); adsRequest.adTagUrl = iinfoVastUrls[iinfoVastUrlIndex]; console.log('Preroll advert: ' + iinfoVastUrls[iinfoVastUrlIndex]); videoContent.muted = false; videoContent.volume = 1; // Specify the linear and nonlinear slot sizes. This helps the SDK to // select the correct creative if multiple are returned. // adsRequest.linearAdSlotWidth = prerollWidth; // adsRequest.linearAdSlotHeight = prerollHeight; adsRequest.nonLinearAdSlotWidth = 0; adsRequest.nonLinearAdSlotHeight = 0; adsLoader.requestAds(adsRequest); } function createAdDisplayContainer() { // We assume the adContainer is the DOM id of the element that will house // the ads. prerollDocument.getElementById('videoContent').style.display = 'none'; adDisplayContainer = new google.ima.AdDisplayContainer( prerollDocument.getElementById('adContainer'), videoContent); } function unmutePrerollAdvert() { adVolume = !adVolume; if (adVolume) { adsManager.setVolume(0.3); prerollDocument.getElementById('adMuteBtn').innerHTML = ''; } else { adsManager.setVolume(0); prerollDocument.getElementById('adMuteBtn').innerHTML = ''; } } function onAdsManagerLoaded(adsManagerLoadedEvent) { // Get the ads manager. const adsRenderingSettings = new google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; adsRenderingSettings.loadVideoTimeout = 12000; // videoContent should be set to the content video element. adsManager = adsManagerLoadedEvent.getAdsManager(videoContent, adsRenderingSettings); // Add listeners to the required events. adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, onContentResumeRequested); adsManager.addEventListener( google.ima.AdEvent.Type.ALL_ADS_COMPLETED, onAdEvent); // Listen to any additional events, if necessary. adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, onAdEvent); playAds(); } function playAds() { // Initialize the container. Must be done through a user action on mobile // devices. videoContent.load(); adDisplayContainer.initialize(); // setupDimensions(); try { // Initialize the ads manager. Ad rules playlist will start at this time. adsManager.init(1920, 1080, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will // start at this time; the call will be ignored for ad rules. adsManager.start(); // window.addEventListener('resize', function (event) { // if (adsManager) { // setupDimensions(); // adsManager.resize(prerollWidth, prerollHeight, google.ima.ViewMode.NORMAL); // } // }); } catch (adError) { // An error may be thrown if there was a problem with the VAST response. // videoContent.play(); } } function onAdEvent(adEvent) { const ad = adEvent.getAd(); console.log('Preroll event: ' + adEvent.type); switch (adEvent.type) { case google.ima.AdEvent.Type.LOADED: if (!ad.isLinear()) { videoContent.play(); } prerollDocument.getElementById('adContainer').style.width = '100%'; prerollDocument.getElementById('adContainer').style.maxWidth = '640px'; prerollDocument.getElementById('adContainer').style.height = '360px'; break; case google.ima.AdEvent.Type.STARTED: window.addEventListener('scroll', onActiveView); if (ad.isLinear()) { intervalTimer = setInterval( function () { // Example: const remainingTime = adsManager.getRemainingTime(); // adsManager.pause(); }, 300); // every 300ms } prerollDocument.getElementById('adMuteBtn').style.display = 'block'; break; case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: if (ad.isLinear()) { clearInterval(intervalTimer); } if (prerollLastError === 303) { playYtVideo(); } break; case google.ima.AdEvent.Type.COMPLETE: if (ad.isLinear()) { clearInterval(intervalTimer); } playYtVideo(); break; } } function onAdError(adErrorEvent) { console.log(adErrorEvent.getError()); prerollLastError = adErrorEvent.getError().getErrorCode(); if (!loadNext()) { playYtVideo(); } } function loadNext() { iinfoVastUrlIndex++; if (iinfoVastUrlIndex < iinfoVastUrls.length) { iinfoPrerollPosition.remove(); playPrerollAd(); } else { return false; } adVolume = 1; return true; } function onContentPauseRequested() { videoContent.pause(); } function onContentResumeRequested() { videoContent.play(); } function onActiveView() { if (prerollContainer) { const containerOffset = prerollContainer.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight/1 && containerOffset.bottom > 0.0) { if (prerollPaused) { adsManager.resume(); prerollPaused = false; } return true; } else { if (!prerollPaused) { adsManager.pause(); prerollPaused = true; } } } return false; } function playYtVideo() { iinfoPrerollPosition.remove(); youtubeIframe.style.display = 'block'; youtubeIframe.src += '&autoplay=1&mute=1'; } }
'; document.getElementById('outstream-iframe').onload = function () { setupIframe(); } replayScreen = document.getElementById('iinfoOutstreamReplay'); iinfoOutstreamPosition = document.getElementById('iinfoOutstreamPosition'); outstreamContainer = document.getElementsByClassName('outstream-container')[0]; setupReplayScreen(); } function setupIframe() { outstreamDocument = document.getElementById('outstream-iframe').contentWindow.document; let el = outstreamDocument.createElement('style'); outstreamDocument.head.appendChild(el); el.innerText = "#adContainer>div:nth-of-type(1),#adContainer>div:nth-of-type(1) > iframe { width: 99% !important;height: 99% !important;max-width: 100%;}#videoContent,body{ width:100vw;height:100vh}body{ font-family:'Helvetica Neue',Arial,sans-serif}#videoContent{ overflow:hidden;background:#000}#adMuteBtn{ width:35px;height:35px;border:0;background:0 0;display:none;position:absolute;fill:rgba(230,230,230,1);bottom:-5px;right:25px}"; videoContent = outstreamDocument.getElementById('contentElement'); videoContent.style.display = 'none'; videoContent.volume = 1; videoContent.muted = false; if ( location.href.indexOf('rejstriky.finance.cz') !== -1 || location.href.indexOf('finance-rejstrik') !== -1 || location.href.indexOf('firmy.euro.cz') !== -1 || location.href.indexOf('euro-rejstrik') !== -1 || location.href.indexOf('/rejstrik/') !== -1 || location.href.indexOf('/rejstrik-firem/') !== -1) { outstreamDirectPlayed = true; soundAllowed = true; iinfoVastUrlIndex = 0; } if (!outstreamDirectPlayed) { console.log('OUTSTREAM direct'); setUpIMA(true); } else { if (soundAllowed) { const playPromise = videoContent.play(); if (playPromise !== undefined) { playPromise.then(function () { console.log('OUTSTREAM sound allowed'); setUpIMA(false); }).catch(function () { console.log('OUTSTREAM sound forbidden'); renderBanner(); }); } } else { renderBanner(); } } } function getWrapper() { let articleWrapper = document.querySelector('.rs-outstream-placeholder'); // Outstream Placeholder from RedSys manipulation if (articleWrapper && articleWrapper.style.display !== 'block') { articleWrapper.innerHTML = ""; articleWrapper.style.display = 'block'; } // Don't render OutStream on homepages if (articleWrapper === null) { if (document.querySelector('body.p-index')) { return null; } } if (articleWrapper === null) { articleWrapper = document.getElementById('iinfo-outstream'); } if (articleWrapper === null) { articleWrapper = document.querySelector('.layout-main__content .detail__article p:nth-of-type(6)'); } if (articleWrapper === null) { // Euro, Autobible, Zdravi articleWrapper = document.querySelector('.o-article .o-article__text p:nth-of-type(6)'); } if (articleWrapper === null) { articleWrapper = document.getElementById('sidebar'); } if (!articleWrapper) { console.error("Outstream wrapper of article was not found."); } return articleWrapper; } function setupDimensions() { outstreamWidth = Math.min(iinfoOutstreamPosition.offsetWidth, 480); outstreamHeight = Math.min(iinfoOutstreamPosition.offsetHeight, 320); } /** * Sets up IMA ad display container, ads loader, and makes an ad request. */ function setUpIMA(direct) { google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true); google.ima.settings.setLocale('cs'); google.ima.settings.setNumRedirects(10); // Create the ad display container. createAdDisplayContainer(); // Create ads loader. adsLoader = new google.ima.AdsLoader(adDisplayContainer); // Listen and respond to ads loaded and error events. adsLoader.addEventListener( google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, onAdsManagerLoaded, false); adsLoader.addEventListener( google.ima.AdErrorEvent.Type.AD_ERROR, onAdError, false); // An event listener to tell the SDK that our content video // is completed so the SDK can play any post-roll ads. const contentEndedListener = function () { adsLoader.contentComplete(); }; videoContent.onended = contentEndedListener; // Request video ads. const adsRequest = new google.ima.AdsRequest(); if (direct) { adsRequest.adTagUrl = directVast; console.log('Outstream DIRECT CAMPAING advert: ' + directVast); videoContent.muted = true; videoContent.volume = 0; outstreamDirectPlayed = true; } else { adsRequest.adTagUrl = iinfoVastUrls[iinfoVastUrlIndex]; console.log('Outstream advert: ' + iinfoVastUrls[iinfoVastUrlIndex]); videoContent.muted = false; videoContent.volume = 1; } // Specify the linear and nonlinear slot sizes. This helps the SDK to // select the correct creative if multiple are returned. // adsRequest.linearAdSlotWidth = outstreamWidth; // adsRequest.linearAdSlotHeight = outstreamHeight; adsRequest.nonLinearAdSlotWidth = 0; adsRequest.nonLinearAdSlotHeight = 0; adsLoader.requestAds(adsRequest); } function setupReplayScreen() { replayScreen.addEventListener('click', function () { iinfoOutstreamPosition.remove(); iinfoVastUrlIndex = 0; outstreamInit(); }); } /** * Sets the 'adContainer' div as the IMA ad display container. */ function createAdDisplayContainer() { // We assume the adContainer is the DOM id of the element that will house // the ads. outstreamDocument.getElementById('videoContent').style.display = 'none'; adDisplayContainer = new google.ima.AdDisplayContainer( outstreamDocument.getElementById('adContainer'), videoContent); } function unmuteAdvert() { adVolume = !adVolume; if (adVolume) { adsManager.setVolume(0.3); outstreamDocument.getElementById('adMuteBtn').innerHTML = ''; } else { adsManager.setVolume(0); outstreamDocument.getElementById('adMuteBtn').innerHTML = ''; } } /** * Loads the video content and initializes IMA ad playback. */ function playAds() { // Initialize the container. Must be done through a user action on mobile // devices. videoContent.load(); adDisplayContainer.initialize(); // setupDimensions(); try { // Initialize the ads manager. Ad rules playlist will start at this time. adsManager.init(1920, 1080, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will // start at this time; the call will be ignored for ad rules. adsManager.start(); // window.addEventListener('resize', function (event) { // if (adsManager) { // setupDimensions(); // adsManager.resize(outstreamWidth, outstreamHeight, google.ima.ViewMode.NORMAL); // } // }); } catch (adError) { // An error may be thrown if there was a problem with the VAST response. // videoContent.play(); } } /** * Handles the ad manager loading and sets ad event listeners. * @param { !google.ima.AdsManagerLoadedEvent } adsManagerLoadedEvent */ function onAdsManagerLoaded(adsManagerLoadedEvent) { // Get the ads manager. const adsRenderingSettings = new google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true; adsRenderingSettings.loadVideoTimeout = 12000; // videoContent should be set to the content video element. adsManager = adsManagerLoadedEvent.getAdsManager(videoContent, adsRenderingSettings); // Add listeners to the required events. adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested); adsManager.addEventListener( google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, onContentResumeRequested); adsManager.addEventListener( google.ima.AdEvent.Type.ALL_ADS_COMPLETED, onAdEvent); // Listen to any additional events, if necessary. adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, onAdEvent); adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, onAdEvent); playAds(); } /** * Handles actions taken in response to ad events. * @param { !google.ima.AdEvent } adEvent */ function onAdEvent(adEvent) { // Retrieve the ad from the event. Some events (for example, // ALL_ADS_COMPLETED) don't have ad object associated. const ad = adEvent.getAd(); console.log('Outstream event: ' + adEvent.type); switch (adEvent.type) { case google.ima.AdEvent.Type.LOADED: // This is the first event sent for an ad - it is possible to // determine whether the ad is a video ad or an overlay. if (!ad.isLinear()) { // Position AdDisplayContainer correctly for overlay. // Use ad.width and ad.height. videoContent.play(); } outstreamDocument.getElementById('adContainer').style.width = '100%'; outstreamDocument.getElementById('adContainer').style.maxWidth = '640px'; outstreamDocument.getElementById('adContainer').style.height = '360px'; break; case google.ima.AdEvent.Type.STARTED: window.addEventListener('scroll', onActiveView); // This event indicates the ad has started - the video player // can adjust the UI, for example display a pause button and // remaining time. if (ad.isLinear()) { // For a linear ad, a timer can be started to poll for // the remaining time. intervalTimer = setInterval( function () { // Example: const remainingTime = adsManager.getRemainingTime(); // adsManager.pause(); }, 300); // every 300ms } outstreamDocument.getElementById('adMuteBtn').style.display = 'block'; break; case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: if (ad.isLinear()) { clearInterval(intervalTimer); } if (outstreamLastError === 303) { if (isBanner) { renderBanner(); } else { replayScreen.style.display = 'flex'; } } break; case google.ima.AdEvent.Type.COMPLETE: // This event indicates the ad has finished - the video player // can perform appropriate UI actions, such as removing the timer for // remaining time detection. if (ad.isLinear()) { clearInterval(intervalTimer); } if (isBanner) { renderBanner(); } else { replayScreen.style.display = 'flex'; } break; } } /** * Handles ad errors. * @param { !google.ima.AdErrorEvent } adErrorEvent */ function onAdError(adErrorEvent) { // Handle the error logging. console.log(adErrorEvent.getError()); outstreamLastError = adErrorEvent.getError().getErrorCode(); if (!loadNext()) { renderBanner(); } } function renderBanner() { if (isBanner) { console.log('Outstream: Render Banner'); iinfoOutstreamPosition.innerHTML = ""; iinfoOutstreamPosition.style.height = "330px"; iinfoOutstreamPosition.appendChild(bannerDiv); } else { console.log('Outstream: Banner is not set'); } } function loadNext() { iinfoVastUrlIndex++; if (iinfoVastUrlIndex < iinfoVastUrls.length) { iinfoOutstreamPosition.remove(); outstreamInit(); } else { return false; } adVolume = 1; return true; } /** * Pauses video content and sets up ad UI. */ function onContentPauseRequested() { videoContent.pause(); // This function is where you should setup UI for showing ads (for example, // display ad timer countdown, disable seeking and more.) // setupUIForAds(); } /** * Resumes video content and removes ad UI. */ function onContentResumeRequested() { videoContent.play(); // This function is where you should ensure that your UI is ready // to play content. It is the responsibility of the Publisher to // implement this function when necessary. // setupUIForContent(); } function onActiveView() { if (outstreamContainer) { const containerOffset = outstreamContainer.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight/1 && containerOffset.bottom > 0.0) { if (outstreamPaused) { adsManager.resume(); outstreamPaused = false; } return true; } else { if (!outstreamPaused) { adsManager.pause(); outstreamPaused = true; } } } return false; } let outstreamInitInterval; if (typeof cpexPackage !== "undefined") { outstreamInitInterval = setInterval(tryToInitializeOutstream, 100); } else { const wrapper = getWrapper(); if (wrapper) { let outstreamInitialized = false; window.addEventListener('scroll', () => { if (!outstreamInitialized) { const containerOffset = wrapper.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight / 1 && containerOffset.bottom > 0.0) { outstreamInit(); outstreamInitialized = true; } } }); } } function tryToInitializeOutstream() { const wrapper = getWrapper(); if (wrapper) { const containerOffset = wrapper.getBoundingClientRect(); const windowHeight = window.innerHeight; if (containerOffset.top < windowHeight / 1 && containerOffset.bottom > 0.0) { if (cpexPackage.adserver.displayed) { clearInterval(outstreamInitInterval); outstreamInit(); } } } else { clearInterval(outstreamInitInterval); } } }
OSZAR »