SSL: Certificate verify failed using LeapHybridCQMSampler (DWave - Quantum Computing) - ssl

I'm having some trouble when trying to use the LeapHybridCQMSampler in the connection with cloud.dwavesys.com. This is the error log:
SSLError: HTTPSConnectionPool(host='cloud.dwavesys.com', port=443):
Max retries exceeded with url: /metadata/v1/regions/ (Caused by
SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]
certificate verify failed: unable to get local issuer certificate
(_ssl.c:1108)')))
I tried using the permissive_ssl parameter, but it doesn't make any difference. I also tried running it in several devices and couldn't solve it either.
Here is the code I'm using, where I just build a simple CQM and send it to the sampler:
import dwave.system
from dimod import Integer, ConstrainedQuadraticModel
x = [Integer(f'x_{i}') for i in range(4)]
cqm = ConstrainedQuadraticModel()
H_Objective = -5*x[0] - x[1] + x[2] - x[3]
cqm.set_objective(H_Objective)
cqm.add_constraint(20 - 10*x[0] - x[1] - x[2] - x[3] >=0)
sampler = dwave.system.LeapHybridCQMSampler()
sampleset = sampler.sample_cqm(cqm, num_reads=5000)

Related

What about my Swift-NIO-SSL handshake is failing?

I am trying to figure out what about my TLS handshake is failing. I am not exactly sure what this error code means. Can someone provide more context here?
2000-00-00T00:00:00-0000 error [[GRPC-LOGG]] : error=handshakeFailed(NIOSSL.BoringSSLError.sslError([Error: 268436496 error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE at /Users/username/Library/Developer/Xcode/DerivedData/ios-dc-bocetydygnmhxsdxqxaivnvasghk/SourcePackages/checkouts/swift-nio-ssl/Sources/CNIOBoringSSL/ssl/tls_record.cc:592])) grpc.conn.addr_local=10.220.93.246 grpc.conn.addr_remote=23.98.156.101 grpc_connection_id=C1C6376D-9F74-48AF-9D7A-D903BB68D716/0 [GRPC] grpc client error
I did take a look at the tls_record.cc file; which is reporting SSL3_AL_FATAL.
The tls_record.cc can be seen below.
tls_record.cc
f (alert_level == SSL3_AL_FATAL) {
OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
ERR_add_error_dataf("SSL alert number %d", alert_descr);
*out_alert = 0; // No alert to send back to the peer.
return ssl_open_record_error;
}
I am using gRPC-Swift to make this call.
var clientConnection: ClientConnection.Builder
var tlsConfig = TLSConfiguration.makeClientConfiguration()
tlsConfig.certificateVerification = .noHostnameVerification
tlsConfig.trustRoots = .certificates([nioCert!])
let clientConfig = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(configuration: tlsConfig, hostnameOverride: sniName)
clientConnection = ClientConnection.usingTLS(with: clientConfig, on: eventLoopGroup)
.withTLSCustomVerificationCallback({ ... })
clientConnection.connect(host: hostName, port: port)
When running curl -v https://hostname:port/foo command, this is what I get back from the server:
* Trying 12.43.425.642:443...
* Connected to q003.ed14.ws.samplecloud.dogi (12.43.425.642) port 443 (#0)
* ALPN: offers h2
* ALPN: offers http/1.1
* CAfile: /etc/ssl/cert.pem
* CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to q003.ed14.ws.samplecloud.dogi:443
* Closing connection 0
curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to q003.ed14.ws.samplecloud.dogi:443
I have added a ClientError Logger to the gRPC connection and this is what I am getting:
[!! GRPC-CLIENT-ERROR]: handshakeFailed(NIOSSL.BoringSSLError.sslError([Error: 268435581 error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED at /Users/username/Library/Developer/Xcode/DerivedData/ios-dc-bocetydygnmhxsdxqxaivnvasghk/SourcePackages/checkouts/swift-nio-ssl/Sources/CNIOBoringSSL/ssl/handshake.cc:393])) file:[<unknown>] line:[0]]
The error in the log above points back to the tls_record:
if (alert_level == SSL3_AL_FATAL) {
OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr); // << this line
ERR_add_error_dataf("SSL alert number %d", alert_descr);
*out_alert = 0; // No alert to send back to the peer.
return ssl_open_record_error;
}
I think there is an issue with how I am attaching my certificates. When I view the network traffic, I do not see any client certificate showing up in the TLS handshake:
Client Certificates: -
Server Certificates: 3
It seems as though I was attaching my certificates to swift-grpc's server part of the framework and not the client, this is how you attach them for the client-side:
tlsConfig.certificateChain = [.certificate(nioCert!)]
let privateKeyNIO = try? NIOSSLPrivateKey.init(bytes: privateKeyByteAry, format: .der)
tlsConfig.privateKey = NIOSSLPrivateKeySource.privateKey(privateKeyNIO!)
Note that I am still getting the same error as reported above.
Update:
I have confirmed that the client certificates are not showing up in the request. I am not sure why this is the case; I am clearly attaching a client cert.
tlsConfig.certificateChain = [NIOSSLCertificateSource.certificate(nioCert!)]
let privateKeyNIO = try? NIOSSLPrivateKey.init(bytes: privateKeyByteAry, format: .der)
tlsConfig.privateKey = NIOSSLPrivateKeySource.privateKey(privateKeyNIO!)

Cannot connect to host www.reddit.com:443 ssl:True

I wanted to use aiohttp.request in order to get Reddit post, but when I ran the code it gives me this error, any possible solution?
Code:
#command(name='meme')
#guild_only()
async def meme_cmd(self, ctx):
async with request("GET", "https://www.reddit.com/r/meme/", headers={}) as response:
data = await response.json()
print(data)
Error:
Command raised an exception: ClientConnectorCertificateError: Cannot connect to host www.reddit.com:443 ssl:True [SSLCertVerificationError: (1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname m
ismatch, certificate is not valid for 'www.reddit.com'. (_ssl.c:1123)")]

enabling SSL for Hyperledger Fabric couchdb

I want to use couchDB(V. 2.3.1) with SSL enabled, so I added [ssl] part to /opt/couchdb/etc/local.d/docker.ini file as shown below:
[ssl]
port = 6984
enable = true
cert_file = /etc/hyperledger/fabric/tls/server.crt
key_file = /etc/hyperledger/fabric/tls/server.key
cacert_file = /etc/hyperledger/fabric/tls/ca.crt
[daemons]
httpsd = {couch_httpd, start_link, [https]}
[admins]
Admin = ...
[couchdb]
uuid = ...
but i can't access the webUI with https! having this error:
This site can’t provide a secure connection
"IP" uses an unsupported protocol.
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Unsupported protocol
The client and server don't support a common SSL protocol version or cipher suite.
this is the logs:
[error] 2020-05-17T06:52:18.046389Z nonode#nohost <0.19077.3> -------- SSL: hello: tls_handshake.erl:127:Fatal error: handshake failure - malformed_handshake_data
[error] 2020-05-17T06:52:18.046426Z nonode#nohost <0.18899.3> -------- application: mochiweb, "Accept failed error", "{error,{tls_alert,\"handshake failure\"}}"
[error] 2020-05-17T06:52:18.046508Z nonode#nohost <0.18899.3> -------- CRASH REPORT Process (<0.18899.3>) with 0 neighbors exited with reason: {error,accept_failed} at mochiweb_acceptor:init/4(line:75) <= proc_lib:init_p_do_apply/3(line:247); initial_call: {mochiweb_acceptor,init,['Argument__1','Argument__2',...]}, ancestors: [https,couch_secondary_services,couch_sup,<0.202.0>], messages: [], links: [<0.253.0>], dictionary: [], trap_exit: false, status: running, heap_size: 1598, stack_size: 27, reductions: 954
can somebody please help me?
I found the solution and wrote a post about it:
https://medium.com/#pouyashojaei85/enabling-ssl-for-docker-couchdb-container-127388eca1a8

SSL issue on Android 9 Google Pixel One

I am trying to perform HTTPS requests to a host 10.10.10.1 from Android host with 10.10.10.2 in network without Internet connection - only WiFi 2 peers AP and Android 9 Google Pixel One device.
I've created network_security_config.xml with my cert that is self-signed and has CN=10.10.10.1 and SAN= DNS: 10.10.10.1 PI: 10.10.10.1.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
<certificates src="#raw/zone"/>
</trust-anchors>
</base-config>
</network-security-config>
I don't receive verification error and observe successful requests incoming to server - data are HTTP request, decrypted and shown on the server log. But the server can't send data back! It sends, but for some reason these data are not being accepted by the Android phone - just ignored.
I see packets are going from the server to the phone and the server repeatedly retries to shutdown SSL socket until error or success (I made such behavior intentionally during surveying) - here is Wireshark dump from WiFi air:
Here is my request from AsyncTask
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(MainActivity.this.getResources().openRawResource(R.raw.zone));
Certificate ca = cf.generateCertificate(caInput);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
URL url = new URL("https://10.10.10.1/connect");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ctx.getSocketFactory());
conn.setRequestProperty("param1", params[0]);
conn.setRequestProperty("param2", params[1]);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
mInputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream _buf = new ByteArrayOutputStream();
int l;
BufferedInputStream bufin = new BufferedInputStream(mInputStream);
while ((l = bufin.read(buffer,0,1024)) != -1) {
_buf.write(buffer, 0, l);
String rec = _buf.toString("UTF-8");
Log.d("MAIN", "Read: " + rec);
result.append(rec);
}
Log.d("MAIN", "Read finished: " + result.toString());
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
I suspect that Android 9 Network Security does block traffic somehow. I tried to use SSLSockets, change port from 443 to e.g. 1234 - no luck.
In fact my app is being created with Qt and firstly I used Qt stuff, but having no luck - I made fallback to Android Java code within my MainActivity, that I call via JNI from Qt code. Result is the same and I have no ideas more...
Where to dig?
UPD1
When the self-signed certificate is generated with SAN containing DNS:10.10.10.1 only (without IP:10.10.10.1) SSL fails with warnings:
W System.err: javax.net.ssl.SSLPeerUnverifiedException: Hostname 10.10.10.1 not verified:
W System.err: certificate: sha1/gyr2GOhy5lA+ZAHEzh0E2SBEgx0=
W System.err: DN: CN=10.10.10.1,O=Some ltd.,L=Knoxville,ST=TN,C=US
W System.err: subjectAltNames: [10.10.10.1]
W System.err: at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:201)
W System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
W ...
And conversely, with SAN IP:10.10.10.1 (without DNS: 10.10.10.1) - works as before - session established, data transferred to server and decrypted, but responses from server to client just ignored by client.
UPD2
I've also tried to use domain name some.device for the 10.10.10.1 device and issued certificate with CN and SAN DNS = some.device. It's resolved by Android 9 client, data is being sent successfully but response is still not being accepting.
Looks like Android bug.
After making additional surveying:
1. Some set of Android devices (builds), including Pixel 1, does not accept TCP session that was not finalized by mutual [FIN,ACK] and received data is not delivered to upper level of stack. Also data may not be accepted if TCP stream was not solid, with many retransmissions and Seq changing.
2. In case of using Qt - Android Network Security Configuration does not affect on communications.
3. This is not TLS related issue.

SecTrustPolicy fail with self-signed cert

So I created this test case (a mish mash of existing alamofire test cases):
func testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess() {
// Given
let expectation = expectationWithDescription("\(URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(serverTrust, policies)
// When
Alamofire.request(.GET, URLString)
.authenticate(user: user, password: password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertTrue(data?.length > 0, "Data not found.")
XCTAssertNil(error, "error should be nil")
}
The Root CA is a self-signed cert for an existing sight that works.
But I get this error back:
Test Suite 'Selected tests' started at 2015-08-12 12:46:37.512 Test
Suite 'StageAuthentication' started at 2015-08-12 12:46:37.514 Test
Case '-[Alamofire_iOS_Tests.StageAuthentication
testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess]'
started. 2015-08-12 12:46:37.663 xctest[3641:12220875]
NSURLSession/NSURLConnection HTTP load failed
(kCFStreamErrorDomainSSL, -9813)
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:309: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertNotNil failed - response should not be nil
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:310: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertTrue failed - Data not found.
/Users/wynne_b/Alamofire/Tests/QuestAuthentication.swift:311: error:
-[Alamofire_iOS_Tests.StageAuthentication testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess] :
XCTAssertNil failed: "Error Domain=NSURLErrorDomain Code=-1202 "The
certificate for this server is invalid. You might be connecting to a
server that is pretending to be “portal.care180.com” which could put
your confidential information at risk."
UserInfo={NSLocalizedDescription=The certificate for this server is
invalid. You might be connecting to a server that is pretending to be
“portal.care180.com” which could put your confidential information at
risk., NSLocalizedRecoverySuggestion=Would you like to connect to the
server anyway?, _kCFStreamErrorDomainKey=3,
NSUnderlyingError=0x7ae21c60 {Error Domain=kCFErrorDomainCFNetwork
Code=-1202 "(null)"
UserInfo={_kCFStreamPropertySSLClientCertificateState=0,
_kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorCodeKey=-9813, _kCFStreamErrorDomainKey=3, kCFStreamPropertySSLPeerTrust=,
kCFStreamPropertySSLPeerCertificates={type = immutable, count = 1, values = ( 0 :
)}}}, _kCFStreamErrorCodeKey=-9813,
NSErrorFailingURLStringKey=https://portal.care180.com/services/init.json,
NSErrorPeerCertificateChainKey={type =
immutable, count = 1, values = ( 0 : )},
NSErrorClientCertificateStateKey=0,
NSURLErrorFailingURLPeerTrustErrorKey=,
NSErrorFailingURLKey=https://portal.care180.com/services/init.json}" -
error should be nil Test Case
'-[Alamofire_iOS_Tests.StageAuthentication
testHTTPBasicAuthenticationWithValidCredentialsSelfSignedSuccess]'
failed (0.156 seconds). Test Suite 'StageAuthentication' failed at
2015-08-12 12:46:37.671. Executed 1 test, with 3 failures (0
unexpected) in 0.156 (0.157) seconds Test Suite 'Selected tests'
failed at 2015-08-12 12:46:37.672. Executed 1 test, with 3 failures
(0 unexpected) in 0.156 (0.160) seconds Program ended with exit code:
1
Sorry for being dense: what am I doing wrong? Or is there an Alamofire test that does this with a different cert and host?
I confused the root and the leaf. My bad.