code.gitea.io/gitea@v1.21.7/models/asymkey/ssh_key_verify.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package asymkey 5 6 import ( 7 "bytes" 8 9 "code.gitea.io/gitea/models/db" 10 "code.gitea.io/gitea/modules/log" 11 12 "github.com/42wim/sshsig" 13 ) 14 15 // VerifySSHKey marks a SSH key as verified 16 func VerifySSHKey(ownerID int64, fingerprint, token, signature string) (string, error) { 17 ctx, committer, err := db.TxContext(db.DefaultContext) 18 if err != nil { 19 return "", err 20 } 21 defer committer.Close() 22 23 key := new(PublicKey) 24 25 has, err := db.GetEngine(ctx).Where("owner_id = ? AND fingerprint = ?", ownerID, fingerprint).Get(key) 26 if err != nil { 27 return "", err 28 } else if !has { 29 return "", ErrKeyNotExist{} 30 } 31 32 err = sshsig.Verify(bytes.NewBuffer([]byte(token)), []byte(signature), []byte(key.Content), "gitea") 33 if err != nil { 34 // edge case for Windows based shells that will add CR LF if piped to ssh-keygen command 35 // see https://github.com/PowerShell/PowerShell/issues/5974 36 if sshsig.Verify(bytes.NewBuffer([]byte(token+"\r\n")), []byte(signature), []byte(key.Content), "gitea") != nil { 37 log.Error("Unable to validate token signature. Error: %v", err) 38 return "", ErrSSHInvalidTokenSignature{ 39 Fingerprint: key.Fingerprint, 40 } 41 } 42 } 43 44 key.Verified = true 45 if _, err := db.GetEngine(ctx).ID(key.ID).Cols("verified").Update(key); err != nil { 46 return "", err 47 } 48 49 if err := committer.Commit(); err != nil { 50 return "", err 51 } 52 53 return key.Fingerprint, nil 54 }