Kubernetes create 5 year certificate for kubeapi - kubernetes

While creating the kubernetes cluster using kubeadm in Centos 7, its creating one year kubeapi certificate. For me this is short time for the cluster. How can I create 5 year certificate during cluster setup?
* SSL connection using TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
* Server certificate:
* subject: CN=kube-apiserver
* start date: Dec 20 14:32:00 2017 GMT
* expire date: Dec 20 14:32:00 2018 GMT
* common name: kube-apiserver
* issuer: CN=kubernetes
I tried this didn't work:
openssl genrsa -out ca.key 2048
export MASTER_IP=192.168.16.171
openssl req -x509 -new -nodes -key ca.key -subj "/CN=${MASTER_IP}" -days 10000 -out ca.crt
kubeadm reset
rm -rf /etc/kubernetes
mkdir -p /etc/kubernetes/ca/pki
cp ca.key ca.crt /etc/kubernetes/ca/pki/
kubeadm init
curl -k -v https://localhost:6443
Server certificate:
* subject: CN=kube-apiserver
* start date: Apr 15 21:07:24 2018 GMT
* expire date: Apr 15 21:07:25 2019 GMT
* common name: kube-apiserver
* issuer: CN=kubernetes
Thanks
SR

Follow the Kubernetes documentation on certificates to the CA certificate.
If you choose openssl or easyrsa use --days=1825, if you are going with cfssl then in ca-config.json specify 5y for .signing.default.expiry.
Put the resulting ca.crt and ca.key in /etc/kubernetes/ca/pki. When you run kubeadm init it will detect those files and will not overwrite them; it will use that CA key & certificate to sign the other certificates needed.

After looking at the code, there is no option to change the API certificate expire date. It set to 1 year in the code.
https://github.com/kubernetes/client-go/blob/master/util/cert/cert.go
// NewSelfSignedCACert creates a CA certificate
func NewSelfSignedCACert(cfg Config, key *rsa.PrivateKey) (*x509.Certificate, error) {
now := time.Now()
tmpl := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0),
Subject: pkix.Name{
CommonName: cfg.CommonName,
Organization: cfg.Organization,
},
NotBefore: now.UTC(),
NotAfter: now.Add(duration365d * 10).UTC(),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &tmpl, &tmpl, key.Public(), key)
if err != nil {
return nil, err
}
return x509.ParseCertificate(certDERBytes)
}

Related

403-Forbidden at ingress controller in AKS cluster

I am trying to configure an AKS cluster and assign a DNS(say abc.com) that is bought from GoDaddy. I have configured following components:
Azure DNS zone for abc.com
Update Name-Servers generated by Azure DNS zone at GoDaddy DNS settings
Add 'DNS zone contributor' role to K8s cluster agentpool.
Setup Ingress controller, External DNS, Cert-manager, ClusterIssuer
Add Ingress route for my application
Deploy my application to setup it's Pod and service on cluster.
When I try to hit the API(https://dev.abc.com/backend/usermanager/api/user) from postman I am getting a 403-Forbidden error.
When I open a shell from ingress-controller container within the cluster and curl above API it gives same 403-Forbidden error with following details:
bash-5.1$ curl -v -d '{"name": "John Doe", "mobileNumber": "1234554321"}' -H 'Content-Type:
application/json' https://dev.abc.com/backend/usermanager/api/user
* Trying 21.81.66.166:443...
* Connected to dev.abc.com (21.81.66.166) port 443 (#0)
* ALPN: offers h2
* ALPN: offers http/1.1
* CAfile: /etc/ssl/certs/ca-certificates.crt
* CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN: server accepted h2
* Server certificate:
* subject: CN=dev.abc.com
* start date: Jul 20 03:29:46 2022 GMT
* expire date: Oct 18 03:29:45 2022 GMT
* subjectAltName: host "dev.abc.com" matched cert's "dev.abc.com"
* issuer: C=US; O=Let's Encrypt; CN=R3
* SSL certificate verify ok.
* Using HTTP2, server supports multiplexing
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* h2h3 [:method: POST]
* h2h3 [:path: /backend/usermanager/api/user]
* h2h3 [:scheme: https]
* h2h3 [:authority: dev.abc.com]
* h2h3 [user-agent: curl/7.83.1]
* h2h3 [accept: */*]
* h2h3 [content-type: application/json]
* h2h3 [content-length: 50]
* Using Stream ID: 1 (easy handle 0x64161d71800)
> POST /backend/usermanager/api/user HTTP/2
> Host: dev.abc.com
> user-agent: curl/7.83.1
> accept: */*
> content-type: application/json
> content-length: 50
>
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
* We are completely uploaded and fine
< HTTP/2 403
< date: Fri, 22 Jul 2022 04:40:59 GMT
< content-length: 0
< vary: Origin
< vary: Access-Control-Request-Method
< vary: Access-Control-Request-Headers
< x-content-type-options: nosniff
< x-xss-protection: 1; mode=block
< cache-control: no-cache, no-store, max-age=0, must-revalidate
< pragma: no-cache
< expires: 0
< strict-transport-security: max-age=15724800; includeSubDomains
< x-frame-options: DENY
<
* Connection #0 to host dev.abc.com left intact
bash-5.1$ * We are completely uploaded and fine
< HTTP/2 403
< date: Fri, 22 Jul 2022 04:40:59 GMT
< content-length: 0
< vary: Origin
< vary: Access-Control-Request-Method
< vary: Access-Control-Request-Headers
< x-content-type-options: nosniff
< x-xss-protection: 1; mode=block
< cache-control: no-cache, no-store, max-age=0, must-revalidate
< pragma: no-cache
< expires: 0
< strict-transport-security: max-age=15724800; includeSubDomains
< x-frame-options: DENY
When I curl the above endpoint directly with the service name as host within a shell from ingress-controller container, it works properly:
bash-5.1$ curl -v -d '{"name": "John Doe", "mobileNumber": "1234554321"}' -H 'Content-Type: application/json' http://usermanager:8082/api/user
* Trying 10.0.236.14:8082...
* Connected to usermanager (10.0.236.14) port 8082 (#0)
> POST /api/user HTTP/1.1
> Host: usermanager:8082
> User-Agent: curl/7.83.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 50
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Fri, 22 Jul 2022 03:58:33 GMT
Following is my ingress route config:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: abc-ingress
namespace: k8sns-abc-dev
annotations:
kubernetes.io/ingress.class: "nginx"
cert-manager.io/cluster-issuer: letsencrypt
spec:
tls:
- hosts:
- dev.abc.com
secretName: tls-secret
rules:
- host: dev.abc.com
http:
paths:
- path: /backend/usermanager
pathType: Prefix
backend:
service:
name: usermanager
port:
number: 8082
Can you please help me identify and fix why am I getting 403-Forbidden error when making an API request through DNS host?
When you are hitting the path https://dev.abc.com/backend/usermanager/api/user
and when you are trying the API inside of container, the path is api/user
Inside your ingress, there is no path re-write config.
So i think your service will be getting the path backend/usermanager/api/user
However, 403 is for unauth so make sure there is no another path logic check or so.

webhook: tls: failed to find "CERTIFICATE" PEM block in certificate input after skipping PEM blocks of the following types: [CERTIFICATE REQUEST]

I am trying to deploy an admission controller / mutating webhook
Image: https://hub.docker.com/layers/247126140/aagashe/label-webhook/1.2.0/images/sha256-acfe141ca782eb8699a3656a77df49a558a1b09989762dbf263a66732fd00910?context=repo
Steps are executed in the below order.
Created the ca-csr.json and ca-config.json as per below
ca-config.json
{
"signing": {
"default": {
"expiry": "175200h"
},
"profiles": {
"default": {
"usages": ["signing", "key encipherment", "server auth", "client auth"],
"expiry": "175200h"
}
}
}
}
ca-csr.json
{
"signing": {
"default": {
"expiry": "175200h"
},
"profiles": {
"default": {
"usages": ["signing", "key encipherment", "server auth", "client auth"],
"expiry": "175200h"
}
}
}
}
Create a docker container and run commands one after the other as below:
docker run -it --rm -v ${PWD}:/work -w /work debian bash
apt-get update && apt-get install -y curl &&
curl -L https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssl_1.5.0_linux_amd64 -o /usr/local/bin/cfssl && \
curl -L https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssljson_1.5.0_linux_amd64 -o /usr/local/bin/cfssljson && \
chmod +x /usr/local/bin/cfssl && \
chmod +x /usr/local/bin/cfssljson
cfssl gencert -initca ca-csr.json | cfssljson -bare /tmp/ca
cfssl gencert \
-ca=/tmp/ca.pem \
-ca-key=/tmp/ca-key.pem \
-config=ca-config.json \
-hostname="label-webhook,label-webhook.default.svc.cluster.local,label-webhook.default.svc,localhost,127.0.0.1" \
-profile=default \
ca-csr.json | cfssljson -bare /tmp/label-webhook
ca_pem_b64="$(openssl base64 -A <"/tmp/ca.pem")"
ls -alrth /tmp/
total 32K
drwxr-xr-x 1 root root 4.0K Jul 5 05:07 ..
-rw-r--r-- 1 root root 2.0K Jul 5 05:13 ca.pem
-rw-r--r-- 1 root root 1.8K Jul 5 05:13 ca.csr
-rw------- 1 root root 3.2K Jul 5 05:13 ca-key.pem
-rw-r--r-- 1 root root 2.2K Jul 5 05:17 label-webhook.pem
-rw-r--r-- 1 root root 1.9K Jul 5 05:17 label-webhook.csr
-rw------- 1 root root 3.2K Jul 5 05:17 label-webhook-key.pem
drwxrwxrwt 1 root root 4.0K Jul 5 05:17 .
cp -apvf /tmp/* .
'/tmp/ca-key.pem' -> './ca-key.pem'
'/tmp/ca.csr' -> './ca.csr'
'/tmp/ca.pem' -> './ca.pem'
'/tmp/label-webhook-key.pem' -> './label-webhook-key.pem'
'/tmp/label-webhook.csr' -> './label-webhook.csr'
'/tmp/label-webhook.pem' -> './label-webhook.pem'
pwd
/work
export ca_pem_b64="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUZqakNDQTNhZ0F3SUJBZ0lVVVVCSHcvTUlPak5IVjE1ZHBhMytF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2h6L09hblIKdDFNWWNKTytpQzJBR09adVlGRnJsbUk0cWlCUHBJc204YmxDVGRoT1FhLzI2RTJWQzJXQk9SQmVrU2VWY3ZzUgpQaXFWMkRzV2I3ODc5UzEwWS9lOVQ2WUhIc3Z4TDVjZnhibVBsRDF2dlR0TmI2TjJiYTYyWmZVVlEvU3E3ZmEwClhKbUtpQ2pLbU9oMVhKRm5ZRmpRb25kMUFSNUVzR0drblI5NW5QN0x5ejd5RmpHMjFndkJHSU0xbHV0alg5aW8KVkdpMjlHdFA4THVQait6TDNsMElUTEZqb0RCOVBiNXFFbjR4MGpqMHlHc09kdFQ0ZGYvSGVja2ZHV0xmNkZEawp5ZmNuMTlRWDB0NXl6YklZVG9qRFV3VXlEUFZDYW44Y0JkdWdCNGptZkNjV2pRPT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="
helm upgrade --install rel-label-webhook chart --namespace mutatingwebhook --create-namespace --set secret.cert=$(cat kubernetes/admissioncontrollers/introduction/tls/label-webhook.csr | base64 -w0) --set secret.key=$(cat kubernetes/admissioncontrollers/introduction/tls/label-webhook.pem | base64 -w0) --set secret.cabundle=$(echo "${ca_pem_b64}"|base64 -w0)
I get an error like below when I check status of pod logs:
k get all
NAME READY STATUS RESTARTS AGE
pod/rel-label-webhook-5575b849dc-d62np 0/1 CrashLoopBackOff 2 (20s ago) 48s
pod/rel-label-webhook-5575b849dc-gg94h 0/1 Error 3 (35s ago) 63s
pod/rel-label-webhook-5575b849dc-zcvc9 0/1 CrashLoopBackOff 2 (19s ago) 48s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/rel-label-webhook ClusterIP 10.0.135.138 <none> 8001/TCP 63s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/rel-label-webhook 0/3 3 0 64s
NAME DESIRED CURRENT READY AGE
replicaset.apps/rel-label-webhook-5575b849dc 3 3 0 64s
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
horizontalpodautoscaler.autoscaling/rel-label-webhook Deployment/rel-label-webhook <unknown>/80%, <unknown>/80% 3 8 3 64s
k logs -f pod/rel-label-webhook-5575b849dc-gg94h
time="2022-07-05T13:37:45Z" level=info msg="listening on :8001"
error: error serving webhook: tls: failed to find "CERTIFICATE" PEM block in certificate input after skipping PEM blocks of the following types: [CERTIFICATE REQUEST]
What I am doing wrong here?
P.S:
Edit 1.
Tried as per larsks but now getting a new error!
Command
azureuser#ubuntuvm:~/container-label-webhook$ helm upgrade --install rel-label-webhook chart --namespace mutatingwebhook --create-namespace --set secret.cert=$(cat kubernetes/admissioncontrollers/introduction/tls/label-webhook.pem | base64 -w0) --set secret.key=$(cat kubernetes/admissioncontrollers/introduction/tls/label-webhook.pem | base64 -w0) --set secret.cabundle="echo "${ca_pem_b64}"|base64 -w0"
Error:
azureuser#ubuntuvm:~/container-label-webhook$ k logs -f pod/rel-label-webhook-5575b849dc-44xrn
time="2022-07-06T02:41:12Z" level=info msg="listening on :8001"
error: error serving webhook: tls: found a certificate rather than a key in the PEM for the private key
The error seems pretty clear: the code is looking for a CERTIFICATE block in a PEM-encoded file, but it is only find a CERTIFICATE REQUEST block. It looks like you're passing a certificate signing request (csr) where the code expects to find an actual SSL certificate. And in fact, looking at your helm upgrade command, that's exactly what you're doing:
helm upgrade ... \
--set secret.cert=$(cat kubernetes/admissioncontrollers/introduction/tls/label-webhook.csr | base64 -w0) ...
You should use label-webhook.pem here instead of label-webhook.csr.

Filtering powershell output with search pattern beginning with some-pattern and ending with other-pattern

I was inspired by the bash command line in which sed outputs the search pattern beginning with "-BEGIN CERTIFICATE-" and ending with "-END CERTIFICATE-"
openssl s_client -connect www.domain.com:443 -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
just how do I get the filter so that it works in powershell, probably with Select-String?
Here is the output of the bash command:
$ openssl s_client -connect google.com:443 -showcerts | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
-----BEGIN CERTIFICATE-----
MIIJVzCCCD+gAwIBAgIRANFJW61SRurECAAAAABTHOIwDQYJKoZIhvcNAQELBQAw
...cut...
jPCWTiAulvBLJJQ9nmggAgaEg7/9bs6da47V5awlyEAKzzmHGAmcNpX71Q==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIESjCCAzKgAwIBAgINAeO0mqGNiqmBJWlQuDANBgkqhkiG9w0BAQsFADBMMSAw
...cut...
USpxu6x6td0V7SvJCCosirSmIatj/9dSSVDQibet8q/7UK4v4ZUN80atnZz1yg==
-----END CERTIFICATE-----
a total of 77 lines
There's nothing builtin quite as concise as sed, but I often find the switch statement useful for parsing multi-line output with regex line-by-line:
# flag to keep track of whether we're between BEGIN/END
$inCert = $false
# suppress stderr output from openssl, assign all output from switch to `$certs`
$certs = switch -Regex ("`n`n"|openssl s_client -connect google.com:443 -showcerts 2>$null){
'-BEGIN CERTIFICATE-' {
# alright, we encountered a BEGIN line, prepare to consume following lines as a cert
$partialCert = #()
$inCert = $true
}
'-END CERTIFICATE-' {
# reach END, output the current certificate
$inCert = $false
$partialCert -join [System.Environment]::NewLine
}
default {
# ignore anything as long as we're not in between BEGIN/END
if($inCert){
$partialCert += $_
}
}
}
# $certs now contain the base64-encoded certificates
It's a pitty you didn't show us an example of the output you received from the showcerts command, but I suppose it will look something like this:
CONNECTED(00000002)
--snip--
---
Certificate chain
0 s:CN = www.openssl.org
i:C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
-----BEGIN CERTIFICATE-----
MIIFVTCCBD2gAwIBAgISAwk9QUiwVmoQAtcCLKybaK7yMA0GCSqGSIb3DQEBCwUA
...
mQBom1EISBOiNyu5koR6iRZcXsn6x/4kwA==
-----END CERTIFICATE-----
1 s:C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
i:O = Digital Signature Trust Co., CN = DST Root CA X3
-----BEGIN CERTIFICATE-----
MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/
...
KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==
-----END CERTIFICATE-----
---
...
If you capture that in a variable, say $rawCerts you can make use of -split, -match and -replace to get an array of the actual base64 encoded certificates like below:
$certs = $rawCerts -split '(?sm)-BEGIN CERTIFICATE[-\r\n]+' | # split into textblocks
Where-Object {$_ -match '-END CERTIFICATE-'} | # take only the blocks that contain '-END CERTIFICATE-'
ForEach-Object { $_ -replace '(?sm)[\r\n-]+END CERTIFICATE.*' } # remove everything after and including '-END CERTIFICATE-'
P.S> (?sm) in the regex means Dot matches newline (s) and Characters ^ and $ match at line breaks (m)
this is the raw output without sed
CONNECTED(00000178)
---
Certificate chain
0 s:C = US, ST = California, L = Mountain View, O = Google LLC, CN = *.google.com
i:C = US, O = Google Trust Services, CN = GTS CA 1O1
-----BEGIN CERTIFICATE-----
MIIJVzCCCD+gAwIBAgIRANFJW61SRurECAAAAABTHOIwDQYJKoZIhvcNAQELBQAw
...<cut>...
jPCWTiAulvBLJJQ9nmggAgaEg7/9bs6da47V5awlyEAKzzmHGAmcNpX71Q==
-----END CERTIFICATE-----
1 s:C = US, O = Google Trust Services, CN = GTS CA 1O1
i:OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign
-----BEGIN CERTIFICATE-----
MIIESjCCAzKgAwIBAgINAeO0mqGNiqmBJWlQuDANBgkqhkiG9w0BAQsFADBMMSAw
...<cut>...
USpxu6x6td0V7SvJCCosirSmIatj/9dSSVDQibet8q/7UK4v4ZUN80atnZz1yg==
-----END CERTIFICATE-----
---
Server certificate
subject=C = US, ST = California, L = Mountain View, O = Google LLC, CN = *.google.com
issuer=C = US, O = Google Trust Services, CN = GTS CA 1O1
---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: ECDSA
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 3807 bytes and written 392 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 256 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
depth=2 OU = GlobalSign Root CA - R2, O = GlobalSign, CN = GlobalSign
verify return:1
depth=1 C = US, O = Google Trust Services, CN = GTS CA 1O1
verify return:1

Missing connection to mongod server

hope you can help me.
I have a java application that use mongodb 2.6.7. Now i must upgrade to 4.4.0 version. During the process
I decided to implement the TLS connection and here my problems began. Connection timed out.
To simplify the work I decided to connect directly using the mongo shell. Now, this is the situation:
i have the mongod server active on a linux pc (ubuntu 20.04 - ip: 192.168.1.191, mongodb installed 4.4.0, OpenSSL installed 1.1.1f), and i trying to connect with a windows 10 pc (2004 version - ip: 192.168.1.193, mongodb installed 4.4.0, OpenSSL installed 1.1.1g).
I created a self signed certificate with this commands:
openssl genrsa -des3 -passout pass:qwer -out ./demoCA/private/cakey.pem 4096
openssl req -new -x509 -days 730 -key ./demoCA/private/cakey.pem -passin pass:qwer -out ./demoCA/cacert.pem -subj '/C=LL/ST=lin/L=lin/O=lin/OU=lin/CN=lin' -outform PEM
cp ./demoCA/cacert.pem ./demoCA/certs/00.pem
cd ./demoCA/certs
ln -s 00.pem `openssl x509 -hash -noout -in 00.pem`.0
cd ..
cd ..
openssl genrsa -out ./private_key.pem 4096
openssl req -new -key ./private_key.pem -out ./request.pem -subj '/C=LL/ST=lin/L=lin/O=lin/OU=lin/CN=192.168.1.191' -outform PEM
openssl ca -in ./request.pem -passin pass:qwer
cp ./demoCA/newcerts/01.pem ./demoCA/certs/01.pem
cd ./demoCA/certs
ln -s 01.pem `openssl x509 -hash -noout -in 01.pem`.0
cd ..
cd ..
cat ./private_key.pem ./demoCA/certs/01.pem > ./certificate.pem
then i started mongod with this command:
mongod --config /etc/mongod.conf
here the mongod.conf:
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 192.168.1.191
tls:
mode: requireTLS
certificateKeyFile: [ABSOLUTE_PATH]/certificate.pem
CAFile: [ABSOLUTE_PATH]/demoCA/cacert.pem
# how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
#security:
security:
authorization: "enabled"
i downloaded on my Win pc certificate.pem and cacert.pem and tried to connect with:
mongo --tls --tlsCertificateKeyFile c:\ssl-cert-lin\certificate.pem --tlsCAFile c:\ssl-cert-lin\cacert.pem -u root -p test --authenticationDatabase mydb --host 192.168.1.191 --port 27017
the result:
Error: couldn't connect to server 192.168.1.191:27017, connection attempt failed: SocketException: The client and server cannot communicate, because they do not possess a common algorithm.
After a thousand attempts, i tried to do viceversa, installing mongodb server on windows and connecting from linux to window. I followed the same procedure creating the certificate, same configuration of mongod, same connection parameters with the mongo command (after the upload of win certificate on linux). Linux mongo command connect correctly to mongod windows server.
So i tried to test connection directly by OpenSSL keeping both the mongo server (on linux and on windows) alive.
From linux (ip:192.168.1.191) i launched command:
root#btksrv:~# openssl s_client -connect 192.168.1.193:27017 -CAfile ./ssl-cert-win/cacert.pem
CONNECTED(00000003)
Can't use SSL_get_servername
depth=1 C = WW, ST = win, L = win, O = win, OU = win, CN = win
verify return:1
depth=0 C = WW, ST = win, O = win, OU = win, CN = 192.168.1.193
verify return:1
---
Certificate chain
0 s:C = WW, ST = win, O = win, OU = win, CN = 192.168.1.193
i:C = WW, ST = win, L = win, O = win, OU = win, CN = win
---
Server certificate
-----BEGIN CERTIFICATE-----
[lines removed...]
-----END CERTIFICATE-----
subject=C = WW, ST = win, O = win, OU = win, CN = 192.168.1.193
issuer=C = WW, ST = win, L = win, O = win, OU = win, CN = win
---
No client certificate CA names sent
Client Certificate Types: RSA sign, DSA sign, ECDSA sign
Requested Signature Algorithms: RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA1:ECDSA+SHA256:ECDSA+SHA384:ECDSA+SHA1:DSA+SHA1:RSA+SHA512:ECDSA+SHA512
Shared Requested Signature Algorithms: RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:ECDSA+SHA256:ECDSA+SHA384:RSA+SHA512:ECDSA+SHA512
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: ECDH, P-384, 384 bits
---
SSL handshake has read 2248 bytes and written 453 bytes
Verification: OK
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 4096 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES256-GCM-SHA384
Session-ID: B84B0000D21B35AF457FBA576C3C1A4BD42DEC5B1DAC2FA33203DEA6E88DE4E7
Session-ID-ctx:
Master-Key: CA4CEC4DE4AA5B67BC577CCA3DF7D5E5DF5ECEC9438592AAC9D7DDDB105E31FB8CB78DBBE962C0A90D99195ECD86FCBB
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1596710695
Timeout : 7200 (sec)
Verify return code: 0 (ok)
Extended master secret: yes
---
read:errno=0
From windows (ip:192.168.1.193) i launched command:
c:\>openssl s_client -connect 192.168.1.191:27017 -CAfile c:\ssl-cert-lin\cacert.pem
CONNECTED(00000120)
Can't use SSL_get_servername
depth=1 C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
verify return:1
depth=0 C = LL, ST = lin, O = lin, OU = lin, CN = 192.168.1.191
verify return:1
---
Certificate chain
0 s:C = LL, ST = lin, O = lin, OU = lin, CN = 192.168.1.191
i:C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
1 s:C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
i:C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
---
Server certificate
-----BEGIN CERTIFICATE-----
[lines removed...]
-----END CERTIFICATE-----
subject=C = LL, ST = lin, O = lin, OU = lin, CN = 192.168.1.191
issuer=C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
---
Acceptable client certificate CA names
C = LL, ST = lin, L = lin, O = lin, OU = lin, CN = lin
Requested Signature Algorithms: ECDSA+SHA256:ECDSA+SHA384:ECDSA+SHA512:Ed25519:Ed448:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA512:ECDSA+SHA224:RSA+SHA224
Shared Requested Signature Algorithms: ECDSA+SHA256:ECDSA+SHA384:ECDSA+SHA512:Ed25519:Ed448:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA512
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 3832 bytes and written 403 bytes
Verification: OK
---
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 4096 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
Protocol : TLSv1.3
Cipher : TLS_AES_256_GCM_SHA384
Session-ID: 0D60B8F6140E7483DDE2D4D3B405E2C81FCC6C18C32B03DA811395A0ED9189A0
Session-ID-ctx:
Resumption PSK: 10782266BDE34F8820365AD13FCB606128B410B6D9DBC31D382542E17058975030B4B472A907730AB63573FBD7E900B3
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
[lines removed...]
Start Time: 1596711179
Timeout : 7200 (sec)
Verify return code: 0 (ok)
Extended master secret: no
Max Early Data: 0
---
read R BLOCK
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
Protocol : TLSv1.3
Cipher : TLS_AES_256_GCM_SHA384
Session-ID: E3A023177260EC48FEF860C30FBF32986E6AA83EA897D5D4E68DD1418329B6C4
Session-ID-ctx:
Resumption PSK: BE969CD81BB54EFF67C1F877A29A15C40839767A145252BDD16BDC2E91242E069C8E04D4A3E3DA7D099120D78749EA12
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 7200 (seconds)
TLS session ticket:
[lines removed...]
Start Time: 1596711179
Timeout : 7200 (sec)
Verify return code: 0 (ok)
Extended master secret: no
Max Early Data: 0
---
read R BLOCK
read:errno=0
Looking at the last 2 code blocks i think there is a mismatch protocol... Linux use TLS 1.3 and windows use 1.2 protocol. Could this be the problem? in this case how can I solve?
Otherwise what can be the problem? (and the solution)
Thanks in advance for your help
P.s. before using mongo v4.4 i tried v4.2... same thing
Found the solution. The problem was in Openssl. Linux has a preinstalled version of OpenSSL. In Windows i downloaded a installer from here: https://slproweb.com/products/Win32OpenSSL.html
the problem is that a third part compiled OpenSSL could has a different encryption.
I uninstalled OpenSSL from both Linux and Windows and downloaded the uncompiled library from https://github.com/openssl/openssl. After the compilation, i recreated the certificates and now windows mongo can connect linux mongod and viceversa

PayPal REST API: trying to activate a billing plan, but getting "HTTP/1.1 401 Unauthorized"

I am building an EC site, where my customers can pay through PayPal API. Now, I am learning how it works, using Sandbox; referring to this page: https://developer.paypal.com/docs/integration/direct/billing-plans/
I have succeeded the prerequisites, i.e., having created a PayPal app,
gotten an access token, and made an API call. And then, I have succeeded making a billing plan, copying-and-pasting the sample command on the page, just replacing the Access Token.
Now, I want to activate the billing plan, but couldn't have succeeded.
The command used is, once again, copied-and-pasted from the page, as below.
curl -v -k -X PATCH https://api.sandbox.paypal.com/v1/payments/billing-plans/P-7DC96732KA7763723UOPKETA/ \
-H 'X-PAYPAL-OAUTH-CONTEXT: {"consumer":{"accountNumber":1181198218909172527,"merchantId":"5KW8F2FXKX5HA"},"merchant":{"accountNumber":1659371090107732880,"merchantId":"2J6QB8YJQSJRJ"},"apiCaller":{"clientId":"AdtlNBDhgmQWi2xk6edqJVKklPFyDWxtyKuXuyVT-OgdnnKpAVsbKHgvqHHP","appId":"APP-6DV794347V142302B","payerId":"2J6QB8YJQSJRJ","accountNumber":"1659371090107732880"},"scopes":["https://api.paypal.com/v1/payments/.*","https://uri.paypal.com/services/payments/futurepayments","openid"]}' \
-H 'Content-Type: application/json' \
-d '[{
"op": "replace",
"path": "/",
"value": {
"state": "ACTIVE"
}
}]'
First, as instructed, I just replaced the Plan ID "P-7DC96732KA7763723UOPKETA" with mine, provided in the previous response for creating the plan.
* Trying 173.0.82.78...
* Connected to api.sandbox.paypal.com (173.0.82.78) port 443 (#0)
* TLS 1.2 connection using TLS_RSA_WITH_AES_256_CBC_SHA256
* Server certificate: api.sandbox.paypal.com
* Server certificate: Symantec Class 3 Secure Server CA - G4
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> PATCH /v1/payments/billing-plans/P-8AX21799EN516221GJMBOECA/ HTTP/1.1
> Host: api.sandbox.paypal.com
> User-Agent: curl/7.43.0
> Accept: */*
> X-PAYPAL-OAUTH-CONTEXT: {"consumer":{"accountNumber":1181198218909172527,"merchantId":"5KW8F2FXKX5HA"},"merchant":{"accountNumber":1659371090107732880,"merchantId":"2J6QB8YJQSJRJ"},"apiCaller":{"clientId":"AdtlNBDhgmQWi2xk6edqJVKklPFyDWxtyKuXuyVT-OgdnnKpAVsbKHgvqHHP","appId":"APP-6DV794347V142302B","payerId":"2J6QB8YJQSJRJ","accountNumber":"1659371090107732880"},"scopes":["ttps://api.paypal.com/v1/payments/.*","ttps://uri.paypal.com/services/payments/futurepayments","openid"]}
> Content-Type: application/json
> Content-Length: 78
>
* upload completely sent off: 78 out of 78 bytes
< HTTP/1.1 401 Unauthorized
< Date: Fri, 17 Feb 2017 12:18:47 GMT
< Server: Apache
< paypal-debug-id: c46e304b4bb46
< Paypal-Debug-Id: c46e304b4bb46
< Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D669689432%26HTTP_X_PP_AZ_LOCATOR%3D; Expires=Fri, 17 Feb 2017 12:48:47 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
< Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
< Content-Length: 0
< Connection: close
< Content-Type: text/plain; charset=ISO-8859-1
<
* Closing connection 0
And I tried with some other parameter replacements, like the Client ID, but no luck.
Do I need to replace other parameters?
Or, have I done something wrong?
SOLVED.
On this page, I found simpler and more straightforward command
and made up below:
curl -v -X PATCH https://api.sandbox.paypal.com/v1/payments/billing-plans/<Plan ID>/ \
-H "Content-Type:application/json" \
-H "Authorization: Bearer <Access Token>" \
-d '[
{
"path":"/",
"value":{"state":"ACTIVE"},
"op":"replace"}
]'
Got the response as below:
* Trying 173.0.82.78...
* Connected to api.sandbox.paypal.com (173.0.82.78) port 443 (#0)
* TLS 1.2 connection using TLS_RSA_WITH_AES_256_CBC_SHA256
* Server certificate: api.sandbox.paypal.com
* Server certificate: Symantec Class 3 Secure Server CA - G4
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> GET /v1/payments/billing-plans/<Plan ID> HTTP/1.1
> Host: api.sandbox.paypal.com
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Type:application/json
> Authorization: Bearer <Access Token>
>
< HTTP/1.1 200 OK
< Date: Sun, 19 Feb 2017 11:36:50 GMT
< Server: Apache
< paypal-debug-id: 3ca31778e271e
< Content-Language: *
< Paypal-Debug-Id: 3ca31778e271e
< Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D1384360280%26HTTP_X_PP_AZ_LOCATOR%3D; Expires=Sun, 19 Feb 2017 12:06:52 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
< Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
< Vary: Authorization
< Content-Length: 1391
< Connection: close
< Content-Type: application/json
<
* Closing connection 0
{"id":"<Plan ID>","state":"ACTIVE","name":"Sample Plan",
...
"rel":"self","method":"GET"}]}
Got HTTP 200 and the state "ACTIVE".
Thanks for your trying to help, many thanks!