[PD2] Server done?

Co-authored-by: tsousa111 <tiagao2001@hotmail.com>
This commit is contained in:
Afonso Franco 2024-05-28 20:08:25 +01:00
parent 08a73a4f76
commit 49a29e43a7
Signed by: afonso
SSH key fingerprint: SHA256:PQTRDHPH3yALEGtHXnXBp3Orfcn21pK20t0tS1kHg54
66 changed files with 2777 additions and 5 deletions

View file

@ -0,0 +1,283 @@
package cryptoUtils
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"errors"
"time"
"log"
"os"
"golang.org/x/crypto/chacha20poly1305"
"software.sslmate.com/src/go-pkcs12"
)
type KeyStore struct {
cert *x509.Certificate
caCertChain []*x509.Certificate
privKey *rsa.PrivateKey
}
func (k KeyStore) GetCert() *x509.Certificate {
return k.cert
}
func (k KeyStore) GetCACertChain() []*x509.Certificate {
return k.caCertChain
}
func (k KeyStore) GetPrivKey() *rsa.PrivateKey {
return k.privKey
}
func ExtractAllOIDValues(cert *x509.Certificate) map[string]string {
oidValueMap := make(map[string]string)
for _, name := range cert.Subject.Names {
oid := name.Type.String()
value := name.Value.(string)
oidValueMap[oid] = value
}
return oidValueMap
}
func LoadKeyStore(keyStorePath string, password string) (KeyStore, error) {
var privKey *rsa.PrivateKey
keystoreBytes, err := os.ReadFile(keyStorePath)
if err != nil {
return KeyStore{}, err
}
privKeyInterface, cert, caCerts, err := pkcs12.DecodeChain(keystoreBytes, password)
if err != nil {
return KeyStore{}, err
}
privKey, ok := privKeyInterface.(*rsa.PrivateKey)
if !ok {
return KeyStore{}, err
}
if err := privKey.Validate(); err != nil {
return KeyStore{}, err
}
return KeyStore{cert: cert, caCertChain: caCerts, privKey: privKey}, err
}
// Check if the cert is signed by the CA and is for the correct user
func (k KeyStore) CheckCert(cert *x509.Certificate, uid string) error {
caCertPool := x509.NewCertPool()
for _, caCert := range k.caCertChain {
caCertPool.AddCert(caCert)
}
opts := x509.VerifyOptions{
Roots: caCertPool,
}
// Check if the certificate is signed by the specified CA
_, err := cert.Verify(opts)
if err != nil {
log.Println("Certificate not signed by a trusted CA")
return err
}
if cert.NotAfter.Before(time.Now()) {
return errors.New("certificate has expired")
}
if cert.NotBefore.After(time.Now()) {
return errors.New("certificate is not valid yet")
}
//Check if the pseudonym field is set to UID
oidMap := ExtractAllOIDValues(cert)
if oidMap["2.5.4.65"] != uid {
log.Println("Certificate does not belong to the message's receiver")
return err
}
return nil
}
func (k *KeyStore) GetTLSConfig() *tls.Config {
certificate := tls.Certificate{Certificate: [][]byte{k.cert.Raw}, PrivateKey: k.privKey, Leaf: k.cert}
//Add the CA certificate chain to a CertPool
caCertPool := x509.NewCertPool()
for _, caCert := range k.caCertChain {
caCertPool.AddCert(caCert)
}
config := &tls.Config{
Certificates: []tls.Certificate{certificate},
}
return config
}
func (k *KeyStore) GetServerTLSConfig() *tls.Config {
tlsConfig := k.GetTLSConfig()
//Add the CA certificate chain to a CertPool
caCertPool := x509.NewCertPool()
for _, caCert := range k.caCertChain {
caCertPool.AddCert(caCert)
}
tlsConfig.ClientCAs = caCertPool
tlsConfig.ClientAuth = tls.RequireAnyClientCert
tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
// Verify the peer's certificate
opts := x509.VerifyOptions{
Roots: caCertPool,
}
for _, certBytes := range rawCerts {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return err
}
if cert.NotAfter.Before(time.Now()) {
return errors.New("certificate has expired")
}
if cert.NotBefore.After(time.Now()) {
return errors.New("certificate is not valid yet")
}
// Check if the certificate is signed by the specified CA
_, err = cert.Verify(opts)
if err != nil {
return errors.New("certificate not signed by trusted CA")
}
}
return nil
}
return tlsConfig
}
func (k *KeyStore) GetClientTLSConfig() *tls.Config {
tlsConfig := k.GetTLSConfig()
//Add the CA certificate chain to a CertPool
caCertPool := x509.NewCertPool()
for _, caCert := range k.caCertChain {
caCertPool.AddCert(caCert)
}
tlsConfig.RootCAs = caCertPool
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
// Verify the peer's certificate
opts := x509.VerifyOptions{
Roots: caCertPool,
}
for _, certBytes := range rawCerts {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return err
}
if cert.NotAfter.Before(time.Now()) {
return errors.New("certificate has expired")
}
if cert.NotBefore.After(time.Now()) {
return errors.New("certificate is not valid yet")
}
oidMap := ExtractAllOIDValues(cert)
// Check if the certificate is signed by the specified CA
_, err = cert.Verify(opts)
if err != nil {
return errors.New("certificate not signed by trusted CA")
}
//Check if the pseudonym field is set to "SERVER"
if oidMap["2.5.4.65"] != "SERVER" {
return errors.New("peer isn't the server")
}
}
return nil
}
return tlsConfig
}
func (k KeyStore) EncryptMessageContent(receiverCert *x509.Certificate, content []byte) ([]byte, error) {
// Digital envolope
// Create a random symmetric key
dataKey := make([]byte, 32)
if _, err := rand.Read(dataKey); err != nil {
return nil, err
}
cipher, err := chacha20poly1305.New(dataKey)
if err != nil {
return nil, err
}
nonce := make([]byte, cipher.NonceSize(), cipher.NonceSize()+len(content)+cipher.Overhead())
if _, err = rand.Read(nonce); err != nil {
return nil, err
}
// sign the message and append the signature
hashedContent := sha256.Sum256(content)
signature, err := rsa.SignPKCS1v15(nil, k.privKey, crypto.SHA256, hashedContent[:])
if err != nil {
return nil, err
}
content = pair(signature, content)
ciphertext := cipher.Seal(nonce, nonce, content, nil)
receiverPubKey := receiverCert.PublicKey.(*rsa.PublicKey)
encryptedDataKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, receiverPubKey, dataKey, nil)
if err != nil {
return nil, err
}
return pair(encryptedDataKey, ciphertext), nil
}
func (k KeyStore) DecryptMessageContent(senderCert *x509.Certificate, cipherContent []byte) ([]byte, error) {
encryptedDataKey, encryptedMsg := unPair(cipherContent)
dataKey, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, k.GetPrivKey(), encryptedDataKey, nil)
if err != nil {
return nil, err
}
// decrypt ciphertext
cipher, err := chacha20poly1305.New(dataKey)
if err != nil {
return nil, err
}
nonce, ciphertext := encryptedMsg[:cipher.NonceSize()], encryptedMsg[cipher.NonceSize():]
contentAndSig, err := cipher.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
// check signature with sender public key
signature, content := unPair(contentAndSig)
hashedContent := sha256.Sum256(content)
senderKey := senderCert.PublicKey.(*rsa.PublicKey)
if err := rsa.VerifyPKCS1v15(senderKey, crypto.SHA256, hashedContent[:], signature); err != nil {
return nil, err
}
return content, nil
}
func pair(l []byte, r []byte) []byte {
length := len(l)
lenBytes := make([]byte, 2)
binary.BigEndian.PutUint16(lenBytes, uint16(length))
lWithLen := append(lenBytes, l...)
return append(lWithLen, r...)
}
func unPair(pair []byte) ([]byte, []byte) {
lenBytes := pair[:2]
pair = pair[2:]
length := binary.BigEndian.Uint16(lenBytes)
l := pair[:length]
r := pair[length:]
return l, r
}

View file

@ -0,0 +1,23 @@
package networking
import (
"crypto/tls"
)
type ClientTLSConfigProvider interface {
GetClientTLSConfig() *tls.Config
}
type Client[T any] struct {
Connection Connection[T]
}
func NewClient[T any](clientTLSConfigProvider ClientTLSConfigProvider) (Client[T],error) {
dialConn, err := tls.Dial("tcp", "localhost:8080", clientTLSConfigProvider.GetClientTLSConfig())
if err != nil {
return Client[T]{},err
}
conn := NewConnection[T](dialConn)
return Client[T]{Connection: conn},nil
}

View file

@ -0,0 +1,51 @@
package networking
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io"
"log"
)
type Connection[T any] struct {
Conn *tls.Conn
encoder *json.Encoder
decoder *json.Decoder
}
func NewConnection[T any](netConn *tls.Conn) Connection[T] {
return Connection[T]{
Conn: netConn,
encoder: json.NewEncoder(netConn),
decoder: json.NewDecoder(netConn),
}
}
func (c Connection[T]) Send(obj T) error {
if err := c.encoder.Encode(&obj); err!=nil {
if err == io.EOF {
log.Println("Connection closed by peer")
}
return err
}
//Return true as connection active
return nil
}
func (c Connection[T]) Receive() (*T, error) {
var obj T
if err := c.decoder.Decode(&obj); err != nil {
if err == io.EOF {
log.Println("Connection closed by peer")
}
return nil,err
}
//Return true as connection active
return &obj, nil
}
func (c Connection[T]) GetPeerCertificate() *x509.Certificate {
state := c.Conn.ConnectionState()
return state.PeerCertificates[0]
}

View file

@ -0,0 +1,56 @@
package networking
import (
"crypto/tls"
"log"
"net"
)
type ServerTLSConfigProvider interface {
GetServerTLSConfig() *tls.Config
}
type Server[T any] struct {
listener net.Listener
C chan Connection[T]
}
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider) (Server[T], error) {
listener, err := tls.Listen("tcp", "127.0.0.1:8080", serverTLSConfigProvider.GetServerTLSConfig())
if err != nil {
return Server[T]{}, err
}
return Server[T]{
listener: listener,
C: make(chan Connection[T]),
}, nil
}
func (s *Server[T]) ListenLoop() {
for {
listenerConn, err := s.listener.Accept()
if err != nil {
log.Println("Server could not accept connection")
continue
}
tlsConn, ok := listenerConn.(*tls.Conn)
if !ok {
log.Println("Connection is not a TLS connection")
continue
}
if err := tlsConn.Handshake(); err != nil {
log.Println(err)
continue
}
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) == 0 {
log.Println("Client did not provide a certificate")
continue
}
conn := NewConnection[T](tlsConn)
s.C <- conn
}
}