What is the reason of this issue org.bouncycastle.tls.TlsFatalAlert - bouncycastle

What is the reason of this issue org.bouncycastle.tls.TlsFatalAlert,Client raised fatal(2) certificate_unknown(46) alert: Failed to read record
org.bouncycastle.tls.TlsFatalAlert: certificate_unknown(46)
Provider: SecureRandom.null algorithm from: BCFIPS_RNG
Mon Mar 28 16:44:00.330 IST 2022 [main] [o.b.jsse.provider.ProvTlsClient: INFO ] - Client raised fatal(2) certificate_unknown(46) alert: Failed to read record
org.bouncycastle.tls.TlsFatalAlert: certificate_unknown(46)
at org.bouncycastle.jsse.provider.ProvSSLSocketDirect.checkServerTrusted(ProvSSLSocketDirect.java:135)
at org.bouncycastle.jsse.provider.ProvTlsClient$1.notifyServerCertificate(ProvTlsClient.java:360)

According to the source code, it is likely that you are not using a trusted CA certificate (or at least, your client program doesn't trust it).
https://github.com/bcgit/bc-java/blob/master/tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLSocketDirect.java#L135 shows the trust store check failing.
This guide (and many others on sf) show how to register a trust store with your client SSL context: https://downloads.bouncycastle.org/fips-java/BC-FJA-(D)TLSUserGuide-1.0.9.pdf
import java.security.Security;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
/**
* Basic SSL Client - using the '!' protocol.
*/
public class TLSClientExample
{
public static void main(
String[] args)
throws Exception
{
Security.addProvider(new BouncyCastleFipsProvider()); // or use regular if not doing fips.
Security.addProvider(new BouncyCastleJsseProvider());
SSLContext sslContext = SSLContext.getInstance("TLS", "BCJSSE");
TrustManagerFactory trustMgrFact = TrustManagerFactory.getInstance(
"PKIX", "BCJSSE");
trustMgrFact.init(Utils.createServerTrustStore()); // <--- a java keystore containing the X509 root CA certificate.
sslContext.init(null, trustMgrFact.getTrustManagers(), null);
SSLSocketFactory fact = sslContext.getSocketFactory();
SSLSocket cSock = (SSLSocket)fact.createSocket(
Utils.HOST, Utils.PORT_NO);
Protocol.doClientSide(cSock);
}
}

Related

azure web app loaded from github repo based on spring boot problem

yesterday i linked my github to an azure web app service
my repo built with rest requests and some of them is working with loading data from firestore based databased , i ran it all on localhost on the tomcat embedded server that comes with spring
,got the web app in the air and my post request which getting resource from firebase , the post request got me an internal 500 server so i check the app insights feature to check what exception i get
java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:165)
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:136)
my init code for fire base is:
package Model;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;
#Service
public class FBInitialize {
#PostConstruct
public void initialize() {
try {
String fileName = "name of json file with Credential.json";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile());
FileInputStream serviceAccount = new FileInputStream(file);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://qr-database-my data base url")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
}
i checked on the logs and i did got the request i just getting this exception is anyone ever encounter
this exception ?
by the way on initiazlizeApp method the getIntstance methood is being called.
Edit:
found where the exception was thrown from :
public static FirebaseApp getInstance(#NonNull String name) {
synchronized(appsLock) {
FirebaseApp firebaseApp = (FirebaseApp)instances.get(normalize(name));
if (firebaseApp != null) {
return firebaseApp;
} else {
List<String> availableAppNames = getAllAppNames();
String availableAppNamesMessage;
if (availableAppNames.isEmpty()) {
availableAppNamesMessage = "";
} else {
availableAppNamesMessage = "Available app names: " + Joiner.on(", ").join(availableAppNames);
}
String errorMessage = String.format("FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage);
throw new IllegalStateException(errorMessage);
}
}
}
The problem may be the source code version on github. Please check build.gradle file under android/app folder.
Add the following line:
apply plugin:'com.google.gms.google-services'
Related Posts:
1. How to solve Exception Error: FirebaseApp with name [DEFAULT] doesn't exist?
2. FirebaseApp with name [DEFAULT] doesn't exist
im working with maven , also i figured it out that its has something with the json file with the google credentials location because repackaging the file changing the root content to BOOT-INF so i took the json file content put it in a String and cast it to Inputstream so the Initializeapp and the init would be independent but it still no joy :(
new update:
now i get a different exception I think its about security
java.lang.IllegalStateException: Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available
agian im working with maven and not on android

When runing fabric-java-sdks something go wrong with the offical example, how to slove it?

import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeoutException;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
class Sample {
public static void main(String[] args) throws IOException {
// Load an existing wallet holding identities used to access the network.
Path walletDirectory = Paths.get("wallet");
Wallet wallet = Wallets.newFileSystemWallet(walletDirectory);
// Path to a common connection profile describing the network.
Path networkConfigFile = Paths.get("connection.json");
// Configure the gateway connection used to access the network.
Gateway.Builder builder = Gateway.createBuilder()
.identity(wallet, "user1")
.networkConfig(networkConfigFile);
// Create a gateway connection
try (Gateway gateway = builder.connect()) {
// Obtain a smart contract deployed on the network.
Network network = gateway.getNetwork("mychannel");
Contract contract = network.getContract("fabcar");
// Submit transactions that store state to the ledger.
byte[] createCarResult = contract.createTransaction("createCar")
.submit("CAR10", "VW", "Polo", "Grey", "Mary");
System.out.println(new String(createCarResult, StandardCharsets.UTF_8));
// Evaluate transactions that query state from the ledger.
byte[] queryAllCarsResult = contract.evaluateTransaction("queryAllCars");
System.out.println(new String(queryAllCarsResult, StandardCharsets.UTF_8));
} catch (ContractException | TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.IllegalArgumentException: Identity not found in wallet: user1
at org.hyperledger.fabric.gateway.impl.GatewayImpl$Builder.identity(GatewayImpl.java:114)
at org.hyperledger.fabric.gateway.impl.GatewayImpl$Builder.identity(GatewayImpl.java:66)
at Sample.main(Sample.java:25)
How to slove it please.
I think you must first make use of the SDK to create a wallet for your identity. For this purpose, you can follow the scripts as described in the fabric-samples repository inside the fabric-samples/fabcar/java directory.
Follow the EnrollAdmin.java script to enroll the admin identity in the wallet.
Follow the RegisterUser.java to register a new user identity and add it to the wallet.
Try using your current script now to perform different chaincode related operations.

Jetty SSL server

Following is my code for the secure ssl server. I have created a keystore "server" and it has the key pair generated with passwords.
public static void main(String[] args) throws Exception {
Server server = new Server();
HttpConfiguration https_config = new HttpConfiguration();
https_config.setSecureScheme("https");
https_config.setSecurePort(8443);
https_config.addCustomizer(new SecureRequestCustomizer());
https_config.setSendServerVersion(true);
File keystoreFile = new File("server");
System.out.print(keystoreFile.getAbsolutePath());
SslContextFactory sslContextFactory = new SslContextFactory();
if (keystoreFile.exists())
{
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setTrustStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("secret");
sslContextFactory.setKeyManagerPassword("secret");
sslContextFactory.setTrustStorePassword("secret");
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
}
ServerConnector https =
new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
https.setPort(8443);
server.setConnectors(new Connector[] { https});
ServletContextHandler scHandler = new ServletContextHandler(server,"/");
scHandler.addServlet(Testpage1.class, "/test");
server.setHandler(scHandler);
server.start();
}
}
when I tried to connect to using the https://localhost:8443/ or https://localhost:8443/test it gives me "web page not available error" and with curl it gives me "curl: (35) Unknown SSL protocol error in connection to localhost:8443"
Could some one guide me to debug this issue.
I decided to post the question after a full day of debugging and trials and but with a little suggestion from a friend I manage to solve the issue by updating the keystore. So the issue I was having was due to the keys I have generated int he key store. It seems you need to use RSA algorithm not the EC algorithm.

javamail api to access gmail inbox messages

I have been trying to use the javamail api to read gmail inbox messages. I found the following code on the internet. I'm trying to run this on Eclipse, but it is failing with an "Invalid credentials exception". I have mail.jar, activation.jar, imap.jar and other jar files in the lib directory of the web-app.
Any ideas as to why I am receiving this exception ? Thanks.
javax.mail.AuthenticationFailedException: Invalid credentials n67if632335wep.219
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:665)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at org.mb.mail.MailReader.main(MailReader.java:23)
package org.mb.mail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.*;
public class MailReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}
Throw away that code and use this code from the JavaMail FAQ, where you'll also find lots of other helpful tips, including debugging tips.
If you see this exception you are in correct path, just you need to change the mail id or create a new gmail id which will have less security.(for example a primary gmail account is much configured in smartphones and its highly secured with google with Oauth2.0, so that gmail account connection will be blocked by google but when you tried with alternate gmail id or gmail id which not configured in mobile can be easily get connected)
Previously this issue broke my head finally got fixed. Thanks

jsf secure tranport mechanism

i have been working on a simple jsf secure transport mechanism where the configured https constraints is set to confidential in web.xml.Now, what i wanted to do was to select a particular page for secure transport. i have a login page that takes me to another page.Login page takes a user name and password and should transport it over secure layer to an ejb that verifies its authenticity before it displays the requested page.Now when i use a url pattern like /faces/pageToView.xhtml for the requested page in web.xml, i get a funny behaviour i dont really understand.First, when i login, my pageToView.xhtml displays without the https and when i click to go to another pageToView2.xhtml my first pageToView.xhtml redisplays with https. Not only that all other pages i navigate to displays https even though i had not configure them for secure transport. I need to know the right way to configure secure transport behaviour for a particular page. Thanks in advance.
The way it seems to be is that when you go to https, and you're generally going to do this on the login page, you stay on https. It seemed to me to be a big overhead for an application with limited security requirements but on looking into it the consensus is that the big risk is session hijacking. So if you had 2 secure pages login & shopping and all the other pages don't use ssl they'll be sending the session cookie over the air/wire in the clear and the cookie could be sniffed.
I think that if you have an apache web server fronting your application server you have a lot more options such as using https between the client browser and apache for certain pages, but using http between apache and the app server. I'm fairly sure that you can do this but I'm no expert and haven't tried it.
When I was looking into this some time ago I came across this filter written by one of the Glassfish team which is supposed to downshift from https - http. My recollection is that having downshifted everything just stopped working, when used in conjunction with container security.
With a few tweaks you could adapt this to your environment, in this example the main.xhtml file is the welcome-file from web.xml, the idea being that this would be the page loaded on successful login so the earliest point at which to downshift from https - http. You'd need to uncomment #WebServlet, use your own logging in place of Log.log() and check any url/pathnames.
Before spending any time on this please remember that I could never get this to work and the the recommendation is to take the hit and use https all the time.
package uk.co.sportquest.jsfbeans.helper;
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. 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.html or
* glassfish/bootstrap/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 glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [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.
*/
import java.io.*;
import java.util.*;
import java.security.*;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.security.jacc.*;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import uk.co.sportquest.general.Log;
/**
* Filter that downshifts from https to http if the given request came in over
* https, but the target resource does not require any confidentiality
* protection.
*
* #author jluehe
* #author monzillo
*/
//#WebFilter(filterName = "CacheFilterStatic", urlPatterns = {"/faces/secure/main.xhtml"},
// dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE})
public class MyFilter implements Filter {
private static final CodeSource cs =
new CodeSource(null, (java.security.cert.Certificate[]) null);
private static final ProtectionDomain pd =
new ProtectionDomain(cs, null, null, null);
// private static final Policy policy = Policy.getPolicy();
private static final Policy policy = Policy.getPolicy();
private static final String httpPort = "8080";
#Override
public void init(javax.servlet.FilterConfig filterConfig)
throws ServletException {
//httpPort = filterConfig.getInitParameter("httpPort");
}
#Override
#SuppressWarnings("static-access")
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain)
throws IOException, ServletException {
if (req.isSecure()) {
HttpServletRequest httpReq = (HttpServletRequest) req;
Permission p = new WebUserDataPermission(httpReq);
p = new WebUserDataPermission(p.getName(), httpReq.getMethod());
//SQLog.log("Filter: " + httpReq.getRequestURI());
boolean isTransportProtected = policy.implies(pd, p) ? false : true;
Log.log();
if (!isTransportProtected) {
// Downshift from https to http, by redirecting to the
// target resource using http
String redirectUrl = "http://" + req.getServerName() + ":"
+ httpPort + httpReq.getRequestURI();
String queryString = httpReq.getQueryString();
if (queryString != null) {
redirectUrl += "?" + queryString;
}
//redirectUrl = "http://localhost:8080/SportQuest/faces/secure/main.xhtml";
Log.log("url: " + redirectUrl);
((HttpServletResponse) res).sendRedirect(redirectUrl);
} else {
// Perform normal request processing
Log.log("normal");
filterChain.doFilter(req, res);
}
} else {
// Perform normal request processing
Log.log("even more normal");
filterChain.doFilter(req, res);
}
}
#Override
public void destroy() {
// Do nothing
}
}

Resources