auth.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package auth
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/base64"
  7. "fmt"
  8. "io"
  9. "log/slog"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "golang.org/x/crypto/ssh"
  14. )
  15. const defaultPrivateKey = "id_ed25519"
  16. func keyPath() (string, error) {
  17. home, err := os.UserHomeDir()
  18. if err != nil {
  19. return "", err
  20. }
  21. return filepath.Join(home, ".ollama", defaultPrivateKey), nil
  22. }
  23. func GetPublicKey() (string, error) {
  24. keyPath, err := keyPath()
  25. if err != nil {
  26. return "", err
  27. }
  28. privateKeyFile, err := os.ReadFile(keyPath)
  29. if err != nil {
  30. slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
  31. return "", err
  32. }
  33. privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
  34. if err != nil {
  35. return "", err
  36. }
  37. publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
  38. return strings.TrimSpace(string(publicKey)), nil
  39. }
  40. func NewNonce(r io.Reader, length int) (string, error) {
  41. nonce := make([]byte, length)
  42. if _, err := io.ReadFull(r, nonce); err != nil {
  43. return "", err
  44. }
  45. return base64.RawURLEncoding.EncodeToString(nonce), nil
  46. }
  47. func Sign(ctx context.Context, bts []byte) (string, error) {
  48. keyPath, err := keyPath()
  49. if err != nil {
  50. return "", err
  51. }
  52. privateKeyFile, err := os.ReadFile(keyPath)
  53. if err != nil {
  54. slog.Info(fmt.Sprintf("Failed to load private key: %v", err))
  55. return "", err
  56. }
  57. privateKey, err := ssh.ParsePrivateKey(privateKeyFile)
  58. if err != nil {
  59. return "", err
  60. }
  61. // get the pubkey, but remove the type
  62. publicKey := ssh.MarshalAuthorizedKey(privateKey.PublicKey())
  63. parts := bytes.Split(publicKey, []byte(" "))
  64. if len(parts) < 2 {
  65. return "", fmt.Errorf("malformed public key")
  66. }
  67. signedData, err := privateKey.Sign(rand.Reader, bts)
  68. if err != nil {
  69. return "", err
  70. }
  71. // signature is <pubkey>:<signature>
  72. return fmt.Sprintf("%s:%s", bytes.TrimSpace(parts[1]), base64.StdEncoding.EncodeToString(signedData.Blob)), nil
  73. }