[PD1] Certs done

This commit is contained in:
Afonso Franco 2024-04-18 13:06:16 +01:00
parent 23584e2901
commit 2c4f1fd2fc
Signed by: afonso
SSH key fingerprint: SHA256:aiLbdlPwXKJS5wMnghdtod0SPy8imZjlVvCyUX9DJNk
6 changed files with 104 additions and 29 deletions

View file

@ -2,6 +2,7 @@ package client
import ( import (
"PD1/internal/protocol" "PD1/internal/protocol"
"PD1/internal/utils/cryptoUtils"
"PD1/internal/utils/networking" "PD1/internal/utils/networking"
"flag" "flag"
"fmt" "fmt"
@ -24,16 +25,19 @@ func Run() {
} }
uid := flag.Arg(1) uid := flag.Arg(1)
subject := flag.Arg(2) subject := flag.Arg(2)
// Read message content from stdin
messageContent := readMessageContent() messageContent := readMessageContent()
cl := networking.NewClient[protocol.Packet]()
clientCert := cryptoUtils.LoadKeyStore("userdata.p12")
cl := networking.NewClient[protocol.Packet](clientCert)
defer cl.Connection.Conn.Close() defer cl.Connection.Conn.Close()
// TODO: getuserinfo client cert
// TODO: ask server for the recieving client's cert
certRequestPacket := protocol.NewRequestUserCertPacket(uid) certRequestPacket := protocol.NewRequestUserCertPacket(uid)
cl.Connection.Send(certRequestPacket) cl.Connection.Send(certRequestPacket)
certPacket := cl.Connection.Receive() certPacket := cl.Connection.Receive()
// TODO: cipherContent := cryptoUtils.encryptMessageContent()
// TODO: Encrypt message
submitMessage(cl,uid,cipherContent) submitMessage(cl,uid,cipherContent)
case "askqueue": case "askqueue":
@ -52,7 +56,7 @@ func Run() {
showHelp() showHelp()
default: default:
fmt.Println("Invalid command. Use 'help' for instructions.") commandError()
} }
} }

View file

@ -14,6 +14,9 @@ func readMessageContent() string {
return scanner.Text() return scanner.Text()
} }
//FIX: Why is this function in the client if it's called by crypto?
// It should be called by the client and the result
// should then be passed into the crypto library
func AskUserPassword() string { func AskUserPassword() string {
fmt.Println("Enter message content (limited to 1000 bytes):") fmt.Println("Enter message content (limited to 1000 bytes):")
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -22,6 +25,12 @@ func AskUserPassword() string {
return scanner.Text() return scanner.Text()
} }
func commandError() {
fmt.Println("MSG SERVICE: command error!")
showHelp()
}
func showHelp() { func showHelp() {
fmt.Println("Comandos da aplicação cliente:") fmt.Println("Comandos da aplicação cliente:")
fmt.Println("-user <FNAME>: Especifica o ficheiro com dados do utilizador. Por omissão, será assumido que esse ficheiro é userdata.p12.") fmt.Println("-user <FNAME>: Especifica o ficheiro com dados do utilizador. Por omissão, será assumido que esse ficheiro é userdata.p12.")

View file

@ -2,6 +2,7 @@ package server
import ( import (
"PD1/internal/protocol" "PD1/internal/protocol"
"PD1/internal/utils/cryptoUtils"
"PD1/internal/utils/networking" "PD1/internal/utils/networking"
"fmt" "fmt"
) )
@ -34,8 +35,13 @@ func Run(port int) {
dataStore := OpenDB() dataStore := OpenDB()
defer dataStore.db.Close() defer dataStore.db.Close()
//TODO: Get the server's keystore path instead of hardcoding it
//Read server keystore
serverKeyStore := cryptoUtils.LoadKeyStore("serverdata.p12")
//Create server listener //Create server listener
server := networking.NewServer[protocol.Packet](port) server := networking.NewServer[protocol.Packet](serverKeyStore,port)
go server.ListenLoop() go server.ListenLoop()
for { for {

View file

@ -2,31 +2,41 @@ package cryptoUtils
import ( import (
"PD1/internal/client" "PD1/internal/client"
"PD1/internal/protocol"
"crypto/rsa" "crypto/rsa"
"crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "encoding/pem"
"log" "log"
"os" "os"
"software.sslmate.com/src/go-pkcs12" "software.sslmate.com/src/go-pkcs12"
) )
func Print() { type KeyStore struct {
fmt.Println("crypto package") cert *x509.Certificate
caCertChain []*x509.Certificate
privKey rsa.PrivateKey
} }
func getUserInfo(certFilename string) ( func (k KeyStore) GetCert() *x509.Certificate {
rsa.PrivateKey, return k.cert
*x509.Certificate, }
[]*x509.Certificate,
error) { func (k KeyStore) GetCACertChain() []*x509.Certificate {
return k.caCertChain
}
func (k KeyStore) GetPrivKey() rsa.PrivateKey {
return k.privKey
}
func LoadKeyStore(keyStorePath string) KeyStore {
var privKey rsa.PrivateKey var privKey rsa.PrivateKey
certFile, err := os.ReadFile(certFilename) certFile, err := os.ReadFile(keyStorePath)
if err != nil { if err != nil {
log.Panicln("Provided certificate %v couldn't be opened", certFilename) log.Panicln("Provided certificate %v couldn't be opened", keyStorePath)
return rsa.PrivateKey{}, nil, nil, err
} }
password := client.AskUserPassword() password := client.AskUserPassword()
@ -34,16 +44,49 @@ func getUserInfo(certFilename string) (
privKey = privKeyInterface.(rsa.PrivateKey) privKey = privKeyInterface.(rsa.PrivateKey)
if err != nil { if err != nil {
log.Panicln("PKCS12 key store couldn't be decoded") log.Panicln("PKCS12 key store couldn't be decoded")
return rsa.PrivateKey{}, nil, nil, err
} }
if err := privKey.Validate(); err != nil { if err := privKey.Validate(); err != nil {
log.Panicln("Private key is not valid") log.Panicln("Private key is not valid")
return rsa.PrivateKey{}, nil, nil, err
} }
return privKey, cert, caCerts, nil return KeyStore{cert: cert, caCertChain: caCerts, privKey: privKey}
} }
func encryptMessageContent(privKey rsa.PrivateKey, peerPubKey rsa.PublicKey, content []byte) []byte { func (k KeyStore)GetTLSConfig() *tls.Config {
certificate ,err := tls.X509KeyPair(k.cert.Raw, pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(&k.privKey)}))
if err!=nil{
log.Panicln("Could not load certificate and privkey to TLS")
}
//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},
ClientCAs: caCertPool,
}
return config
}
func (k KeyStore)GetTLSConfigServer() *tls.Config {
config := k.GetTLSConfig()
config.ClientAuth = tls.RequireAndVerifyClientCert
return config
}
func (k KeyStore)GetTLSConfigClient() *tls.Config {
config:= k.GetTLSConfig()
config.ServerName = "SERVER"
return config
}
func (k KeyStore)EncryptMessageContent(peerPubKey rsa.PublicKey, content []byte) []byte {
// Digital envolope // Digital envolope
return nil
} }

View file

@ -1,13 +1,21 @@
package networking package networking
import "net" import (
"crypto/tls"
"net"
)
type ClientTLSConfigProvider interface {
GetTLSConfigClient() *tls.Config
}
type Client[T any] struct { type Client[T any] struct {
Connection Connection[T] Connection Connection[T]
} }
func NewClient[T any]() Client[T] { func NewClient[T any](clientTLSConfigProvider ClientTLSConfigProvider) Client[T] {
dialConn, err := net.Dial("tcp", "localhost:8080") dialConn, err := tls.Dial("tcp", "localhost:8080", clientTLSConfigProvider.GetTLSConfigClient())
if err != nil { if err != nil {
panic("Could not open connection to server") panic("Could not open connection to server")
} }

View file

@ -1,18 +1,23 @@
package networking package networking
import ( import (
"crypto/tls"
"fmt" "fmt"
"net" "net"
) )
type ServerTLSConfigProvider interface {
GetServerTLSConfig() *tls.Config
}
type Server[T any] struct { type Server[T any] struct {
listener net.Listener listener net.Listener
C chan Connection[T] C chan Connection[T]
} }
func NewServer[T any](port int) Server[T]{ func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider,port int) Server[T]{
listener, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)) listener, err := tls.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port), serverTLSConfigProvider.GetServerTLSConfig())
if err != nil { if err != nil {
panic("Server could not bind to address") panic("Server could not bind to address")
} }