-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathmain.go
More file actions
249 lines (225 loc) · 7.47 KB
/
Copy pathmain.go
File metadata and controls
249 lines (225 loc) · 7.47 KB
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
// Copyright 2019, 2021, 2022, 2025 The Alpaca Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"crypto/tls"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/user"
"strconv"
)
var BuildVersion string
func whoAmI() string {
me, err := user.Current()
if err != nil {
return ""
}
return me.Username
}
type stringArrayFlag []string
func (s *stringArrayFlag) String() string {
return fmt.Sprintf("%v", *s)
}
func (s *stringArrayFlag) Set(value string) error {
if value == "" {
return nil
}
*s = append(*s, value)
return nil
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
var hosts stringArrayFlag
flag.Var(&hosts, "l", "address to listen on")
port := flag.Int("p", 3128, "port number to listen on")
pacurl := flag.String("C", "", "url of proxy auto-config (pac) file")
domain := flag.String("d", "", "domain of the proxy account (for NTLM auth)")
username := flag.String("u", whoAmI(), "username for proxy auth (NTLM)")
printHash := flag.Bool("H", false, "print hashed NTLM credentials for non-interactive use")
noKerberos := flag.Bool("no-kerberos", false,
"disable Kerberos/Negotiate auto-detection (macOS only)")
quiet := flag.Bool("q", false, "quiet mode, suppress all log output")
version := flag.Bool("version", false, "print version number")
enableSocks := flag.Bool("enable-socks", false, "allow SOCKS5 proxies from PAC files")
flag.Parse()
if *quiet {
log.SetOutput(io.Discard)
}
// default to localhost if no hosts are specified
if len(hosts) == 0 {
hosts = append(hosts, "localhost")
}
if *version {
fmt.Println("Alpaca", BuildVersion)
os.Exit(0)
}
var basicAuth *basicAuthenticator
var a *authenticator
// Basic credentials come from BASIC_CREDENTIALS to avoid leaking the
// password into shell history (mirrors how NTLM_CREDENTIALS works).
if value := os.Getenv("BASIC_CREDENTIALS"); value != "" {
basicAuth = newBasicAuthenticator(value)
log.Println("Basic proxy authentication configured from BASIC_CREDENTIALS")
}
// NTLM credential sources
var src credentialSource
if *domain != "" {
src = fromTerminal().forUser(*domain, *username)
} else if value := os.Getenv("NTLM_CREDENTIALS"); value != "" {
src = fromEnvVar(value)
} else {
src = fromKeyring()
}
if src != nil {
var err error
a, err = src.getCredentials()
if err != nil {
// The keyring source returns an error whenever NoMAD
// isn't installed and configured — the dominant case
// for any developer Mac without the specific NoMAD
// plist. The terminal and env-var sources return an
// error when the user supplied creds but they're
// malformed; today both cases land on this branch
// indistinguishably. Log a calm one-liner so a user
// without NoMAD doesn't see what looks like an error.
log.Println("NTLM credentials not available from the " +
"configured source")
}
}
if *printHash {
if a == nil {
fmt.Println("Please specify a domain (using -d) and username (using -u)")
os.Exit(1)
}
fmt.Printf("# Add this to your ~/.profile (or equivalent) and restart your shell\n")
fmt.Printf("NTLM_CREDENTIALS=%q; export NTLM_CREDENTIALS\n", a)
os.Exit(0)
}
// Build auth chain: Negotiate → NTLM → Basic (matches Chrome's hierarchy;
// Basic has the lowest security score because it sends credentials unencrypted).
//
// Kerberos/Negotiate is auto-detected on macOS: if a valid ticket is
// present at startup (or appears within -w seconds), Negotiate is
// added to the chain. No flag needed for the common "Apple SSO is
// signed in" case — alpaca behaves like the keyring source.
var methods []proxyAuthenticator
if !*noKerberos {
if neg := newNegotiateAuthenticator(); neg != nil {
log.Println("Kerberos/Negotiate authentication available")
methods = append(methods, neg)
}
}
if a != nil {
methods = append(methods, a)
}
if basicAuth != nil {
methods = append(methods, basicAuth)
}
auth := newAuthChain(methods...)
if auth != nil {
// Resolve the proxy-auth allowlist. Empty / unset is permissive
// (any host receives credentials) — parseAuthAllowlist treats
// "" as nil. Picking env-var-only (no companion flag) keeps the
// "either a flag or an env var, never both" convention the rest
// of alpaca already follows for security-sensitive inputs like
// BASIC_CREDENTIALS and NTLM_CREDENTIALS.
auth.hostAllowlist = parseAuthAllowlist(os.Getenv("ALPACA_PROXY_AUTH_ALLOWLIST"))
if len(auth.hostAllowlist) > 0 {
log.Printf("Proxy auth allowlist active: %v",
auth.hostAllowlist)
} else {
// Discoverability nudge for users who want to restrict
// where credentials go. The default is permissive because
// most users trust their PAC implicitly, but a hostile or
// MITM'd PAC over plain HTTP could otherwise direct
// alpaca to authenticate against attacker-named proxies.
// One line at startup; quiet enough not to be noise.
log.Println("Proxy auth allowlist: permissive (any host " +
"nominated by your PAC will receive credentials). " +
"Set ALPACA_PROXY_AUTH_ALLOWLIST to restrict.")
}
}
if auth == nil {
log.Println("No authentication methods configured; alpaca will " +
"surface proxy 407 responses as 502 Bad Gateway to clients")
}
errch := make(chan error)
s := createServer(*port, *pacurl, auth, *enableSocks)
for _, host := range hosts {
address := net.JoinHostPort(host, strconv.Itoa(*port))
for _, network := range networks(host) {
go func(network string) {
l, err := net.Listen(network, address)
if err != nil {
errch <- err
} else {
log.Printf("Listening on %s %s", network, address)
errch <- s.Serve(l)
}
}(network)
}
}
log.Fatal(<-errch)
}
func createServer(port int, pacurl string, auth *authChain, enableSocks bool) *http.Server {
pacWrapper := NewPACWrapper(PACData{Port: port})
proxyFinder := NewProxyFinder(pacurl, pacWrapper, enableSocks)
proxyHandler := NewProxyHandler(auth, getProxyFromContext, proxyFinder.blockProxy)
mux := http.NewServeMux()
pacWrapper.SetupHandlers(mux)
// build the handler by wrapping middleware upon middleware
var handler http.Handler = mux
handler = RequestLogger(handler)
handler = proxyHandler.WrapHandler(handler)
handler = proxyFinder.WrapHandler(handler)
handler = AddContextID(handler)
return &http.Server{
Handler: handler,
// TODO: Implement HTTP/2 support. In the meantime, set TLSNextProto to a non-nil
// value to disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
}
func networks(hostname string) []string {
if hostname == "" {
return []string{"tcp"}
}
addrs, err := net.LookupIP(hostname)
if err != nil {
log.Fatal(err)
}
nets := make([]string, 0, 2)
ipv4 := false
ipv6 := false
for _, addr := range addrs {
// addr == net.IPv4len doesn't work because all addrs use IPv6 format.
if addr.To4() != nil {
ipv4 = true
} else {
ipv6 = true
}
}
if ipv4 {
nets = append(nets, "tcp4")
}
if ipv6 {
nets = append(nets, "tcp6")
}
return nets
}