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
///This module contains all error Types.
use core::fmt::{Display, Formatter};
#[derive(Debug)]
///This is the error type for this crate
pub enum Error {
///This represents an error from the regular windows api
///String is the method the error occurred in
///u32 is the Error, that occurred
Winapi(&'static str, u32),
///Gets returned from NTDLL calls.
///This maps, if NTStatus is considered a Warning or Error.
///(Because typically NTDLL calls don't succeed, even if the return type is just a Warning)
Ntdll(i32),
///Gets returned, if a Wide String cannot be converted into a regular string.
WTFConvert(widestring::error::DecodeUtf16Error), //Windows u16 string stuff
#[cfg(feature = "std")]
///Passes errors from std::io.
Io(std::io::Error),
#[cfg(target_family = "windows")]
///Contains errors from the pelite crate.
///
///See [pelite::Error]
Pelite(pelite::Error),
///This is mapped, if a certain thing could potentially be supported with more work, but just has not been implemented yet.
Unsupported(Option<&'static str>),
///This represents Error Codes generated by this crate.
InjectLib(CustomError),
}
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
//It is fine for additional Error variants to appear in a patch release.
//Disappearing Error variants is always a breaking change.
#[non_exhaustive]
///This Represents Error Codes generated by this Crate
pub enum CustomError {
///This is thrown, if all available injectors cannot be used in a certain situation.
///This should only happen, if the feature x86tox64 is disabled, but the library is compiled into a x86 binary, which tries injecting into a x64 process.
NoViableInjector,
///Special Return codes returned only by WaitForSingleObject
WaitForSingleObject(u32),
///This occurs, if some predicate is supplied, that doesn't select an element in a module list
ModuleListLoop,
///If for some reason a function call returns zero bytes, but succeeded, this error will get used
ZeroBytes,
///If the LDR is unpopulated during a get_module_in_proc call
LDRUninit,
///This errror Indicates, that there is possibly a problem with a structure in this crate
InvalidStructure,
///Dll file path name does not end in a file
DllPathNoFile,
///The Memory Page was not allocated in the expected process.
MempageInvalidProcess,
///The input parameters were invalid.
InvalidInput,
///The requested operation would have resulted in a Permission error.
PermissionDenied,
///This occures when it was expexted, that a Library is Loaded, but not found.
LibraryNotFound(alloc::string::String),
}
impl From<CustomError> for Error {
fn from(x: CustomError) -> Self {
Error::InjectLib(x)
}
}
#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
///Converts a std::Io::Error into a Error for use in this crate
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
impl Error {
///Gets the contents of Error::Winapi, if self holds data of that type
fn get_winapi(&self) -> Option<(&&'static str, &u32)> {
match self {
Error::Winapi(x, y) => Some((x, y)),
_ => None,
}
}
///Gets the contents of Error::NTDLL, if self holds data of that type
fn get_ntdll(&self) -> Option<&i32> {
match self {
Error::Ntdll(x) => Some(x),
_ => None,
}
}
///Gets the contents of Error::WTFConvert, if self holds data of that type
fn get_wtfconvert(&self) -> Option<&widestring::error::DecodeUtf16Error> {
match self {
Error::WTFConvert(x) => Some(x),
_ => None,
}
}
#[cfg(feature = "std")]
///Gets the contents of Error::Io, if self holds data of that type
fn get_io(&self) -> Option<&std::io::Error> {
match self {
Error::Io(x) => Some(x),
_ => None,
}
}
///Gets the contents of Error::Unsupported, if self holds data of that type
fn get_unsupported(&self) -> Option<&Option<&'static str>> {
match self {
Error::Unsupported(x) => Some(x),
_ => None,
}
}
#[cfg(target_family = "windows")]
///Gets the contents of Error::Pelite, if self holds data of that type
fn get_pelite(&self) -> Option<&pelite::Error> {
match self {
Error::Pelite(x) => Some(x),
_ => None,
}
}
///Gets the contents of Error::InjectLib, if self holds data of that type
fn get_injectlib(&self) -> Option<&CustomError> {
match self {
Error::InjectLib(x) => Some(x),
_ => None,
}
}
}
//due to equality testing for Error::Io, we cannot impl Eq for Error{}
impl PartialEq<Self> for Error {
fn eq(&self, other: &Self) -> bool {
fn helper(me: &Error, other: &Error) -> Option<bool> {
Some(match me {
Error::Winapi(x, y) => other.get_winapi()?.eq(&(x, y)),
Error::Ntdll(x) => other.get_ntdll()?.eq(x),
Error::WTFConvert(x) => other.get_wtfconvert()?.eq(x),
#[cfg(feature = "std")]
Error::Io(x) => other.get_io()?.kind() == x.kind(), //todo:improve equality testing for Error::Io
#[cfg(target_family = "windows")]
Error::Pelite(x) => other.get_pelite()?.eq(x),
Error::InjectLib(x) => other.get_injectlib()?.eq(x),
Error::Unsupported(x) => other.get_unsupported()?.eq(x),
})
}
*helper(self, other).get_or_insert(false)
}
}
#[cfg(target_family = "windows")]
mod windows {
use crate::error::Error;
use winapi::um::errhandlingapi::GetLastError;
impl From<pelite::Error> for Error {
fn from(e: pelite::Error) -> Self {
Error::Pelite(e)
}
}
impl From<&'static str> for Error {
fn from(s: &'static str) -> Self {
Error::Winapi(s, unsafe { GetLastError() })
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Error::Winapi(s, n) => write!(f, "Winapi error:{} failed with code {}", s, n),
Error::Ntdll(n) => write!(f, "Ntdll({:#x})", n),
Error::WTFConvert(_) => write!(f, "WTFConvert: Buffer contained non UTF-8 characters."), //todo: should I print osstring here?
Error::Unsupported(r) => write!(
f,
"Unsupported({})",
if let Some(s) = r { s } else { "None" }
),
#[cfg(feature = "std")]
Error::Io(e) => write!(f, "io:{}", e),
Error::InjectLib(e) => write!(f, "Inject-Lib({})", e),
#[cfg(target_family = "windows")]
Error::Pelite(e) => write!(f, "pelite({})", e),
}
}
}
impl Display for CustomError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
CustomError::NoViableInjector=>write!(f,"Could not find a viable injection method for the circumstances"),
CustomError::WaitForSingleObject(x)=>write!(f,"WaitForSingleObject return code {:#x}",x),
CustomError::ModuleListLoop=>write!(f,"We looped through the whole InLoadOrderModuleList, but still have no match. Aborting, because this would end in an endless loop."),
CustomError::ZeroBytes=>write!(f,"Zero bytes read, but the requested type is not Zero sized."),
CustomError::LDRUninit=>write!(f,"LDR is not initialised"),
CustomError::InvalidStructure=>write!(f,"a structure in inject-lib is invalid."),
CustomError::DllPathNoFile=>write!(f,"The Dll File Path provided did not point to a file."),
CustomError::MempageInvalidProcess=>write!(f,"The Mempage did not belong to the expected Process."),
CustomError::InvalidInput=>write!(f,"The Provided Input was invalid."),
CustomError::PermissionDenied=>write!(f,"The requested Action would result in a Permission Error."),
CustomError::LibraryNotFound(lib)=>write!(f,"It was expected, that the Library:'{}' would be loaded when it wasn't",lib),
}
}
}
#[derive(Debug, Clone)]
///Abstracts a NTStatus return type.
pub enum Ntdll {
///Maps, if Ntdll considers the NTStatus a Success
Success(i32),
///Maps, if Ntdll considers the NTStatus a Information
Information(i32),
///Maps, if Ntdll considers the NTStatus a Warning
Warning(i32),
///Maps, if Ntdll considers the NTStatus an Error
Error(i32),
///Maps, if nothing else maps. Ideally this should go unused
Other(i32),
}
impl Ntdll {
///Get the contained Variable in the Ntdll enum
pub fn get_status(&self) -> &i32 {
match self {
Ntdll::Error(v) => v,
Ntdll::Warning(v) => v,
Ntdll::Other(v) => v,
Ntdll::Success(v) => v,
Ntdll::Information(v) => v,
}
}
}
impl Display for Ntdll {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Ntdll::Error(v) => write!(f, "Ntdll::Error({:#x})", v),
Ntdll::Warning(v) => write!(f, "Ntdll::Warning({:#x})", v),
Ntdll::Other(v) => write!(f, "Ntdll::Other({:#x})", v),
Ntdll::Success(v) => write!(f, "Ntdll::Success({:#x})", v),
Ntdll::Information(v) => write!(f, "Ntdll::Information({:#x})", v),
}
}
}
#[cfg(windows)]
mod ntdll {
use crate::error::{Error, Ntdll};
use log::error;
use winapi::shared::ntdef::{NTSTATUS, NT_ERROR, NT_INFORMATION, NT_SUCCESS, NT_WARNING};
impl crate::error::Ntdll {
///Create a new Ntdll enum from a NTSTATUS
pub fn new(n: NTSTATUS) -> Self {
if NT_ERROR(n) {
Ntdll::Error(n)
} else if NT_WARNING(n) {
Ntdll::Warning(n)
} else if NT_INFORMATION(n) {
Ntdll::Information(n)
} else if NT_SUCCESS(n) {
Ntdll::Success(n)
} else {
error!("");
Ntdll::Other(n)
}
}
///Returns true, if the enum contains Error discriminant
pub fn is_error(&self) -> bool {
match self {
Ntdll::Error(_) => true,
_ => false,
}
}
///Returns true, if the enum contains Warning discriminant
pub fn is_warning(&self) -> bool {
match self {
Ntdll::Warning(_) => true,
_ => false,
}
}
///Returns true, if the enum contains Information discriminant
pub fn is_info(&self) -> bool {
match self {
Ntdll::Information(_) => true,
_ => false,
}
}
///Returns true, if the enum contains Success discriminant
pub fn is_success(&self) -> bool {
match self {
Ntdll::Success(_) => true,
_ => false,
}
}
///Returns true, if the enum contains Other discriminant
pub fn is_other(&self) -> bool {
match self {
Ntdll::Other(_) => true,
_ => false,
}
}
}
impl Into<Error> for Ntdll {
///Transform Ntdll enum into Error
fn into(self) -> Error {
match self {
Ntdll::Error(v) => Error::Ntdll(v),
Ntdll::Warning(v) => Error::Ntdll(v),
Ntdll::Information(v) => Error::Ntdll(v),
Ntdll::Success(v) => Error::Ntdll(v),
Ntdll::Other(v) => Error::Ntdll(v),
}
}
}
}