-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
320 lines (292 loc) · 9.15 KB
/
main.go
File metadata and controls
320 lines (292 loc) · 9.15 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type hop struct {
IP string `json:"ip"`
MAC string `json:"mac"`
}
type hopChain struct {
Hops []hop `json:"hops"`
}
type randomizer struct {
r *rand.Rand
}
func newRandomizer(seed int64) *randomizer {
return &randomizer{r: rand.New(rand.NewSource(seed))}
}
func (r *randomizer) buildChain(count int) hopChain {
if count < 1 {
count = 1
}
hops := make([]hop, 0, count)
for i := 0; i < count; i++ {
hops = append(hops, hop{
IP: fmt.Sprintf("%d.%d.%d.%d", r.r.Intn(223)+1, r.r.Intn(256), r.r.Intn(256), r.r.Intn(256)),
MAC: fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", r.r.Intn(256), r.r.Intn(256), r.r.Intn(256), r.r.Intn(256), r.r.Intn(256), r.r.Intn(256)),
})
}
return hopChain{Hops: hops}
}
type app struct {
client *http.Client
randomSource *randomizer
publicURL string
}
const (
appName = "gooNproxy"
appVersion = "1.0"
torProxyEnv = "GOONPROXY_TOR_PROXY"
publicURLEnv = "GOONPROXY_PUBLIC_URL"
)
const page = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>` + appName + `</title>
<style>
body { font-family: Arial, sans-serif; margin: 2rem; max-width: 900px; }
.card { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; margin-top: 1rem; }
input[type=text] { width: 70%; padding: .5rem; }
button { padding: .5rem .8rem; }
pre { white-space: pre-wrap; word-break: break-word; background:#fafafa; padding: 1rem; border-radius: 8px; }
.error { color: #b00020; font-weight: bold; }
</style>
</head>
<body>
<h1>` + appName + `</h1>
<p>Privacy-focused search proxy with simulated multi-hop IP/MAC randomization.</p>
{{ if .PublicURL }}
<p><strong>Public website:</strong> <a href="{{ .PublicURL }}">{{ .PublicURL }}</a></p>
{{ end }}
<form method="get" action="/search">
<label for="q">Search</label><br>
<input id="q" name="q" type="text" value="{{ .Query }}" placeholder="type your query">
<button type="submit">Search via proxy</button>
</form>
{{ if .ErrorMessage }}
<p class="error">{{ .ErrorMessage }}</p>
{{ end }}
{{ if .ShowResult }}
<div class="card">
<h2>Search Result (DuckDuckGo via proxy)</h2>
<p><strong>Target:</strong> {{ .TargetURL }}</p>
<h3>Simulated Multi-hop Identity Chain</h3>
<pre>{{ .ChainJSON }}</pre>
<h3>Response Preview</h3>
<pre>{{ .ResultPreview }}</pre>
</div>
{{ end }}
<div class="card">
<h2>Random Chain (Website Tool)</h2>
<p>Generate a randomized hop chain directly from the web interface.</p>
<label for="hops">Hops (1-10)</label>
<input id="hops" type="number" min="1" max="10" value="3">
<button id="generateChain" type="button">Generate chain</button>
<pre id="chainOutput">Press "Generate chain" to load JSON from /api/random-chain.</pre>
</div>
<script>
(function () {
var button = document.getElementById('generateChain');
var hopsInput = document.getElementById('hops');
var output = document.getElementById('chainOutput');
if (!button || !hopsInput || !output) {
return;
}
button.addEventListener('click', function () {
var hops = hopsInput.value || '3';
fetch('/api/random-chain?hops=' + encodeURIComponent(hops))
.then(function (response) {
return response.text().then(function (body) {
return { ok: response.ok, body: body };
});
})
.then(function (result) {
output.textContent = result.body;
if (!result.ok) {
output.textContent = 'Request failed: ' + result.body;
}
})
.catch(function (error) {
output.textContent = 'Request failed: ' + error;
});
});
})();
</script>
</body>
</html>`
var tmpl = template.Must(template.New("page").Parse(page))
type pageData struct {
Query string
ShowResult bool
TargetURL string
ChainJSON string
ResultPreview string
ErrorMessage string
PublicURL string
}
func renderPage(w http.ResponseWriter, data pageData) error {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return err
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err := w.Write(buf.Bytes())
return err
}
func (a *app) index(w http.ResponseWriter, r *http.Request) {
if err := renderPage(w, pageData{PublicURL: a.publicURL}); err != nil {
http.Error(w, "failed to render page", http.StatusInternalServerError)
}
}
func (a *app) search(w http.ResponseWriter, r *http.Request) {
query := strings.TrimSpace(r.URL.Query().Get("q"))
if query == "" {
w.WriteHeader(http.StatusBadRequest)
if err := renderPage(w, pageData{ErrorMessage: "Please enter a search query."}); err != nil {
http.Error(w, "failed to render page", http.StatusInternalServerError)
}
return
}
target := "https://duckduckgo.com/html/?q=" + url.QueryEscape(query)
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, target, nil)
if err != nil {
http.Error(w, "failed to create upstream request", http.StatusInternalServerError)
return
}
req.Header.Set("User-Agent", appName+"/"+appVersion+" (+privacy-search-proxy)")
chain := a.randomSource.buildChain(3)
chainBytes, err := json.MarshalIndent(chain, "", " ")
if err != nil {
http.Error(w, "failed to build randomized chain", http.StatusInternalServerError)
return
}
resultPreview := ""
res, err := a.client.Do(req)
if err != nil {
resultPreview = "upstream request failed: " + err.Error()
} else {
defer res.Body.Close()
body, readErr := io.ReadAll(io.LimitReader(res.Body, 3000))
if readErr != nil {
resultPreview = "upstream response read failed: " + readErr.Error()
} else {
resultPreview = string(body)
}
}
data := pageData{
Query: query,
ShowResult: true,
TargetURL: target,
ChainJSON: string(chainBytes),
ResultPreview: resultPreview,
PublicURL: a.publicURL,
}
if err := renderPage(w, data); err != nil {
http.Error(w, "failed to render search result", http.StatusInternalServerError)
}
}
func (a *app) apiChain(w http.ResponseWriter, r *http.Request) {
hops := 3
if val := strings.TrimSpace(r.URL.Query().Get("hops")); val != "" {
parsed, err := strconv.Atoi(val)
if err != nil || parsed < 1 || parsed > 10 {
http.Error(w, "hops must be an integer between 1 and 10", http.StatusBadRequest)
return
}
hops = parsed
}
chain := a.randomSource.buildChain(hops)
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(chain); err != nil {
http.Error(w, "failed to encode randomized chain", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(buf.Bytes()); err != nil {
fmt.Fprintf(os.Stderr, "failed writing api response: %v\n", err)
}
}
func parseTorProxyURL(rawTorProxy string) (*url.URL, error) {
parsed, err := url.Parse(rawTorProxy)
if err != nil {
return nil, err
}
if parsed.Host == "" {
return nil, fmt.Errorf("tor proxy URL missing host component")
}
if parsed.Scheme != "socks5" && parsed.Scheme != "socks5h" {
return nil, fmt.Errorf("unsupported scheme %q: expected socks5 or socks5h", parsed.Scheme)
}
return parsed, nil
}
func parsePublicURL(rawPublicURL string) (*url.URL, error) {
parsed, err := url.Parse(rawPublicURL)
if err != nil {
return nil, err
}
if parsed.Host == "" {
return nil, fmt.Errorf("public URL missing host component")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, fmt.Errorf("unsupported scheme %q: expected http or https", parsed.Scheme)
}
return parsed, nil
}
func newHTTPClient() *http.Client {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = http.ProxyFromEnvironment
if rawTorProxy := strings.TrimSpace(os.Getenv(torProxyEnv)); rawTorProxy != "" {
if parsed, err := parseTorProxyURL(rawTorProxy); err == nil {
transport.Proxy = http.ProxyURL(parsed)
} else {
fmt.Fprintf(os.Stderr, "invalid %s value: %v; expected socks5://host:port or socks5h://host:port\n", torProxyEnv, err)
}
}
return &http.Client{
Timeout: 15 * time.Second,
Transport: transport,
}
}
func routes(now time.Time) http.Handler {
publicURL := ""
if rawPublicURL := strings.TrimSpace(os.Getenv(publicURLEnv)); rawPublicURL != "" {
if parsed, err := parsePublicURL(rawPublicURL); err == nil {
publicURL = parsed.String()
} else {
fmt.Fprintf(os.Stderr, "invalid %s value: %v; expected http://host or https://host\n", publicURLEnv, err)
}
}
a := &app{
client: newHTTPClient(),
randomSource: newRandomizer(now.UnixNano()),
publicURL: publicURL,
}
mux := http.NewServeMux()
mux.HandleFunc("/", a.index)
mux.HandleFunc("/search", a.search)
mux.HandleFunc("/api/random-chain", a.apiChain)
return mux
}
func main() {
server := &http.Server{
Addr: ":8080",
Handler: routes(time.Now()),
ReadHeaderTimeout: 5 * time.Second,
}
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "server failed: %v\n", err)
}
}