Error mac did not verify

I have been trying to implement some basic push functionality with primefaces in jsf. I have used there counter example http://www.primefaces.org/showcase-labs/push/counter.jsf. Essentially its a b...

ByteArrayGuard class randomly outputs «ERROR: MAC did not verify!» messages to the error console. This only occurs when client side viewstate encryption is enabled and that multiple clients are running against the server.

So you must change that class in your Java Server Faces references with…

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
 * or packager/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at packager/legal/LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.sun.faces.renderkit;

import com.sun.faces.util.FacesLogger;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.faces.FacesException;

/**
 * <p>This utility class is to provide both encryption and
 * decryption <code>Ciphers</code> to <code>ResponseStateManager</code>
 * implementations wishing to provide encryption support.</p>
 * 
 * <p>The algorithm used to encrypt byte array is AES with CBC.</p>
 *  
 * <p>Original author Inderjeet Singh, J2EE Blue Prints Team. Modified to suit JSF
 * needs.</p> 
 */
public final class ByteArrayGuard {


     // Log instance for this class
    private static final Logger LOGGER = FacesLogger.RENDERKIT.getLogger();

    private static final int MAC_LENGTH = 32;
    private static final int KEY_LENGTH = 128;
    private static final int IV_LENGTH = 16;

    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_CODE = "AES/CBC/PKCS5Padding";
    private static final String MAC_CODE = "HmacSHA256";
    private SecretKey sk;

    // ------------------------------------------------------------ Constructors

    public ByteArrayGuard() {

        try {
            setupKeyAndMac();
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.SEVERE)) { 
                LOGGER.log(Level.SEVERE,
                           "Unexpected exception initializing encryption."
                           + "  No encryption will be performed.",
                           e);
            }
            System.err.println("ERROR: Initializing Ciphers");
        }
    }

    // ---------------------------------------------------------- Public Methods    


    /**
     * This method:
     *    Encrypts bytes using a cipher.  
     *    Generates MAC for intialization vector of the cipher
     *    Generates MAC for encrypted data
     *    Returns a byte array consisting of the following concatenated together:
     *       |MAC for cnrypted Data | MAC for Init Vector | Encrypted Data |
     * @param bytes The byte array to be encrypted.
     * @return the encrypted byte array.
     */
    public byte[] encrypt(byte[] bytes) {
        byte[] securedata = null;
        try {
            // Generate IV
            SecureRandom rand = new SecureRandom();
            byte[] iv = new byte[16];
            rand.nextBytes(iv);
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            Cipher encryptCipher = Cipher.getInstance(CIPHER_CODE);
            encryptCipher.init(Cipher.ENCRYPT_MODE, sk, ivspec);
            Mac encryptMac = Mac.getInstance(MAC_CODE);
            encryptMac.init(sk);
            encryptMac.update(iv);
            // encrypt the plaintext
            byte[] encdata = encryptCipher.doFinal(bytes);
            byte[] macBytes = encryptMac.doFinal(encdata);
            byte[] tmp = concatBytes(macBytes, iv);
            securedata = concatBytes(tmp, encdata);
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.SEVERE)) {
                LOGGER.log(Level.SEVERE,
                           "Unexpected exception initializing encryption."
                           + "  No encryption will be performed.",
                           e);
            }
            return null;
        }
        return securedata;
    }

    /**
     * This method decrypts the provided byte array.
     * The decryption is only performed if the regenerated MAC
     * is the same as the MAC for the received value.
     * @param bytes Encrypted byte array to be decrypted.
     * @return Decrypted byte array.
     */
    public byte[] decrypt(byte[] bytes) {
        try {
            // Extract MAC
            byte[] macBytes = new byte[MAC_LENGTH];
            System.arraycopy(bytes, 0, macBytes, 0, macBytes.length);

            // Extract IV
            byte[] iv = new byte[IV_LENGTH];
            System.arraycopy(bytes, macBytes.length, iv, 0, iv.length);

            // Extract encrypted data
            byte[] encdata = new byte[bytes.length - macBytes.length - iv.length];
            System.arraycopy(bytes, macBytes.length + iv.length, encdata, 0, encdata.length);

            IvParameterSpec ivspec = new IvParameterSpec(iv);
            Cipher decryptCipher = Cipher.getInstance(CIPHER_CODE);
            decryptCipher.init(Cipher.DECRYPT_MODE, sk, ivspec);

            // verify MAC by regenerating it and comparing it with the received value
            Mac decryptMac = Mac.getInstance(MAC_CODE);
            decryptMac.init(sk);
            decryptMac.update(iv);
            decryptMac.update(encdata);
            byte[] macBytesCalculated = decryptMac.doFinal();
            if (Arrays.equals(macBytes, macBytesCalculated)) {
                // continue only if the MAC was valid
                // System.out.println("Valid MAC found!");
                byte[] plaindata = decryptCipher.doFinal(encdata);
                return plaindata;
            } else {
                System.err.println("ERROR: MAC did not verify!");
                return null;
            }
        } catch (Exception e) {
            System.err.println("ERROR: Decrypting:"+e.getCause());
            return null; // Signal to JSF runtime
        }
    }

    // --------------------------------------------------------- Private Methods

    /**
     * Generates secret key.
     * Initializes MAC(s).
     */
    private void setupKeyAndMac() {

        try {
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            kg.init(KEY_LENGTH);   // 256 if you're using the Unlimited Policy Files
            sk = kg.generateKey(); 

        } catch (Exception e) {
            throw new FacesException(e);
        }
    }

    /**
     * This method concatenates two byte arrays
     * @return a byte array of array1||array2
     * @param array1 first byte array to be concatenated
     * @param array2 second byte array to be concatenated
     */
    private static byte[] concatBytes(byte[] array1, byte[] array2) {
        byte[] cBytes = new byte[array1.length + array2.length];
        try {
            System.arraycopy(array1, 0, cBytes, 0, array1.length);
            System.arraycopy(array2, 0, cBytes, array1.length, array2.length);
        } catch(Exception e) {
            throw new FacesException(e);
        }
        return cBytes;
    }    
}

And reload this jar.
JSF_REFERENCE

Hi all,

I’m new to Primefaces and building my first website with.

I’m always get the error : ERROR: MAC did not verify (3 lines at a time, every 4 seconds)

Here is my xhtml page

Code: Select all

<h:body>
		<h:form>
	    	<style type="text/css">
		        .ui-inputfield.ui-state-focus, .ui-widget-content .ui-inputfield.ui-state-focus, .ui-widget-header .ui-inputfield.ui-state-focus {
				    -moz-box-shadow: none;
				    -webkit-box-shadow: none;
				    box-shadow: none;
				}
	    	</style>
	    </h:form>
    	
		<p:panelGrid>
			<f:facet name="header">
				<p:row>
					<p:column colspan="4">
						<ui:include src="/header.xhtml"/>
					</p:column>
				</p:row>
				<p:row>
					<p:column colspan="4">
						<ui:include src="/mainMenu.xhtml"/>
					</p:column>
				</p:row>
			</f:facet>
			
			<p:row>
				<p:column>
					
				</p:column>
				
				<p:column>
					<h:form>
	    				<p:dataTable id="dtbl" value="#{adminAcceuilBackbean.cdmCarAcc}" var="c" rows="1" first="#{acceuilBackbean.page}">
	    					<p:column>
		    					<p:panelGrid columns="2" style="width:100%">
		    						<p:graphicImage url="#{c.cheminImage}" width="#{c.styleImage}"/>
		    						
		    						<p:inputTextarea value="#{c.texte}" rows="#{c.hauteurTexte}" cols="#{c.largeurTexte}" readonly="true" style="#{c.styleTexte}"/>
		    					</p:panelGrid>
	    					</p:column>
	    				</p:dataTable>
			    		<p:poll interval="10" listener="#{acceuilBackbean.scrollCar}" update="dtbl"/>
	    			</h:form>
	    			
	    			<h:form>
	    				<p:dataTable value="#{adminAcceuilBackbean.cdmAcc}" var="c">
	    					<p:column>
		    					<p:panelGrid columns="2" style="width:100%">
		    						<p:graphicImage url="#{c.cheminImage}" width="#{c.styleImage}"/>
		    						
		    						<p:inputTextarea value="#{c.texte}" rows="#{c.hauteurTexte}" cols="#{c.largeurTexte}" readonly="true" style="#{c.styleTexte}"/>
		    					</p:panelGrid>
	    					</p:column>
	    				</p:dataTable>
	    			</h:form>
				</p:column>
				
				<p:column>
					
				</p:column>
			</p:row>
		</p:panelGrid>
	</h:body>

BackBean

Code: Select all

@ManagedBean
@ViewScoped
public class AcceuilBackbean {
	private ContenuDataModel cdmCarAcc;
	private ContenuDataModel cdmAcc;
	private int page;
	
	private Utiles ut;
	
	public AcceuilBackbean(){
		ut = new Utiles();
		cdmCarAcc = new ContenuDataModel(ut.getListes().listContenuByEmplacement(Emplacement.ACCEUIL_CAROUSSEL));
		cdmAcc = new ContenuDataModel(ut.getListes().listContenuByEmplacement(Emplacement.ACCEUIL));
		page = 0;
	}
	
	// Actions
	public void scrollCar(){
		page = (page >= cdmCarAcc.getRowCount() - 1)? 0:page + 1;
	}

	// Getters & Setters
	public ContenuDataModel getCdmCarAcc() {
		return cdmCarAcc;
	}

	public void setCdmCarAcc(ContenuDataModel cdmCarAcc) {
		this.cdmCarAcc = cdmCarAcc;
	}

	public ContenuDataModel getCdmAcc() {
		return cdmAcc;
	}

	public void setCdmAcc(ContenuDataModel cdmAcc) {
		this.cdmAcc = cdmAcc;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}	
}

If I change the saving state method to «server», I ran into a null pointer exception :

mai 04, 2014 1:33:06 PM org.apache.catalina.core.StandardWrapperValve invoke
Grave: «Servlet.service()» pour la servlet Faces Servlet a généré une exception
java.lang.NullPointerException
at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:485)
at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:73)
at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:619)
at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:116)
at org.primefaces.context.PrimePartialResponseWriter.startDocument(PrimePartialResponseWriter.java:134)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:199)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:124)
at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

I also tried a fresh install of a new development virtual machine, it first solve the problem but, after 3-4 hours of development it start to give the ERROR: MAC did not verify again.

javax.faces.STATE_SAVING_METHOD или ERROR: MAC did not verify

      В дескрипторе развертывания web.xml в web приложения JAVA EE можно добавить параметр javax.faces.STATE_SAVING_METHOD для определения места хранения состояния представления между запросами приложения.
Всего есть два варианта где хранить данное состояние:

  • На стороне сервера (server);
  • На стороне клиента (client).

      Если не определять данный параметр, то по умолчанию используется значение server. Если значение параметра присвоено значении client, состояние будет сохраняться прямо в HTML код страницы.

Так что выбрать?

       Если у вас ограниченные возможности сервера, то лучше выбрать client вариант. При пересылке больших объемов данных между клиентом и сервером то вариант с server значением будет выглядеть более быстрее. Во время разработки лучше использовать server вариант что бы не отвлекаться на предупреждения и ошибки сервера приложения, такие как: «ERROR: MAC did not verify». Ну а лучше всего протестировать готовое приложение под нагрузкой и выбрать оптимальный вариант.

Популярные сообщения из этого блога

Этот пост поможет правильно установить и сконфигурировать Oracle Enterprise Manager 13c. Oracle Enterprise Manager — Это централизованный центр управления и мониторинга для всех продуктов Oracle. OEM способен управлять и мониторить и сторонние приложения и сообщать о всех критических проблемах основанные на установленных правилах установленные администратором. Первоначальные настройки системы Oracle Linux 6.7 64 Bit Virtual Machine VirtualBox 5.1.6 for Windows hosts Oracle Database 12.1.0.2 Oracle Enterprise Manager 13c Выделена оперативной памяти 12 Гб . На операционной системе Oracle Linux 6.7 64 Bit предустановлена база данных Oracle Database 12c установка которой тут не рассматривается. Предустановленные пакеты для корректной установки и настройки Oracle Management Service (OMS) make-3.81 binutils-2.20 gcc-4.4.4 libaio-0.3.107 glibc-common-2.12-1 libstdc++-4.4.4 libXtst-1.0.99 (x86_64) sysstat-9.0.4 glibc-2.12 glibc-devel-2.1

Шпаргалка по работе с пакетным менеджером Yum (Yellowdog Updater, Modified), который используется в популярных Linux дистрибутивах: RedHat, CentOS, Scientific Linux (и других). В целях экономии места вывод команд не представлен. отображение команд и опций #yum help список названий пакетов из репозиторий #yum list список всех доступных пакетов #yum list available список всех установленных пакетов #yum list installed установлен ли указанный пакет #yum list installed httpd список установленных и доступных пакетов #yum list all список пакетов, относящихся к ядру #yum list kernel отображение информации о пакете #yum info httpd список зависимостей и необходимых пакетов #yum deplist httpd найти пакет, который содержит файл #yum provides «*bin/top» поиск пакета по имени и описанию #yum search httpd #yum search yum получить информацию о доступных обновлениях безопасности #yum updateinfo list security вывести список групп #yum gr

Я расскажу вам, как запустить приложение Spring Boot из командной строки в окне терминала. Есть несколько способов, и оба предполагают, что вы уже создали приложение Spring Boot. Добавить плагин Maven в POM . XML Чтобы мы могли запускать приложение Spring Boot в виде единого исполняемого файла JAR Java , нам сначала нужно обновить файл pom . xml нашего проекта и добавить к нему подключаемый модуль maven . Откройте файл pom . xml и добавьте следующий фрагмент XML ниже списка зависимостей проекта. <build> <plugins> <plugin> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-maven-plugin </artifactId> </plugin> </plugins> </build> Сборка Spring Boot проекта с Maven Чтобы иметь возможность запускать приложение Spring Boot , вам необходимо сначала его собрать. Чтобы собрать и упаковать приложение Spring Boot в один исполняемый файл Jar с

Я пытаюсь реализовать некоторые базовые функции push с первичными в jsf. Я использовал там встречный пример http://www.primefaces.org/showcase-labs/push/counter.jsf. По существу это кнопка, которая увеличивает общий счетчик. При запуске этого примера я всегда получаю эту ошибку:

ERROR: MAC did not verify!

Я понимаю, что Mac генерируется каждый сеанс, а затем проверяется каждое входящее сообщение, чтобы убедиться, что источник не изменился (я думаю). Я не смог найти причину этого и посмотрел на другие потоки, такие как:

ОШИБКА: MAC не подтвердил! PrimeFaces

JSF: миграция Mojarra с 2.1 по 2.2, вызывающая ViewExpiredException

К сожалению, это не решило мою проблему. Оба, похоже, вызваны представлением ViewExpiredException, которое я не получаю. Единственное, что я нашел, чтобы остановить это, — это изменить способ сохранения состояния с клиента на сервер в web.xml:

<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>

Однако при этом счетчик больше не используется, но, похоже, для пользователя, чего я не хочу. Моя конечная цель — создать чат, который по большей части есть, но прямо сейчас он использует короткий опрос, который не очень масштабируемый. Взглянув на то, что я понял, я думал, что это будет идеально, но изо всех сил пытались его использовать.

Я пробовал на нескольких веб-серверах (Tomcat, Jetty и Glassfish) и пытался использовать разные версии JSF (Mojarra) и версии перьев (3.4 и 4.0). Я тестировал его в нескольких браузерах и на нескольких компьютерах. Иногда я могу увеличить счетчик несколько раз, прежде чем я получу ошибку, иногда это происходит сразу. У меня нет исключений или ошибок сервера, и все компилируется. Я также хотел бы упомянуть, что раньше у меня была эта ошибка в других проектах, но после перезагрузки сервера она исчезла. При использовании перфоризмов это всегда происходит. Любая помощь будет оценена.

ИЗМЕНИТЬ

При сохранении сохранения состояния на сервере в web.xml, чтобы избежать ошибки MAC, я заметил, что общий счетчик работает в браузере с одного компьютера. Значение, если у меня есть несколько вкладок или окон, обновляя счетчик в одном обновлении во всех них. Но он не работает в браузерах, изменение счетчика в firefox не отражается на хром или IE, или на других путях. Это также не отражается, если на двух отдельных компьютерах. Я не знаю, помогает ли это, но подумал, что я бы сказал об этом.

ИЗМЕНИТЬ

Увидев, что bean в этом примере является областью действия сеанса, я изменил ее на область приложения. Разумеется, сеансовое охват означает, что каждый браузер имеет свою собственную копию. Теперь изменения отражаются в браузере и машинах. Вернемся к исходной проблеме, но я все равно хотел бы знать, почему изменение состояния сохранения на сервере устраняет ошибку MAC и каковы последствия этого? Я предполагаю, что сервер теперь должен поддерживать состояния представления для каждого сеанса, а не для клиента, менее масштабируемый/более трафик клиент-сервер? Из того, что я прочитал, если вы установили состояние сохранения на сервер, вы не можете проверять исключения с истекшим временем просмотра или запрещать пользователям создавать представления, если их уже слишком много, правильно ли это?

У меня есть одно доменное имя, указывающее на один сервер, на котором запущен проект JoinFaces + PrimeFaces. Когда я нажимаю p:commandButton в форме на сервере через его IP-адрес, все работает нормально. Но когда я делаю то же самое через доменное имя (вместо IP-адреса), я получаю ошибку ERROR: MAC did not verify / javax.faces.application.ViewExpiredException. Любая идея, почему сервер будет вести себя по-разному в зависимости от того, осуществляется ли к нему доступ через его IP-адрес или через его доменное имя?

1 ответ

Лучший ответ

Оказалось, что проблема связана с агрессивной конфигурацией кеширования в CloudFlare (то есть, включая состояние просмотра).


1

mossaab
10 Авг 2021 в 19:51

У меня проблема с представлением «Первичные и клиентские стороны»

<context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
</context-param>

При попытке восстановить представление запроса AJAX я получаю исключение ViewExpiredException.
Это происходит только тогда, когда аутентификация через Spring RememberMe была выполнена и применяется только к запросу AJAX, а не, если страница полностью перезагружена.

Некоторый анализ:

Система пытается восстановить представление в

com.sun.faces.renderkit.ClientSideStateHelper.doGetState(String stateString)

который затем вызывает

com.sun.faces.renderkit.ByteArrayGuard.decrypt(byte[] bytes)

Здесь метод

 Arrays.equals(macBytes, macBytesCalculated)

завершается сбой, а ошибка

ERROR: MAC did not verify!

что предотвращает восстановление вида.
Я предполагаю, что это связано с различной логикой шифрования между данным содержимым запроса AJAX и расшифровкой в ​​ByteArrayGuard.

Я также протестировал последнюю версию, указанную в https://java.net/jira/browse/JAVASERVERFACES-2553, однако она не изменила поведение. (в отличие от JAVASERVERFACES-2553 моя проблема не связана с безопасностью потоков…)

Любые идеи?

Спасибо и любезны, Крис

StackTrace:

ERROR: MAC did not verify!
Nov 29, 2013 2:58:15 AM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.faces.application.ViewExpiredException: viewId:/page.xhtml - Ansicht /pages.xhtml konnte nicht wiederhergestellt werden.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:210)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

Comments

@bilalmalik777

i updated my application from 2.2 to 3.1 and facing the following error.It was working perfectly in 2.2 with docker
'error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure'

it was working fine with 2.2 but now facing an error in development mode. i run the following command to generate the dev certificate

dotnet dev-certs https -ep %APPDATA%ASP.NETHttpsTT.Core.Portal.Web.AzureHybrid.pfx -p password
dotnet dev-certs https --trust
dotnet user-secrets -p TT.Core.Portal.Web.AzureHybrid.csproj set "Kestrel:Certificates:Development:Password" "password"

program.cs

            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseKestrel(options =>
                             {
                                 bool.TryParse(Environment.GetEnvironmentVariable("IsDockerDeployment"), out bool isDockerDeployment);
                                 if (isDockerDeployment)
                                 {
                                     options.Listen(new IPEndPoint(IPAddress.Any, 443), listenOptions =>
                                     {
                                         var configuration = (IConfiguration)options.ApplicationServices.GetService(typeof(IConfiguration));
                                         var certPassword = Environment.GetEnvironmentVariable("ASPNETCORE_Kestrel__Certificates__Development__Password");
                                         var certPath = Environment.GetEnvironmentVariable("ASPNETCORE_Kestrel__Certificates__Development__Path");
                                         Console.WriteLine(certPassword);
                                         Console.WriteLine(certPath);

                                         var certificate = new X509Certificate2(certPath, certPassword);
                                         Console.WriteLine("Certificate provided");
                                         var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                                         {
                                             ClientCertificateMode = ClientCertificateMode.NoCertificate,
                                             SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
                                             ServerCertificate = certificate,
                                         };
                                         listenOptions.UseHttps(httpsConnectionAdapterOptions);
                                     });
                                 }
                             });
                    ////webBuilder.UseIIS();
                    webBuilder.UseStartup<Startup>();
                });

i also declared both environment varibale ASPNETCORE_Kestrel__Certificates__Development__Password && ASPNETCORE_Kestrel__Certificates__Development__Path in the docker compose file.
Please help me to solve this issue

@mkArtakMSFT

Thanks for contacting us.
@Tratcher do you see any issues with this code? Or is this an issue with the generated cert?

@Tratcher

@bilalmalik777

yes, i am getting command line output correctly. I attached images of error with both UseKestrel & ConfigureKestrel and output screen image in which circle of output pf password . Also, the docker-compose and docker-compose override configuration is given below. interestingly in production, it is working fine only doing the problem in the development environment

### Evviornment variable file

env=devdocker
isDockerDeployment=true
appCertificate=/root/.aspnet/https/TT.Core.Api.pfx
appCertificatepassword=bfe4e20f-bcb4-4e95-9c76-9b7bfce2f35e

**docker-compose file**

version: '3.4'

services:

  tt.core.api:
    image: ${DOCKER_REGISTRY-}ttcoreapi
    build:
      context: .
      dockerfile: TT.Core.Api/Dockerfile
    restart: always
    networks:
     - app-network

networks:
  app-network:
    ipam:
      driver: default
      config:
        - subnet: 172.24.0.0/24


**docker-compose override**

version: '3.4'

services:
  tt.core.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=${env}
      - IsDockerDeployment=${isDockerDeployment}
      - ASPNETCORE_URLS=https://+:443;http://+:80
      - ASPNETCORE_HTTPS_PORT=44379
      - KestrelPath=${appCertificate}
      - KestrelPassword=${appCertificatepassword}
      - ASPNETCORE_Kestrel__Certificates__Development__Password=${appCertificatepassword}
      - ASPNETCORE_Kestrel__Certificates__Development__Path=${appCertificate}
    ports:
      - "50515:80"
      - "44379:443"
    volumes:
      - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

_**appsettings.json**_
  "Kestrel": {
    "Certificates": {
      "Default": {
        "Path": "/root/.aspnet/https/TT.Core.Api.pfx",
        "Password": "bfe4e20f-bcb4-4e95-9c76-9b7bfce2f35e"
      }
    }
  },

2021-01-08 06_15_36-Window
2021-01-08 06_26_27-Window
Inked2021-01-08 07_01_46-Window_LI

@Tratcher

Ok, I’m going to transfer this to the runtime team to see if they can help dig into that.

@Tratcher
Tratcher

transferred this issue from dotnet/aspnetcore

Jan 8, 2021

@Dotnet-GitSync-Bot

I couldn’t figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

@msftbot

Tagging subscribers to this area: @bartonjs, @vcsjones, @krwq
See info in area-owners.md if you want to be subscribed.

Issue Details


i updated my application from 2.2 to 3.1 and facing the following error.It was working perfectly in 2.2 with docker
'error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure'

it was working fine with 2.2 but now facing an error in development mode. i run the following command to generate the dev certificate

dotnet dev-certs https -ep %APPDATA%ASP.NETHttpsTT.Core.Portal.Web.AzureHybrid.pfx -p password
dotnet dev-certs https --trust
dotnet user-secrets -p TT.Core.Portal.Web.AzureHybrid.csproj set "Kestrel:Certificates:Development:Password" "password"

program.cs

            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseKestrel(options =>
                             {
                                 bool.TryParse(Environment.GetEnvironmentVariable("IsDockerDeployment"), out bool isDockerDeployment);
                                 if (isDockerDeployment)
                                 {
                                     options.Listen(new IPEndPoint(IPAddress.Any, 443), listenOptions =>
                                     {
                                         var configuration = (IConfiguration)options.ApplicationServices.GetService(typeof(IConfiguration));
                                         var certPassword = Environment.GetEnvironmentVariable("ASPNETCORE_Kestrel__Certificates__Development__Password");
                                         var certPath = Environment.GetEnvironmentVariable("ASPNETCORE_Kestrel__Certificates__Development__Path");
                                         Console.WriteLine(certPassword);
                                         Console.WriteLine(certPath);

                                         var certificate = new X509Certificate2(certPath, certPassword);
                                         Console.WriteLine("Certificate provided");
                                         var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
                                         {
                                             ClientCertificateMode = ClientCertificateMode.NoCertificate,
                                             SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
                                             ServerCertificate = certificate,
                                         };
                                         listenOptions.UseHttps(httpsConnectionAdapterOptions);
                                     });
                                 }
                             });
                    ////webBuilder.UseIIS();
                    webBuilder.UseStartup<Startup>();
                });

i also declared both environment varibale ASPNETCORE_Kestrel__Certificates__Development__Password && ASPNETCORE_Kestrel__Certificates__Development__Path in the docker compose file.
Please help me to solve this issue

Author: bilalmalik777
Assignees:
Labels:

area-System.Security, untriaged

Milestone:

@bartonjs

That error comes out of OpenSSL, and just means that the password is incorrect. But since easy answers aren’t working I’ll be a bit more verbose, maybe we’re in the 0.5% case here.

What that error /really/ means is that when the password was used as input to the MAC KDF the resulting key + the file contents did not verify against the embedded MAC value. The almost always case is that the password is not the same as when the file was generated (either «the password is incorrect» or «this isn’t the file you think it is»). The 0.5% case is that the file has become corrupted.

If it works with 3.1 when you’re using a release configuration but fails when using a debug configuration that suggests that something in the configuration layout is wrong.

  • Your debug configuration has the wrong password (is there maybe an accidental space at the end?)
  • Your debug configuration has the wrong (outdated, perhaps?) file
  • Your debug configuration is corrupting the file on copy
  • (Or, perhaps, something I can’t envision as being relevant is relevant 😄)

If I’ve misunderstood the state and all that is known is that a 2.x release configuration worked and a 3.1 debug configuration doesn’t, then please try 3.1 release to close down variables.

@bilalmalik777

Hi @bartonjs, today I came back to the office from leaves that is why I did not respond to you. I deleted the pfx file and regenerated the file still facing the same error, also double-checked the password and debug configuration. What is the meaning of the last line? please try 3.1 release to close down variables.

@vcsjones

@bilalmalik777

regenerated the file still facing the same error

If you can generate a test PFX file that reproduces the error, where you can open in in 2.1 successfully but not 3.1, and share it with us here and the password for it, that can help us figure this out.

What is the meaning of the last line? please try 3.1 release to close down variables.

I believe @bartonjs was asking if you can reproduce the issue in a Debug build and a Release build to make sure the right environment variables. Does it fail for both or just one?

@bilalmalik777

it only gets fail in debug mode on my machine, but over the release system it is working fine
password is «bfe4e20f-bcb4-4e95-9c76-9b7bfce2f35e», please find attach file of cert.
TT.Core.Api.zip

@vcsjones

Release / Debug should not make an impact when loading a PFX file, but, just to be sure, I tried using a simpler program to reproduce the issue:

using static System.Console;
using System;
using System.Security.Cryptography.X509Certificates;

#if RELEASE
WriteLine("Release");
#elif DEBUG
WriteLine("Debug");
#endif

try
{
    using X509Certificate2 cert = new("TT.Core.Api.pfx", "bfe4e20f-bcb4-4e95-9c76-9b7bfce2f35e");
    WriteLine(cert.Subject);
}
catch (Exception e)
{
    WriteLine("failed: " + e.Message);
}

I am unable to load this PFX/PKCS12 using the password for all combinations of netcoreapp3.1 and netcoreapp2.2.

/code/personal/scratch > dotnet run --framework netcoreapp2.2 -c release
Release
failed: error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure
 /code/personal/scratch > dotnet run --framework netcoreapp2.2 -c debug  
Debug
failed: error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure
 /code/personal/scratch > dotnet run --framework netcoreapp3.1 -c release
Release
failed: error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure
 /code/personal/scratch > dotnet run --framework netcoreapp3.1 -c debug  
Debug
failed: error:23076071:PKCS12 routines:PKCS12_parse:mac verify failure

It seems the password and the file do not match up for all versions of .NET Core.

@bartonjs

Since

  • There hasn’t been any activity on the issue in a long time
  • The error code is coming out of OpenSSL’s PKCS12_parse
  • We stopped using PKCS12_parse with .NET 5 (wrote our own PFX loader)
  • We weren’t able to reproduce the error

I’m going to close the issue.

@msftbot
msftbot
bot

locked as resolved and limited conversation to collaborators

Aug 6, 2021

“I was pumped up about the new macOS Catalina. But after downloading the OS, I am getting an error message while trying to install it. How do I fix this?”

macOS Catalina Could Not be Verified is a common error message that came with macOS Catalina. A lot of users have complained about this issue on the official forums but not to worry; there are fixes available that will help you to install this latest Operating System on your Mac successfully. The article below contains all the fixes for this particular error of macOS Catalina, have a look:

  • Part 1: Why macOS Catalina Could Not be Verified
  • Part 2: How to Solve macOS Catalina Could Not be Verified?
  • Extra Tip: How to Recover Disappeared Files after macOS Catalina Update

Part 1: Why macOS Catalina Could Not be Verified

Before we get to the solutions for macOS Catalina Could Not be Verified, you should learn about the reasons behind this daunting error.

There could be quite a few reasons behind this particular error, take a look:

  • Check macOS Catalina Compatibility

    There could be a compatibility issue. It is possible that the Mac model you are using or trying to update is not compatible with the new macOS Catalina. It could be the reason behind the said error.

  • macOS Disk Running Error

    A disk running error with the macOS could lead to the said error during the installation.

  • Storage Space is Not Enough

    The size of any version of macOS is quite large. And due to that fact, huge storage space is required for the installation. If you don’t have enough space, then macOS won’t install.

  • Old macOS Installation Files in Application Folder

    If the old macOS installation files are still available inside the Application folder, then macOS Catalina could show the said error.

  • Poor Wi-Fi network

    During the installation of macOS, a strong internet connection is required. So, if you are updating macOS via Wi-Fi, then the poor connection can lead to such results.

Part 2: How to Solve macOS Catalina Could Not be Verified?

Here are the most effective solutions for fixing macOS Catalina Could Not be Verified, issue. Take a look

  • Way 1: Change System Date and Time on your Mac
  • Way 2: Reboot Your Mac and Install macOS Catalina Again
  • Way 3: Boot into macOS Recovery to Run First Aid

Way 1: Change System Date and Time on your Mac

It is possible that due to the wrong date and time on your Mac, Apple servers are having difficulty to verify the newly downloaded macOS Catalina. Here are the steps:

  • Step 1: Simply, go to the Apple menu and click on ‘System Preferences’.
  • Step 2: Then, navigate to ‘Date & Time’.
  • Step 3: In the ‘Date & Time’ panel, you need to make sure that you have chosen ‘Set date and time automatically’. Also, connect the Mac to the internet.

mac os catalina could not be verified

If you don’t have an internet connection, then you have to set the date and time manually. You also need to deselect ‘Set date and time automatically’.

Way 2: Reboot Your Mac and Install macOS Catalina Again

So, if you are unable to install macOS Catalina even after successfully downloading it. Then you need to use the following steps in order to execute the procedure successfully:

  • Step 1: First, reboot the Mac.
  • Step 2: After the reboot, open ‘System Preferences’ and click on ‘Software Update’.
  • Step 3: Mac will search for the update. After it finds it, click on ‘More Info’.
  • Step 4: Then, click ‘Update Now’ and you are ready to update. You will be asked to restart the device. You can choose between ‘Not Now’ and ‘Restart’.

macos catalina cannot be verified

Possibly you will have a successful installation of macOS Catalina, now.

Way 3: Boot into macOS Recovery to Run First Aid

You can also boot Mac into Recovery Mode and try to complete the installation. There is an option called ‘First Aid’, you need to run it in Recovery Mode. Here are steps:

  • Step 1: Turn on Mac, press and hold ‘Command + R’ keys immediately after hearing the startup music.
  • Step 2: You need to hold those keys until the Apple logo is visible on the screen. The utility window will be visible on the screen.
  • mac recovery mode

  • Step 3: Choose ‘Disk Utility’ from the window and click ‘Continue’ to proceed.
  • Step 4: Then, choose the drive that you want to repair.
  • Step 5: Click on ‘First Aid’ at the top of the utility window.
  • Step 6: Lastly, click on the ‘Run’ button to continue.

macos catalina could not be verified

Extra Tip: How to Recover Disappeared Files after macOS Catalina Update

Now, it is possible that after all that trouble you went through for installing macOS Catalina; some files from your Mac may disappear. It is a common glitch of macOS Catalina and numerous users have complained about it.

So, if you are facing data loss after the installation, then you need to recover them immediately. As more time goes by, the chances of recovery get lower. It will be helpful for you to use a professional data recovery program.

Such programs are genuine and designed specifically for data recovery. We recommend using, Tenorshare 4DDiG. It is close to a perfect data recovery program with an outstanding success rate. The steps are also very safe and simple too. Take a look:

windows download btn

mac download btn

Step 1 Start by download and installation of Tenorshare UltData on your Mac. Upon completing the installation of the program, run UltData. Select the location of the disappeared data on your hard drive and click “Scan”.

select location to fix catalina could not be verified

Step 2 The complete scan of the partition will take more than a few minutes. After the scan is complete, the results will be displayed on the screen.

fix catalina could not be verified with ultdata for mac-preview data

Step 3 Now, you need to choose files from the scan results. The files that were lost after the installation of macOS Catalina. Then, click on the ‘Recover’ button below. You are also required to select a location for the recovered files but choose a different partition, instead of the partition from where they were list initially.

fix macos catalina could not be verified with ultdata for mac-recover the disappeared files

Tenorshare UltData is one of the most effective data recovery programs out there and it is quite excellent. Use it without any hesitation if you have lost a few files from your Mac.

Video Guide: How to Recover Lost or Deleted Files on macOS Catalina?

Conclusion

Hence, macOS Catalina Could Not be Verified is one of the most recognized errors that came with macOS Catalina. And due to that fact, there are quite a few ways available to fix the said issue and complete the installation successfully. But after the successful installation of macOS Catalina, you may have to face another recognized error with the said OS. Lost files! It has happened with numerous users and most of them were unable to recover those files. But if it has happened to you after the installation, then immediately download and install Tenorshare 4DDiG for Mac Data Recovery and use its advanced features to recover those lost files within a few minutes.

windows download btn

mac download btn

Понравилась статья? Поделить с друзьями:
  • Error m587 failed to add ssid to remembered list another spi transfer is pending
  • Error m587 expected string expression
  • Error m3u8 download detected but ffmpeg or avconv could not be found please install one
  • Error lvalue required as unary operand
  • Error lvalue required as left operand of assignment перевод