-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecret_site_esp32.ino
More file actions
240 lines (196 loc) · 7.34 KB
/
Copy pathsecret_site_esp32.ino
File metadata and controls
240 lines (196 loc) · 7.34 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
/*
Secret Site ESP32
- Cria um Access Point (AP) com SSID oculto
- Serve um site em uma URL secreta (token)
- Exige Basic Auth (usuario/senha)
- O site so funciona enquanto o ESP estiver ligado
Compatível: ESP32 / ESP32-S3 (Arduino core)
*/
#include <WiFi.h>
#include <WebServer.h>
#include <esp_system.h>
// ---------------------------
// Configuracoes do Access Point
// ---------------------------
// SSID "oculto": ainda existe, mas nao aparece na lista de redes.
static const char* AP_SSID = "ESP-Secret";
static const char* AP_PASSWORD = "Troque_Essa_Senha_123"; // Minimo 8 caracteres
// IP fixo do AP (padrao de AP do ESP32 costuma ser 192.168.4.1)
static IPAddress AP_IP(192, 168, 4, 1);
static IPAddress AP_GW(192, 168, 4, 1);
static IPAddress AP_MASK(255, 255, 255, 0);
// ---------------------------
// Autenticacao HTTP (Basic Auth)
// ---------------------------
static const char* AUTH_USER = "admin";
static const char* AUTH_PASS = "admin123"; // Troque no seu fork
// ---------------------------
// Servidor
// ---------------------------
WebServer server(80);
// Token/rota secreta. Exemplo final: /s/AB12CD34EF
static String secretToken; // gerado no boot
static String secretPath; // "/s/" + token
// Controle simples anti-spam
static unsigned long lastRequestMs = 0;
static const unsigned long MIN_REQUEST_INTERVAL_MS = 30; // 30ms (bem leve)
// HTML simples (pode trocar por algo maior depois)
static String buildHomeHtml() {
String html;
html.reserve(1800);
html += "<!doctype html><html lang='pt-br'><head>";
html += "<meta charset='utf-8'/>";
html += "<meta name='viewport' content='width=device-width,initial-scale=1'/>";
html += "<title>Secret Site</title>";
html += "<style>";
html += "body{font-family:system-ui,Arial;margin:0;background:#0b0f17;color:#e6e6e6}";
html += ".wrap{max-width:860px;margin:0 auto;padding:24px}";
html += ".card{background:#111827;border:1px solid #1f2937;border-radius:16px;padding:18px}";
html += "h1{font-size:22px;margin:0 0 10px}";
html += "p{line-height:1.5}";
html += "code{background:#0b1220;border:1px solid #1f2937;padding:2px 6px;border-radius:8px}";
html += ".row{display:flex;gap:12px;flex-wrap:wrap;margin-top:14px}";
html += "a.btn{display:inline-block;padding:10px 14px;border-radius:12px;background:#2563eb;color:#fff;text-decoration:none}";
html += "a.btn:hover{filter:brightness(1.08)}";
html += "</style></head><body><div class='wrap'>";
html += "<div class='card'>";
html += "<h1>✅ Site secreto no ESP32</h1>";
html += "<p>Este site so existe enquanto o ESP estiver ligado e conectavel.</p>";
html += "<div class='row'>";
html += "<a class='btn' href='";
html += secretPath;
html += "/status'>Ver status</a>";
html += "<a class='btn' href='";
html += secretPath;
html += "/reboot' onclick=\"return confirm('Reiniciar o ESP?')\">Reiniciar</a>";
html += "</div>";
html += "<p style='margin-top:14px'>Dica: mantenha a senha do AP forte e troque o token/usuario/senha.</p>";
html += "</div></div></body></html>";
return html;
}
// Gera token baseado em aleatoriedade + um pedaço do MAC (sem depender de RTC)
static String generateToken() {
// Mistura um RNG de hardware do ESP32 com parte do MAC para dar unicidade
uint32_t r1 = esp_random();
uint32_t r2 = esp_random();
uint64_t mac = ESP.getEfuseMac(); // identificador unico do chip
uint32_t macLow = (uint32_t)(mac); // parte baixa
uint32_t mixed = r1 ^ (r2 << 1) ^ macLow;
// Token hex curto e prático
char buf[11]; // 8 hex + '\0' + margem
snprintf(buf, sizeof(buf), "%08lX", (unsigned long)mixed);
return String(buf);
}
// Verifica se o request respeita intervalo minimo (anti flood bem simples)
static bool allowRequest() {
unsigned long now = millis();
if (now - lastRequestMs < MIN_REQUEST_INTERVAL_MS) return false;
lastRequestMs = now;
return true;
}
// Helper: exige Basic Auth
static bool ensureAuth() {
if (!server.authenticate(AUTH_USER, AUTH_PASS)) {
server.requestAuthentication(); // responde 401
return false;
}
return true;
}
// Resposta 404 padrao
static void handleNotFound() {
server.send(404, "text/plain", "404 - Nao encontrado");
}
// Rota raiz (nao revela nada)
static void handleRoot() {
if (!allowRequest()) {
server.send(429, "text/plain", "Muitas requisicoes. Tente novamente.");
return;
}
// Nao entrega o site aqui (evita "descoberta" por scanners)
server.send(404, "text/plain", "Nada aqui.");
}
// Home secreta
static void handleSecretHome() {
if (!allowRequest()) {
server.send(429, "text/plain", "Muitas requisicoes. Tente novamente.");
return;
}
if (!ensureAuth()) return;
server.send(200, "text/html; charset=utf-8", buildHomeHtml());
}
// Status secreto
static void handleStatus() {
if (!allowRequest()) {
server.send(429, "text/plain", "Muitas requisicoes. Tente novamente.");
return;
}
if (!ensureAuth()) return;
String json;
json.reserve(512);
json += "{";
json += "\"ap_ssid\":\""; json += AP_SSID; json += "\",";
json += "\"ap_ip\":\""; json += WiFi.softAPIP().toString(); json += "\",";
json += "\"rssi\":0,"; // AP nao tem RSSI como STA
json += "\"uptime_ms\":"; json += String(millis()); json += ",";
json += "\"free_heap\":"; json += String(ESP.getFreeHeap());
json += "}";
server.send(200, "application/json", json);
}
// Reboot secreto
static void handleReboot() {
if (!allowRequest()) {
server.send(429, "text/plain", "Muitas requisicoes. Tente novamente.");
return;
}
if (!ensureAuth()) return;
server.send(200, "text/plain", "Reiniciando...");
delay(200);
ESP.restart();
}
static void printAccessInfo() {
Serial.println();
Serial.println("=== Secret Site ESP32 ===");
Serial.print("AP SSID (oculto): "); Serial.println(AP_SSID);
Serial.print("AP senha: "); Serial.println(AP_PASSWORD);
Serial.print("IP do AP: "); Serial.println(WiFi.softAPIP());
Serial.println();
Serial.println("Acesse (URL secreta):");
Serial.print(" http://"); Serial.print(WiFi.softAPIP()); Serial.println(secretPath);
Serial.println();
Serial.println("Basic Auth:");
Serial.print(" usuario: "); Serial.println(AUTH_USER);
Serial.print(" senha: "); Serial.println(AUTH_PASS);
Serial.println();
Serial.println("Observacao: como o SSID e oculto, talvez voce precise conectar manualmente.");
Serial.println("=========================");
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(200);
// Gera rota secreta no boot (muda a cada reinicio)
secretToken = generateToken();
secretPath = "/s/" + secretToken;
// Sobe AP com IP fixo
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(AP_IP, AP_GW, AP_MASK);
// 'hidden' = 1 -> SSID oculto
// max_connection = 4 (ajuste se quiser)
bool ok = WiFi.softAP(AP_SSID, AP_PASSWORD, 1 /*channel*/, 1 /*hidden*/, 4 /*max conn*/);
if (!ok) {
Serial.println("Falha ao iniciar o Access Point. Verifique senha/ambiente.");
}
// Rotas
server.on("/", HTTP_GET, handleRoot);
// Rotas secretas (somente se souber o caminho)
server.on(secretPath.c_str(), HTTP_GET, handleSecretHome);
server.on((secretPath + "/status").c_str(), HTTP_GET, handleStatus);
server.on((secretPath + "/reboot").c_str(), HTTP_GET, handleReboot);
server.onNotFound(handleNotFound);
server.begin();
printAccessInfo();
}
void loop() {
// Processa requisicoes HTTP
server.handleClient();
}