Matrix/entities/device/keyController.go

91 lines
2.3 KiB
Go
Raw Normal View History

2020-10-11 21:11:30 +00:00
package device
import (
2020-10-17 10:07:39 +00:00
"bytes"
"encoding/base64"
2020-10-11 21:11:30 +00:00
"encoding/json"
"fmt"
"net/http"
2020-10-17 10:07:39 +00:00
"time"
2020-10-11 21:11:30 +00:00
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
}
2020-10-17 10:07:39 +00:00
response := ServerKeys{
2020-10-11 21:11:30 +00:00
ServerName: config.Homeserver,
VerifyKeys: make(map[string]verifyKey),
}
2020-10-17 10:07:39 +00:00
response.VerifyKeys[config.KeyId] = verifyKey{Key: base64.RawStdEncoding.EncodeToString(config.PublicKey)}
2020-10-11 21:11:30 +00:00
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-17 10:07:39 +00:00
func GetVerifyKey(server string, id string) (key []byte, err error) {
2020-10-11 21:11:30 +00:00
if val, ok := config.VerifyKeys[server][id]; ok {
key = val
} else {
2020-10-17 10:07:39 +00:00
requestUrl := fmt.Sprintf("%s://%s/_matrix/key/v2/server", config.HttpString, server)
client := &http.Client{Timeout: 2 * time.Second}
var req *http.Request
req, err = http.NewRequest(http.MethodGet, requestUrl, bytes.NewBuffer(nil))
if err != nil {
return
}
2020-10-11 21:11:30 +00:00
var res *http.Response
2020-10-17 10:07:39 +00:00
res, err = client.Do(req)
2020-10-11 21:11:30 +00:00
if err != nil {
return
}
2020-10-17 10:07:39 +00:00
if res.StatusCode != http.StatusOK {
utils.HandleHTTPError(res)
}
serverKeyRes := ServerKeys{}
2020-10-11 21:11:30 +00:00
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&serverKeyRes)
config.VerifyKeys[server] = make(map[string][]byte)
for keyId, verifyKey := range serverKeyRes.VerifyKeys {
2020-10-17 10:07:39 +00:00
verifyKeyBytes, err := base64.RawStdEncoding.DecodeString(verifyKey.Key)
if err == nil {
config.VerifyKeys[server][keyId] = verifyKeyBytes
if id == keyId {
key = verifyKeyBytes
}
2020-10-11 21:11:30 +00:00
}
}
}
return
}