[PD2] Client done except jwt token, login and register functions

This commit is contained in:
Afonso Franco 2024-05-30 21:02:28 +01:00
parent c94831d0a2
commit 78031d8e70
Signed by: afonso
SSH key fingerprint: SHA256:PQTRDHPH3yALEGtHXnXBp3Orfcn21pK20t0tS1kHg54
16 changed files with 698 additions and 337 deletions

View file

@ -1 +1 @@
7C475B59D1510F54E042BF4BFDBE811BF4EDAF37
7C475B59D1510F54E042BF4BFDBE811BF4EDAF38

View file

@ -0,0 +1,29 @@
-----BEGIN CERTIFICATE-----
MIIFBTCCAu2gAwIBAgIUfEdbWdFRD1TgQr9L/b6BG/TtrzgwDQYJKoZIhvcNAQEL
BQAwDTELMAkGA1UEAwwCQ0EwHhcNMjQwNTMwMTYyMjIyWhcNMjkwNTI5MTYyMjIy
WjAoMRQwEgYDVQQLDAtNU0cgU0VSVklDRTEQMA4GA1UEQQwHR0FURVdBWTCCAiIw
DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMdXub0WoiMi2RZhnaKW1ncpCe0z
GNutuD2xfyNG4YcYIxaXcZk/XprJly3txyKARnUj2kz+gR2ZNY75YIbqo5rJQlkf
ZcIl80stnkxI1eMedZlTs0JfWeobGhhkqr5JI5ylKMYfVNKyhWYac9VAmgIdWS5z
XJOk9gIdKvPkIHYDXozLZMNwfP+4PH+s11dKWhLcYy+MgO3ynv3kfo/9EdOMpmUa
ozpBSd/COJXz7XM0MSaaEtx2M7nH8Ok8urQ33a+AtaMYlK3wTiZWM0SNthDyQ6jV
492vFcHOJ24qrx1wJgB5GYwOmOl32LDh9+tyV7taqUrFutYEir3RRzxbEKPDWIUm
NTkgtIpuD+I9AiD08jjW5CHmK4zZA4lA8eyga8f9ge5Yul5TtUEkBP/epVrPoeyK
XEloFKM3/mE3oTLb2+oAiRWbCK+jML1jBEWJu7zmw1b7wBuG9vNZXPnyfIP9Us9R
kllyV0T41nuqV/coD0C63Lj4zMy0t3QmQfA+YA4NixBdKZx7G8nfHZ83tFHCE7AU
MkXggJBNZMC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NMQ7k8d2irC+lkRYcaidJClhl6V5UtDdhV8LC4894T
bRLajEDxAnrEBuiW5257YprdTUWo+nS/QHNwwwFzt8LfuiDoLHe0kXfEIPujm6mJ
mQKCAQAqsJ6X29gknwUXnQzuwuD8vuQ3K/z+oSFZj9VGWlnwKT4k9rmP3b1mrTKQ
8mXrVX44BkYgjRO4myDqVdEugBQS6vmGyu+BJR0OYC2MWeWaUU5ABgsh/uR+lWRa
AHEKbf04OMZN2uj5dcARsDE0501T4znm0EzMKs3pBEzzbX5KuJG/F7s+7bpr+pq/
IGxW5/kx7TjMvgVYZjPOuF4HbpBDHNU4dL+girPfPmVd7X9hsYs8r6YLB/F4sIQo
qnDEhiRXFpb4HrFbCoP+HpqAs7jvqnH9VwJdI1XARQjubPui3IrcvyO1IV70qPcQ
d7UO8BCUj9IMU7pG2RmEWzw35AJJ
-----END PRIVATE KEY-----

Binary file not shown.

BIN
Projs/PD2/gateway.db Normal file

Binary file not shown.

View file

@ -3,16 +3,24 @@ package client
import (
"PD2/internal/protocol"
"PD2/internal/utils/cryptoUtils"
"PD2/internal/utils/networking"
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"sort"
"strconv"
)
const baseURL = "https://127.0.0.1:9090"
func Run() {
var userFile string
flag.StringVar(&userFile, "user", "userdata.p12", "Specify user data file")
@ -28,6 +36,8 @@ func Run() {
log.Fatalln(err)
}
token = cryptoUtils.GetUserToken()
command := flag.Arg(0)
switch command {
case "send":
@ -65,10 +75,11 @@ func Run() {
}
}
err := askQueueCommand(clientKeyStore, page, pageSize)
page, pageSize, listClientMessageInfo, err := askQueueCommand(clientKeyStore, page, pageSize)
if err != nil {
log.Fatalln(err)
}
showMessagesInfo(page, pageSize, listClientMessageInfo)
case "getmsg":
if flag.NArg() < 2 {
@ -81,10 +92,11 @@ func Run() {
if err != nil {
log.Fatalln(err)
}
err = getMsgCommand(clientKeyStore, num)
msg, err := getMsgCommand(clientKeyStore, num)
if err != nil {
printError(err.Error())
}
showMessage(msg)
case "help":
showHelp()
@ -96,6 +108,11 @@ func Run() {
}
func getHTTPClient(tlsConfig *tls.Config) *http.Client {
transport := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: transport}
}
func sendCommand(clientKeyStore cryptoUtils.KeyStore, plainSubject, plainBody, uid string) error {
//Turn content to bytes
plainSubjectBytes, err := Marshal(plainSubject)
@ -107,18 +124,10 @@ func sendCommand(clientKeyStore cryptoUtils.KeyStore, plainSubject, plainBody, u
return err
}
// FIX: adapt to api
cl, err := networking.NewClient[protocol.Packet](&clientKeyStore)
receiverCert, err := getUserCert(clientKeyStore, uid)
if err != nil {
return err
}
defer cl.Connection.Conn.Close()
receiverCert, err := getUserCert(cl, clientKeyStore, uid)
if err != nil {
return err
}
// NOTE: this will stay the same
subject, err := clientKeyStore.EncryptMessageContent(receiverCert, uid, plainSubjectBytes)
if err != nil {
return err
@ -128,159 +137,257 @@ func sendCommand(clientKeyStore cryptoUtils.KeyStore, plainSubject, plainBody, u
return err
}
// FIX: adapt to api
sendMsgPacket := protocol.NewSendMsgPacket(uid, subject, body)
if err := cl.Connection.Send(sendMsgPacket); err != nil {
return err
}
answerSendMsg, err := cl.Connection.Receive()
client := getHTTPClient(clientKeyStore.GetClientTLSConfig())
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return err
return fmt.Errorf("error parsing URL: %v", err)
}
if answerSendMsg.Flag == protocol.FlagReportError {
reportError, err := protocol.UnmarshalReportError(answerSendMsg.Body)
if err != nil {
parsedURL.JoinPath("message")
sendMsgPacket := protocol.NewSendMsg(uid, subject, body)
jsonData, err := json.Marshal(sendMsgPacket)
if err != nil {
return fmt.Errorf("error marshaling JSON: %v", err)
}
//TODO: ADD THE HEADER WITH THE TOKEN
req, err := http.NewRequest("POST", parsedURL.String(), bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response body: %v", err)
}
if resp.StatusCode != 200 {
var reportError protocol.ReportError
if err := json.Unmarshal(responseBody, &reportError); err != nil {
return err
}
return errors.New(reportError.ErrorMessage)
}
return nil
return nil
}
func getMsgCommand(clientKeyStore cryptoUtils.KeyStore, num int) error {
cl, err := networking.NewClient[protocol.Packet](&clientKeyStore)
func getMsgCommand(clientKeyStore cryptoUtils.KeyStore, num int) (ClientMessage, error) {
client := getHTTPClient(clientKeyStore.GetClientTLSConfig())
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return err
return ClientMessage{}, fmt.Errorf("error parsing URL: %v", err)
}
defer cl.Connection.Conn.Close()
packet := protocol.NewGetMsgPacket(num)
if err := cl.Connection.Send(packet); err != nil {
return err
parsedURL.JoinPath("message")
newGetMsg := protocol.NewGetMsg(num)
jsonData, err := json.Marshal(newGetMsg)
if err != nil {
return ClientMessage{}, fmt.Errorf("error marshaling JSON: %v", err)
}
receivedMsgPacket, err := cl.Connection.Receive()
//TODO: ADD THE HEADER WITH THE TOKEN
req, err := http.NewRequest("GET", parsedURL.String(), bytes.NewBuffer(jsonData))
if err != nil {
return err
return ClientMessage{}, fmt.Errorf("error creating request: %v", err)
}
if receivedMsgPacket.Flag == protocol.FlagReportError {
reportError, err := protocol.UnmarshalReportError(receivedMsgPacket.Body)
if err != nil {
return err
resp, err := client.Do(req)
if err != nil {
return ClientMessage{}, fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return ClientMessage{}, fmt.Errorf("error reading response body: %v", err)
}
if resp.StatusCode != 200 {
var reportError protocol.ReportError
if err := json.Unmarshal(body, &reportError); err != nil {
return ClientMessage{}, err
}
return errors.New(reportError.ErrorMessage)
return ClientMessage{}, errors.New(reportError.ErrorMessage)
}
answerGetMsg, err := protocol.UnmarshalAnswerGetMsg(receivedMsgPacket.Body)
var answerGetMsg protocol.AnswerGetMsg
if err := json.Unmarshal(body, &answerGetMsg); err != nil {
return ClientMessage{}, err
}
senderCert, err := getUserCert(clientKeyStore, answerGetMsg.FromUID)
if err != nil {
return err
return ClientMessage{}, err
}
senderCert, err := getUserCert(cl, clientKeyStore, answerGetMsg.FromUID)
oidMap := cryptoUtils.ExtractAllOIDValues(clientKeyStore.GetCert())
myUID := oidMap["2.5.4.65"]
if myUID == "" {
return ClientMessage{}, errors.New("no pseudonym field on my certificate")
}
decSubjectBytes, err := clientKeyStore.DecryptMessageContent(senderCert, myUID, answerGetMsg.Subject)
if err != nil {
return err
return ClientMessage{}, err
}
decSubjectBytes, err := clientKeyStore.DecryptMessageContent(senderCert, answerGetMsg.Subject)
decBodyBytes, err := clientKeyStore.DecryptMessageContent(senderCert, myUID, answerGetMsg.Body)
if err != nil {
return err
return ClientMessage{}, err
}
decBodyBytes, err := clientKeyStore.DecryptMessageContent(senderCert, answerGetMsg.Body)
messageSubject, err := Unmarshal(decSubjectBytes)
if err != nil {
return err
return ClientMessage{}, err
}
subject, err := Unmarshal(decSubjectBytes)
messageBody, err := Unmarshal(decBodyBytes)
if err != nil {
return err
return ClientMessage{}, err
}
body, err := Unmarshal(decBodyBytes)
if err != nil {
return err
}
message := newClientMessage(answerGetMsg.FromUID, answerGetMsg.ToUID, subject, body, answerGetMsg.Timestamp)
showMessage(message)
return nil
message := newClientMessage(answerGetMsg.FromUID, answerGetMsg.ToUID, messageSubject, messageBody, answerGetMsg.Timestamp)
return message, nil
}
func getUserCert(cl networking.Client[protocol.Packet], keyStore cryptoUtils.KeyStore, uid string) (*x509.Certificate, error) {
getUserCertPacket := protocol.NewGetUserCertPacket(uid)
if err := cl.Connection.Send(getUserCertPacket); err != nil {
return nil, err
}
var answerGetUserCertPacket *protocol.Packet
answerGetUserCertPacket, err := cl.Connection.Receive()
func getUserCert(keyStore cryptoUtils.KeyStore, uid string) (*x509.Certificate, error) {
client := getHTTPClient(keyStore.GetClientTLSConfig())
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return nil, err
return nil, fmt.Errorf("error parsing URL: %v", err)
}
if answerGetUserCertPacket.Flag == protocol.FlagReportError {
reportError, err := protocol.UnmarshalReportError(answerGetUserCertPacket.Body)
parsedURL.JoinPath("cert")
parsedURL.JoinPath(uid)
//TODO: ADD THE HEADER WITH THE TOKEN
req, err := http.NewRequest("GET", parsedURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %v", err)
}
if resp.StatusCode == 200 {
var answerGetUserCert protocol.AnswerGetUserCert
if err := json.Unmarshal(body, &answerGetUserCert); err != nil {
return nil, err
}
userCert, err := x509.ParseCertificate(answerGetUserCert.Certificate)
if err != nil {
return nil, err
}
if err := keyStore.CheckCert(userCert, uid, "MSG SERVICE"); err != nil {
return nil, err
}
return userCert, nil
} else {
var reportError protocol.ReportError
if err := json.Unmarshal(body, &reportError); err != nil {
return nil, err
}
return nil, errors.New(reportError.ErrorMessage)
}
answerGetUserCert, err := protocol.UnmarshalAnswerGetUserCert(answerGetUserCertPacket.Body)
if err != nil {
return nil, err
}
userCert, err := x509.ParseCertificate(answerGetUserCert.Certificate)
if err != nil {
return nil, err
}
if err := keyStore.CheckCert(userCert, uid); err != nil {
return nil, err
}
return userCert, nil
}
func getManyMessagesInfo(cl networking.Client[protocol.Packet], keyStore cryptoUtils.KeyStore) (protocol.AnswerGetUnreadMsgsInfo, map[string]*x509.Certificate, error) {
answerGetUnreadMsgsInfoPacket, err := cl.Connection.Receive()
func getUnreadMessagesInfo(keyStore cryptoUtils.KeyStore, page int, pageSize int) (protocol.AnswerGetUnreadMsgsInfo, map[string]*x509.Certificate, error) {
client := getHTTPClient(keyStore.GetClientTLSConfig())
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return protocol.NewAnswerGetUnreadMsgsInfo(0, 0, nil), nil, err
return protocol.AnswerGetUnreadMsgsInfo{}, nil, fmt.Errorf("error parsing URL: %v", err)
}
if answerGetUnreadMsgsInfoPacket.Flag == protocol.FlagReportError {
reportError, err := protocol.UnmarshalReportError(answerGetUnreadMsgsInfoPacket.Body)
if err != nil {
parsedURL.JoinPath("queue")
getUnreadMessagesInfo := protocol.NewGetUnreadMsgsInfo(page, pageSize)
jsonData, err := json.Marshal(getUnreadMessagesInfo)
if err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, fmt.Errorf("error marshaling JSON: %v", err)
}
//TODO: ADD THE HEADER WITH THE TOKEN
req, err := http.NewRequest("GET", parsedURL.String(), bytes.NewBuffer(jsonData))
if err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, fmt.Errorf("error reading response body: %v", err)
}
if resp.StatusCode == 200 {
//Create Set of needed certificates
var answerGetUnreadMsgsInfo protocol.AnswerGetUnreadMsgsInfo
if err := json.Unmarshal(body, &answerGetUnreadMsgsInfo); err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, err
}
return protocol.NewAnswerGetUnreadMsgsInfo(0, 0, nil), nil, errors.New(reportError.ErrorMessage)
}
answerGetUnreadMsgsInfo, err := protocol.UnmarshalAnswerGetUnreadMsgsInfo(answerGetUnreadMsgsInfoPacket.Body)
if err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, err
}
//Create Set of needed certificates
senderSet := map[string]bool{}
for _, messageInfo := range answerGetUnreadMsgsInfo.MessagesInfo {
senderSet[messageInfo.FromUID] = true
}
certificatesMap := map[string]*x509.Certificate{}
//Get senders' certificates
for senderUID := range senderSet {
senderCert, err := getUserCert(cl, keyStore, senderUID)
if err == nil {
certificatesMap[senderUID] = senderCert
senderSet := map[string]bool{}
for _, messageInfo := range answerGetUnreadMsgsInfo.MessagesInfo {
senderSet[messageInfo.FromUID] = true
}
certificatesMap := map[string]*x509.Certificate{}
//Get senders' certificates
for senderUID := range senderSet {
senderCert, err := getUserCert(keyStore, senderUID)
if err == nil {
certificatesMap[senderUID] = senderCert
}
}
return answerGetUnreadMsgsInfo, certificatesMap, nil
} else {
var reportError protocol.ReportError
if err := json.Unmarshal(body, &reportError); err != nil {
return protocol.AnswerGetUnreadMsgsInfo{}, nil, err
}
return protocol.AnswerGetUnreadMsgsInfo{}, nil, errors.New(reportError.ErrorMessage)
}
return answerGetUnreadMsgsInfo, certificatesMap, nil
}
func askQueueCommand(clientKeyStore cryptoUtils.KeyStore, page int, pageSize int) error {
cl, err := networking.NewClient[protocol.Packet](&clientKeyStore)
if err != nil {
return err
}
defer cl.Connection.Conn.Close()
return askQueueRec(cl, clientKeyStore, page, pageSize)
}
func askQueueCommand(clientKeyStore cryptoUtils.KeyStore, page int, pageSize int) (int, int, []ClientMessageInfo, error) {
func askQueueRec(cl networking.Client[protocol.Packet], clientKeyStore cryptoUtils.KeyStore, page int, pageSize int) error {
requestUnreadMsgsQueuePacket := protocol.NewGetUnreadMsgsInfoPacket(page, pageSize)
if err := cl.Connection.Send(requestUnreadMsgsQueuePacket); err != nil {
return err
}
unreadMsgsInfo, certificates, err := getManyMessagesInfo(cl, clientKeyStore)
unreadMsgsInfo, certificates, err := getUnreadMessagesInfo(clientKeyStore, page, pageSize)
if err != nil {
return err
return 0, 0, nil, err
}
var clientMessages []ClientMessageInfo
for _, message := range unreadMsgsInfo.MessagesInfo {
@ -295,7 +402,12 @@ func askQueueRec(cl networking.Client[protocol.Packet], clientKeyStore cryptoUti
clientMessages = append(clientMessages, clientMessageInfo)
continue
}
decryptedSubjectBytes, err := clientKeyStore.DecryptMessageContent(senderCert, message.Subject)
oidMap := cryptoUtils.ExtractAllOIDValues(clientKeyStore.GetCert())
myUID := oidMap["2.5.4.65"]
if myUID == "" {
return 0, 0, nil, errors.New("no pseudonym field on my certificate")
}
decryptedSubjectBytes, err := clientKeyStore.DecryptMessageContent(senderCert, myUID, message.Subject)
if err != nil {
clientMessageInfo = newClientMessageInfo(message.Num, message.FromUID, "", message.Timestamp, err)
clientMessages = append(clientMessages, clientMessageInfo)
@ -315,13 +427,5 @@ func askQueueRec(cl networking.Client[protocol.Packet], clientKeyStore cryptoUti
return clientMessages[i].Num > clientMessages[j].Num
})
action := showMessagesInfo(unreadMsgsInfo.Page, unreadMsgsInfo.NumPages, clientMessages)
switch action {
case -1:
return askQueueRec(cl, clientKeyStore, max(1, unreadMsgsInfo.Page-1), pageSize)
case 1:
return askQueueRec(cl, clientKeyStore, max(1, unreadMsgsInfo.Page+1), pageSize)
default:
return nil
}
return unreadMsgsInfo.Page, unreadMsgsInfo.NumPages, clientMessages, nil
}

View file

@ -0,0 +1,191 @@
package gateway
import (
"PD2/internal/protocol"
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
const baseURL = "https://127.0.0.1:8080"
func getHTTPClient(tlsConfig *tls.Config) *http.Client{
transport := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: transport}
}
func forwardStoreUserCert(tlsConfig *tls.Config,uid string,storeUserCertificate protocol.StoreUserCert) (int,[]byte,error) {
client := getHTTPClient(tlsConfig)
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return 0,nil,fmt.Errorf("error parsing URL: %v", err)
}
parsedURL.JoinPath("certs")
parsedURL.JoinPath(uid)
jsonData, err := json.Marshal(storeUserCertificate)
if err != nil {
return 0,nil,fmt.Errorf("error marshaling JSON: %v", err)
}
req, err := http.NewRequest("POST", parsedURL.String(), bytes.NewBuffer(jsonData))
if err != nil {
return 0,nil,fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return 0,nil,fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0,nil,fmt.Errorf("error reading response body: %v", err)
}
return resp.StatusCode,body,nil
}
func forwardGetMessage(tlsConfig *tls.Config,uid string,getMsg protocol.GetMsg) (int,[]byte,error) {
client := getHTTPClient(tlsConfig)
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return 0,nil,fmt.Errorf("error parsing URL: %v", err)
}
parsedURL.JoinPath("message")
parsedURL.JoinPath(uid)
parsedURL.JoinPath(fmt.Sprint(getMsg.Num))
req, err := http.NewRequest("GET", parsedURL.String(), nil)
if err != nil {
return 0,nil,fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return 0,nil,fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0,nil,fmt.Errorf("error reading response body: %v", err)
}
return resp.StatusCode,body,nil
}
func forwardGetUnreadMsgsInfo(tlsConfig *tls.Config,uid string,getUnreadMsgsInfo protocol.GetUnreadMsgsInfo) (int,[]byte,error) {
client := getHTTPClient(tlsConfig)
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return 0,nil,fmt.Errorf("error parsing URL: %v", err)
}
parsedURL.JoinPath("queue")
parsedURL.JoinPath(uid)
query := parsedURL.Query()
query.Set("page", fmt.Sprint(getUnreadMsgsInfo.Page))
query.Set("pagesize", fmt.Sprint(getUnreadMsgsInfo.PageSize))
parsedURL.RawQuery = query.Encode()
req, err := http.NewRequest("GET", parsedURL.String(), nil)
if err != nil {
return 0,nil,fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return 0,nil,fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0,nil,fmt.Errorf("error reading response body: %v", err)
}
return resp.StatusCode,body,nil
}
func forwardGetUserCert(tlsConfig *tls.Config,getUserCert protocol.GetUserCert) (int,[]byte,error) {
client := getHTTPClient(tlsConfig)
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return 0,nil,fmt.Errorf("error parsing URL: %v", err)
}
parsedURL.JoinPath("cert")
parsedURL.JoinPath(getUserCert.UID)
req, err := http.NewRequest("GET", parsedURL.String(), nil)
if err != nil {
return 0,nil,fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return 0,nil,fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0,nil,fmt.Errorf("error reading response body: %v", err)
}
return resp.StatusCode,body,nil
}
func forwardSendMessage(tlsConfig *tls.Config,uid string,sendMsg protocol.SendMsg) (int,[]byte,error) {
client := getHTTPClient(tlsConfig)
// Parse the base URL
parsedURL, err := url.Parse(baseURL)
if err != nil {
return 0,nil,fmt.Errorf("error parsing URL: %v", err)
}
parsedURL.JoinPath("message")
parsedURL.JoinPath(uid)
jsonData, err := json.Marshal(sendMsg)
if err != nil {
return 0,nil,fmt.Errorf("error marshaling JSON: %v", err)
}
req, err := http.NewRequest("POST", parsedURL.String(), bytes.NewBuffer(jsonData))
if err != nil {
return 0,nil,fmt.Errorf("error creating request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
return 0,nil,fmt.Errorf("error making request: %v", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0,nil,fmt.Errorf("error reading response body: %v", err)
}
return resp.StatusCode,body,nil
}

View file

@ -4,28 +4,96 @@ import (
"PD2/internal/protocol"
"PD2/internal/utils/cryptoUtils"
"crypto/x509"
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func HandleGetMessage(c *gin.Context) {
fmt.Println("Get Message Handler")
func HandleGetMessage(c *gin.Context, keyStore cryptoUtils.KeyStore) {
var getMsg protocol.GetMsg
err := c.Bind(getMsg)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Request body is not a GetMsg"})
return
}
uid, exists := c.Get("uid")
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "User does not exist"})
return
}
uidString := uid.(string)
statusCode, body, err := forwardGetMessage(keyStore.GetGatewayOutgoingTLSConfig(), uidString, getMsg)
if err != nil {
log.Println(err.Error())
} else {
c.JSON(statusCode, body)
}
}
func HandleGetUnreadMsgsInfo(c *gin.Context, keyStore cryptoUtils.KeyStore) {
var getUnreadMsgsInfo protocol.GetUnreadMsgsInfo
err := c.Bind(getUnreadMsgsInfo)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Request body is not a GetUnreadMsgsInfo"})
return
}
uid, exists := c.Get("uid")
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "User does not exist"})
return
}
uidString := uid.(string)
statusCode, body, err := forwardGetUnreadMsgsInfo(keyStore.GetGatewayOutgoingTLSConfig(), uidString, getUnreadMsgsInfo)
if err != nil {
log.Println(err.Error())
} else {
c.JSON(statusCode, body)
}
}
func HandleGetUnreadMsgsInfo(c *gin.Context) {
fmt.Println("Get Unread Messages Info Handler")
func HandleGetUserCert(c *gin.Context,keyStore cryptoUtils.KeyStore) {
var getUserCert protocol.GetUserCert
err := c.Bind(getUserCert)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Request body is not a GetUserCert"})
return
}
statusCode, body, err := forwardGetUserCert(keyStore.GetGatewayOutgoingTLSConfig(), getUserCert)
if err != nil {
log.Println(err.Error())
} else {
c.JSON(statusCode, body)
}
}
func HandleGetUserCert(c *gin.Context) {
fmt.Println("Get User Cert Handler")
func HandleSendMessage(c *gin.Context, keyStore cryptoUtils.KeyStore) {
var sendMsg protocol.SendMsg
err := c.Bind(sendMsg)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Request body is not a SendMsg"})
return
}
}
func HandleSendMessage(c *gin.Context) {
fmt.Println("Send Message Handler")
uid, exists := c.Get("uid")
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "User does not exist"})
return
}
uidString := uid.(string)
statusCode, body, err := forwardSendMessage(keyStore.GetGatewayOutgoingTLSConfig(), uidString, sendMsg)
if err != nil {
log.Println(err.Error())
} else {
c.JSON(statusCode, body)
}
}
func HandleRegister(c *gin.Context, dataStore DataStore, keyStore cryptoUtils.KeyStore) {
@ -36,22 +104,12 @@ func HandleRegister(c *gin.Context, dataStore DataStore, keyStore cryptoUtils.Ke
return
}
//Check if the certificate pseudonym matches the uid in postRegister
//And if it's signed by the CA
userCert, err := x509.ParseCertificate(postRegister.Certificate)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "User certificate is invalid"})
return
}
oidMap := cryptoUtils.ExtractAllOIDValues(userCert)
//Check if certificate usage is MSG SERVICE
usage := oidMap["2.5.4.11"]
if usage != "MSG SERVICE" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Certificate usage is not \"MSG SERVICE\""})
return
}
err = keyStore.CheckCert(userCert, postRegister.UID, "MSG SERVICE")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "User certificate is invalid, not trusted, belongs to another user or has incorrect usage field"})
@ -68,9 +126,13 @@ func HandleRegister(c *gin.Context, dataStore DataStore, keyStore cryptoUtils.Ke
log.Fatalln("Could not insert user into DB")
}
//TODO: Send the certificate to the server
c.JSON(http.StatusOK, gin.H{})
storeUserCertificate := protocol.NewStoreUserCert(userCert.Raw)
statusCode, body, err := forwardStoreUserCert(keyStore.GetGatewayOutgoingTLSConfig(), postRegister.UID, storeUserCertificate)
if err != nil {
log.Println(err.Error())
} else {
c.JSON(statusCode, body)
}
}
@ -101,7 +163,6 @@ func HandleLogin(c *gin.Context, dataStore DataStore, keyStore cryptoUtils.KeySt
}
func AuthMiddleware(c *gin.Context) {
fmt.Println("Authentication Middleware")
tokenList := c.Request.Header["Token"]
if tokenList == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "No authentication token provided"})
@ -137,19 +198,19 @@ func Run() {
})
auth.GET("/message/:num", func(c *gin.Context) {
HandleGetMessage(c)
HandleGetMessage(c, keyStore)
})
auth.GET("/queue", func(c *gin.Context) {
HandleGetUnreadMsgsInfo(c)
HandleGetUnreadMsgsInfo(c, keyStore)
})
auth.GET("/cert/:user", func(c *gin.Context) {
HandleGetUserCert(c)
HandleGetUserCert(c, keyStore)
})
auth.POST("/message", func(c *gin.Context) {
HandleSendMessage(c)
HandleSendMessage(c, keyStore)
})
router.POST("/register", func(c *gin.Context) {
@ -161,7 +222,7 @@ func Run() {
})
server := http.Server{
Addr: "0.0.0.0:8080",
Addr: "0.0.0.0:9090",
Handler: router,
TLSConfig: keyStore.GetGatewayIncomingTLSConfig(),
}

View file

@ -31,6 +31,10 @@ type (
Certificate []byte `json:"certificate"`
}
StoreUserCert struct {
Certificate []byte `json:"certificate"`
}
AnswerGetUnreadMsgsInfo struct {
Page int `json:"page"`
NumPages int `json:"num_pages"`
@ -59,8 +63,8 @@ type (
}
PostLogin struct {
UID string `json:"uid"`
Password string `json:"password"`
UID string `json:"uid"`
Password string `json:"password"`
}
ReportError struct {
@ -113,19 +117,24 @@ func NewMsgInfo(num int, fromUID string, subject []byte, timestamp time.Time) Ms
}
}
func NewPostRegister(UID string,Password string,Certificate []byte) PostRegister {
return PostRegister{
UID: UID,
Password: Password,
Certificate: Certificate,
}
func NewPostRegister(UID string, Password string, Certificate []byte) PostRegister {
return PostRegister{
UID: UID,
Password: Password,
Certificate: Certificate,
}
}
func NewStoreUserCert(certificate []byte) StoreUserCert {
return StoreUserCert{
Certificate: certificate,
}
}
func NewPostLogin(UID string,Password string) PostLogin {
return PostLogin{
UID: UID,
Password: Password,
}
func NewPostLogin(UID string, Password string) PostLogin {
return PostLogin{
UID: UID,
Password: Password,
}
}
func NewAnswerGetMsg(fromUID, toUID string, subject []byte, body []byte, timestamp time.Time, last bool) AnswerGetMsg {

View file

@ -226,11 +226,6 @@ func (ds DataStore) userExists(uid string) bool {
}
func (ds DataStore) storeUserCertIfNotExists(uid string, cert x509.Certificate) error {
// Check if the user already exists
if ds.userExists(uid) {
return nil
}
// Insert the user certificate
insertQuery := `
INSERT INTO users (UID, userCert)

View file

@ -3,6 +3,7 @@ package server
import (
"PD2/internal/protocol"
"PD2/internal/utils/cryptoUtils"
"crypto/x509"
"log"
"net/http"
"strconv"
@ -20,20 +21,58 @@ func HandleGetUserCert(c *gin.Context, dataStore DataStore) {
}
}
func HandleGetUnreadMsgsInfo(c *gin.Context, dataStore DataStore) {
func HandleStoreUserCert(c *gin.Context, dataStore DataStore) {
user := c.Param("user")
var getUnreadMsgsInfo protocol.GetUnreadMsgsInfo
if err := c.BindJSON(getUnreadMsgsInfo); err != nil {
var storeUserCert protocol.StoreUserCert
if err := c.Bind(storeUserCert); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if getUnreadMsgsInfo.Page <= 0 || getUnreadMsgsInfo.PageSize <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page and PageSize need to be >= 1"})
userCert, err := x509.ParseCertificate(storeUserCert.Certificate)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "User certificate is invalid"})
return
}
unreadMsgsInfo, err := dataStore.GetUnreadMsgsInfo(user, getUnreadMsgsInfo.Page, getUnreadMsgsInfo.PageSize)
err = dataStore.storeUserCertIfNotExists(user, *userCert)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "User already has a certificate stored in the database"})
return
}
c.JSON(http.StatusOK, gin.H{})
}
func HandleGetUnreadMsgsInfo(c *gin.Context, dataStore DataStore) {
user := c.Param("user")
pageStr := c.Query("page")
pagesizeStr := c.Query("pagesize")
var page int
var err error
if pageStr != "" {
page, err = strconv.Atoi(pageStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page is not a number"})
}
} else {
page = 1
}
var pagesize int
if pagesizeStr != "" {
pagesize, err = strconv.Atoi(pagesizeStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Pagesize is not a number"})
}
} else {
pagesize = 5
}
if page <= 0 || pagesize <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page and Pagesize need to be >= 1"})
return
}
unreadMsgsInfo, err := dataStore.GetUnreadMsgsInfo(user, page, pagesize)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@ -115,15 +154,19 @@ func Run() {
HandleSendMessage(c, dataStore)
})
r.POST("/cert/:user", func(c *gin.Context) {
HandleStoreUserCert(c, dataStore)
})
server := http.Server{
Addr: "0.0.0.0:8080",
Handler: r,
//TODO: Verify if it's the gateway
Addr: "0.0.0.0:8080",
Handler: r,
//TODO: Verify if it's the gateway
TLSConfig: serverKeyStore.GetServerTLSConfig(),
}
err = server.ListenAndServeTLS("", "")
if err!=nil {
log.Fatal(err.Error())
}
if err != nil {
log.Fatal(err.Error())
}
}

View file

@ -11,7 +11,6 @@ import (
"errors"
"time"
"log"
"os"
"golang.org/x/crypto/chacha20poly1305"
@ -143,25 +142,7 @@ func (k *KeyStore) GetTLSConfig() *tls.Config {
func (k *KeyStore) GetGatewayIncomingTLSConfig() *tls.Config {
tlsConfig := k.GetTLSConfig()
tlsConfig.ClientAuth = tls.RequireAnyClientCert
tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
for _, certBytes := range rawCerts {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return err
}
if err = k.CheckCertCA(cert); err != nil {
return err
}
if err = k.CheckCertTime(cert); err != nil {
return err
}
if err = k.CheckCertUsage(cert, "MSG SERVICE"); err != nil {
return err
}
}
return nil
}
tlsConfig.ClientAuth = tls.NoClientCert
return tlsConfig
}

View file

@ -1,23 +0,0 @@
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

@ -1,51 +0,0 @@
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

@ -1,56 +0,0 @@
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
}
}