@@ -17,21 +17,9 @@ import (
1717 "code.gitea.io/gitea/modules/log"
1818 "code.gitea.io/gitea/modules/setting"
1919 "code.gitea.io/gitea/modules/util"
20+ "golang.org/x/crypto/ssh"
2021)
2122
22- // _____ __ .__ .__ .___
23- // / _ \ __ ___/ |_| |__ ___________|__|_______ ____ __| _/
24- // / /_\ \| | \ __\ | \ / _ \_ __ \ \___ // __ \ / __ |
25- // / | \ | /| | | Y ( <_> ) | \/ |/ /\ ___// /_/ |
26- // \____|__ /____/ |__| |___| /\____/|__| |__/_____ \\___ >____ |
27- // \/ \/ \/ \/ \/
28- // ____ __.
29- // | |/ _|____ ___.__. ______
30- // | <_/ __ < | |/ ___/
31- // | | \ ___/\___ |\___ \
32- // |____|__ \___ > ____/____ >
33- // \/ \/\/ \/
34- //
3523// This file contains functions for creating authorized_keys files
3624//
3725// There is a dependence on the database within RegeneratePublicKeys however most of these functions probably belong in a module
@@ -49,6 +37,23 @@ func WithSSHOpLocker(f func() error) error {
4937 return f ()
5038}
5139
40+ // removeSSHKeyComment removes the trailing comment from an SSH public key line.
41+ func removeSSHKeyComment (pubKeyLine string ) (string , error ) {
42+ pubKeyLine = strings .TrimSpace (pubKeyLine )
43+ if pubKeyLine == "" || strings .HasPrefix (pubKeyLine , "#" ) {
44+ return pubKeyLine , nil
45+ }
46+
47+ pubKey , _ , _ , _ , err := ssh .ParseAuthorizedKey ([]byte (pubKeyLine ))
48+ if err != nil {
49+ return "" , fmt .Errorf ("invalid public key: %w" , err )
50+ }
51+
52+ // MarshalAuthorizedKey returns "<type> <base64>\n"
53+ key := strings .TrimSpace (string (ssh .MarshalAuthorizedKey (pubKey )))
54+ return key , nil
55+ }
56+
5257// AuthorizedStringForKey creates the authorized keys string appropriate for the provided key
5358func AuthorizedStringForKey (key * PublicKey ) string {
5459 sb := & strings.Builder {}
@@ -60,7 +65,13 @@ func AuthorizedStringForKey(key *PublicKey) string {
6065 "Key" : key ,
6166 })
6267
63- return fmt .Sprintf (tplPublicKey , util .ShellEscape (sb .String ()), key .Content )
68+ content , err := removeSSHKeyComment (key .Content )
69+ if err != nil {
70+ log .Error ("Failed to remove comment from SSH key ID %d: %v" , key .ID , err )
71+ content = key .Content
72+ }
73+
74+ return fmt .Sprintf (tplPublicKey , util .ShellEscape (sb .String ()), content )
6475}
6576
6677// appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
0 commit comments