2021-12-19 06:37:18 +01:00
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
2022-11-27 19:20:29 +01:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-12-19 06:37:18 +01:00
|
|
|
|
|
|
|
package asymkey
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-10-14 10:37:24 +02:00
|
|
|
"context"
|
2021-12-19 06:37:18 +01:00
|
|
|
|
|
|
|
"code.gitea.io/gitea/models/db"
|
|
|
|
"code.gitea.io/gitea/modules/log"
|
2021-12-20 18:58:38 +01:00
|
|
|
|
2021-12-19 06:37:18 +01:00
|
|
|
"github.com/42wim/sshsig"
|
|
|
|
)
|
|
|
|
|
|
|
|
// VerifySSHKey marks a SSH key as verified
|
2023-10-14 10:37:24 +02:00
|
|
|
func VerifySSHKey(ctx context.Context, ownerID int64, fingerprint, token, signature string) (string, error) {
|
|
|
|
ctx, committer, err := db.TxContext(ctx)
|
2021-12-19 06:37:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer committer.Close()
|
|
|
|
|
|
|
|
key := new(PublicKey)
|
|
|
|
|
|
|
|
has, err := db.GetEngine(ctx).Where("owner_id = ? AND fingerprint = ?", ownerID, fingerprint).Get(key)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
} else if !has {
|
|
|
|
return "", ErrKeyNotExist{}
|
|
|
|
}
|
|
|
|
|
2023-12-14 03:39:32 +01:00
|
|
|
err = sshsig.Verify(bytes.NewBuffer([]byte(token)), []byte(signature), []byte(key.Content), "gitea")
|
|
|
|
if err != nil {
|
|
|
|
// edge case for Windows based shells that will add CR LF if piped to ssh-keygen command
|
|
|
|
// see https://github.com/PowerShell/PowerShell/issues/5974
|
|
|
|
if sshsig.Verify(bytes.NewBuffer([]byte(token+"\r\n")), []byte(signature), []byte(key.Content), "gitea") != nil {
|
|
|
|
log.Error("Unable to validate token signature. Error: %v", err)
|
|
|
|
return "", ErrSSHInvalidTokenSignature{
|
|
|
|
Fingerprint: key.Fingerprint,
|
|
|
|
}
|
2021-12-19 06:37:18 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
key.Verified = true
|
|
|
|
if _, err := db.GetEngine(ctx).ID(key.ID).Cols("verified").Update(key); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := committer.Commit(); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return key.Fingerprint, nil
|
|
|
|
}
|