forked from lib/pq
/
krb_unix.go
128 lines (99 loc) · 2.5 KB
/
krb_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//go:build !windows
// +build !windows
package kerberos
import (
"fmt"
"os"
"os/user"
"strings"
"github.com/jcmturner/gokrb5/v8/client"
"github.com/jcmturner/gokrb5/v8/config"
"github.com/jcmturner/gokrb5/v8/credentials"
"github.com/jcmturner/gokrb5/v8/spnego"
)
/*
* UNIX Kerberos support, using jcmturner's pure-go
* implementation
*/
// GSS implements the pq.GSS interface.
type GSS struct {
cli *client.Client
}
// NewGSS creates a new GSS provider.
func NewGSS() (*GSS, error) {
g := &GSS{}
err := g.init()
if err != nil {
return nil, err
}
return g, nil
}
func (g *GSS) init() error {
cfgPath, ok := os.LookupEnv("KRB5_CONFIG")
if !ok {
cfgPath = "/etc/krb5.conf"
}
cfg, err := config.Load(cfgPath)
if err != nil {
return err
}
u, err := user.Current()
if err != nil {
return err
}
ccpath := "/tmp/krb5cc_" + u.Uid
ccname := os.Getenv("KRB5CCNAME")
if strings.HasPrefix(ccname, "FILE:") {
ccpath = strings.SplitN(ccname, ":", 2)[1]
}
ccache, err := credentials.LoadCCache(ccpath)
if err != nil {
return err
}
cl, err := client.NewFromCCache(ccache, cfg, client.DisablePAFXFAST(true))
if err != nil {
return err
}
cl.Login()
g.cli = cl
return nil
}
// GetInitToken implements the GSS interface.
func (g *GSS) GetInitToken(host string, service string) ([]byte, error) {
// Resolve the hostname down to an 'A' record, if required (usually, it is)
if g.cli.Config.LibDefaults.DNSCanonicalizeHostname {
var err error
host, err = canonicalizeHostname(host)
if err != nil {
return nil, err
}
}
spn := service + "/" + host
return g.GetInitTokenFromSpn(spn)
}
// GetInitTokenFromSpn implements the GSS interface.
func (g *GSS) GetInitTokenFromSpn(spn string) ([]byte, error) {
s := spnego.SPNEGOClient(g.cli, spn)
st, err := s.InitSecContext()
if err != nil {
return nil, fmt.Errorf("kerberos error (InitSecContext): %s", err.Error())
}
b, err := st.Marshal()
if err != nil {
return nil, fmt.Errorf("kerberos error (Marshaling token): %s", err.Error())
}
return b, nil
}
// Continue implements the GSS interface.
func (g *GSS) Continue(inToken []byte) (done bool, outToken []byte, err error) {
t := &spnego.SPNEGOToken{}
err = t.Unmarshal(inToken)
if err != nil {
return true, nil, fmt.Errorf("kerberos error (Unmarshaling token): %s", err.Error())
}
state := t.NegTokenResp.State()
if state != spnego.NegStateAcceptCompleted {
return true, nil, fmt.Errorf("kerberos: expected state 'Completed' - got %d", state)
}
return true, nil, nil
}