auth.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package auth
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/ed25519"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "log/slog"
  13. "os"
  14. "path/filepath"
  15. "golang.org/x/crypto/ssh"
  16. )
  17. const defaultPrivateKey = "id_ed25519"
  18. func privateKey() (ssh.Signer, error) {
  19. home, err := os.UserHomeDir()
  20. if err != nil {
  21. return nil, err
  22. }
  23. keyPath := filepath.Join(home, ".ollama", defaultPrivateKey)
  24. privateKeyFile, err := os.ReadFile(keyPath)
  25. if errors.Is(err, os.ErrNotExist) {
  26. err := initializeKeypair()
  27. if err != nil {
  28. return nil, err
  29. }
  30. return privateKey()
  31. } else if err != nil {
  32. slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
  33. return nil, err
  34. }
  35. return ssh.ParsePrivateKey(privateKeyFile)
  36. }
  37. func GetPublicKey() (ssh.PublicKey, error) {
  38. // try to read pubkey first
  39. home, err := os.UserHomeDir()
  40. if err != nil {
  41. return nil, err
  42. }
  43. pubkeyPath := filepath.Join(home, ".ollama", defaultPrivateKey+".pub")
  44. pubKeyFile, err := os.ReadFile(pubkeyPath)
  45. if errors.Is(err, os.ErrNotExist) {
  46. // try from privateKey
  47. privateKey, err := privateKey()
  48. if err != nil {
  49. return nil, fmt.Errorf("failed to read public key: %w", err)
  50. }
  51. return privateKey.PublicKey(), nil
  52. } else if err != nil {
  53. return nil, fmt.Errorf("failed to read public key: %w", err)
  54. }
  55. pubKey, _, _, _, err := ssh.ParseAuthorizedKey(pubKeyFile)
  56. return pubKey, err
  57. }
  58. func NewNonce(r io.Reader, length int) (string, error) {
  59. nonce := make([]byte, length)
  60. if _, err := io.ReadFull(r, nonce); err != nil {
  61. return "", err
  62. }
  63. return base64.RawURLEncoding.EncodeToString(nonce), nil
  64. }
  65. func Sign(ctx context.Context, bts []byte) (string, error) {
  66. privateKey, err := privateKey()
  67. if err != nil {
  68. return "", err
  69. }
  70. // get the pubkey, but remove the type
  71. publicKey, err := GetPublicKey()
  72. if err != nil {
  73. return "", err
  74. }
  75. publicKeyBytes := ssh.MarshalAuthorizedKey(publicKey)
  76. parts := bytes.Split(publicKeyBytes, []byte(" "))
  77. if len(parts) < 2 {
  78. return "", fmt.Errorf("malformed public key")
  79. }
  80. signedData, err := privateKey.Sign(rand.Reader, bts)
  81. if err != nil {
  82. return "", err
  83. }
  84. // signature is <pubkey>:<signature>
  85. return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
  86. }
  87. func initializeKeypair() error {
  88. home, err := os.UserHomeDir()
  89. if err != nil {
  90. return err
  91. }
  92. privKeyPath := filepath.Join(home, ".ollama", "id_ed25519")
  93. pubKeyPath := filepath.Join(home, ".ollama", "id_ed25519.pub")
  94. _, err = os.Stat(privKeyPath)
  95. if errors.Is(err, os.ErrNotExist) {
  96. fmt.Printf("Couldn't find '%s'. Generating new private key.\n", privKeyPath)
  97. cryptoPublicKey, cryptoPrivateKey, err := ed25519.GenerateKey(rand.Reader)
  98. if err != nil {
  99. return err
  100. }
  101. privateKeyBytes, err := ssh.MarshalPrivateKey(cryptoPrivateKey, "")
  102. if err != nil {
  103. return err
  104. }
  105. if err := os.MkdirAll(filepath.Dir(privKeyPath), 0o755); err != nil {
  106. return fmt.Errorf("could not create directory %w", err)
  107. }
  108. if err := os.WriteFile(privKeyPath, pem.EncodeToMemory(privateKeyBytes), 0o600); err != nil {
  109. return err
  110. }
  111. sshPublicKey, err := ssh.NewPublicKey(cryptoPublicKey)
  112. if err != nil {
  113. return err
  114. }
  115. publicKeyBytes := ssh.MarshalAuthorizedKey(sshPublicKey)
  116. if err := os.WriteFile(pubKeyPath, publicKeyBytes, 0o644); err != nil {
  117. return err
  118. }
  119. fmt.Printf("Your new public key is: \n\n%s\n", publicKeyBytes)
  120. }
  121. return nil
  122. }