Windows 10 WebUSB printing issues with Zebra LP2844 DOMException: Access denied - google-chrome

In a project I'm trying to use the WebUSB API available in Chrome to print using a Zebra LP2844 printer.
I succeeded on OSX without issues and eventually on Ubuntu and on ChromeOS thanks to this post that talked about unbinding the kernel driver so Chrome was able to access the device.
The page I'm using for this is served though https as the documentation requires it.
On Windows 10 however, I'm able to connect to the printer with navigator.usb.requestDevice as shown here
but when I call open() on the connected printer during the print routine, I keep getting the next error
Error
DOMException: Access denied.
Here is the print method code:
print : async function(printString) {
let startTime = new Date().getTime();
if (!this.pairedPrinter) {
console.log("No printer connected");
return;
}
try {
if (!this.pairedPrinter.opened) {
await this.pairedPrinter.open();
}
await this.pairedPrinter.claimInterface(0);
let encoder = new TextEncoder();
const printBuffer = encoder.encode(printString);
let printResult = await this.pairedPrinter.transferOut(6, printBuffer);
await this.pairedPrinter.releaseInterface(0);
await this.pairedPrinter.close();
} catch (err) {
console.log("Error");
console.log(err);
} finally {
let endTime = new Date().getTime();
let printTime = endTime - startTime;
console.log("Print time: " + printTime + " ms");
}
}
I found a similar question here, that points to this other answer. It makes perfect sense that the default driver being installed by Windows when I plug the printer prevents Chrome from accessing it (just like Ubuntu does).
So, I implemented a custom .inf file as described here.
This is my inf file
;
;
; Installs WinUsb
;
; =================== Strings ===================
[Strings]
ManufacturerName = "Zebra"
ClassName = "Universal Serial Bus devices"
DeviceName = "Aeropost Zebra LP2844"
SourceName = "Aeropost Zebra LP2844 Install Disk"
DeviceID = "VID_0A5F&PID_0009"
DeviceGUID = "{c3bd2e26-7e03-4189-8c9d-852faf628494}"
REG_MULTI_SZ = 0x00010000
[Version]
Signature = "$Windows NT$"
Class = Printer
ClassGuid = {4d36e979-e325-11ce-bfc1-08002be10318}
Provider = %ManufacturerName%
CatalogFile = zebrawinusb.cat
DriverVer = 03/02/2018,1.0.0.0
; ========== Class definition ===========
[ClassInstall32]
AddReg = ClassInstall_AddReg
[ClassInstall_AddReg]
HKR,,,0,"Universal Serial Bus devices"
HKR,,Icon,,-20
; ========== Manufacturer/Models sections ===========
[Manufacturer]
%ManufacturerName% = Standard,NTx86
%ManufacturerName% = Standard,NTamd64
[Standard.NTx86]
%DeviceName% = USB_Install, USB\%DeviceID%
[Standard.NTamd64]
%DeviceName% = USB_Install, USB\%DeviceID%
; =================== Installation ===================
[USB_Install]
Include = winusb.inf
Needs = WINUSB.NT
[USB_Install.Services]
Include = winusb.inf
Needs = WINUSB.NT.Services
[USB_Install.Wdf]
KmdfService = WINUSB, WinUsb_Install
[WinUSB_Install]
KmdfLibraryVersion = 1.11
[USB_Install.HW]
AddReg=Dev_AddReg
[Dev_AddReg]
HKR,,DeviceInterfaceGUIDs,0x10000,%DeviceGUID%
[USB_Install.CoInstallers]
AddReg = CoInstallers_AddReg
CopyFiles = CoInstallers_CopyFiles
[CoInstallers_AddReg]
HKR,,CoInstallers32,0x00010000,"WdfCoInstaller01011.dll,WdfCoInstaller","WinUsbCoInstaller2.dll"
[CoInstallers_CopyFiles]
WinUsbCoInstaller2.dll
WdfCoInstaller01011.dll
[DestinationDirs]
; If your INF needs to copy files, you must not use the DefaultDestDir directive here.
CoInstallers_CopyFiles=11
; ================= Source Media Section =====================
[SourceDisksNames]
1 = %SourceName%
[SourceDisksFiles.x86]
WinUSBCoInstaller2.dll = 1,x86
WdfCoInstaller01011.dll = 1,x86
[SourceDisksFiles.x64]
WinUSBCoInstaller2.dll = 1,x64
WdfCoInstaller01011.dll = 1,x64
Built the driver using inf2cat, test-signed it and when I try to update the printer driver to use it, it fails with error "the file specified could not be found (0x00000002)".
setupapi.dev.log file provides no info whatsoever about which file is not being found though.
Here's the log file for the driver update process:
>>> [Device Install (DiShowUpdateDevice) - USBPRINT\ZEBRA_LP2844_\6&3295E28F&3&USB001]
>>> Section start 2018/03/02 16:14:00.023
cmd: "C:\WINDOWS\system32\mmc.exe" C:\WINDOWS\system32\devmgmt.msc
dvi: {DIF_UPDATEDRIVER_UI} 16:14:00.023
dvi: Class installer: Enter 16:14:00.023
dvi: Class installer: Exit
dvi: Default installer: Enter 16:14:00.039
dvi: Default installer: Exit
dvi: {DIF_UPDATEDRIVER_UI - exit(0xe000020e)} 16:14:00.054
ndv: {Update Driver Software Wizard - USBPRINT\ZEBRA_LP2844_\6&3295E28F&3&USB001}
dvi: {DIF_SELECTDEVICE} 16:14:05.662
dvi: Class installer: Enter 16:14:05.678
dvi: Class installer: Exit
dvi: {DIF_SELECTDEVICE - exit(0xe000020e)} 16:14:05.678
dvi: {DIF_SELECTDEVICE} 16:14:12.148
dvi: Class installer: Enter 16:14:12.148
dvi: Class installer: Exit
dvi: {DIF_SELECTDEVICE - exit(0xe000020e)} 16:14:12.163
ndv: Driver package 'C:\WINDOWS\System32\DriverStore\FileRepository\zebrawinusb.inf_amd64_ddcc3ed00fd3e8a8\zebrawinusb.inf' is already imported.
sto: {Setup Import Driver Package: c:\zebrawinusbdriver\zebrawinusb.inf} 16:14:16.158
sto: Driver package already imported as 'oem20.inf'.
sto: {Setup Import Driver Package - exit (0x00000000)} 16:14:16.180
dvi: Searching for hardware ID(s):
dvi: usbprint\zebra_lp2844_5bc4
dvi: zebra_lp2844_5bc4
dvi: Class GUID of device remains: {4d36e979-e325-11ce-bfc1-08002be10318}.
dvi: {Plug and Play Service: Device Install for USBPRINT\ZEBRA_LP2844_\6&3295E28F&3&USB001}
dvi: Driver INF Path: C:\WINDOWS\INF\oem20.inf
dvi: Driver Node Name: zebrawinusb.inf:c14ce8840c48fa1f:USB_Install:1.0.0.0:usb\vid_0a5f&pid_0009,
dvi: Driver Store Path: C:\WINDOWS\System32\DriverStore\FileRepository\zebrawinusb.inf_amd64_ddcc3ed00fd3e8a8\zebrawinusb.inf
dvi: Searching for hardware ID(s):
dvi: usbprint\zebra_lp2844_5bc4
dvi: zebra_lp2844_5bc4
dvi: Class GUID of device changed to: {4d36e979-e325-11ce-bfc1-08002be10318}.
dvi: {Core Device Install} 16:14:16.313
! pol: Selected driver node does not match this device (force-install)
dvi: {Install Device - USBPRINT\ZEBRA_LP2844_\6&3295E28F&3&USB001} 16:14:16.316
dvi: Device Status: 0x0180200a, Problem: 0x0 (0x00000000)
dvi: Parent device: USB\VID_0A5F&PID_0009\42J113802152
! dvi: Unable to determine matching device ID for oem20.inf. Error = 0xE0000228
! dvi: Unable to configure device, falling back to standard device installation.
dvi: {DIF_ALLOW_INSTALL} 16:14:16.324
dvi: Using exported function 'ClassInstall32' in module 'C:\WINDOWS\system32\ntprint.dll'.
dvi: Class installer == ntprint.dll,ClassInstall32
dvi: Class installer: Enter 16:14:16.336
dvi: Class installer: Exit
dvi: Default installer: Enter 16:14:16.340
dvi: Default installer: Exit
dvi: {DIF_ALLOW_INSTALL - exit(0xe000020e)} 16:14:16.342
dvi: {DIF_INSTALLDEVICEFILES} 16:14:16.343
dvi: Class installer: Enter 16:14:16.344
!!! dvi: Class installer: failed(0x00000002)!
dvi: {DIF_INSTALLDEVICEFILES - exit(0x00000002)} 16:14:16.383
! dvi: Queueing up error report for device install failure.
dvi: {Install Device - exit(0x00000002)} 16:14:16.383
dvi: {Core Device Install - exit(0x00000002)} 16:14:16.383
dvi: {DIF_DESTROYPRIVATEDATA} 16:14:16.383
dvi: Class installer: Enter 16:14:16.383
dvi: Class installer: Exit
dvi: Default installer: Enter 16:14:16.399
dvi: Default installer: Exit
dvi: {DIF_DESTROYPRIVATEDATA - exit(0xe000020e)} 16:14:16.399
ump: {Plug and Play Service: Device Install exit(00000002)}
!!! ndv: Device install failed for device.
ndv: {Update Driver Software Wizard exit(00000002)}
<<< Section end 2018/03/02 16:15:14.498
<<< [Exit status: FAILURE(0x00000002)]
I even tried replacing the printer driver using zadig, with the same results (Access denied error).
At this point, any assistance is highly appreciated.
UPDATE 03/05/2018
Today I managed to make my custom inf installer finish successfully, by following the next steps:
prevent windows 10 from searching the web for drivers and installing them when I plug in the printer (view details here)
update my custom inf installer to use the USBDevice class and the {88bae032-5a81-49f0-bc3d-a4ff138216d6} ClassGuid values
built the driver cat file and signed it
uninstall all drivers for the device and unplug the printer
restart the computer
plug the printer again. At this point, in the Device Manager, the device is detected as a Universal Serial Bus device
finally, followed followed this instructions to update the device drivers using the one created before.
Driver installation succeeded and regedit reflects the device is now using WinUSB
Sadly, I continue getting the "DOMException: Access denied." error when I try to print from the web page... so I still need help :(
ps: this is probably the longest post on stackoverflow I know (or top 10 at least).
UPDATE 03/06/2018
As per Reilly Grant's request, I'm including the output of USBView (lsusb equivalent for windows)
[Port1] : Aeropost Zebra LP2844
Is Port User Connectable: yes
Is Port Debug Capable: no
Companion Port Number: 10
Companion Hub Symbolic Link Name: USB#ROOT_HUB30#4&4f0abe8&0&0#{f18a0e88-c30c-11d0-8815-00a0c906bed8}
Protocols Supported:
USB 1.1: yes
USB 2.0: yes
USB 3.0: no
Device Power State: PowerDeviceD0
---===>Device Information<===---
*!*ERROR: No String Descriptor for index 4!
ConnectionStatus:
Current Config Value: 0x01 -> Device Bus Speed: Full (is not SuperSpeed or higher capable)
Device Address: 0x01
Open Pipes: 2
===>Device Descriptor<===
bLength: 0x12
bDescriptorType: 0x01
bcdUSB: 0x0100
bDeviceClass: 0x07
*!*ERROR: unknown bDeviceClass 7
bDeviceSubClass: 0x01
*!*ERROR: bDeviceSubClass of 1 is invalid
bDeviceProtocol: 0x02
*!*ERROR: bDeviceProtocol of 2 is invalid
bMaxPacketSize0: 0x08 = (8) Bytes
idVendor: 0x0A5F = Zebra Technologies
idProduct: 0x0009
bcdDevice: 0x0001
iManufacturer: 0x02
*!*ERROR: No String Descriptor for index 2!
iProduct: 0x04
*!*ERROR: No String Descriptor for index 4!
iSerialNumber: 0x06
*!*ERROR: No String Descriptor for index 6!
bNumConfigurations: 0x01
---===>Open Pipes<===---
===>Endpoint Descriptor<===
bLength: 0x07
bDescriptorType: 0x05
bEndpointAddress: 0x85 -> Direction: IN - EndpointID: 5
bmAttributes: 0x02 -> Bulk Transfer Type
wMaxPacketSize: 0x0040 = 0x40 bytes
bInterval: 0x00
===>Endpoint Descriptor<===
bLength: 0x07
bDescriptorType: 0x05
bEndpointAddress: 0x06 -> Direction: OUT - EndpointID: 6
bmAttributes: 0x02 -> Bulk Transfer Type
wMaxPacketSize: 0x0040 = 0x40 bytes
bInterval: 0x00
---===>Full Configuration Descriptor<===---
===>Configuration Descriptor<===
bLength: 0x09
bDescriptorType: 0x02
wTotalLength: 0x0020 -> Validated
bNumInterfaces: 0x01
bConfigurationValue: 0x01
iConfiguration: 0x00
bmAttributes: 0xC0 -> Self Powered
-> Bus Powered
MaxPower: 0x00 = 0 mA
===>Interface Descriptor<===
bLength: 0x09
bDescriptorType: 0x04
bInterfaceNumber: 0x00
bAlternateSetting: 0x00
bNumEndpoints: 0x02
bInterfaceClass: 0x07 -> This is a Printer USB Device Interface Class
bInterfaceSubClass: 0x01
bInterfaceProtocol: 0x02
iInterface: 0x00
===>Endpoint Descriptor<===
bLength: 0x07
bDescriptorType: 0x05
bEndpointAddress: 0x85 -> Direction: IN - EndpointID: 5
bmAttributes: 0x02 -> Bulk Transfer Type
wMaxPacketSize: 0x0040 = 0x40 bytes
bInterval: 0x00
===>Endpoint Descriptor<===
bLength: 0x07
bDescriptorType: 0x05
bEndpointAddress: 0x06 -> Direction: OUT - EndpointID: 6
bmAttributes: 0x02 -> Bulk Transfer Type
wMaxPacketSize: 0x0040 = 0x40 bytes
bInterval: 0x00
Interestingly (bizarrely actually) enough, while trying to get this new information, my Google Chrome started throwing
TypeError: Cannot read property 'getDevices' of undefined
error in the console, and typing navigator.usb in the console returned undefined.
Since that didn't make any sense, I reinstalled Chrome, but the error continued
Because of that I installed Chrome Canary (where navigator.usb existed) and turns out that THE PRINTER STARTED PRINTING and the Access Denied error was gone.
I uninstalled Chrome Canary and somehow GA Chrome also worked. That was until I closed Chrome and opened it again. Then I got the "Cannot read property 'getDevices' of undefined" error again.
I noticed that deleting Chrome's User Data folder in AppData/Local/Google (the entire profile folder) makes Chrome work again, until I close it and open it again.
Perhaps something in my printing code is leaving something "held" despite I'm calling releaseInterface and close?
Any ideas now that the problem seem to have changed a bit?

After a few tests on other windows machines, I managed to make everything work using Zadig software to replace the windows installed driver with WinUSB.
The key was restarting the computer after replacing the drivers.
The custom driver I developed also works, but Zadig's program makes things much easier ;)

maybe you could do a quick test with my WebUSB tester here: https://larsgk.github.io/webusb-tester/ it should show you which interfaces are claimed by the system (If this is the reason why it fails).

Related

JDBC: SunCertPathBuilderException: unable to find valid certification path to requested target [duplicate]

I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate. Is it possible to ignore the client-server authentication? If so, how?
package com.da;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;
public class RSDDownloadFile {
static FileOutputStream fos;
public void DownloadFile(String URI, String Request) throws Exception
{
java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
"Lang=EN&AuthToken=package", null);
System.out.println("URI Query: " + uri.toString());
HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
Future<Boolean> future = httpclient.execute(
new HttpAsyncGet(uri),
new ResponseCallback(), null);
Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("\nRequest successfully executed");
} else {
System.out.println("Request failed");
}
}
catch(Exception e){
System.out.println("[DownloadFile] Exception: " + e.getMessage());
}
finally {
System.out.println("Shutting down");
httpclient.shutdown();
}
System.out.println("Done");
}
static class ResponseCallback extends AsyncCharConsumer<Boolean> {
#Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println("Response: " + response.getStatusLine());
System.out.println("Header: " + response.toString());
try {
//if(response.getStatusLine().getStatusCode()==200)
fos = new FileOutputStream( "Response.html" );
}catch(Exception e){
System.out.println("[onResponseReceived] Exception: " + e.getMessage());
}
}
#Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try
{
while (buf.hasRemaining())
{
//System.out.print(buf.get());
fos.write(buf.get());
}
}catch(Exception e)
{
System.out.println("[onCharReceived] Exception: " + e.getMessage());
}
}
#Override
protected void onCleanup() {
try
{
if(fos!=null)
fos.close();
}catch(Exception e){
System.out.println("[onCleanup] Exception: " + e.getMessage());
}
System.out.println("onCleanup()");
}
#Override
protected Boolean buildResult() {
return Boolean.TRUE;
}
}
}
Errors:
URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
at javax.net.ssl.SSLEngine.wrap(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
... 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 21 more
onCleanup()
[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done
The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.
In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.
See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.
Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.
openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit
I had the same issue with a valid signed wildcard certificate from symantec.
First try running your java application with -Djavax.net.debug=SSL to see what is really going on.
I ended up importing the intermediate certificate which was causing the cert chain to break.
I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).
And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:
keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer
Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt
Go to your JRE_HOME/bin or JDK/JRE/bin
Type the command
keytool -keystore ..\lib\security\cacerts -import -alias your.ssl.server.name -file .\relative-path-to-cert-file\your.ssl.server.name.crt
Restart your Java process
#Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.
Install a certificate from host:
> sudo ./java-cert-importer.sh example.com
Remove the certificate that installed already.
> sudo ./java-cert-importer.sh example.com --delete
java-cert-importer.sh
#!/usr/bin/env bash
# Exit on error
set -e
# Ensure script is running as root
if [ "$EUID" -ne 0 ]
then echo "WARN: Please run as root (sudo)"
exit 1
fi
# Check required commands
command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }
# Get command line args
host=$1; port=${2:-443}; deleteCmd=${3:-${2}}
# Check host argument
if [ ! ${host} ]; then
cat << EOF
Please enter required parameter(s)
usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]
EOF
exit 1
fi;
if [ "$JAVA_HOME" ]; then
javahome=${JAVA_HOME}
elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
javahome=$(readlink -f $(which java) | sed "s:bin/java::")
elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
javahome="$(/usr/libexec/java_home)/jre"
fi
if [ ! "$javahome" ]; then
echo "WARN: Java home cannot be found."
exit 1
elif [ ! -d "$javahome" ]; then
echo "WARN: Detected Java home does not exists: $javahome"
exit 1
fi
echo "Detected Java Home: $javahome"
# Set cacerts file path
cacertspath=${javahome}/lib/security/cacerts
cacertsbackup="${cacertspath}.$$.backup"
if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
echo "Certificate is deleted for ${host}"
exit 0
fi
# Get host info from user
#read -p "Enter server host (E.g. example.com) : " host
#read -p "Enter server port (Default 443) : " port
# create temp file
tmpfile="/tmp/${host}.$$.crt"
# Create java cacerts backup file
cp ${cacertspath} ${cacertsbackup}
echo "Java CaCerts Backup: ${cacertsbackup}"
# Get certificate from speficied host
openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}
# Import certificate into java cacerts file
sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit
# Remove temp certificate file
rm ${tmpfile}
# Check certificate alias name (same with host) that imported successfully
result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")
# Show results to user
if [ "$result" ]; then
echo "Success: Certificate is imported to java cacerts for ${host}";
else
echo "Error: Something went wrong";
fi;
Quoting from No more 'unable to find valid certification path to requested target'
when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.
Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.
Basically, you want to add the server's certificate to the KeyStore with your trusted certificates
Try the code provided there. It might help.
This solved my issue,
We need to import the cert onto the local java. If not we could get the below exception.
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
SSLPOKE is a tool where you can test the https connectivity from your local machine.
Command to test the connectivity:
"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 15 more
keytool -import -alias <anyname> -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>
this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.
Verfication:
C:\tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
Successfully connected
Simple Steps that I followed.
problem: I was trying to connect to an endpoint(https://%s.blob.core.windows.net) using a simple java class(main method).
So I was getting this certification issue as mentioned above, in the question.
Solution:
Get the certificate using a browser(chrome). To do this paste your endpoint URL in the browser and enter. Now you will see a lock icon, click on that -->certificate--> details --> copy to files--> download it.
open the cmd(i am using windows) as admin and then navigate to the directory where you have downloaded the .cer file.
3.(Optional)If you are using multiple JDK in the same machine then change your JDK version the same as you are using in your application.
Now use the below command
keytool -import -alias mycertificate -keystore "C:\Program
Files\Java\jdk-11.0.5\lib\security\cacerts" -file myurlcrt.cer
Give the default password: changeit
Trust this certificate: yes
And you are done.
Thanks!
I was able to get it working with code only, i.e. no need to use keytool:
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class Test
{
private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);
public static void main(String[] args) throws Exception
{
SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy()
{
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
return true;
}
})
.build();
SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());
Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", sslSessionStrategy)
.build();
DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT.get())
.setConnectTimeout(CONNECT_TIMEOUT.get())
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
.setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
.build();
CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
.setSSLStrategy(sslSessionStrategy)
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.build();
httpClient.start();
// use httpClient...
}
private static class AllowAll implements X509HostnameVerifier
{
#Override
public void verify(String s, SSLSocket sslSocket) throws IOException
{}
#Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {}
#Override
public void verify(String s, String[] strings, String[] strings2) throws SSLException
{}
#Override
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
}
}
The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 22 more
In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.
For Windows only, follow these steps:
In Chrome go to settings.
In Settings click show advance settings.
Under HTTPS/SSL Click on Manage Certificates.
Export Your Certificate.
In Windows searchs (Pressing windows key on keyboard) type java.
Select (Configure Java) Option Which will open Java Control Panel
Select Security tab in Java Control Panel
Select Manage Certificates
Click Import
Under (User) tab selected and certificate type as (Trusted Certificates)
Click import button and browse to downloaded certificate and import it.
There is a lot of way to solve this...
One way is set the TrustStore certificates in a keystore file and put it in the path of the application, and set these system properties in the main method:
public static void main(String[] args) {
System.setProperty("javax.net.ssl.trustStore", "trust-store.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "TrustStore");
...
}
Other way is place the keystore as resource file inside the project jar file and load it:
public static SSLContext createSSLContext(String resourcePath, String pass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
// initialise the keystore
final char[] password = pass.toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(ThisClass.class.getResourceAsStream(resourcePath
), password);
// Setup the key manager factory.
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
// Setup the trust manager factory.
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslc = SSLContext.getInstance("TLS");
sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslc;
}
public static void main(String[] args) {
SSLContext.setDefault(
createSSLContext("/trust-store.jks", "TrustStore"));
...
}
In windows you can try this solution too: https://stackoverflow.com/a/59056537/980442
I created the keystore file from a Certificate authority CA .crt file in this way:
keytool -import -alias ca -keystore trust-store.jks -storepass TrustStore -trustcacerts -file ca.crt
FYI: https://docs.oracle.com/javadb/10.8.3.0/adminguide/cadminsslclient.html
For those who like Debian and prepackaged Java:
sudo mkdir /usr/share/ca-certificates/test/ # don't mess with other certs
sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
sudo update-ca-certificates --fresh --verbose
Don't forget to check /etc/default/cacerts for:
# enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
cacerts_updates=yes
To remove cert:
sudo rm /usr/share/ca-certificates/test/test.loc.crt
sudo rm /etc/ssl/certs/java/cacerts
sudo update-ca-certificates --fresh --verbose
UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:
Import the self-signed certificate:
keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks
Add the official root certificates:
keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks
Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.
ORIGINAL POSTING:
Nobody will believe this, I know. Still, if all else fails, give it a try:
After a reboot of my Mac the problem was gone. Grrr.
Background:
./gradlew jar kept giving me "unable to find valid certification path to requested target"
I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:
org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks" -Djavax.net.ssl.trustStorePassword=changeit
As mentioned, this only worked after a reboot.
Had the issue like this image.
Tried a few solutions.
But found that even if it's same project, when it's on other one's working place, it's totally fine. No extra settings needed. So we guessed it's an enviroment issue. We tried changing JDK version, IDE but didn't work. it took about 4 hours for investigation, until we tried the top-rated answer. I didn't find the error mentioned in that answer but I found via my browser about HTTP URL (lock) that there was a certification of Charles. Then I realized my charles was on all the time. As long as I turned that off, it's working all fine.
So I left my experience that could be helpful for your case.
This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.
Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.
More info on the issue can be found here, as well as how to resolve it on your server if you need to now.
AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.
Solution: enter in AVG section called "Web and email" and disable the "email protection".
AVG block the certificate if the site isn't secure.
I had the same problem with the certificates error and it was because of SNI: the http client that I used didn't have SNI implemented. So a version update did the job
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
Download the certificate from Nexus3 Browser (click on the lock-pad for View Site Information in case of Edge broser)
Click on Connection is secure
Click on the certificate details
Click on Copy To file (it opens up export certificate wizard)
Choose Base-64 encoding
Browse and select a download location and file-name (let’s say mycert)
Open cmd
Goto the download location and execute the below command
keytool -import -alias mycert -keystore "<<your-JAVA_HOME-directory>>\jre\lib\security\cacerts" -file mycert.cer
Restart the machine
Execute maven build again.
And if you are here in 2022 and are on mac follow this
1. Download the certificate.
echo -n | openssl s_client -connect <ServerName>:<PORT> -servername <ServerName> \
| openssl x509 > /tmp/<ServerName>.cert
2. Find your JDK path by executing the command.
/usr/libexec/java_home
3. Now import the cert into the cert-store of jdk.
sudo keytool -import -alias mycertificate -keystore "<JDK_HOME>/lib/security/cacerts" -file /tmp/<ServerName>.cert
You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:
jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
Make sure that the https://176.66.3.69:6443/ have a valid certificate.
you can check it via browser firstly if it works in browser it will work in java.
that is working for me
If getting this error in maven, or maven with TestNG :
download the certificate from the target website and install certificate on your machine (using keytool as suggested above, or on windows)
add the following content to the maven arguments (command line and/or IDE):
-Djavax.net.ssl.trustStore=C:\Users\me.keystore -Djavax.net.ssl.trustStorePassword=X
Where X is the password you used at the keytool step.
note : C:\Users\me.keystore should also be set to match your machine.
For instance :
mvn -ea -Dtestng.dtd.http=true -Djavax.net.ssl.trustStore=C:\Users\me\.keystore -Djavax.net.ssl.trustStorePassword=X -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true -Dcucumber.features=src/test/resources -Dcucumber.glue=com.myapp -Dcucumber.filter.tags="#MY_TEST"
In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).
Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.
bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit
first Download the ssl certificate then you can go to your java bin path execute the below command in the console.
C:\java\JDK1.8.0_66-X64\bin>keytool -printcert -file C:\Users\lova\openapi.cer -keystore openapistore
In my case I had both keystore and truststore having the same certificate so removing truststore helped. Sometimes the chain of certificates can be an issue if you've multiple copies of certificates.
As original question was - how to ignore the cert error, here is solution for those using SpringBoot and RestTemplate
#Service
public class SomeService {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
private static HttpComponentsClientHttpRequestFactory createRequestFactory() {
try {
SSLContextBuilder sslContext = new SSLContextBuilder();
sslContext.loadTrustMaterial(null, new TrustAllStrategy());
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
return requestFactory;
} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException var3) {
throw new IllegalStateException("Couldn't create HTTP Request factory ignore SSL cert validity: ", var3);
}
}
#Autowired
public SomeService(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.dimetorURL = dimetorURL;
restTemplate.setRequestFactory(createRequestFactory());
}
public ResponseEntity<ResponseObject> sendRequest(RequestObject requestObject) {
//...
return restTemplate.exchange(url, HttpMethod.GET, ResponseObject.class);
//...
}
}
This is what worked for me on macOS. Replace server-name and server-port with your own.
Run these two commands on your terminal.
Download certificate from the remote server
openssl x509 -in <(openssl s_client -connect server-name:server-port -prexit 2>/dev/null) -out ~/server-name.crt
Import cert to Java keystore
sudo keytool -importcert -file ~/server-name.crt -alias server-name -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit
Restart your application and the certs errors should go away!
This works on any OS you just need JDK installed :
Download the certificate from the remote server :
keytool -printcert -rfc -sslserver <your remote server hostname> > /tmp/remorte-cert.crt
Import the certificate to your JDK keystore :
keytool -importcert -file /tmp/remorte-cert.crt -alias <an alias for your remote server> -storepass changeit -keystore "${JAVA_HOME}/lib/security/cacerts" -noprompt

JDBC to mysql 5.7.21 with java 1.8.0_162 ; Unsupported record version Unknown-0.0

I am trying to connect to mysql with JDBC.
I generated keys as follows on my Windows 10:
winpty openssl pkcs12 -export -inkey ssl_cert/client-key.pem -in ssl_cert/client-cert.pem -out client.packet
keytool -importkeystore -deststorepass <password> -destkeypass <password> -destkeystore mysqldb.jks -srckeystore client.packet -srcstoretype PKCS12 -srcstorepass <password> -alias 1
keytool -importcert -alias mysqlCA -trustcacerts -file ssl_cert/ca.pem -keystore mysqldb.jks
My JDBC code looks like this :
System.setProperty("javax.net.ssl.trustStore", "ks-production-mysqldb.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "<password> ");
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
System.setProperty("javax.net.ssl.keyStore", "mysqldb.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "<password> ");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
String dbURL = "jdbc:mysql://localhost:1234/sb?"
+ "verifyServerCertificate=true&useSSL=true&requireSSL=true";
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
I am getting following error :
Caused by: javax.net.ssl.SSLException: Unsupported record version
Unknown-0.0 at
sun.security.ssl.InputRecord.checkRecordVersion(InputRecord.java:552)
at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:565)
at sun.security.ssl.InputRecord.read(InputRecord.java:529) at
sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983) at
sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at
sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at
sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at
org.mariadb.jdbc.internal.mysql.MySQLProtocol.connect(MySQLProtocol.java:444)
... 7 more
I googled for this and found out that it may be due to difference in SSL protocol between server and java, which they say must have been solved java 7 or greater.
But still I am getting error ? What am I missing?
Port forwarding before connection to localhost:1234:
try {
JSch jsch = new JSch();
jsch.addIdentity(privateKey);
logger.info("Establishing connection to " + sshHost + " by user " + sshUser);
session = jsch.getSession(sshUser, sshHost, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
int assignedPort = session.setPortForwardingL(localPort, remoteHost, remotePort);
logger.info("assigned Port = " + assignedPort);
} catch (JSchException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return session;
openssl command output :
$ openssl s_client -connect localhost:1234
CONNECTED(00000003)
140108247099296:error:140790E5:SSL routines:ssl23_write:ssl handshake failure:s23_lib.c:177:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 289 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.2
Cipher : 0000
Session-ID:
Session-ID-ctx:
Master-Key:
Key-Arg : None
Krb5 Principal: None
PSK identity: None
PSK identity hint: None
Start Time: 1519473350
Timeout : 300 (sec)
Verify return code: 0 (ok)
---
There is no solution posted, so for anyone who is facing this issue:
We use MariaDB and have been facing this issue, after trying all things, upgrading mariaDB java client driver version to latest solved the problem. Hope it helps.
Upgrade to JDK 8 at least u181. It works for me for a ReST connection showing the same error.
As other answers adviced I upgraded Java from 1.8.0_121 to 1.8.0_362 and the error changed but I still had an SSL error.
I had to add ?useSSL=false&requireSSL=false to the jdbc URL to disable SSL.

Selenium chromedriver unknown error while running chrome 59 headless with browsermob proxy

I wrote a simple Selenium test (opening a page) of a secured site in a headless mode using Chrome 59 beta version.
I'm getting an the following exception while executing my code. The exception is thrown while initializing the driver
When I rerun my script after commenting the headless option (options.addArguments("headless")) it shows Chrome and running fine but my objective is to run it as headless. Could you please provide your thoughts on resolving my problem?
Exception:
Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 4971
Only local connections are allowed.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.2 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.14 seconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
Here are the steps:
I'm using Scala with SBT on Mac.
Chrome 59 beta version
ChromeDrive 2.29 release version.
Added the following dependencies
"org.seleniumhq.selenium" % "selenium-chrome-driver" % "3.4.0"
"org.seleniumhq.selenium" % "selenium-support" % "3.4.0"
"net.lightbody.bmp" % "browsermob-core" % "2.1.4"
Scala Code:
val username = "username"
val password = "password"
val domainname = "yoursecuredomain.com"
val browserMobProxyServer = new BrowserMobProxyServer()
browserMobProxyServer.start(0)
browserMobProxyServer.autoAuthorization(domainname, username, password, AuthType.BASIC)
val seleniumProxy = ClientUtil.createSeleniumProxy(browserMobProxyServer)
val options = new ChromeOptions()
options.addArguments("headless")
options.addArguments("--disable-gpu")
options.setBinary("""/Applications/Google Chrome.app/Contents/MacOS/Google Chrome""")
val desiredCapabilities = new DesiredCapabilities()
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options)
desiredCapabilities.setCapability(CapabilityType.PROXY, seleniumProxy)
val driver: WebDriver = new ChromeDriver(desiredCapabilities)
val baseUrlString = s"""https://$domainname"""
driver.navigate().to(baseUrlString)
Thread.sleep(3000)
println("title: " + driver.getTitle)
driver.quit()
browserMobProxyServer.abort()
According to the 2.29 webdriver notes page, It says that
----------ChromeDriver v2.29 (2017-04-04)----------
Supports Chrome v56-58
so u have to downgrade your chrome version to be compatible with the latest chrome webdriver.
source:
https://chromedriver.storage.googleapis.com/2.29/notes.txt

How can one connect to remote hypertable in python

I'm trying to connect to a hypertable master machine, hypertable is deployed via mesos, When I copy hypertable.cfg file from master machine to some arbitrary machine, after running start-thriftbroker.sh, all I get is about ten lines of "Waiting for ThriftBroker to come up..." and then "ERROR: ThriftBroker did not come up", ThirftBroker's logfile says:
1342340080 NOTICE ThriftBroker : (/root/src/hypertable/src/cc/Common/Config.cc:526) Initializing ThriftBroker (Hypertable 0.9.5.6 (v0.9.5.6-dirty))...
CPU cores count=1
CephBroker.MonAddr=10.0.1.245:6789
CephBroker.Port=38030
CephBroker.Workers=20
DfsBroker.Host=localhost
DfsBroker.Local.Port=38030
DfsBroker.Local.Root=fs/local
DfsBroker.Port=38030
HdfsBroker.Port=38030
HdfsBroker.Workers=20
HdfsBroker.fs.default.name=hdfs://<ip>:9010
Hyperspace.GracePeriod=200000
Hyperspace.KeepAlive.Interval=30000
Hyperspace.Lease.Interval=1000000
Hyperspace.Replica.Dir=hyperspace
Hyperspace.Replica.Host=[<ip>]
Hyperspace.Replica.Port=38040
Hyperspace.Replica.Workers=20
Hypertable.Master.Port=38050
Hypertable.Master.Workers=20
Hypertable.RangeServer.Port=38060
Hypertable.Verbose=true
ThriftBroker.Port=38080
pidfile=/opt/hypertable/current/run/ThriftBroker.pid
port=38080
reactors=1
verbose=true
1342340080 INFO ThriftBroker : (/root/src/hypertable/src/cc/Hyperspace/Session.cc:63) Hyperspace session setup to reconnect
1342340082 ERROR ThriftBroker : main (/root/src/hypertable/src/cc/ThriftBroker/ThriftBroker.cc:2404): Hypertable::Exception: Hyperspace 'mkdir' error, name=/hypertable/namemap/names - HYPERSPACE file exists
at void Hyperspace::Session::mkdir(const std::string&, bool, const std::vector<Hyperspace::Attribute, std::allocator<Hyperspace::Attribute> >*, Hypertable::Timer*) (/root/src/hypertable/src/cc/Hyperspace/Session.cc:1257)
It got solved by updating to new version of ht.

OpenShift domain status failing

So I created an account at open shift, created an app, and installed the command line tool. when I do the command rhc domain status it fails:
Loaded suite /usr/bin/rhc-chk
Started
.E
===============================================================================
Error: test_connectivity(Test1_Connectivity)
ArgumentError: too few arguments
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:204:in `sprintf'
201: message = sprintf(get_message(:errors,name),*(args.shift || ''))
202: solution = get_message(:solutions,name)
203: if solution
=> 204: message << "\n" << sprintf(solution,*(args.shift || ''))
205: end
206: message
207: end
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:204:in `error_for'
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:270:in `test_connectivity'
===============================================================================
F
===============================================================================
Failure:
You need to be able to connect to the server in order to test authentication.
<false> is not true.
test_authentication(Test2_Authentication)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:280:in `test_authentication'
277: # Checking Authentication
278: #
279: def test_authentication
=> 280: assert $connectivity, error_for(:cant_connect)
281:
282: data = {'rhlogin' => $rhlogin}
283: response = fetch_url_json("/broker/userinfo", data)
===============================================================================
..F
===============================================================================
Failure: You must have an account on the server in order to test: whether you have a valid key loaded in your agent.
test_03_remote_ssh_keys(Test3_SSH)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:317:in `require_login'
314: end
315:
316: def require_login(test)
=> 317: flunk(error_for(:no_account,test)) if $user_info.nil?
318: end
319:
320: def require_remote_keys(test)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:321:in `require_remote_keys'
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:376:in `test_03_remote_ssh_keys'
===============================================================================
F
===============================================================================
Failure: You must have an account on the server in order to test: connecting to your applications.
test_04_ssh_connect(Test3_SSH)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:317:in `require_login'
314: end
315:
316: def require_login(test)
=> 317: flunk(error_for(:no_account,test)) if $user_info.nil?
318: end
319:
320: def require_remote_keys(test)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:383:in `test_04_ssh_connect'
===============================================================================
Finished in 2.403595 seconds.
7 tests, 8 assertions, 3 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications
42.8571% passed
Not really understanding why it's not able to connect. I was able to use: rhc domain show, with no problems.
Anyone have any suggestions on how to fix this?
It's a bug that should get fixed in the upcoming release. Even though you see this error it shouldn't affect any other behaviour.