-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebStuff.ino
3808 lines (3640 loc) · 161 KB
/
WebStuff.ino
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//char suspinBuff[512];
//int suspBufferIndex = 0;
// max command length = 31 chars
const char* const cmd_string_table[] = {"saveyield", "save", "RAMyield", "GET / HTTP/", "erase", "ntp", "help", "showiplog", "showversion", "fandefault",
"fan", "showsockets", "showPVIdebug", "showPVOstring", "Seriallogging", "showbufferremaining", "showPluvioURL", "GoUpdateDNS", "UpdateDNSKey", "Ethernetlogging",
"showmem", "yield", "forceEmail", "showlogging", "showWeatherlog", "showPVOutputlog", "showip", "showmaillog", "UDPon", "UDPoff",
"showHTTPlogging", "PluvioEna", "showinverterlog", "showbrlog", "showextended", "showsuspectURL", "WolfSSLmail", "showabuslog", "showunknowncmd", "dump",
"reportunkwncmd", "SuspEmail", "UnknownCmdEmail", "setBrCorrFact", "startTFTP", "testIPwhitelist", "testHTTPblacklist"
};
#define numcmd_string_table (int)sizeof(cmd_string_table) / sizeof(cmd_string_table[0]) //array size
const char* const icon_string_table[] = {"zonnig", "bliksem", "regen", "buien", "hagel", "mist", "sneeuw", "bewolkt", "halfbewolkt", "zwaarbewolkt", "nachtmist", "helderenacht", "wolkennacht", "lichtbewolkt", "nachtbewolkt"};
#define numicon_string_table (int)sizeof(icon_string_table) / sizeof(icon_string_table[0])
const char* br = "<br>";
long httpShown = 1;
int httphacks = 0;
uint8_t ipreadvalueshown[4];
int readvalueshown;
time_t timereadvalueshown = 0;
uint8_t iptesthttpblacklistshown[4];
int testhttpblacklistshown = 0;
time_t timetesthttpblacklistshown = 0;
uint8_t iptestipwhitelistshown[4];
int testipwhitelistshown = 0;
time_t timetestipwhitelistshown = 0;
uint8_t ipstarttftpshown[4];
int starttftpshown = 0;
time_t timestarttftpshown = 0;
uint8_t ipsetbrcorrfactshown[4];
int setbrcorrfactshown = 0;
time_t timesetbrcorrfactshown = 0;
uint8_t iperasecountersshown[4];
int erasecountersshown = 0;
time_t timeerasecountersshown = 0;
uint8_t ipfandefaultshown[4];
int fandefaultshown = 0;
time_t timefandefaultshown = 0;
uint8_t ipwolfsslmailswitchshown[4];
int wolfsslmailswitchshown = 0;
time_t timewolfsslmailswitchshown = 0;
uint8_t ipshowfanshown[4];
int showfanshown = 0;
time_t timeshowfanshown = 0;
uint8_t ipswitchloggingshown[4];
int switchloggingshown = 0;
time_t timeswitchloggingshown = 0;
uint8_t ipshowpvoutputlogshown[4];
int showpvoutputlogshown = 0;
time_t timeshowpvoutputlogshown = 0;
uint8_t ipshowmailloggingshown[4];
int showmailloggingshown = 0;
time_t timeshowmailloggingshown = 0;
uint8_t ipshowiplogshown[4];
int showiplogshown = 0;
time_t timeshowiplogshown = 0;
uint8_t ipshowweatherlogshown[4];
int showweatherlogshown = 0;
time_t timeshowweatherlogshown = 0;
uint8_t ipsaveyieldshown[4];
int saveyieldshown = 0;
time_t timesaveyieldshown = 0;
uint8_t ipsavevalueshown[4];
int savevalueshown = 0;
time_t timesavevalueshown = 0;
uint8_t ipshowipshown[4];
int showipshown = 0;
time_t timeshowipshown = 0;
uint8_t ipshowversionshown[4];
int showversionshown = 0;
time_t timeshowversionshown = 0;
uint8_t ipsendRobotstxtshown[4];
int sendRobotstxtshown = 0;
time_t timesendRobotstxtshown = 0;
uint8_t ipsend404shown[4];
int send404shown = 0;
time_t timesend404shown = 0;
uint8_t ipdumpyieldshown[4];
int dumpyieldshown = 0;
time_t timedumpyieldshown = 0;
uint8_t ipflash_serial_dump_tableshown[4];
int flash_serial_dump_tableshown = 0;
time_t timeflash_serial_dump_tableshown = 0;
uint8_t ipupdatetimewebshown[4];
int updatetimewebshown = 0;
time_t timeupdatetimewebshown = 0;
uint8_t iphelpshown[4];
int helpshown = 0;
time_t timehelpshown = 0;
uint8_t ipshowpvostringshown[4];
int showpvostringshown = 0;
time_t timeshowpvostringshown = 0;
uint8_t ipshowunknowncmdshown[4];
int showunknowncmdshown = 0;
time_t timeshowunknowncmdshown = 0;
uint8_t ipshowsuspecturlshown[4];
int showsuspecturlshown = 0;
time_t timeshowsuspecturlshown = 0;
uint8_t ipshowstatusshown[4];
int showstatusshown = 0;
time_t timeshowstatusshown = 0;
uint8_t ipshowstatusextshown[4];
int showstatusextshown = 0;
time_t timeshowstatusextshown = 0;
uint8_t ipshowpvidebugshown[4];
int showpvidebugshown = 0;
time_t timeshowpvidebugshown = 0;
uint8_t ipshowpluviourlshown[4];
int showpluviourlshown = 0;
time_t timeshowpluviourlshown = 0;
uint8_t ipgoupdatednsshown[4];
int goupdatednsshown = 0;
time_t timegoupdatednsshown = 0;
uint8_t ipupdatednskeyshown[4];
int updatednskeyshown = 0;
time_t timeupdatednskeyshown = 0;
uint8_t ipethernetloggingshown[4];
int ethernetloggingshown = 0;
time_t timeethernetloggingshown = 0;
uint8_t ipshowbufferremainingshown[4];
int showbufferremainingshown = 0;
time_t timeshowbufferremainingshown = 0;
uint8_t ipshow_loggingshown[4];
int show_loggingshown = 0;
time_t timeshow_loggingshown = 0;
uint8_t ipdisplay_memoryinfoshown[4];
int display_memoryinfoshown = 0;
time_t timedisplay_memoryinfoshown = 0;
uint8_t ipforceemailshown[4];
int forceemailshown = 0;
time_t timeforceemailshown = 0;
uint8_t ipshowsockstatusshown[4];
int showsockstatusshown = 0;
time_t timeshowsockstatusshown = 0;
time_t httphacksTime = 0;
int httpbuffoverflow = 0;
time_t httpbuffoverflowTime = 0;
void printprintable(char c) {
char cbuff[4];
cbuff[0] = c;
cbuff[1] = '\0';
if (((byte)c > 0x1F) && ((byte)c < 0x7F)) {
textlog(cbuff, false);
}
else {
sprintf(temptxtbuff, " 0x%02X ", (byte)c);
textlog(temptxtbuff, false);
}
}
bool isIPself(IPAddress reqIP) {
IPAddress segm = Ethernet.localIP();
for (int iip = 0; iip < 3; iip++) {
if ((iip == 0) || (iip == 1)) {
if (reqIP[iip] != segm[iip]) {
return false;
}
}
/*
Comment the next conditional out if all public class C networks are accepted as local.Now 192.168.17 and larger are noted.
*/
if (iip == 2) {
if (reqIP[iip] > 16) {
return false;
}
}
}
return true;
}
String HTTPlineEncode(const char *src, int CALen) {
const char *hexarray = "0123456789ABCDEF";
String target = "";
int charcnt = 0;
int charpos = 0;
// textlog("\r\ncharacter in bewerking: ", false);
while ((charpos < CALen) && (charcnt < 272))
{
// Serial.print(*src);
// if (('a' <= *src && *src <= 'z') || ('A' <= *src && *src <= 'Z') || ('0' <= *src && *src <= '9') || *src == '-' || *src == '_' || *src == '.' || *src == '~')
if (' ' <= *src && *src <= '~')
{
target += *src;
charcnt++;
}
else
{
target += '%';
target += hexarray[*src >> 4];
target += hexarray[*src & 0xf];
charcnt += 3;
}
src++;
charpos++;
// textlog("\r\nnext char: ", false);
}
if (!min_serial && !HTTPlog) {
Serial.print("\r\nconverted string: ");
Serial.print(target);
}
return target;
}
void Send_header(EthernetClient client) {
client << (F("HTTP/1.1 200 OK\r\n"));
client << (F("Content-Type: text/html; charset=utf-8\r\n"));
client << (F("Connection: close\r\n\r\n"));
client << F("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\r\n");
client << (F("<html>\r\n")) << (F("<head>\r\n"));
client << (F("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\r\n"));
client << (F("<meta name=\"robots\" content=\"noindex,nofollow\">\r\n"));
client << (F("<link rel=\"icon\" type =\"image/x-icon\" href=\"/favicon.ico\">\r\n"));
client << (F("<style type=\"text/css\">\r\n"));
// client << (F("body {padding:8;text-align:center;word-wrap:break-word;}\r\n"));
client << (F("body {padding:8;text-align:center;word-wrap:break-word;}\r\n"));
client << (F("pre {font-family:courier, \"courier new\", monospace; font-size:1em; color:#000; background-color:#fff;}\r\n"));
client << (F("</style>\r\n"));
client << (F("<title>Zonocta PVI - Aurora Power One 3.6 </title>\r\n"));
// client << (F("</head>\r\n")) << (F("<body>\r\n"));
client << (F("</head>\r\n")) << (F("<body>\r\n"));
}
void sendHTMLheaderwarning(EthernetClient client) {
client << (F("Unauthorized access prohibited. You have no business here.\r\nUsername: \r\n"));
client << (F("Connection: close\r\n\r\n"));
}
char StrSuspcsCmd2Long(EthernetClient webclient, int bufferSize, IPAddress segm, char *inBuff, char c) {
String cmdencoded = "";
sprintf(temptxtbuff, "\r\nERROR: max linebuffer is %d, current buffer position is: %d", bufferMax, bufferSize); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
for (int bx = 0; bx < 4; bx++) {
suspicious_ips[suspicious_index][bx] = segm[bx];
}
suspicious_string[suspicious_index][bufferSize] = c;
bufferSize++;
suspicious_string[suspicious_index][bufferSize] = '\0';
textlog("\r\nHTTP received line: ", false);
textlog(inBuff, false);
textStringLog("\r\nIgnored part of cmdline: ", false);
printprintable(c);
while (webclient.available() && (c != '\n') )
{
c = webclient.read();
printprintable(c);
if (bufferSize < 255) {
// suspicious_length[suspicious_index] = bufferSize;
suspicious_string[suspicious_index][bufferSize] = c; // store all character and translate afterwards to HTML encoded
bufferSize++;
}
suspicious_string[suspicious_index][bufferSize] = '\0'; // always terminate
if (bufferSize == 255) {
textStringLog("\r\nERROR, suspicious_string too long to log completely", false);
bufferSize++; //disable
}
}
if (!min_serial) {
textStringLog("\r\n", false);
}
cmdencoded = "port=888 Long line received on IOTdev: " + HTTPlineEncode(suspicious_string[suspicious_index], bufferSize);
int cmdenclen = cmdencoded.length();
if (cmdenclen > 255) {
sprintf(temptxtbuff, "\r\nERROR: Encoded command is too long (%d)to store completely, shortened to 255.", cmdenclen); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
cmdenclen = 255;
}
cmdencoded.toCharArray(suspicious_string[suspicious_index], cmdenclen + 1) ;
suspicious_length[suspicious_index] = cmdenclen;
suspicious_perc[suspicious_index] = 0;
suspicious_time[suspicious_index] = now();
if (suspicious_mail) { // if enabled send for every suspicious command an email
sprintf(mailsubj, "baaisolar: Too long suspicious HTML commands received");
if (!sendEmail(11)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d ERROR: Sending mail for too long suspicious command.", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
}
suspicious_index++;
if (suspicious_index == SUSPARRAYDEPTH) {
suspicious_index = 0;
}
suspicious_total++;
return c;
}
void RqstCntnDtgrm(int bx, IPAddress segm) {
String cmdencoded = "";
if ( bx > 255 ) {
sprintf(temptxtbuff, "\r\nERROR, unwanted unsolicited datagram too long, %d bytes, to completely log", bx);
textlog(temptxtbuff, false);
bx = 255;
}
for (bx = 0; bx < 4; bx++) {
suspicious_ips[suspicious_index][bx] = segm[bx];
}
cmdencoded = HTTPlineEncode(suspicious_string[suspicious_index], bx);
cmdencoded = "port=888 unsolicited datagram request=" + cmdencoded;
bx = cmdencoded.length();
if (bx > 255) {
sprintf(temptxtbuff, "\r\nERROR: Encoded RqstCntnDtgrm is too long (%d)to store completely, shortened to 255.", bx); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
bx = 255;
}
cmdencoded.toCharArray(suspicious_string[suspicious_index], bx + 1) ;
suspicious_length[suspicious_index] = bx;
suspicious_perc[suspicious_index] = 0;
suspicious_time[suspicious_index] = now();
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Suspicious unsolicited datagram request stored in index %d", hour(), minute(), second(), suspicious_index); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
if (suspicious_mail) { // if enabled send for every suspicious command an email
sprintf(mailsubj, "baaisolar: suspicious HTML command received contains unsolicited datagram");
if (!sendEmail(11)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d ERROR: Sending mail for suspicious received HTML command which contains unsolicited datagram.", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
}
suspicious_index++;
if (suspicious_index == SUSPARRAYDEPTH) {
suspicious_index = 0;
}
suspicious_total++;
}
bool checkknownIP(IPAddress segm) {
/*
Ranges to be excluded from reporting to abuseIPDB
*/
bool result = false;
long int flashaddr;
uint8_t* readPtr = rdbuffer; //position off scan point to detect a \r\n position char of ipaddres in text
uint32_t bx = 0;
uint8_t uisegm[4];
for (int iip = 0; iip < 4; iip++) {
uisegm[iip] = segm[iip];
}
if (HTTPlog) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Scanning for IP address: %d.%d.%d.%d", hour(), minute(), second(), uisegm[0], uisegm[1], uisegm[2], uisegm[3]); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
abuse_well_known_scans++;
flashaddr = abusefilter1_addr;
abuse_array_scan_start_time = millis();
flash.readByteArray(flashaddr, rdbuffer, EEPROM_PAGE_SIZE);
while (*readPtr != 0xFF) {
if (*readPtr == uisegm[0]) {
// sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFORMATION: Subnet IP %d comparing to %d", hour(), minute(), second(), *readPtr, uisegm[0]); // temptxtbuff is max 1024
// textlog(temptxtbuff, false);
if (*(readPtr + 1) == uisegm[1]) {
if (*(readPtr + 2) == uisegm[2]) {
if ((*(readPtr + 3) == uisegm[3]) || (*(readPtr + 3) == 0)) {
if (HTTPlog) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFORMATION: Subnet IP %d.%d.%d.%d found in well known subnet array", hour(), minute(), second(), uisegm[0], uisegm[1], uisegm[2], uisegm[3]); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
result = true;
abuse_well_known_hits++;
break;
}
}
}
}
bx++;
readPtr += 4;
// sprintf(temptxtbuff, "\r\n%02d:%02d:%02d DEBUG: Buffer read pointer address: 0x%08x offset in buffer is: 0x%08x", hour(), minute(), second(), readPtr, (readPtr-rdbuffer)); // temptxtbuff is max 1024
// textlog(temptxtbuff, false);
if (readPtr == (rdbuffer + EEPROM_PAGE_SIZE)) {
flashaddr += EEPROM_PAGE_SIZE;
flash.readByteArray(flashaddr, rdbuffer, EEPROM_PAGE_SIZE);
readPtr = rdbuffer;
// sprintf(temptxtbuff, "\r\n%02d:%02d:%02d SUCCESS: Flash read success address: 0x%08x", hour(), minute(), second(), flashaddr); // temptxtbuff is max 1024
// textlog(temptxtbuff, false);
}
}
abuse_array_scan_run_time = millis() - abuse_array_scan_start_time;
if (HTTPlog && !result) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFORMATION: Subnet IP not found in well known subnet array", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
if (HTTPlog) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFORMATION: Subnet IP scanned %d subnets in %dms.", hour(), minute(), second(), bx, abuse_array_scan_run_time); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
return result;
}
bool checkForUnknownHTTPcommand(String unknwncmdStr) {
uint8_t* readPtr = rdbuffer; //position off scan point to detect a \r\n position in the textlist
uint32_t flashaddr = HTTPblacklist1_addr;
char HTTPcmd[17];
uint8_t HTTPcmdptr = 0;
String HTTPtext; // HTML blacklisttextfragment+0x00, string is max 15 positions
// convert the command to uppercase
unknwncmdStr.toUpperCase();
flash.readByteArray(flashaddr, rdbuffer, EEPROM_PAGE_SIZE);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d SUCCESS: Flash read success address: 0x%08x, first byte 0x%02X", hour(), minute(), second(), flashaddr, *readPtr); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
// while (*readPtr != 0xFF) {
while ((readPtr < (rdbuffer + EEPROM_PAGE_SIZE)) && (*readPtr != 0xFF)) {
while ( *readPtr != 0 ) {
HTTPcmd[HTTPcmdptr++] = *readPtr++;
}
HTTPcmd[HTTPcmdptr] = '\0';
if ( *readPtr == 0 ) {
HTTPtext = (String)HTTPcmd;
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d %s:%s:%04d DEBUG: checking unknown HTML command: %s via string: %s.", hour(), minute(), second(), FILENAME, __func__, __LINE__, HTTPcmd, HTTPtext.c_str()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
HTTPtext.toUpperCase();
if ( unknwncmdStr.indexOf(HTTPtext) != -1) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d %s:%s:%04d INFO: Unknown HTML command found in blacklist.", hour(), minute(), second(), FILENAME, __func__, __LINE__); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
return true;
}
readPtr += 16 - HTTPcmdptr;
HTTPcmdptr = 0;
}
}
if (readPtr == (rdbuffer + EEPROM_PAGE_SIZE)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFO Flash read pagebreak detected, reading last Flash page for converted blacklisted HTML fragments.", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
flashaddr += EEPROM_PAGE_SIZE;
if (flashaddr == (HTTPblacklist2_addr + EEPROM_PAGE_SIZE)) {
return false;
}
flash.readByteArray(flashaddr, rdbuffer, EEPROM_PAGE_SIZE);
readPtr = rdbuffer;
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d SUCCESS: Flash read success address: 0x%08x", hour(), minute(), second(), flashaddr); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
// }
return false;
}
void charsReceivedNoCmd(int bufferSize, char *inBuff, IPAddress segm) {
// deze zou afgevangen moeten worden door StrSuspcsCmd0Start
String ncavlbl;
bool TLStry = false;
if (inBuff[0] == 0) {
ncavlbl = "port=888 Binarycommand starting with 0: " + HTTPlineEncode(inBuff, bufferSize);
}
else if (bufferSize > 0) {
if (((byte)inBuff[0] == 0x16) && ((byte)inBuff[1] == 0x03)) {
if (checkknownIP(segm)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d INFORMATION: TLS connection from known IP source", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
return;
}
TLStry = true;
ncavlbl = "port=888 client is trying to connect by TLS, not allowed for this port.";
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d ERROR: %s", hour(), minute(), second(), ncavlbl.c_str()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
else {
ncavlbl = "port=888 Binary protocol request-> " + HTTPlineEncode(inBuff, bufferSize);
}
}
else {
ncavlbl = "port=888 no valid HTTP header available";
}
errorHTMLnocharavlbl++;
if (HTTPlog) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Storing suspicious command or incorrect protocol by charsReceivedNoCmd: %s", hour(), minute(), second(), ncavlbl.c_str()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
int bx = ncavlbl.length();
if (bx > 255) {
sprintf(temptxtbuff, "\r\nERROR: Encoded charsReceivedNoCmd is too long (%d)to store completely, shortened to 255.", bx); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
bx = 255;
}
suspicious_length[suspicious_index] = bx;
ncavlbl.toCharArray(suspicious_string[suspicious_index], suspicious_length[suspicious_index] + 1);
for (bx = 0; bx < 4; bx++) {
suspicious_ips[suspicious_index][bx] = segm[bx];
}
suspicious_perc[suspicious_index] = 0;
suspicious_time[suspicious_index] = now();
if (suspicious_mail) { // send email for every suspicious command
sprintf(mailsubj, "baaisolar: suspicious connection request received, characters received but no HTTP command");
if (!sendEmail(11)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d ERROR: Sending mail for modulo 5 number of suspicious commands.", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
}
suspicious_index++;
if (suspicious_index == SUSPARRAYDEPTH) {
suspicious_index = 0;
}
suspicious_total++;
sprintf(temptxtbuff, "\r\nhttphacks increased in line: %d ", __LINE__ + 2); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
httphacks++;
httphacksTime = now();
}
void StoreUnknwnCmd(String unknwncmdStr, IPAddress segm) {
int ucsl;
if (checkknownIP(segm)) {
sprintf(temptxtbuff, "\r\nINFORMATION: String Unknown Command is originated from adddres in whitelist, no action taken.", ucsl); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
unkcmdfrmwhl++;
unknownCmd_wkwnips[unknownCmd_index] = true;
}
else {
unknownCmd_wkwnips[unknownCmd_index] = false;
}
ucsl = unknwncmdStr.length();
if ( ucsl > 255 ) {
ucsl = 255;
sprintf(temptxtbuff, "\r\nERROR: String Unknown Command is too long (%d)to store completely, shortened to 255.", ucsl); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
sprintf(temptxtbuff, "\r\nTo store in unknown command index: %d stringlength=%d, unknwncmdStr=%s", unknownCmd_index, unknwncmdStr.length(), unknwncmdStr.c_str()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
unknwncmdStr.toCharArray(unknownCmd_string[unknownCmd_index], ucsl + 1); //unknown_string is max 256
// sprintf(temptxtbuff, "\r\nAfter conversion to char array, unknwncmdStr= %s", unknownCmd_string[unknownCmd_index]); // temptxtbuff is max 1024
// textlog(temptxtbuff, false);
unknownCmd_length[unknownCmd_index] = unknwncmdStr.length();
for (int bx = 0; bx < 4; bx++) {
unknownCmd_ips[unknownCmd_index][bx] = segm[bx];
}
// convert the command to uppercase
unknwncmdStr.toUpperCase();
if (checkForUnknownHTTPcommand(unknwncmdStr)) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Match in well known dictionary, queued without manual intervention on array index %d.", hour(), minute(), second(), unknownCmd_index);
textlog(temptxtbuff, false);
unknownCmd_queued[unknownCmd_index] = 1;
unknownCmd_sema = true;
}
else {
unknownCmd_queued[unknownCmd_index] = 0; // verification requested
}
unknownCmd_perc[unknownCmd_index] = 0;
unknownCmd_time[unknownCmd_index] = now();
if (unknownCmd_mail) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Sending email for unknown HTML command index array position %d", hour(), minute(), second(), unknownCmd_index);
textlog(temptxtbuff, false);
sprintf(mailsubj, "baaisolar: Unknown HTML command received");
sendEmail(16);
}
unknownCmd_index++;
if (unknownCmd_index == UNKWNCMDARRAYDEPTH) {
unknownCmd_index = 0;
}
unknownCmd_total++;
}
bool showRxLine(int bufferSize, const char *inBuff) {
bool inBuffisValid = true;
String encodedLine = "";
if (HTTPlog) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d The length of the received HTTP request line is: %d, if necessary the line is automatic HTML encoded for display", hour(), minute(), second(), bufferSize); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
if (bufferSize > 0 ) {
for (int inbx = 0; inbx < bufferSize; inbx++) {
if (inBuff[inbx] == '\0') {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d ERROR: the received HTTP request line contains a NULL character at position: %d (index is 0)", hour(), minute(), second(), inbx); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
inBuffisValid = false;
break;
}
}
if (HTTPlog) {
if (inBuffisValid) {
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d The received HTTP request line URL unencoded is: %s", hour(), minute(), second(), inBuff); // temptxtbuff is max 1024
}
else {
encodedLine = HTTPlineEncode(inBuff, bufferSize);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d The received HTTP request line HTTP encoded is: %s", hour(), minute(), second(), encodedLine.c_str()); // temptxtbuff is max 1024
}
textlog(temptxtbuff, false);
}
}
return inBuffisValid;
}
void ServeWebClients() {
EthernetClient webclient = server.available();
if (webclient)
{
int bufferSize = 0;
int bx = 0;
int charcnt = 0;
int inbx = 0;
char inBuff[bufferMax]; // max is 256
String cmdString = "";
// cmdString[0] = '\0';
char optcmd[32];
bool cmdRcvd = false;
bool currentLineIsBlank = true;
bool cmdprocessed = false;
char c = '\0';
// suspBufferIndex = 0;
// suspinBuff[0] = '\0';
inBuff[0] = '\0';
unsigned long starttime = millis();
// char valbuff[20];
webclient.setConnectionTimeout(5000);
IPAddress segm = webclient.remoteIP();
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d New HTTP client, remote IP address: %d.%d.%d.%d", hour(), minute(), second(), segm[0], segm[1], segm[2], segm[3]);
textlog(temptxtbuff, false);
while (webclient.connected() && ((millis() - starttime) < 5000))
{
if ( webclient.available())
{
c = webclient.read();
if ( c == '\0' && currentLineIsBlank) {
// this must be a suspicious command, pull down the datagram and return the last received char/byte
sprintf(temptxtbuff, "\r\nERROR: A new line has started with a NULL character, datagram pulled last character received: %c, in hex 0x%02X", c, (byte)c); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
while (webclient.available()) { //empty readbuffer
c = webclient.read();
if (bufferSize < bufferMax - 1) {
inBuff[bufferSize] = c;
bufferSize++;
inBuff[bufferSize] = '\0'; //allways terminate the buffer
}
}
charsReceivedNoCmd(bufferSize, inBuff, segm);
bufferSize = 0;
inBuff[0] = '\0';
sprintf(temptxtbuff, "\r\nhttphacks increased in line: %d ", __LINE__ + 2); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
break;
}
if ( c == '\n' && currentLineIsBlank) {
// this is most probably the regular header line that marks the end of header, a valid command should be received
// cmdString = webclient.readStringUntil('\n'); // for debug reasons, surge the whole header
// textStringLog("\r\nInterpreting command: ", false);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d Interpreting command: ", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
char cobuff[512];
int cpybuflen;
if (cmdString.length() > 511) {
cpybuflen = 511;
}
else {
cpybuflen = cmdString.length();
}
cmdString.toCharArray(cobuff, cpybuflen + 1); // the +1 toCharArray sets terminator
textlog(cobuff, false);
// command index selection
if (HTTPlog) {
sprintf(temptxtbuff, "\r\nlength numcmd_string_table: %d", numcmd_string_table); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
int cmdi = 0;
for ( cmdi = 0 ; cmdi < numcmd_string_table ; cmdi++ ) {
if (cmdi > numcmd_string_table) {
sprintf(temptxtbuff, "\r\nERROR comparisition command check tablelength out of bound, CHECK array for quotes!"); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
break;
}
strcpy(optcmd, cmd_string_table[cmdi]); // Necessary casts and dereferencing, just copy.
if (HTTPlog) {
sprintf(temptxtbuff, "\r\nOptional command: %d from equal test: %s -> test: ", cmdi, optcmd); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
delay(3);
}
if (Command(cmdString, optcmd)) {
if (HTTPlog) textlog("true", false);
break;
}
if (HTTPlog) {
textlog("false", false);
}
}
if (cmdi == numcmd_string_table) {
// textStringLog("\r\nNo matching command in lookuptable, check for fan command remains: ", false);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d No matching command in lookuptable, check for fan command remains: ", hour(), minute(), second()); // temptxtbuff is max 1024
}
else {
// textStringLog("\r\nHTTP Response sending for command: ", false);
// textlog(optcmd, false);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d HTTP Response sending for command: %s", hour(), minute(), second(), optcmd); // temptxtbuff is max 1024
Send_header(webclient);
}
textlog(temptxtbuff, false);
textStringLog(", index nr: ", false);
itoa(cmdi, cobuff, 10);
textlog(cobuff, false);
switch (cmdi) {
case 0:
SaveYield(webclient, segm); // "saveyield" the variables of this day
break;
case 1:
SaveValue(webclient, segm); // "save" the variables of this day
break;
case 2:
DumpYield(webclient, 0, segm); // "RAMyield" dump the daily yield for last three months from RAM array
break;
case 3:
ShowStatus(webclient, false, segm); //shows received commands that not could interpreted
break;
case 4:
eraseCounters(webclient, segm); // "erase" the saved variables of this day, restore @startup
break;
case 5:
UpdateTimeWeb(webclient, segm); // "ntp" update time from web
break;
case 6:
help(webclient, segm); // "help", show the commands
break;
case 7:
showIPlog(webclient, segm); // "showiplog" shows and toggles the WAN IP logging
break;
case 8:
showversion(webclient, 1, segm, true); // "showversion", show the version build
break;
case 9:
fanDefault(webclient, segm); // "fandefault", sets the default thresholds for fan temperature
break;
case 10:
showFan(webclient, segm); // "fan", show the actual temperature thresholds
break;
case 11:
ShowSockStatus(webclient, segm); // "showsockets", shows the forced disconnects
break;
case 12:
showPVIdebug(webclient, segm); // "showPVIdebug", shows the PVI measurement values
break;
case 13:
showPVOstring(webclient, segm); // "showPVOstring", shows the PVOutput add outputstring
break;
case 14:
switchLogging(webclient, segm); // "Seriallogging", Toggles serial traces
break;
case 15:
showBufferremaining(webclient, segm); // "showbufferremaining",
break;
case 16:
showPluvioURL(webclient, segm); // "showPluvioURL", shows the url to get the pluvio
break;
case 17:
GoUpdateDNS(webclient, segm); // "GoUpdateDNS", updates the DynDNS
break;
case 18:
UpdateDNSKey(webclient, cmdString, segm); // "UpdateDNSKey", updates the DynDNS updatekey
break;
case 19:
ethernetlogging(webclient, segm); // "Ethernetlogging", toggles ethernetlogging
break;
case 20:
display_memoryinfo(webclient, segm); // "showmem", show memory usage
break;
case 21:
DumpYield(webclient, 1, segm); // "yield", dump the daily yield for last three monthes from flash
break;
case 22:
forceEmail(webclient, segm); // "forceEmail", force to send email
break;
case 23:
show_logging(webclient, segm); // "showlogging", shows the actual status of the logging flags
break;
case 24:
showWeatherlog(webclient, segm); // "showWeatherlog", Toggles weather buffer in logging
break;
case 25:
showPVOutputlog(webclient, segm); // "showPVOutputlog", toggles the logging to pvoutput
break;
case 26:
showIP(webclient, segm); // "showip", shows the actual networkinterface configuration
break;
case 27:
showMailLogging(webclient, segm); // "showmaillog" Toggles maillogging
break;
case 28:
setUDPon(webclient, segm); // "UDPon" switch ethernet UDP client logging on
break;
case 29:
setUDPoff(webclient, segm); // "UDPoff"switch ethernet UDP client logging on
break;
case 30:
setHTTPlogging(webclient, segm); // "setHTTPlog"switch HTTP client logging on
break;
case 31:
setPluvioEna(webclient, segm); // enbles requests to buienradar
break;
case 32:
setInverterlog(webclient, segm); // enables inverter logging
break;
case 33:
setbrlogging(webclient, segm); //enables buienradar.nl logging
break;
case 34:
ShowStatus(webclient, true, segm); //shows the extended status including debug counters
break;
case 35:
ShowSuspectURL(webclient, segm); //shows the suspected commands
break;
case 36:
WolfSSLMailSwitch(webclient, segm); //shows the suspected commands
break;
case 37:
setabuslogging(webclient, segm); //enables AbuseIPDB logging
break;
case 38:
showUnknownCmd(webclient, segm); //shows received commands that not could interpreted
break;
case 39:
flash_serial_dump_table(webclient, segm); // "dump" the content of the flash
break;
case 40:
reportunkwncmd(webclient, cmdString, segm); // reports an unknown command for abuse
break;
case 41:
SuspEmail(webclient, segm); // reports an unknown command for abuse
break;
case 42:
UnknownCmdEmail(webclient, segm); // reports an unknown command for abuse
break;
case 43:
setBrCorrFact(webclient, cmdString, segm); // sets the correction factor for Buienradar pluvio, must contain a real in commandstring
break;
case 44:
startTFTP(webclient, segm); // reports an unknown command for abuse
break;
case 45:
testIPwhitelist(webclient, segm); // test for reports an unknown command for abuse
break;
case 46:
testHTTPblacklist(webclient, cmdString, segm); // test reports an unknown command for abuse
break;
default:
//check if it is a fan command;
int i = cmdString.indexOf("?");
if ((i != -1) && ((cmdString[i + 1] == 'A') || (cmdString[i + 1] == 'B') || (cmdString[i + 1] == 'C'))) {
Send_header(webclient);
ReadValue(cmdString, i, webclient, segm);
}
else {
if (!min_serial) {
textStringLog("\r\nNo command matches, 404 send. ", false);
}
/*
Only GET is supported
HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH are not supported and reported, somebody is too curious....
*/
if (cmdString.length() > 0) {
// We received an unknown command, store this to a different catogory. Per definition it is not suspicious could be a typo, but most of the time it is an attempted intrusion
StoreUnknwnCmd (cmdString, segm);
sprintf(temptxtbuff, "\r\nhttphacks increased: %d ", __LINE__); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
httphacks++;
httphacksTime = now();
}
send404(webclient, segm);
// ShowStatus(webclient, false);
}
}
cmdprocessed = true;
httpShown++;
if (HTTPlog && showbufferremaining && (webclient.available() > 0)) {
textlog("\r\nEmptying buffer, content of data is: ", true);
}
bx = 0;
while (webclient.available()) { //empty readbuffer
c = webclient.read();
if (bx < 255) {
suspicious_string[suspicious_index][bx] = c;
suspicious_string[suspicious_index][bx + 1] = '\0';
}
bx++;
if (HTTPlog && showbufferremaining) {
printprintable(c); // temptxtbuff is max 1024
}
}
if (HTTPlog && showbufferremaining && (bx != 0)) {
textlog("\r\n", false);
sprintf(temptxtbuff, "Buffer contained %d characters of data.", bx);
textlog(temptxtbuff, false);
}
if (bx > 3) {
// the remaining data in the request containt additional datagram which is suspicious
RqstCntnDtgrm(bx, segm);
}
bufferSize = 0;
inBuff[bufferSize] = '\0';
break;
}
else if (c == '\n') {
// we're starting a new line
currentLineIsBlank = true;
// if line contain non ASCII, the header is invalid
if (!showRxLine(bufferSize, inBuff)) {
while (webclient.available()) { //empty readbuffer
c = webclient.read();
if (bufferSize < bufferMax - 1) {
inBuff[bufferSize] = c;
bufferSize++;
inBuff[bufferSize] = '\0'; //allways terminate the buffer
}
}
charsReceivedNoCmd(bufferSize, inBuff, segm);
bufferSize = 0;
inBuff[0] = '\0';
break;
}
if ( !cmdRcvd ) {
String tmpString = String(inBuff);
// reset command buffer
bufferSize = 0;
inBuff[0] = '\0';
if ( tmpString.indexOf("/favicon") != -1 )
{
// textStringLog("\r\nHTTP Response sending favicon", false);
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d HTTP Response sending favicon", hour(), minute(), second()); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
// Cache-Control: max-age=31536000\r\nAccept-Ranges: bytes\r\n
webclient << F("HTTP/1.0 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: bytes\r\nContent-Type: image/x-icon\r\nConnection: close\r\n") << endl;
favicon(webclient);
bufferSize = 0;
bool susprqst = false;
while (webclient.available()) { //empty readbuffer
c = webclient.read();
if ((byte)c == 0) {
susprqst = true;
}
if (bufferSize < bufferMax - 1) {
inBuff[bufferSize] = c;
bufferSize++;
inBuff[bufferSize] = '\0'; //allways terminate the buffer
if (HTTPlog && showbufferremaining) {
if (bufferSize == 1) {
textlog("\r\nReadbuffer after favicon request contains:", false);
}
printprintable(c);
}
}
}
if (susprqst && (bufferSize > 5)) { // prevent that it triggers on the end of a valid header
charsReceivedNoCmd(bufferSize, inBuff, segm);
}
if (bufferSize > 0) {
sprintf(temptxtbuff, " -> flushed %d characters from buffer after favicon request", bufferSize); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
bufferSize = 0;
inBuff[0] = '\0';
break;
}
else if ( tmpString.indexOf("PRI * HTTP/2.0") != -1 ) {
textStringLog("\r\nHTTP Response sending PRI not supported", false);
// Cache-Control: max-age=31536000\r\nAccept-Ranges: bytes\r\n
//Illegal request, responding with status '501 Not Implemented': Unsupported HTTP method: PRI
webclient << F("HTTP/1.0 501 Not Implemented\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: none\r\nConnection: close\r\n") << endl;
bufferSize = 0;
while (webclient.available()) { //empty readbuffer
c = webclient.read();
bufferSize++;
if (HTTPlog && showbufferremaining) {
if (bufferSize == 1) {
textlog("\r\n", false);
}
printprintable(c);
}
}
if (bufferSize > 0) {
sprintf(temptxtbuff, " -> flushed %d characters from buffer by PRI command", bufferSize); // temptxtbuff is max 1024
textlog(temptxtbuff, false);
}
bufferSize = 0;
inBuff[0] = '\0';
break;
}
else if ( tmpString.indexOf("GET /robots.txt HTTP/") != -1 ) {
sendRobotstxt(webclient, segm); // answer that robots are not appreciated
bufferSize = 0;
inBuff[0] = '\0';
break;
}
else if ( tmpString.indexOf("GET /sitemap.xml HTTP/") != -1 ) {
send404(webclient, segm);
bufferSize = 0;
inBuff[0] = '\0';
break;
}
// else if ( tmpString.indexOf("GET /") != -1 ) {
else { // the first line is always the HTTP request method
cmdString = tmpString;
sprintf(temptxtbuff, "\r\n%02d:%02d:%02d HTTP cmd rcvd: ", hour(), minute(), second());
textlog(temptxtbuff, false);