2021-07-24 11:16:34 +01:00
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-07-24 11:16:34 +01:00
|
|
|
|
2021-12-10 16:14:24 +08:00
|
|
|
package asymkey
|
2021-07-24 11:16:34 +01:00
|
|
|
|
|
|
|
|
import (
|
2022-05-20 22:08:52 +08:00
|
|
|
"context"
|
2021-07-24 11:16:34 +01:00
|
|
|
"fmt"
|
|
|
|
|
|
2021-09-19 19:49:59 +08:00
|
|
|
"code.gitea.io/gitea/models/db"
|
2021-11-17 20:34:35 +08:00
|
|
|
|
2021-07-24 11:16:34 +01:00
|
|
|
"golang.org/x/crypto/ssh"
|
2023-12-07 15:27:36 +08:00
|
|
|
"xorm.io/builder"
|
2021-07-24 11:16:34 +01:00
|
|
|
)
|
|
|
|
|
|
2025-07-12 15:13:01 +08:00
|
|
|
// The database is used in checkKeyFingerprint. However, most of these functions probably belong in a module
|
2021-07-24 11:16:34 +01:00
|
|
|
|
2025-07-12 15:13:01 +08:00
|
|
|
// checkKeyFingerprint only checks if key fingerprint has been used as a public key,
|
2021-07-24 11:16:34 +01:00
|
|
|
// it is OK to use same key as deploy key for multiple repositories/users.
|
2022-05-20 22:08:52 +08:00
|
|
|
func checkKeyFingerprint(ctx context.Context, fingerprint string) error {
|
2023-12-07 15:27:36 +08:00
|
|
|
has, err := db.Exist[PublicKey](ctx, builder.Eq{"fingerprint": fingerprint})
|
2021-07-24 11:16:34 +01:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
} else if has {
|
|
|
|
|
return ErrKeyAlreadyExist{0, fingerprint, ""}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func calcFingerprintNative(publicKeyContent string) (string, error) {
|
|
|
|
|
// Calculate fingerprint.
|
|
|
|
|
pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
return ssh.FingerprintSHA256(pk), nil
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-05 03:18:50 +08:00
|
|
|
// CalcFingerprint calculate public key's fingerprint
|
|
|
|
|
func CalcFingerprint(publicKeyContent string) (string, error) {
|
2025-04-08 09:15:28 -07:00
|
|
|
fp, err := calcFingerprintNative(publicKeyContent)
|
2021-07-24 11:16:34 +01:00
|
|
|
if err != nil {
|
|
|
|
|
if IsErrKeyUnableVerify(err) {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
2025-04-08 09:15:28 -07:00
|
|
|
return "", fmt.Errorf("CalcFingerprint: %w", err)
|
2021-07-24 11:16:34 +01:00
|
|
|
}
|
|
|
|
|
return fp, nil
|
|
|
|
|
}
|