-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer-overflow.html
More file actions
979 lines (876 loc) · 34.3 KB
/
buffer-overflow.html
File metadata and controls
979 lines (876 loc) · 34.3 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Buffer Overflow Visualization — overflow.c</title>
<style>
:root {
--bg: #1a1b26;
--bg2: #24283b;
--bg3: #2f3347;
--fg: #c0caf5;
--fg-dim: #565f89;
--accent: #7aa2f7;
--green: #9ece6a;
--red: #f7768e;
--orange: #ff9e64;
--yellow: #e0af68;
--purple: #bb9af7;
--cyan: #7dcfff;
--teal: #73daca;
--col-retaddr: #f7768e;
--col-savedebp: #bb9af7;
--col-buffer: #7aa2f7;
--col-username: #73daca;
--col-padding: #3b4261;
--col-arg: #ff9e64;
--col-overflow: #f7768e;
--col-danger: #ff2040;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', 'Consolas', monospace;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
overflow-x: hidden;
}
h1 {
text-align: center;
padding: 16px 0 4px;
font-size: 1.25rem;
color: var(--accent);
letter-spacing: 0.5px;
}
h1 span { color: var(--fg-dim); font-weight: 400; font-size: 0.85rem; }
/* layout */
.app {
display: grid;
grid-template-columns: 300px 1fr 300px;
grid-template-rows: auto auto 1fr;
gap: 10px;
padding: 0 14px 14px;
max-width: 1440px;
margin: 0 auto;
height: calc(100vh - 60px);
}
/* input bar */
.input-bar {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
padding: 6px 0;
}
.input-bar label {
color: var(--fg-dim);
font-size: 0.8rem;
white-space: nowrap;
}
.input-bar input[type="text"] {
flex: 1;
min-width: 200px;
max-width: 500px;
background: var(--bg3);
border: 1px solid var(--fg-dim);
border-radius: 6px;
padding: 8px 12px;
color: var(--fg);
font-family: inherit;
font-size: 0.85rem;
outline: none;
transition: border-color 0.2s;
}
.input-bar input[type="text"]:focus { border-color: var(--accent); }
.input-bar input[type="text"].danger { border-color: var(--col-danger); box-shadow: 0 0 8px rgba(255,32,64,0.3); }
.presets { display: flex; gap: 6px; flex-wrap: wrap; }
.presets button {
background: var(--bg3);
color: var(--fg);
border: 1px solid var(--fg-dim);
border-radius: 6px;
padding: 6px 12px;
font-family: inherit;
font-size: 0.75rem;
cursor: pointer;
transition: all 0.15s;
white-space: nowrap;
}
.presets button:hover { background: var(--accent); color: var(--bg); border-color: var(--accent); }
.presets button.danger-btn { border-color: var(--red); color: var(--red); }
.presets button.danger-btn:hover { background: var(--red); color: #fff; }
.byte-counter {
font-size: 0.78rem;
color: var(--fg-dim);
min-width: 90px;
text-align: center;
}
.byte-counter.warn { color: var(--orange); }
.byte-counter.crit { color: var(--col-danger); font-weight: 700; }
/* panels */
.panel {
background: var(--bg2);
border-radius: 10px;
border: 1px solid var(--bg3);
overflow: hidden;
display: flex;
flex-direction: column;
}
.panel-title {
background: var(--bg3);
padding: 8px 14px;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 1.2px;
color: var(--fg-dim);
flex-shrink: 0;
}
.panel-body {
padding: 10px 14px;
overflow-y: auto;
flex: 1;
font-size: 0.82rem;
line-height: 1.7;
}
/* code panel */
.code-panel { grid-column: 1; grid-row: 3; }
.code-line {
display: flex;
padding: 1px 6px;
border-radius: 4px;
transition: background 0.2s;
white-space: pre;
}
.code-line.highlight-c { background: rgba(158,206,106,0.15); }
.line-no {
color: var(--fg-dim);
min-width: 24px;
text-align: right;
margin-right: 10px;
user-select: none;
}
.code-section { margin-bottom: 14px; }
.code-section-label {
font-size: 0.7rem;
color: var(--fg-dim);
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 4px;
padding-left: 2px;
}
.code-line.highlight-asm { background: rgba(122,162,247,0.2); }
.line-addr {
color: var(--fg-dim);
min-width: 76px;
margin-right: 8px;
user-select: none;
}
.kw { color: var(--purple); }
.fn { color: var(--accent); }
.num { color: var(--orange); }
.cmt { color: var(--fg-dim); font-style: italic; }
.reg { color: var(--cyan); }
.op { color: var(--red); }
.mem { color: var(--yellow); }
/* stack panel */
.stack-panel { grid-column: 2; grid-row: 3; }
.stack-panel .panel-body {
display: flex;
flex-direction: column;
align-items: center;
padding: 10px 10px;
}
.stack-container { width: 100%; max-width: 600px; }
.high-addr-label, .low-addr-label {
text-align: center;
font-size: 0.65rem;
color: var(--fg-dim);
letter-spacing: 1px;
text-transform: uppercase;
padding: 2px 0;
}
/* byte-level stack table */
.stack-table {
width: 100%;
border-collapse: collapse;
font-size: 0.76rem;
}
.stack-table th {
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.8px;
color: var(--fg-dim);
padding: 4px 6px;
text-align: center;
border-bottom: 1px solid var(--bg3);
position: sticky;
top: 0;
background: var(--bg2);
z-index: 1;
}
.stack-table td {
padding: 3px 4px;
text-align: center;
border-bottom: 1px solid rgba(47,51,71,0.5);
transition: all 0.25s;
}
.stack-table .addr-col { color: var(--fg-dim); font-size: 0.72rem; text-align: right; padding-right: 8px; white-space: nowrap; }
.stack-table .region-col { font-size: 0.68rem; text-align: left; padding-left: 8px; white-space: nowrap; }
.stack-table .ptr-col { font-size: 0.7rem; font-weight: 700; width: 36px; text-align: center; }
.stack-table .sep-row td { border-bottom: 2px solid var(--fg-dim); }
.byte-cell {
display: inline-block;
width: 28px;
height: 26px;
line-height: 26px;
text-align: center;
border-radius: 3px;
margin: 1px;
font-size: 0.73rem;
transition: all 0.2s;
border: 1px solid transparent;
}
.ascii-cell {
display: inline-block;
width: 20px;
height: 26px;
line-height: 26px;
text-align: center;
font-size: 0.73rem;
margin: 0 1px;
border-radius: 3px;
transition: all 0.2s;
}
.byte-buffer { background: rgba(122,162,247,0.15); border-color: rgba(122,162,247,0.3); color: var(--col-buffer); }
.byte-username { background: rgba(115,218,202,0.15); border-color: rgba(115,218,202,0.3); color: var(--col-username); }
.byte-savedebp { background: rgba(187,154,247,0.15); border-color: rgba(187,154,247,0.3); color: var(--col-savedebp); }
.byte-retaddr { background: rgba(247,118,142,0.15); border-color: rgba(247,118,142,0.3); color: var(--col-retaddr); }
.byte-empty { background: rgba(59,66,97,0.3); color: var(--fg-dim); }
.byte-arg { background: rgba(255,158,100,0.15); border-color: rgba(255,158,100,0.3); color: var(--col-arg); }
.byte-overflow {
background: rgba(255,32,64,0.3) !important;
border-color: var(--col-danger) !important;
color: #fff !important;
animation: pulse 0.8s ease-in-out infinite alternate;
}
@keyframes pulse {
0% { box-shadow: 0 0 2px rgba(255,32,64,0.3); }
100% { box-shadow: 0 0 8px rgba(255,32,64,0.6); }
}
.byte-null {
opacity: 0.5;
}
.word-val {
font-size: 0.7rem;
color: var(--fg-dim);
min-width: 80px;
text-align: center;
}
/* info/warnings panel */
.info-panel { grid-column: 3; grid-row: 3; display: flex; flex-direction: column; gap: 10px; }
.status-box {
background: var(--bg2);
border-radius: 10px;
border: 1px solid var(--bg3);
overflow: hidden;
flex-shrink: 0;
}
.status-box .panel-title { background: var(--bg3); padding: 8px 14px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1.2px; color: var(--fg-dim); }
.status-body { padding: 10px 14px; }
.status-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 0;
font-size: 0.78rem;
}
.status-item .label { color: var(--fg-dim); }
.status-item .val { font-weight: 600; }
.val-safe { color: var(--green); }
.val-warn { color: var(--orange); }
.val-danger { color: var(--col-danger); }
.alert-box {
border-radius: 8px;
padding: 10px 14px;
font-size: 0.78rem;
line-height: 1.6;
margin-top: 8px;
transition: all 0.3s;
}
.alert-safe {
background: rgba(158,206,106,0.1);
border: 1px solid var(--green);
color: var(--green);
}
.alert-warn {
background: rgba(255,158,100,0.1);
border: 1px solid var(--orange);
color: var(--orange);
}
.alert-danger {
background: rgba(255,32,64,0.15);
border: 1px solid var(--col-danger);
color: var(--col-danger);
}
.alert-critical {
background: rgba(255,32,64,0.25);
border: 2px solid var(--col-danger);
color: #fff;
animation: dangerPulse 1s ease-in-out infinite alternate;
}
@keyframes dangerPulse {
0% { box-shadow: 0 0 5px rgba(255,32,64,0.3); }
100% { box-shadow: 0 0 20px rgba(255,32,64,0.5); }
}
.explanation-panel {
background: var(--bg2);
border-radius: 10px;
border: 1px solid var(--bg3);
overflow: hidden;
flex: 1;
display: flex;
flex-direction: column;
}
.explanation-panel .panel-title { background: var(--bg3); padding: 8px 14px; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1.2px; color: var(--fg-dim); }
.explanation-panel .panel-body {
padding: 12px 14px;
font-size: 0.78rem;
line-height: 1.6;
overflow-y: auto;
flex: 1;
}
.explanation-panel .panel-body p { margin-bottom: 8px; }
.explanation-panel .panel-body code {
background: var(--bg3);
padding: 1px 5px;
border-radius: 3px;
font-size: 0.76rem;
color: var(--cyan);
}
/* legend */
.legend {
grid-column: 1 / -1;
display: flex;
justify-content: center;
gap: 16px;
flex-wrap: wrap;
padding: 4px 0 0;
font-size: 0.7rem;
}
.legend-item { display: flex; align-items: center; gap: 5px; }
.legend-swatch { width: 14px; height: 14px; border-radius: 3px; border: 1px solid; }
/* step mode controls */
.step-controls {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.step-controls button {
background: var(--bg3);
color: var(--fg);
border: 1px solid var(--fg-dim);
border-radius: 6px;
padding: 6px 14px;
font-family: inherit;
font-size: 0.8rem;
cursor: pointer;
transition: all 0.15s;
}
.step-controls button:hover:not(:disabled) { background: var(--accent); color: var(--bg); border-color: var(--accent); }
.step-controls button:disabled { opacity: 0.3; cursor: default; }
.mode-toggle {
display: flex;
align-items: center;
gap: 6px;
margin-left: 16px;
font-size: 0.78rem;
color: var(--fg-dim);
}
.mode-toggle input { accent-color: var(--accent); }
.step-indicator {
color: var(--fg-dim);
font-size: 0.78rem;
min-width: 140px;
text-align: center;
}
@media (max-width: 1100px) {
.app {
grid-template-columns: 1fr;
height: auto;
}
.code-panel, .stack-panel, .info-panel { grid-column: 1; }
.code-panel { max-height: 300px; }
.stack-panel { max-height: 500px; }
.legend { grid-column: 1; }
}
</style>
</head>
<body>
<h1>Buffer Overflow Visualization <span>— overflow.c (x86-32)</span></h1>
<div class="app">
<!-- Input bar -->
<div class="input-bar">
<label>./overflow</label>
<input type="text" id="inputField" placeholder='Type argv[1] here... (e.g. "hello" or "AAAAAAAAAAAABBBBBBBBBBBBCCCCDDDD")' spellcheck="false" autocomplete="off">
<span class="byte-counter" id="byteCounter">0 bytes</span>
<div class="presets">
<button onclick="setInput('hello')">Safe: "hello"</button>
<button onclick="setInput('AAAAAAAAAAAABBBB')">Overwrite username</button>
<button onclick="setInput('AAAAAAAAAAAABBBBBBBBBBBBCCCC')">Overwrite saved EBP</button>
<button class="danger-btn" onclick="setInput('AAAAAAAAAAAABBBBBBBBBBBBCCCC\\xef\\xbe\\xad\\xde')">Overwrite return addr</button>
</div>
</div>
<!-- Step controls -->
<div class="step-controls">
<button id="btnReset" title="Reset">Reset</button>
<button id="btnPrev" title="Previous">‹ Prev</button>
<span class="step-indicator" id="stepIndicator">Step 0 / 0</span>
<button id="btnNext" title="Next">Next ›</button>
<button id="btnEnd" title="Run to end">Run All »</button>
<div class="mode-toggle">
<label><input type="checkbox" id="liveMode" checked> Live mode</label>
</div>
</div>
<!-- Left: Code -->
<div class="panel code-panel">
<div class="panel-title">Source & Assembly</div>
<div class="panel-body" id="codePanel"></div>
</div>
<!-- Center: Stack -->
<div class="panel stack-panel">
<div class="panel-title">Stack Memory (byte-level view)</div>
<div class="panel-body">
<div class="high-addr-label">▲ Higher addresses</div>
<div class="stack-container" id="stackContainer"></div>
<div class="low-addr-label">▼ Lower addresses</div>
</div>
</div>
<!-- Right: Info -->
<div class="info-panel">
<div class="status-box">
<div class="panel-title">Overflow Status</div>
<div class="status-body" id="statusBody"></div>
</div>
<div class="explanation-panel">
<div class="panel-title">What's happening</div>
<div class="panel-body" id="explPanel"></div>
</div>
</div>
<!-- Legend -->
<div class="legend">
<div class="legend-item"><div class="legend-swatch" style="background:rgba(122,162,247,0.15);border-color:var(--col-buffer)"></div> buffer[12]</div>
<div class="legend-item"><div class="legend-swatch" style="background:rgba(115,218,202,0.15);border-color:var(--col-username)"></div> username[12]</div>
<div class="legend-item"><div class="legend-swatch" style="background:rgba(187,154,247,0.15);border-color:var(--col-savedebp)"></div> Saved EBP</div>
<div class="legend-item"><div class="legend-swatch" style="background:rgba(247,118,142,0.15);border-color:var(--col-retaddr)"></div> Return Address</div>
<div class="legend-item"><div class="legend-swatch" style="background:rgba(255,32,64,0.3);border-color:var(--col-danger)"></div> Overflowed byte</div>
</div>
</div>
<script>
// ============================================================
// MEMORY LAYOUT
// ============================================================
// Stack frame for main() on x86-32:
//
// Address Content Region
// 0xBFFFF6F4 0x00000000 argc (simplified)
// 0xBFFFF6F0 0xB7E21637 return address (to __libc_start_main)
// 0xBFFFF6EC 0xBFFFF700 saved EBP
// 0xBFFFF6E0 username[0..11] ebp-12 .. ebp-1
// 0xBFFFF6D4 buffer[0..11] ebp-24 .. ebp-13
// ... (ESP after sub)
//
// buffer starts at 0xBFFFF6D4 (lower address)
// username starts at 0xBFFFF6E0 (higher address)
// Overflow from buffer goes: buffer -> username -> saved EBP -> return addr
const BASE_ADDR = 0xBFFFF6D4; // buffer[0]
// Total bytes we visualize: buffer(12) + username(12) + savedEBP(4) + retaddr(4) = 32
const TOTAL_BYTES = 32;
// Regions: [startOffset, length, name, cssClass]
const REGIONS = [
{ start: 0, len: 12, name: 'buffer[12]', cls: 'buffer', label: 'buffer' },
{ start: 12, len: 12, name: 'username[12]', cls: 'username', label: 'username' },
{ start: 24, len: 4, name: 'Saved EBP', cls: 'savedebp', label: 'saved EBP' },
{ start: 28, len: 4, name: 'Return Address', cls: 'retaddr', label: 'ret addr' },
];
function getRegion(offset) {
for (const r of REGIONS) {
if (offset >= r.start && offset < r.start + r.len) return r;
}
return null;
}
// Initial memory state (before strcpy of argv[1])
// username already has "ec521\0" from the first strcpy
// saved EBP = 0xBFFFF700, return addr = 0xB7E21637
function makeInitialMem() {
const mem = new Uint8Array(TOTAL_BYTES);
// buffer: uninitialized (show as 00)
for (let i = 0; i < 12; i++) mem[i] = 0x00;
// username: "ec521\0\0\0\0\0\0\0"
const uname = [0x65, 0x63, 0x35, 0x32, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
for (let i = 0; i < 12; i++) mem[12 + i] = uname[i];
// saved EBP: 0xBFFFF700 (little-endian)
mem[24] = 0x00; mem[25] = 0xF7; mem[26] = 0xFF; mem[27] = 0xBF;
// return addr: 0xB7E21637 (little-endian)
mem[28] = 0x37; mem[29] = 0x16; mem[30] = 0xE2; mem[31] = 0xB7;
return mem;
}
// ============================================================
// C SOURCE & ASSEMBLY
// ============================================================
const C_LINES = [
'#include <string.h>',
'#include <stdio.h>',
'',
'int main(int argc, char** argv) {',
'',
' char username[12];',
' char buffer[12];',
'',
' strcpy(username, "ec521");',
' strcpy(buffer, argv[1]);',
'',
' printf("%p %s\\n", buffer, buffer);',
' printf("%p %s\\n", username, username);',
'',
' return 0;',
'}',
];
const ASM_LINES = [
{ addr: '08048420', text: 'push\u00a0\u00a0 ebp', id: 'push_ebp' },
{ addr: '08048421', text: 'mov\u00a0\u00a0\u00a0 ebp, esp', id: 'mov_ebp' },
{ addr: '08048423', text: 'sub\u00a0\u00a0\u00a0 esp, 0x28', id: 'sub_esp' },
{ addr: '', text: '; strcpy(username, "ec521")', id: 'cmt1', isCmt: true },
{ addr: '08048426', text: 'push\u00a0\u00a0 0x80484E0', id: 'push_str', note: '"ec521"' },
{ addr: '0804842B', text: 'lea\u00a0\u00a0\u00a0 eax, [ebp-12]', id: 'lea_uname' },
{ addr: '0804842E', text: 'push\u00a0\u00a0 eax', id: 'push_uname' },
{ addr: '0804842F', text: 'call\u00a0\u00a0 strcpy', id: 'call_strcpy1' },
{ addr: '08048434', text: 'add\u00a0\u00a0\u00a0 esp, 8', id: 'clean1' },
{ addr: '', text: '; strcpy(buffer, argv[1])', id: 'cmt2', isCmt: true },
{ addr: '08048437', text: 'mov\u00a0\u00a0\u00a0 eax, [ebp+12]', id: 'load_argv' },
{ addr: '0804843A', text: 'mov\u00a0\u00a0\u00a0 eax, [eax+4]', id: 'load_argv1' },
{ addr: '0804843D', text: 'push\u00a0\u00a0 eax', id: 'push_src' },
{ addr: '0804843E', text: 'lea\u00a0\u00a0\u00a0 edx, [ebp-24]', id: 'lea_buf' },
{ addr: '08048441', text: 'push\u00a0\u00a0 edx', id: 'push_dst' },
{ addr: '08048442', text: 'call\u00a0\u00a0 strcpy', id: 'call_strcpy2' },
{ addr: '08048447', text: 'add\u00a0\u00a0\u00a0 esp, 8', id: 'clean2' },
{ addr: '', text: '; printf calls omitted...', id: 'cmt3', isCmt: true },
{ addr: '08048470', text: 'mov\u00a0\u00a0\u00a0 eax, 0', id: 'mov_ret' },
{ addr: '08048475', text: 'leave', id: 'leave' },
{ addr: '08048476', text: 'ret', id: 'ret' },
];
// ============================================================
// STEP DEFINITIONS
// ============================================================
// Steps for the step-by-step mode
// Each step represents one byte being copied by strcpy, or a setup/teardown step
function parseInput(raw) {
// Handle \xNN escape sequences
const bytes = [];
let i = 0;
while (i < raw.length) {
if (raw[i] === '\\' && raw[i+1] === 'x' && i + 3 < raw.length) {
const hex = raw.substring(i+2, i+4);
const val = parseInt(hex, 16);
if (!isNaN(val)) {
bytes.push(val);
i += 4;
continue;
}
}
bytes.push(raw.charCodeAt(i));
i++;
}
return bytes;
}
// ============================================================
// STATE
// ============================================================
let inputBytes = [];
let mem = makeInitialMem();
let stepIndex = 0; // -1 = initial, 0..N = byte being copied, N+1 = null terminator written
let liveMode = true;
// ============================================================
// RENDERING
// ============================================================
function escHtml(s) {
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function hexByte(b) { return b.toString(16).padStart(2, '0').toUpperCase(); }
function hexAddr(offset) { return '0x' + (BASE_ADDR + offset).toString(16).toUpperCase(); }
function toAscii(b) {
if (b >= 0x20 && b <= 0x7e) return String.fromCharCode(b);
if (b === 0) return '\\0';
return '.';
}
function renderCode() {
const panel = document.getElementById('codePanel');
let html = '';
// Which C line to highlight
let cHighlight = -1;
if (stepIndex < 0) {
cHighlight = 8; // strcpy(username, ...)
} else {
cHighlight = 9; // strcpy(buffer, argv[1])
}
html += '<div class="code-section"><div class="code-section-label">C Source</div>';
C_LINES.forEach((line, i) => {
const cls = (i === cHighlight) ? ' highlight-c' : '';
html += `<div class="code-line${cls}"><span class="line-no">${i+1}</span><span>${escHtml(line)}</span></div>`;
});
html += '</div>';
// Assembly
let asmHighlight = '';
if (stepIndex < 0) asmHighlight = 'call_strcpy1';
else if (stepIndex <= inputBytes.length) asmHighlight = 'call_strcpy2';
else asmHighlight = 'leave';
html += '<div class="code-section"><div class="code-section-label">Assembly (simplified)</div>';
ASM_LINES.forEach(line => {
const isHl = line.id === asmHighlight;
const cls = isHl ? ' highlight-asm' : '';
const addrHtml = line.isCmt ? '' : `<span class="line-addr">${line.addr}</span>`;
let textHtml;
if (line.isCmt) {
textHtml = `<span class="cmt">${escHtml(line.text)}</span>`;
} else {
textHtml = colorAsm(line.text);
}
html += `<div class="code-line${cls}">${addrHtml}${textHtml}</div>`;
});
html += '</div>';
panel.innerHTML = html;
}
function colorAsm(text) {
const parts = text.split(/(\u00a0+| +)/);
return parts.map(part => {
if (/^[\u00a0 ]+$/.test(part)) return part;
if (part.includes(',')) return part.split(',').map(colorAsmToken).join(',');
if (/^\[.*\]$/.test(part)) {
const inner = part.slice(1, -1);
return '[<span class="mem">' + colorAsmToken(inner) + '</span>]';
}
return colorAsmToken(part);
}).join('');
}
function colorAsmToken(tok) {
if (/^(push|pop|mov|sub|add|call|leave|ret|lea|DWORD|BYTE)$/i.test(tok)) return `<span class="op">${tok}</span>`;
if (/^(eax|ebx|ecx|edx|esp|ebp|eip|esi|edi)$/i.test(tok)) return `<span class="reg">${tok}</span>`;
if (/^0x[0-9a-fA-F]+$/.test(tok)) return `<span class="num">${tok}</span>`;
if (/^\d+$/.test(tok)) return `<span class="num">${tok}</span>`;
if (/^strcpy$/.test(tok)) return `<span class="fn">${tok}</span>`;
return escHtml(tok);
}
function renderStack() {
const container = document.getElementById('stackContainer');
// How many bytes from input have been written so far
const written = liveMode ? inputBytes.length + 1 : stepIndex + 1; // +1 for null terminator
const bytesWritten = liveMode
? Math.min(inputBytes.length + 1, TOTAL_BYTES) // include null term
: Math.min(Math.max(stepIndex + 1, 0), TOTAL_BYTES);
// Build current memory
mem = makeInitialMem();
const writeCount = liveMode ? inputBytes.length : Math.max(stepIndex, 0);
for (let i = 0; i < writeCount && i < TOTAL_BYTES; i++) {
mem[i] = inputBytes[i];
}
// null terminator
if (writeCount < TOTAL_BYTES) {
mem[writeCount] = 0x00;
}
// Render as 4-byte rows, from highest address to lowest
let html = '<table class="stack-table">';
html += '<tr><th></th><th>Address</th><th colspan="4">Hex bytes</th><th colspan="4">ASCII</th><th>32-bit word</th><th>Region</th></tr>';
// We display from offset 31 down to 0, in groups of 4
for (let rowStart = TOTAL_BYTES - 4; rowStart >= 0; rowStart -= 4) {
const region = getRegion(rowStart);
const regionName = region ? region.name : '';
// Is this row a boundary between regions?
const nextRegion = getRegion(rowStart + 4);
const isSep = nextRegion && region && nextRegion.cls !== region.cls;
// EBP / ESP pointers
const ebpOffset = 24; // saved EBP is at offset 24, so EBP points to offset 24
const espOffset = -6 * 4; // not relevant for display, skip
let ptrLabel = '';
if (rowStart === 24) ptrLabel = '<span style="color:var(--col-savedebp)">EBP▶</span>';
// Build 4 byte cells (little-endian: show left=lowest addr, right=highest addr within row)
let hexCells = '';
let asciiCells = '';
let wordVal = 0;
for (let b = 0; b < 4; b++) {
const offset = rowStart + b;
const val = mem[offset];
wordVal |= (val << (b * 8));
const reg = getRegion(offset);
let cellCls = reg ? `byte-${reg.cls}` : 'byte-empty';
// Is this byte an overflow byte? (written by strcpy into a region beyond buffer)
const isWritten = offset < writeCount || (offset === writeCount); // strcpy wrote here
const isOverflow = isWritten && offset >= 12 && offset < writeCount; // past buffer, not null term in buffer
const isNullInOverflow = offset === writeCount && offset >= 12; // null terminator landed in overflow
if (isOverflow || isNullInOverflow) {
cellCls += ' byte-overflow';
}
if (val === 0 && isWritten && offset <= writeCount) {
// null terminator or zero
}
const hex = hexByte(val);
const ascii = toAscii(val);
hexCells += `<td><span class="byte-cell ${cellCls}">${hex}</span></td>`;
asciiCells += `<td><span class="ascii-cell ${cellCls}">${escHtml(ascii)}</span></td>`;
}
const wordHex = '0x' + wordVal.toString(16).padStart(8, '0').toUpperCase();
html += `<tr class="${isSep ? 'sep-row' : ''}">`;
html += `<td class="ptr-col">${ptrLabel}</td>`;
html += `<td class="addr-col">${hexAddr(rowStart)}</td>`;
html += hexCells;
html += asciiCells;
html += `<td class="word-val">${wordHex}</td>`;
html += `<td class="region-col">${regionName}</td>`;
html += '</tr>';
}
html += '</table>';
container.innerHTML = html;
}
function renderStatus() {
const body = document.getElementById('statusBody');
const writeCount = liveMode ? inputBytes.length : Math.max(stepIndex, 0);
const bufferUsed = Math.min(writeCount, 12);
const usernameCorrupted = writeCount > 12;
const ebpCorrupted = writeCount > 24;
const retCorrupted = writeCount > 28;
// Read current username from mem
let usernameStr = '';
for (let i = 12; i < 24; i++) {
if (mem[i] === 0) break;
usernameStr += String.fromCharCode(mem[i]);
}
// Read current return addr
let retVal = 0;
for (let b = 0; b < 4; b++) retVal |= (mem[28 + b] << (b * 8));
const retHex = '0x' + (retVal >>> 0).toString(16).padStart(8, '0').toUpperCase();
// Read current saved EBP
let ebpVal = 0;
for (let b = 0; b < 4; b++) ebpVal |= (mem[24 + b] << (b * 8));
const ebpHex = '0x' + (ebpVal >>> 0).toString(16).padStart(8, '0').toUpperCase();
let html = '';
html += `<div class="status-item"><span class="label">Input length:</span><span class="val ${writeCount > 11 ? (writeCount > 24 ? 'val-danger' : 'val-warn') : 'val-safe'}">${writeCount} byte${writeCount !== 1 ? 's' : ''} + \\0</span></div>`;
html += `<div class="status-item"><span class="label">buffer[12] used:</span><span class="val">${bufferUsed}/12</span></div>`;
html += `<div class="status-item"><span class="label">username now:</span><span class="val ${usernameCorrupted ? 'val-warn' : 'val-safe'}">"${escHtml(usernameStr)}"</span></div>`;
html += `<div class="status-item"><span class="label">Saved EBP:</span><span class="val ${ebpCorrupted ? 'val-danger' : 'val-safe'}">${ebpHex}</span></div>`;
html += `<div class="status-item"><span class="label">Return addr:</span><span class="val ${retCorrupted ? 'val-danger' : 'val-safe'}">${retHex}</span></div>`;
// Alert
if (retCorrupted) {
html += `<div class="alert-box alert-critical"><strong>CRITICAL:</strong> Return address overwritten!<br>When <code>main()</code> returns, EIP will jump to <code>${retHex}</code>.<br>This is <strong>arbitrary code execution</strong>.</div>`;
} else if (ebpCorrupted) {
html += `<div class="alert-box alert-danger"><strong>DANGER:</strong> Saved frame pointer (EBP) corrupted!<br>EBP = <code>${ebpHex}</code><br>Stack frame chain is broken. Further overwrite will reach the return address.</div>`;
} else if (usernameCorrupted) {
html += `<div class="alert-box alert-warn"><strong>WARNING:</strong> Buffer overflow detected!<br><code>strcpy</code> has written past <code>buffer[12]</code> into <code>username</code>.<br>username changed from <code>"ec521"</code> to <code>"${escHtml(usernameStr)}"</code></div>`;
} else {
html += `<div class="alert-box alert-safe"><strong>Safe:</strong> Input fits within buffer[12]. No overflow.</div>`;
}
body.innerHTML = html;
}
function renderExplanation() {
const panel = document.getElementById('explPanel');
const writeCount = liveMode ? inputBytes.length : Math.max(stepIndex, 0);
let html = '';
html += `<p><code>strcpy(buffer, argv[1])</code> copies bytes from the source string into <code>buffer</code> starting at address <code>0xBFFFF6D4</code>, writing byte after byte toward <strong>higher addresses</strong> until it hits a null terminator <code>\\0</code>.</p>`;
html += `<p>The stack layout is:</p>`;
html += `<p><code>buffer[12]</code> at <code>[ebp-24]</code> = <code>0xBFFFF6D4</code><br>`;
html += `<code>username[12]</code> at <code>[ebp-12]</code> = <code>0xBFFFF6E0</code><br>`;
html += `<code>Saved EBP</code> at <code>[ebp]</code> = <code>0xBFFFF6EC</code><br>`;
html += `<code>Return addr</code> at <code>[ebp+4]</code> = <code>0xBFFFF6F0</code></p>`;
if (writeCount <= 11) {
html += `<p style="color:var(--green)">The input (${writeCount} bytes + null terminator) fits within <code>buffer[12]</code>. <code>strcpy</code> stops copying and no adjacent memory is corrupted.</p>`;
} else if (writeCount <= 23) {
const overflow = writeCount - 12;
html += `<p style="color:var(--orange)">The input is <strong>${writeCount} bytes</strong> — that's ${overflow} byte${overflow > 1 ? 's' : ''} past the end of <code>buffer[12]</code>!</p>`;
html += `<p style="color:var(--orange)"><code>strcpy</code> has no bounds checking. It blindly continues writing into <code>username</code>'s memory, corrupting its contents. The <code>printf</code> for <code>username</code> would now print the overflowed data instead of <code>"ec521"</code>.</p>`;
} else if (writeCount <= 27) {
html += `<p style="color:var(--col-danger)">The input has <strong>overflowed past both arrays</strong> and is now corrupting the <strong>saved EBP</strong> (frame pointer).</p>`;
html += `<p style="color:var(--col-danger)">When <code>main</code> executes <code>leave</code>, it will restore EBP to a corrupted value. This breaks the stack frame chain and will likely cause a crash when the caller tries to access its local variables.</p>`;
} else {
html += `<p style="color:var(--col-danger);font-weight:700">The saved <strong>return address</strong> has been overwritten!</p>`;
html += `<p style="color:var(--col-danger)">When <code>main</code> executes <code>ret</code>, the CPU will pop this corrupted value into <code>EIP</code> and jump to it. An attacker can craft the input to set this to any address — for example, the address of injected shellcode.</p>`;
html += `<p style="color:var(--col-danger)">This is the fundamental mechanism behind <strong>stack-based buffer overflow exploits</strong>. By controlling the return address, the attacker achieves <strong>arbitrary code execution</strong>.</p>`;
}
panel.innerHTML = html;
}
function renderStepControls() {
const maxStep = inputBytes.length + 1; // +1 for null terminator
document.getElementById('stepIndicator').textContent =
liveMode ? 'Live mode' : `strcpy byte ${Math.max(stepIndex, 0)} / ${inputBytes.length}`;
document.getElementById('btnPrev').disabled = liveMode || stepIndex <= -1;
document.getElementById('btnNext').disabled = liveMode || stepIndex >= maxStep;
document.getElementById('btnEnd').disabled = liveMode;
// Input field danger styling
const inp = document.getElementById('inputField');
const writeCount = liveMode ? inputBytes.length : Math.max(stepIndex, 0);
inp.classList.toggle('danger', writeCount > 24);
// Byte counter
const bc = document.getElementById('byteCounter');
bc.textContent = `${inputBytes.length} bytes`;
bc.className = 'byte-counter' + (inputBytes.length > 24 ? ' crit' : inputBytes.length > 11 ? ' warn' : '');
}
function render() {
renderCode();
renderStack();
renderStatus();
renderExplanation();
renderStepControls();
}
// ============================================================
// INPUT HANDLING
// ============================================================
function setInput(val) {
document.getElementById('inputField').value = val;
onInputChange();
}
function onInputChange() {
const raw = document.getElementById('inputField').value;
inputBytes = parseInput(raw);
if (liveMode) {
stepIndex = inputBytes.length; // show final state
} else {
stepIndex = -1; // reset to beginning
}
render();
}
document.getElementById('inputField').addEventListener('input', onInputChange);
document.getElementById('liveMode').addEventListener('change', function() {
liveMode = this.checked;
if (liveMode) {
stepIndex = inputBytes.length;
} else {
stepIndex = -1;
}
render();
});
document.getElementById('btnReset').addEventListener('click', () => {
stepIndex = -1;
render();
});
document.getElementById('btnPrev').addEventListener('click', () => {
if (stepIndex > -1) { stepIndex--; render(); }
});
document.getElementById('btnNext').addEventListener('click', () => {
if (stepIndex < inputBytes.length + 1) { stepIndex++; render(); }
});
document.getElementById('btnEnd').addEventListener('click', () => {
stepIndex = inputBytes.length;
render();
});
document.addEventListener('keydown', e => {
if (document.activeElement === document.getElementById('inputField')) return;
if (e.key === 'ArrowRight') { e.preventDefault(); if (!liveMode && stepIndex < inputBytes.length + 1) { stepIndex++; render(); } }
if (e.key === 'ArrowLeft') { e.preventDefault(); if (!liveMode && stepIndex > -1) { stepIndex--; render(); } }
});
// ============================================================
// INITIAL RENDER
// ============================================================
render();
</script>
</body>
</html>