Failed to connect to all addresses - gRPC with Go and NodeJS - node.js

"Failed to connect to all addresses" occurs while adding TLS certs to envoy.yaml, full error:
code: 14,
metadata: Metadata { _internal_repr: {}, flags: 0 },
details: 'failed to connect to all addresses'
Envoy config (Envoy is running on port 50000, and itemService on 50052):
transport_socket:
name: envoy.transport_sockets.tls
typed_config:
"#type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext
common_tls_context:
tls_certificates:
- certificate_chain:
filename: server.cert
private_key:
filename: server.key
Client code Nodejs - (NextJS on server side - getServerSideProps)
options = {
key: readFileSync("certs/client.key"),
cert: readFileSync("certs/ca.crt"),
csr: readFileSync("certs/client.crt"),
};
const creds = credentials.createSsl(
options.cert,
options.key,
options.csr
);
grpcServer.servicesList.itemsService = new ItemsServiceClient(
"localhost:50000",
creds,
{
"grpc.ssl_target_name_override": "localhost",
"grpc.default_authority": "localhost",
}
);
Request works normally when removing TLS certs from envoy.yaml.
Error I get from grpcurl tool: Failed to dial target host "localhost:50000" x509: certificate relies on legacy Common Name field, use SANs instead.
When I set GODEBUG=x509ignoreCN=0, seems like error stays same.

Related

AWS XRAY on Fargate service

I want to add xray to my Fargate service. Everything works (synth/deploy) but in the logs I'am seeing the following error:
2022-02-07T13:38:22Z [Error] Sending segment batch failed with:
AccessDeniedException: 2022-02-07 14:38:22status code: 403, request
id: cdc23f61-5c2e-4ede-8bda-5328e0c8ac8f
The user I'am using to deploy the application has the AWSXrayFullAccess permission.
Do I have to grant the task the permission manually? If so how?
Here is a snippet of the application:
const cdk = require('#aws-cdk/core');
const ecs = require('#aws-cdk/aws-ecs');
const ecsPatterns = require('#aws-cdk/aws-ecs-patterns');
class API extends cdk.Stack {
constructor(parent, id, props) {
super(parent, id, props);
this.apiXRayTaskDefinition = new ecs.FargateTaskDefinition(this, 'apixRay-definition', {
cpu: 256,
memoryLimitMiB: 512,
});
this.apiXRayTaskDefinition.addContainer('api', {
image: ecs.ContainerImage.fromAsset('./api'),
environment: {
"QUEUE_URL": props.queue.queueUrl,
"TABLE": props.table.tableName,
"AWS_XRAY_DAEMON_ADDRESS": "0.0.0.0:2000"
},
logging: ecs.LogDriver.awsLogs({ streamPrefix: 'api' }),
}).addPortMappings({
containerPort: 80
})
this.apiXRayTaskDefinition.addContainer('xray', {
image: ecs.ContainerImage.fromRegistry('public.ecr.aws/xray/aws-xray-daemon:latest'),
logging: ecs.LogDriver.awsLogs({ streamPrefix: 'xray' }),
}).addPortMappings({
containerPort: 2000,
protocol: ecs.Protocol.UDP,
});
// API
this.api = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'api', {
cluster: props.cluster,
taskDefinition: this.apiXRayTaskDefinition,
desiredCount: 2,
cpu: 256,
memory: 512,
createLogs: true
})
props.queue.grantSendMessages(this.api.service.taskDefinition.taskRole);
props.table.grantReadWriteData(this.api.service.taskDefinition.taskRole);
}
}
The user I'am using to deploy the application has the AWSXrayFullAccess permission.
This is irrelevant, the task will not get all the rights of the user that deploys the stack.
Yes, you need to add the required permissions to the task with
this.apiXRayTaskDefinition.taskRole.addManagedPolicy(
iam.ManagedPolicy.fromAwsManagedPolicyName('AWSXRayDaemonWriteAccess')
);
References:
AWS managed policy with required access for the X-Ray daemon: https://docs.aws.amazon.com/xray/latest/devguide/security_iam_id-based-policy-examples.html#xray-permissions-managedpolicies
Import an AWS-managed policy: https://docs.aws.amazon.com/cdk/api/v1/docs/#aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname
Access the task role: https://docs.aws.amazon.com/cdk/api/v1/docs/#aws-cdk_aws-ecs.FargateTaskDefinition.html#taskrole-1
Add a policy: https://docs.aws.amazon.com/cdk/api/v1/docs/#aws-cdk_aws-iam.IRole.html#addwbrmanagedwbrpolicypolicy

Unable to connect to AWS Aurora Serverless with SSL

I'm working with AWS Aurora Serverless V1 (with Postgres engine) and I'm trying to connect using node-postgres. I was able to connect without SSL perfectly, but when I add the SSL config at the pg client I keep receiving this error:
{
"message": "unable to get local issuer certificate",
"stack": "Error: unable to get local issuer certificate\n at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)\n at TLSSocket.emit (events.js:315:20)\n at TLSSocket.EventEmitter.emit (domain.js:467:12)\n at TLSSocket._finishInit (_tls_wrap.js:932:8)\n at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12)"
}
This is how the SSL config object is been declared
const ca = `-----BEGIN CERTIFICATE-----
MIIEBjCCAu6gAwIBAgIJAMc0ZzaSUK51MA0GCSqGSIb3DQEBCwUAMIGPMQswCQYD
VQQGEwJVUzEQMA4GA1UEBwwHU2VhdHRsZTETMBEGA1UECAwKV2FzaGluZ3RvbjEi
MCAGA1UECgwZQW1hem9uIFdlYiBTZXJ2aWNlcywgSW5jLjETMBEGA1UECwwKQW1h
em9uIFJEUzEgMB4GA1UEAwwXQW1hem9uIFJEUyBSb290IDIwMTkgQ0EwHhcNMTkw
ODIyMTcwODUwWhcNMjQwODIyMTcwODUwWjCBjzELMAkGA1UEBhMCVVMxEDAOBgNV
BAcMB1NlYXR0bGUxEzARBgNVBAgMCldhc2hpbmd0b24xIjAgBgNVBAoMGUFtYXpv
biBXZWIgU2VydmljZXMsIEluYy4xEzARBgNVBAsMCkFtYXpvbiBSRFMxIDAeBgNV
BAMMF0FtYXpvbiBSRFMgUm9vdCAyMDE5IENBMIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEArXnF/E6/Qh+ku3hQTSKPMhQQlCpoWvnIthzX6MK3p5a0eXKZ
oWIjYcNNG6UwJjp4fUXl6glp53Jobn+tWNX88dNH2n8DVbppSwScVE2LpuL+94vY
0EYE/XxN7svKea8YvlrqkUBKyxLxTjh+U/KrGOaHxz9v0l6ZNlDbuaZw3qIWdD/I
6aNbGeRUVtpM6P+bWIoxVl/caQylQS6CEYUk+CpVyJSkopwJlzXT07tMoDL5WgX9
O08KVgDNz9qP/IGtAcRduRcNioH3E9v981QO1zt/Gpb2f8NqAjUUCUZzOnij6mx9
McZ+9cWX88CRzR0vQODWuZscgI08NvM69Fn2SQIDAQABo2MwYTAOBgNVHQ8BAf8E
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUc19g2LzLA5j0Kxc0LjZa
pmD/vB8wHwYDVR0jBBgwFoAUc19g2LzLA5j0Kxc0LjZapmD/vB8wDQYJKoZIhvcN
AQELBQADggEBAHAG7WTmyjzPRIM85rVj+fWHsLIvqpw6DObIjMWokpliCeMINZFV
ynfgBKsf1ExwbvJNzYFXW6dihnguDG9VMPpi2up/ctQTN8tm9nDKOy08uNZoofMc
NUZxKCEkVKZv+IL4oHoeayt8egtv3ujJM6V14AstMQ6SwvwvA93EP/Ug2e4WAXHu
cbI1NAbUgVDqp+DRdfvZkgYKryjTWd/0+1fS8X1bBZVWzl7eirNVnHbSH2ZDpNuY
0SBd8dj5F6ld3t58ydZbrTHze7JJOd8ijySAp4/kiu9UfZWuTPABzDa/DSdz9Dk/
zPW4CXXvhLmE02TA9/HeCw3KEHIwicNuEfw=
-----END CERTIFICATE-----`
module.exports = {
rejectUnauthorized: true,
ca,
checkServerIdentity: (host, cert) => {
const error = tls.checkServerIdentity(host, cert)
if (
error &&
!cert.subject.CN.endsWith('.rds.amazonaws.com')
) {
return error
}
}
}
I am downloading the certificate directly from Amazon https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html
Aurora Serverless docs say that SSL is enforced by default, so I think I'm doing all the neccesary things to make the connection right, but it isn't working though. Maybe there is something about "serverless connections" that work differently from classic ones and I'm not understanding it.

MySQL xdevapi Node Error: SELF_SIGNED_CERT_IN_CHAIN

Windows 10 Pro
MySQL8.0
node.js v14.15.5
openssl 1.1.1c
I'm trying to connect to a MySQL database using node, I'm able to connect without TLS just fine. I used openssl to create a private key and self signed certificate. When I try to use TLS in my node app, I keep getting the following error:
$ NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js
(node:15480) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'SELF_SIGNED_CERT_IN_CHAIN'
}
TypeError: Cannot read property 'sql' of undefined
at C:\Users\gregb\Desktop\PROGRAMMING\VS Code Workspace\xdevapi2\index.js:40:32
at processTicksAndRejections (internal/process/task_queues.js:93:5)
[]
[]
Index.js
let mysqlx = require('#mysql/xdevapi');
let fs = require('fs');
require('dotenv').config();
let rows = [];
let columns = [];
// Works without TLS
// let config = {
// host: 'localhost',
// port: 33060,
// user: 'root',
// database: 'user',
// password: process.env.password
// };
const config = {
host: 'localhost',
port: 33060,
user: 'root',
database: 'user',
password: process.env.password,
ssl: true,
tls: {
rejectUnauthorized: false,
key: fs.readFileSync('./privatekey2.pem'),
cert: fs.readFileSync('./example.crt'),
ca: './cacert.pem'
}
};
(async function () {
let session;
try {
session = await mysqlx.getSession(config);
} catch(err) {
console.log(err);
}
try {
let result = await session.sql('SELECT "firstName" AS c1, "lastName" AS c2')
.execute(row => rows.push(row), column => columns = columns.concat(column));
session.close();
} catch(err) {
console.log(err);
}
console.log(rows); // [['foo', 'bar']]
console.log(columns.map(column => column.getColumnLabel())); // ['c1', 'c2']
})();
I also tried:
NODE_TLS_REJECT_UNAUTHORIZED='0' node index.js
How I used openssl:
Create a public/private key file pair:
openssl genrsa -out privkey2.pem 4096
Split into public/private:
openssl ssh-keygen -t rsa -b 4096 -f privatekey2.pem
Create a cert
openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout privatekey2.pem -out example.crt
The problem does not seem to be related to the certificate you are using. It should be related to the fact that you provide a path for the certificate authority file (ca). You do this when you want the client to verify that the server certificate was signed using a certificate in the CA chain, which only works if rejectUnauthorized is true, which is automatically set once you provide that valid CA file path, thus, your custom rejectUnauthorized: false is ignored.
Which begs the question, Is the server certificate signed by the CA you are providing? I suspect it is not, in which case, the error is legitimate.
If so, then it is a bug, and you should report it using the public MySQL issue tracker. However, I ran a few tests and I'm convinced there is no issue, but if you are able to produce a server certificate that was, indeed, signed by that particular CA, which allows to reproduce the same exact scenario, maybe we can dig some dirt.
Disclaimer: I'm the lead developer of MySQL X DevAPI Connector for Node.js

How to collect and pass certificate thumbprint value from win_certificate_store to win_iis_webbinding module

I'm not able to register the certificate thumbprint value from win_certificate_store module in a format that win_iis_webbinding module would accept it.
Here are my ansible tasks:
- name: Import certificate to Target local cert store
win_certificate_store:
path: C:\Certs\{{ansible_hostname}}.cert.p12
file_type: pkcs12
password: XXXXXXXXXX
store_location: LocalMachine
key_storage: machine
state: present
register: cert_import
- name: Debug thumbprints variable
debug:
var: cert_import.thumbprints
- name: Bind the issued certificate to Default Web Site in IIS
win_iis_webbinding:
name: Default Web Site
protocol: https
port: 443
certificate_hash: "{{ cert_import.thumbprints }}"
state: present
And this is the output:
TASK [Import certificate to Target local cert store] *******************************************************************************************************************************
task path: /home/weseroot/.ansible/roles/certman/tasks/import_bind_cert.yml:7
Using module file /usr/local/lib/python3.6/dist-packages/ansible/modules/windows/win_certificate_store.ps1
Pipelining is enabled.
<10.0.0.5> ESTABLISH WINRM CONNECTION FOR USER: weseadmin on PORT 5985 TO 10.0.0.5
EXEC (via pipeline wrapper)
ok: [10.0.0.5] => {
"changed": false,
"invocation": {
"module_args": {
"file_type": "pkcs12",
"key_exportable": true,
"key_storage": "machine",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"path": "C:\\Certs\\w2016-IIS-1.cert.p12",
"state": "present",
"store_location": "LocalMachine",
"store_name": "My",
"thumbprint": null
}
},
"thumbprints": [
"C85F1FC23B89DFB88416EDFAE9C91C586515C8ED"
]
}
TASK [Debug thumbprints variable] **************************************************************************************************************************************************
task path: /home/weseroot/.ansible/roles/certman/tasks/import_bind_cert.yml:17
ok: [10.0.0.5] => {
"cert_import.thumbprints": [
"C85F1FC23B89DFB88416EDFAE9C91C586515C8ED"
]
}
TASK [Bind the issued certificate to Default Web Site in IIS] **********************************************************************************************************************
task path: /home/weseroot/.ansible/roles/certman/tasks/import_bind_cert.yml:27
Using module file /usr/local/lib/python3.6/dist-packages/ansible/modules/windows/win_iis_webbinding.ps1
Pipelining is enabled.
<10.0.0.5> ESTABLISH WINRM CONNECTION FOR USER: weseadmin on PORT 5985 TO 10.0.0.5
EXEC (via pipeline wrapper)
The full traceback is:
Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: System.Object[]
At line:157 char:15
+ If (-Not (Test-Path $cert_path) )
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-Path], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.TestPathCommand
ScriptStackTrace:
at <ScriptBlock>, <No file>: line 157
fatal: [10.0.0.5]: FAILED! => {
"changed": false,
"msg": "Unhandled exception while executing module: Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: System.Object[]"
}
Any suggestions how the thumbprint variable could be passed to win_iis_webbinding module in an acceptable format?
OK I don't know if you are still looking for the answer but I was. win_certificate_store returns a dictionary with the key 'thumbprints' tied to a list:
TASK [Debug thumbprints variable] **************************************************************************************************************************************************
task path: /home/weseroot/.ansible/roles/certman/tasks/import_bind_cert.yml:17
ok: [10.0.0.5] => {
"cert_import.thumbprints": [
"C85F1FC23B89DFB88416EDFAE9C91C586515C8ED"
]
}
You will want to do something like this:
- name: Import certificate to Target local cert store
win_certificate_store:
path: C:\Certs\{{ansible_hostname}}.cert.p12
file_type: pkcs12
password: XXXXXXXXXX
store_location: LocalMachine
key_storage: machine
state: present
register: cert_import
- name: Debug thumbprints variable
debug:
var: cert_import.thumbprints
- name: Bind the issued certificate to Default Web Site in IIS
win_iis_webbinding:
name: Default Web Site
protocol: https
port: 443
certificate_hash: "{{ cert_import.thumbprints[-1] }}"
state: present

nodemailer with virtualmin and postfix - authentication failed

Im using virtual min. I have a working email account no-reply#mydomain.com
I can login through webmin / virtual min and send emails.
Now I want to send mails from node.js using nodemailer.
Btw this also works from the command line.
mail -s "testing email" mygmail#gmail.com < /dev/null
Here is my nodemailer config:
{
"smtp" : {
"host": "localhost",
"secure": false,
"auth": {
"user": "no-reply#mydomain.com",
"pass": "mypass"
},
"tls": {
"rejectUnauthorized": false
},
"debug" : true
},
"from" : "Resourceful Network <no-reply#resourcefulnetwork.nl>"
}
I found the following config in postfix config file:
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions = permit_mynetworks permit_sasl_authenticated reject_unauth_destination
smtp_tls_security_level = may
This is all set by virtual min.
I get this error
Error: Invalid login: 535 5.7.8 Error: authentication failed: authentication failure
code: 'EAUTH',
response: '535 5.7.8 Error: authentication failed: authentication failure',
responseCode: 535,
command: 'AUTH PLAIN'
I'm 100% sure the password is correct.
If I set "secure" : true in nodemailer config I get this error
errno: 'ECONNREFUSED',
code: 'ESOCKET',
syscall: 'connect',
address: '127.0.0.1',
port: 465,
So that doesn't seem to be the way to go.
Not sure what login protocol to use.. Do I need to set authMethod?
Secure or not secure?
I was able to fix this by removing auth from the nodemailer configuration.
I now realise smtpd_recipient_restrictions = permit_mynetworks means anyone on localhost is automatically allowed to send. And somehow still provider a (correct) username + password tripped things up?

Resources