├── .gitattributes
├── .gitignore
├── Code Cave.sln
├── Code Cave
├── Code Cave.vcxproj
├── Code Cave.vcxproj.filters
├── main.cpp
└── main.h
├── README.md
└── Shellcode
├── Shellcode.vcxproj
├── Shellcode.vcxproj.filters
├── main.c
└── main.h
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/Code Cave.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29709.97
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Code Cave", "Code Cave\Code Cave.vcxproj", "{B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}"
7 | EndProject
8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Shellcode", "Shellcode\Shellcode.vcxproj", "{E195F177-18C6-4673-A8D1-D38CAF7D2AAD}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|x64 = Debug|x64
13 | Debug|x86 = Debug|x86
14 | Release|x64 = Release|x64
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Debug|x64.ActiveCfg = Debug|x64
19 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Debug|x64.Build.0 = Debug|x64
20 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Debug|x86.ActiveCfg = Debug|Win32
21 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Debug|x86.Build.0 = Debug|Win32
22 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Release|x64.ActiveCfg = Release|x64
23 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Release|x64.Build.0 = Release|x64
24 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Release|x86.ActiveCfg = Release|Win32
25 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}.Release|x86.Build.0 = Release|Win32
26 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Debug|x64.ActiveCfg = Debug|x64
27 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Debug|x64.Build.0 = Debug|x64
28 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Debug|x86.ActiveCfg = Debug|Win32
29 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Debug|x86.Build.0 = Debug|Win32
30 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Release|x64.ActiveCfg = Release|x64
31 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Release|x64.Build.0 = Release|x64
32 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Release|x86.ActiveCfg = Release|Win32
33 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}.Release|x86.Build.0 = Release|Win32
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | GlobalSection(ExtensibilityGlobals) = postSolution
39 | SolutionGuid = {644AC29C-BAD0-4F75-831D-8437E7AE1EC2}
40 | EndGlobalSection
41 | EndGlobal
42 |
--------------------------------------------------------------------------------
/Code Cave/Code Cave.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 | 16.0
23 | {B71EF414-9D9D-4FCE-938A-FD83BCB7F26D}
24 | CodeCave
25 | 10.0
26 |
27 |
28 |
29 | Application
30 | true
31 | v142
32 | MultiByte
33 |
34 |
35 | Application
36 | false
37 | v142
38 | true
39 | MultiByte
40 |
41 |
42 | Application
43 | true
44 | v142
45 | Unicode
46 |
47 |
48 | Application
49 | false
50 | v142
51 | true
52 | Unicode
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | true
74 |
75 |
76 | true
77 |
78 |
79 | false
80 |
81 |
82 | false
83 |
84 |
85 |
86 | Level3
87 | true
88 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
89 | true
90 | MultiThreadedDLL
91 |
92 |
93 | Console
94 | true
95 |
96 |
97 |
98 |
99 | Level3
100 | true
101 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
102 | true
103 |
104 |
105 | Console
106 | true
107 |
108 |
109 |
110 |
111 | Level3
112 | true
113 | true
114 | true
115 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
116 | true
117 | MultiThreadedDLL
118 |
119 |
120 | Console
121 | true
122 | true
123 | true
124 |
125 |
126 |
127 |
128 | Level3
129 | true
130 | true
131 | true
132 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
133 | true
134 |
135 |
136 | Console
137 | true
138 | true
139 | true
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
--------------------------------------------------------------------------------
/Code Cave/Code Cave.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Header Files
20 |
21 |
22 |
23 |
24 | Source Files
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Code Cave/main.cpp:
--------------------------------------------------------------------------------
1 | #include "main.h"
2 |
3 | PIMAGE_SECTION_HEADER pISH;
4 |
5 | // Converts an RVA to a raw offset
6 | ULONG RvaToOffset(PIMAGE_NT_HEADERS pnth, ULONG Rva)
7 | {
8 | PIMAGE_SECTION_HEADER psh = IMAGE_FIRST_SECTION(pnth);
9 | USHORT NumberOfSections = pnth->FileHeader.NumberOfSections;
10 |
11 | for (int i = 0; i < NumberOfSections; i++)
12 | if (psh[i].VirtualAddress <= Rva && (psh[i].VirtualAddress + psh[i].Misc.VirtualSize) > Rva)
13 | return Rva - psh[i].VirtualAddress + psh[i].PointerToRawData;
14 |
15 | return -1;
16 | }
17 |
18 | // Returns a pointer to MessageBoxA from the Imports
19 | DWORD GetFunctionAddress(PVOID base, LPCSTR name)
20 | {
21 | PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)base;
22 | PIMAGE_NT_HEADERS pNTH = (PIMAGE_NT_HEADERS)((DWORD)pIDH + pIDH->e_lfanew);
23 |
24 | PIMAGE_IMPORT_DESCRIPTOR pDescriptor =
25 | (PIMAGE_IMPORT_DESCRIPTOR)((char*)base + RvaToOffset(pNTH, pNTH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress));
26 |
27 | while (pDescriptor->Name)
28 | {
29 | LPCSTR pDllName = (LPCSTR)((char*)base + RvaToOffset(pNTH, pDescriptor->Name));
30 | HMODULE hDll = LoadLibraryA(pDllName);
31 |
32 | if (hDll)
33 | {
34 | PIMAGE_THUNK_DATA pThunk;
35 | PIMAGE_THUNK_DATA pAddrThunk;
36 |
37 | if (pDescriptor->OriginalFirstThunk)
38 | {
39 | pThunk = (PIMAGE_THUNK_DATA)((char*)base + RvaToOffset(pNTH, pDescriptor->OriginalFirstThunk));
40 | }
41 | else
42 | {
43 | pThunk = (PIMAGE_THUNK_DATA)((char*)base + RvaToOffset(pNTH, pDescriptor->FirstThunk));
44 | }
45 |
46 | pAddrThunk = (PIMAGE_THUNK_DATA)((char*)base + RvaToOffset(pNTH, pDescriptor->FirstThunk));
47 |
48 | PIMAGE_THUNK_DATA pAddrThunk2 = (PIMAGE_THUNK_DATA)((DWORD)pNTH->OptionalHeader.ImageBase + pDescriptor->FirstThunk);
49 | while (pThunk->u1.AddressOfData)
50 | {
51 | PIMAGE_IMPORT_BY_NAME pImport = (PIMAGE_IMPORT_BY_NAME)((char*)base + RvaToOffset(pNTH, pThunk->u1.AddressOfData));
52 | if (!strcmp(pImport->Name, name))
53 | {
54 | return (DWORD)pAddrThunk2;
55 | }
56 |
57 | pThunk++;
58 | pAddrThunk++;
59 | pAddrThunk2++;
60 | }
61 | }
62 |
63 | pDescriptor++;
64 | }
65 |
66 | return 0;
67 | }
68 |
69 | // Process relocations
70 | void CreateRelocs(LPVOID lpMapped, uintptr_t functionAddress)
71 | {
72 | PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)lpMapped;
73 | PIMAGE_NT_HEADERS pNTH = (PIMAGE_NT_HEADERS)((DWORD)pIDH + pIDH->e_lfanew);
74 | PIMAGE_BASE_RELOCATION pRelocTable =
75 | (PIMAGE_BASE_RELOCATION)((char*)lpMapped + RvaToOffset(pNTH, pNTH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress));
76 |
77 | uintptr_t pRelocTableLast = (uintptr_t)pRelocTable + pNTH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
78 |
79 | while (pRelocTable->SizeOfBlock)
80 | {
81 | short* pRelocationData = (short*)((char*)pRelocTable + sizeof(IMAGE_BASE_RELOCATION));
82 | int NumberOfRelocationData = (pRelocTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(short);
83 |
84 | PIMAGE_BASE_RELOCATION pNextRelocTable = (PIMAGE_BASE_RELOCATION)((char*)pRelocTable + pRelocTable->SizeOfBlock);
85 | if (pNextRelocTable->VirtualAddress < functionAddress)
86 | {
87 | pRelocTable = (PIMAGE_BASE_RELOCATION)((char*)pRelocTable + pRelocTable->SizeOfBlock);
88 | continue;
89 | }
90 |
91 | short relocToInsert = (IMAGE_REL_BASED_HIGHLOW << 0xC) + functionAddress - pRelocTable->VirtualAddress; // This is the reloc we are injecting
92 |
93 | for (int i = 0; i < NumberOfRelocationData; i++)
94 | {
95 | if (pRelocationData[i] > relocToInsert // Address is bigger
96 | || ((PIMAGE_BASE_RELOCATION)((char*)pRelocTable + pRelocTable->SizeOfBlock) == 0 && (pRelocationData[i] >> 0xC) == IMAGE_REL_BASED_ABSOLUTE)) // Hit the end of the last reloc table
97 | {
98 | /***********Insert Relocation***********/
99 | uintptr_t source = (uintptr_t)pRelocationData + i * 2;
100 | uintptr_t dest = (uintptr_t)pRelocationData + i * 2 + 2;
101 | SIZE_T length = ((uintptr_t)pRelocTableLast) - source;
102 |
103 | memmove((short*)dest, (short*)source, length);
104 | pRelocationData[i] = relocToInsert;
105 | pRelocTable->SizeOfBlock += 2;
106 | //NumberOfRelocationData++;
107 |
108 | /**************Fix Padding**************/
109 |
110 | if (pRelocationData[NumberOfRelocationData] >> 0xC == IMAGE_REL_BASED_ABSOLUTE)
111 | {
112 | uintptr_t source2 = (uintptr_t)pRelocationData + NumberOfRelocationData * 2 + 4;
113 | uintptr_t dest2 = (uintptr_t)pRelocationData + NumberOfRelocationData * 2 + 2;
114 | SIZE_T length2 = ((uintptr_t)pRelocTableLast) - source2;
115 |
116 | memmove((short*)dest2, (short*)source2, length2);
117 | pRelocTable->SizeOfBlock -= 2;
118 | }
119 | else
120 | {
121 | uintptr_t source2 = (uintptr_t)pRelocationData + NumberOfRelocationData * 2 + 2;
122 | uintptr_t dest2 = (uintptr_t)pRelocationData + NumberOfRelocationData * 2 + 4;
123 | SIZE_T length2 = ((uintptr_t)pRelocTableLast) - source2;
124 |
125 | memmove((short*)dest2, (short*)source2, length2);
126 | pRelocationData[NumberOfRelocationData + 1] = 0;
127 | pRelocTable->SizeOfBlock += 2;
128 | }
129 |
130 | return;
131 | }
132 | }
133 | }
134 | }
135 |
136 | // Returns an insertion point
137 | int GetInsertionPoint(LPVOID lpMapped, PIMAGE_DOS_HEADER pIDH, PIMAGE_NT_HEADERS pNTH, int& sectionNumber)
138 | {
139 | SIZE_T InsertionPointOffset = 0;
140 | int countZeroes = 0;
141 |
142 | // Loop through each section
143 | for (sectionNumber = 0; sectionNumber < pNTH->FileHeader.NumberOfSections; sectionNumber++)
144 | {
145 | // Loop through each byte in section
146 | for (int j = 0; j < pISH[sectionNumber].SizeOfRawData; j++)
147 | {
148 | // Break if we've reached a large enough size to insert the shellcode
149 | if (sectionNumber != 1 && countZeroes == sizeof(shellcode) + 16 /*To avoid damaging other code, be safe and get a head start of 16 bytes*/)
150 | {
151 | InsertionPointOffset = pISH[sectionNumber].PointerToRawData + j - countZeroes + 16;
152 | printf("Found suitable insertion at point 0x%p, which is in %s\n", InsertionPointOffset, pISH[sectionNumber].Name);
153 | break;
154 | }
155 | // Check if byte is zero
156 | else if (*((LPBYTE)lpMapped + pISH[sectionNumber].PointerToRawData + j) == 0)
157 | {
158 | countZeroes++;
159 | }
160 | // Reset counter if we've reached a non-zero;
161 | else
162 | {
163 | countZeroes = 0;
164 | }
165 | }
166 |
167 | if (InsertionPointOffset)
168 | break;
169 | }
170 |
171 | return InsertionPointOffset;
172 | }
173 |
174 | int main(int argc, char** argv)
175 | {
176 | printf("Opening File: %s\n", argv[1]);
177 | HANDLE hFile = CreateFile(argv[1], FILE_READ_ACCESS | FILE_WRITE_ACCESS, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
178 | if (!hFile)
179 | return -1;
180 | printf("Created handle to file: 0x%X\n", hFile);
181 |
182 | HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
183 | if (!hMapping)
184 | return -1;
185 | printf("Created file mapping for: 0x%X\n", hMapping);
186 |
187 | LPVOID lpMapped = MapViewOfFile(hMapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
188 | if (!lpMapped)
189 | return -1;
190 | printf("Mapped view of file: 0x%X\n", lpMapped);
191 |
192 | PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)lpMapped;
193 | PIMAGE_NT_HEADERS pNTH = (PIMAGE_NT_HEADERS)((UINT_PTR)pIDH + pIDH->e_lfanew);
194 | pISH = IMAGE_FIRST_SECTION(pNTH);
195 |
196 | int sectionIndex;
197 | int InsertionPointOffset = GetInsertionPoint(lpMapped, pIDH, pNTH, sectionIndex);
198 | if (!InsertionPointOffset)
199 | return -1;
200 |
201 | pISH[sectionIndex].Characteristics |= IMAGE_SCN_MEM_EXECUTE;
202 | printf("Set %s characteristics to IMAGE_SCN_MEM_EXECUTE\n", pISH[sectionIndex].Name);
203 |
204 | uintptr_t functionAddr = GetFunctionAddress(lpMapped, "MessageBoxA");
205 | if (!functionAddr)
206 | {
207 | printf("The specified API does not exist in the program's IAT!");
208 | getchar();
209 | return -1;
210 | }
211 |
212 | *(uintptr_t*)(shellcode + MESSAGEBOXA_OFFSET) = functionAddr; // Add MessageBoxA
213 | uintptr_t rva = pNTH->OptionalHeader.AddressOfEntryPoint - pISH[sectionIndex].VirtualAddress - (InsertionPointOffset - pISH[sectionIndex].PointerToRawData) - (SHELLCODE_JMP_ADR_OFFSET + 4); //JMP to original Entrypoint
214 | *(uintptr_t*)(shellcode + SHELLCODE_JMP_ADR_OFFSET) = rva;
215 |
216 | pNTH->OptionalHeader.AddressOfEntryPoint = InsertionPointOffset + pISH[sectionIndex].VirtualAddress - pISH[sectionIndex].PointerToRawData;
217 |
218 | for (int i = 0; i < sizeof(shellcode); i++)
219 | {
220 | ((LPBYTE)lpMapped + InsertionPointOffset)[i] = shellcode[i];
221 | }
222 |
223 | if (RvaToOffset(pNTH, pNTH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress) != -1)
224 | {
225 | printf("File has relocations\n");
226 | CreateRelocs(lpMapped, (InsertionPointOffset - pISH[sectionIndex].PointerToRawData) + MESSAGEBOXA_OFFSET);
227 | }
228 |
229 | UnmapViewOfFile(lpMapped);
230 | CloseHandle(hMapping);
231 | CloseHandle(hFile);
232 |
233 | printf("Done\n");
234 |
235 | (void)getchar();
236 | }
--------------------------------------------------------------------------------
/Code Cave/main.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #define MESSAGEBOXA_OFFSET 0xA
5 | #define SHELLCODE_JMP_ADR_OFFSET 0x11
6 |
7 |
8 | unsigned char shellcode[32] = {
9 | 0x60, 0x9C, 0x33, 0xC0, 0x50, 0x50, 0x50, 0x50, 0xFF, 0x15, 0xAA, 0xAA, 0xAA, 0xAA, 0x9D, 0x61,
10 | 0xE9, 0xBB, 0xBB, 0xBB, 0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
11 | };
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Code-Cave
2 | It is simple to inject shellcode (position-independent code). However, I have not seen an example where someone injects **position-dependent** code (which requires relocations). This project injects a MessageBox into a code cave (a gap of unusued bytes) in an executable file, and applies relocations to the injected code.
3 |
4 | # Notes
5 | **The file must already have the API (MessageBoxA) in its Import Address Table.** Injecting the import into the IAT of the file may be possible but is incredibly complicated to do. It would require a large amount of adjustments to the other sections and offsets/addresses. At that point, it would be much more logical to write position-independent code.
6 |
7 | # Screenshots
8 |
9 | Demo injection into putty:
10 |
11 | 
12 |
--------------------------------------------------------------------------------
/Shellcode/Shellcode.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 | 16.0
23 | {E195F177-18C6-4673-A8D1-D38CAF7D2AAD}
24 | Shellcode
25 | 10.0
26 |
27 |
28 |
29 | Application
30 | true
31 | v142
32 | MultiByte
33 |
34 |
35 | Application
36 | false
37 | v142
38 | true
39 | MultiByte
40 |
41 |
42 | Application
43 | true
44 | v142
45 | Unicode
46 |
47 |
48 | Application
49 | false
50 | v142
51 | true
52 | Unicode
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | true
74 |
75 |
76 | true
77 |
78 |
79 | false
80 |
81 |
82 | false
83 |
84 |
85 |
86 | Level3
87 | true
88 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
89 | true
90 | MultiThreaded
91 |
92 |
93 | Console
94 | true
95 |
96 |
97 |
98 |
99 | Level3
100 | true
101 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions)
102 | true
103 |
104 |
105 | Console
106 | true
107 |
108 |
109 |
110 |
111 | Level3
112 | true
113 | true
114 | true
115 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
116 | true
117 | MultiThreaded
118 | false
119 | MinSpace
120 |
121 |
122 | Windows
123 | true
124 | true
125 | main
126 |
127 |
128 |
129 |
130 | Level3
131 | true
132 | true
133 | true
134 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
135 | true
136 |
137 |
138 | Console
139 | true
140 | true
141 | true
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
--------------------------------------------------------------------------------
/Shellcode/Shellcode.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Header Files
20 |
21 |
22 |
23 |
24 | Source Files
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Shellcode/main.c:
--------------------------------------------------------------------------------
1 | #include "main.h"
2 |
3 | _declspec (naked) main()
4 | {
5 | __asm
6 | {
7 | pushad
8 | pushfd
9 | }
10 |
11 | // If you do not mark it as volate, it will put it in the .rdata section, which will create relocs in the shellcode
12 | //volatile char text[] = "Injected!";
13 | (*(t_MessageBoxA*)(0xAAAAAAAA))(0,0,0,0);
14 |
15 | __asm
16 | {
17 | popfd
18 | popad
19 | _emit 0xE9 __asm _emit 0xBB __asm _emit 0xBB __asm _emit 0xBB __asm _emit 0xBB // jmp to OEP (SHELLCODE_JMP_OFFSET)
20 | }
21 | }
--------------------------------------------------------------------------------
/Shellcode/main.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | typedef (WINAPI *t_MessageBoxA)(
5 | _In_opt_ HWND hWnd,
6 | _In_opt_ LPCSTR lpText,
7 | _In_opt_ LPCSTR lpCaption,
8 | _In_ UINT uType);
9 |
--------------------------------------------------------------------------------