90 lines
2.3 KiB
Go
90 lines
2.3 KiB
Go
package device
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.nutfactory.org/hoernschen/Matrix/config"
|
|
"git.nutfactory.org/hoernschen/Matrix/utils"
|
|
)
|
|
|
|
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: base64.RawStdEncoding.EncodeToString(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)
|
|
}
|
|
}
|
|
|
|
func GetVerifyKey(server string, id string) (key []byte, err error) {
|
|
if val, ok := config.VerifyKeys[server][id]; ok {
|
|
key = val
|
|
} else {
|
|
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
|
|
}
|
|
var res *http.Response
|
|
res, err = client.Do(req)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
utils.HandleHTTPError(res)
|
|
}
|
|
serverKeyRes := ServerKeys{}
|
|
decoder := json.NewDecoder(res.Body)
|
|
err = decoder.Decode(&serverKeyRes)
|
|
config.VerifyKeys[server] = make(map[string][]byte)
|
|
for keyId, verifyKey := range serverKeyRes.VerifyKeys {
|
|
verifyKeyBytes, err := base64.RawStdEncoding.DecodeString(verifyKey.Key)
|
|
if err == nil {
|
|
config.VerifyKeys[server][keyId] = verifyKeyBytes
|
|
if id == keyId {
|
|
key = verifyKeyBytes
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return
|
|
}
|