2020-10-11 21:11:30 +00:00
|
|
|
package device
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2020-10-12 14:16:28 +00:00
|
|
|
"git.nutfactory.org/hoernschen/Matrix/config"
|
|
|
|
"git.nutfactory.org/hoernschen/Matrix/utils"
|
2020-10-11 21:11:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func InitServerSigningKey() (err error) {
|
|
|
|
publicKey, privateKey, err := utils.GenerateKeyPair()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
config.PublicKey = publicKey
|
|
|
|
config.PrivateKey = privateKey
|
|
|
|
config.KeyId = "ed25519:1"
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetServerSigningKeyHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if config.PublicKey == nil {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Server Signing Key Missing"}); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
response := serverKeys{
|
|
|
|
ServerName: config.Homeserver,
|
|
|
|
VerifyKeys: make(map[string]verifyKey),
|
|
|
|
}
|
|
|
|
response.VerifyKeys[config.KeyId] = verifyKey{Key: string(config.PublicKey)}
|
|
|
|
content, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: fmt.Sprintf("Error creating Signatures: %s", err)}); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
response.Signatures = utils.SignContent(content)
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-12 14:16:28 +00:00
|
|
|
// TODO: Use Function
|
2020-10-11 21:11:30 +00:00
|
|
|
func getVerifyKey(server string, id string) (key []byte, err error) {
|
|
|
|
if val, ok := config.VerifyKeys[server][id]; ok {
|
|
|
|
key = val
|
|
|
|
} else {
|
|
|
|
httpString := "https"
|
|
|
|
requestUrl := fmt.Sprintf("%s://%s/_matrix/key/v2/server", httpString, server)
|
|
|
|
var res *http.Response
|
|
|
|
res, err = http.Get(requestUrl)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
serverKeyRes := serverKeys{}
|
|
|
|
decoder := json.NewDecoder(res.Body)
|
|
|
|
err = decoder.Decode(&serverKeyRes)
|
|
|
|
config.VerifyKeys[server] = make(map[string][]byte)
|
|
|
|
for keyId, verifyKey := range serverKeyRes.VerifyKeys {
|
|
|
|
config.VerifyKeys[server][keyId] = []byte(verifyKey.Key)
|
|
|
|
if id == keyId {
|
|
|
|
key = []byte(verifyKey.Key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|