forked from cyfdecyf/cow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
262 lines (238 loc) · 6.34 KB
/
auth.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package main
import (
"bytes"
"fmt"
"math/rand"
"net"
"os"
"strconv"
"strings"
"text/template"
"time"
)
const (
authRealm = "cow proxy"
authRawBodyTmpl = `<!DOCTYPE html>
<html>
<head> <title>COW Proxy</title> </head>
<body>
<h1>407 Proxy authentication required</h1>
<hr />
Generated by <i>COW</i>
</body>
</html>
`
)
type netAddr struct {
ip net.IP
mask net.IPMask
}
var auth struct {
required bool
user string
passwd string
ha1 string // used in request digest
allowedClient []netAddr
authed *TimeoutSet // cache authentication based on client i
template *template.Template
}
func parseAllowedClient(val string) {
if val == "" {
return
}
auth.required = true
arr := strings.Split(val, ",")
auth.allowedClient = make([]netAddr, len(arr), len(arr))
for i, v := range arr {
s := strings.TrimSpace(v)
ipAndMask := strings.Split(s, "/")
if len(ipAndMask) > 2 {
fmt.Println("allowedClient syntax error: client should be the form ip/nbitmask")
os.Exit(1)
}
ip := net.ParseIP(ipAndMask[0])
if ip == nil {
fmt.Printf("allowedClient syntax error %s: ip address not valid\n", s)
os.Exit(1)
}
var mask net.IPMask
if len(ipAndMask) == 2 {
nbit, err := strconv.Atoi(ipAndMask[1])
if err != nil {
fmt.Printf("allowedClient syntax error %s: %v\n", s, err)
os.Exit(1)
}
if nbit > 32 {
fmt.Println("allowedClient error: mask number should <= 32")
os.Exit(1)
}
mask = NewNbitIPv4Mask(nbit)
} else {
mask = NewNbitIPv4Mask(32)
}
auth.allowedClient[i] = netAddr{ip.Mask(mask), mask}
}
}
func parseUserPasswd(val string) {
if val == "" {
return
}
auth.required = true
arr := strings.SplitN(val, ":", 2)
if len(arr) != 2 || arr[0] == "" || arr[1] == "" {
fmt.Println("User password syntax wrong, should be in the form of user:passwd")
os.Exit(1)
}
auth.user, auth.passwd = arr[0], arr[1]
}
func initAuth() {
parseUserPasswd(config.UserPasswd)
parseAllowedClient(config.AllowedClient)
if !auth.required {
return
}
rand.Seed(time.Now().Unix())
auth.authed = NewTimeoutSet(time.Duration(config.AuthTimeout) * time.Hour)
if auth.user == "" {
return
}
auth.ha1 = md5sum(auth.user + ":" + authRealm + ":" + auth.passwd)
rawTemplate := "HTTP/1.1 407 Proxy Authentication Required\r\n" +
"Proxy-Authenticate: Digest realm=\"" + authRealm + "\", nonce=\"{{.Nonce}}\", qop=\"auth\"\r\n" +
"Content-Type: text/html\r\n" +
"Cache-Control: no-cache\r\n" +
"Content-Length: " + fmt.Sprintf("%d", len(authRawBodyTmpl)) + "\r\n\r\n" + authRawBodyTmpl
var err error
if auth.template, err = template.New("auth").Parse(rawTemplate); err != nil {
errl.Println("Internal error generating auth template:", err)
os.Exit(1)
}
}
// Return err = nil if authentication succeed. nonce would be not empty if
// authentication is needed, and should be passed back on subsequent call.
func Authenticate(conn *clientConn, r *Request) (err error) {
clientIP, _ := splitHostPort(conn.RemoteAddr().String())
if auth.authed.has(clientIP) {
debug.Printf("%s has already authed\n", clientIP)
return
}
if authIP(clientIP) { // IP is allowed
return
}
err = authUserPasswd(conn, r)
if err == nil {
auth.authed.add(clientIP)
}
return
}
// authIP checks whether the client ip address matches one in allowedClient.
// It uses a sequential search.
func authIP(clientIP string) bool {
ip := net.ParseIP(clientIP)
if ip == nil {
panic("authIP should always get IP address")
}
for _, na := range auth.allowedClient {
if ip.Mask(na.mask).Equal(na.ip) {
debug.Printf("client ip %s allowed\n", clientIP)
return true
}
}
return false
}
func genNonce() string {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%x", time.Now().Unix())
return buf.String()
}
func calcRequestDigest(kv map[string]string, ha1, method string) string {
// Refer to rfc2617 section 3.2.2.1 Request-Digest
buf := bytes.NewBufferString(ha1)
buf.WriteByte(':')
buf.WriteString(kv["nonce"])
buf.WriteByte(':')
buf.WriteString(kv["nc"])
buf.WriteByte(':')
buf.WriteString(kv["cnonce"])
buf.WriteByte(':')
buf.WriteString("auth") // qop value
buf.WriteByte(':')
buf.WriteString(md5sum(method + ":" + kv["uri"]))
return md5sum(buf.String())
}
func checkProxyAuthorization(r *Request) error {
debug.Println("authorization:", r.ProxyAuthorization)
arr := strings.SplitN(r.ProxyAuthorization, " ", 2)
if len(arr) != 2 {
errl.Println("auth: malformed ProxyAuthorization header:", r.ProxyAuthorization)
return errBadRequest
}
if strings.ToLower(strings.TrimSpace(arr[0])) != "digest" {
errl.Println("auth: client using unsupported authenticate method:", arr[0])
return errBadRequest
}
authHeader := parseKeyValueList(arr[1])
if len(authHeader) == 0 {
errl.Println("auth: empty authorization list")
return errBadRequest
}
nonceTime, err := strconv.ParseInt(authHeader["nonce"], 16, 64)
if err != nil {
return err
}
// If nonce time too early, reject. iOS will create a new connection to do
// authenticate.
if time.Now().Sub(time.Unix(nonceTime, 0)) > time.Minute {
return errAuthRequired
}
if authHeader["username"] != auth.user {
errl.Println("auth: username mismatch:", authHeader["username"])
return errAuthRequired
}
if authHeader["qop"] != "auth" {
errl.Println("auth: qop wrong:", authHeader["qop"])
return errBadRequest
}
response, ok := authHeader["response"]
if !ok {
errl.Println("auth: no request-digest")
return errBadRequest
}
digest := calcRequestDigest(authHeader, auth.ha1, r.Method)
if response == digest {
return nil
}
errl.Println("auth: digest not match, maybe password wrong")
return errAuthRequired
}
func authUserPasswd(conn *clientConn, r *Request) (err error) {
if r.ProxyAuthorization != "" {
// client has sent authorization header
err = checkProxyAuthorization(r)
if err == nil {
return
} else if err != errAuthRequired {
sendErrorPage(conn, errCodeBadReq, "Bad authorization request", "")
return
}
}
nonce := genNonce()
data := struct {
Nonce string
}{
nonce,
}
buf := new(bytes.Buffer)
if err := auth.template.Execute(buf, data); err != nil {
errl.Println("Error generating auth response:", err)
return errInternal
}
if debug {
debug.Println("authorization response:", buf.String())
}
if _, err := conn.Write(buf.Bytes()); err != nil {
errl.Println("Sending auth response error:", err)
return errShouldClose
}
return errAuthRequired
}