blooemu 0.1.9

the best library for OS API's manipulation
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
#[cfg(target_os = "linux")]
use procfs::process::{all_processes, Process, ProcessStat};
#[cfg(target_os = "windows")]
use std::ffi::CStr;
#[cfg(target_os = "windows")]
use std::ptr::null_mut;
#[cfg(target_os = "windows")]
use winapi::shared::minwindef::FILETIME;
#[cfg(target_os = "windows")]
use winapi::um::handleapi::CloseHandle;
#[cfg(target_os = "windows")]
use winapi::um::processthreadsapi::GetProcessTimes;
#[cfg(target_os = "windows")]
use winapi::um::processthreadsapi::OpenProcess;
#[cfg(target_os = "windows")]
use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
#[cfg(target_os = "windows")]
use winapi::um::tlhelp32::{
    CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS,
};
#[cfg(target_os = "windows")]
use winapi::um::winnt::PROCESS_QUERY_INFORMATION;

use std::time::Duration;


#[cfg(target_os = "windows")]
#[allow(dead_code)]
pub fn elevate_privileges_by_pid(pid: u32) -> bool {
    use winapi::um::processthreadsapi::{OpenProcess, OpenProcessToken};
    use winapi::um::winnt::{HANDLE, PROCESS_QUERY_INFORMATION, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY, SE_PRIVILEGE_ENABLED};
    use winapi::um::securitybaseapi::{AdjustTokenPrivileges};
    use winapi::um::winbase::LookupPrivilegeValueA;
    use winapi::um::errhandlingapi::GetLastError;
    use winapi::um::handleapi::CloseHandle;
    use std::ptr::null_mut;
    use std::ffi::CString;

    unsafe {
        // Открываем процесс по PID
        let process_handle: HANDLE = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);

        if process_handle.is_null() {
            eprintln!("Failed to open process with PID: {}, error: {}", pid, GetLastError());
            return false;
        }

        // Открываем токен процесса
        let mut token_handle: HANDLE = null_mut();
        if OpenProcessToken(process_handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &mut token_handle) == 0 {
            eprintln!("Failed to open process token, error: {}", GetLastError());
            CloseHandle(process_handle);
            return false;
        }

        // Получаем LUID для привилегии SeDebugPrivilege
        let priv_name = CString::new("SeDebugPrivilege").unwrap();
        let mut luid = std::mem::zeroed();
        if LookupPrivilegeValueA(null_mut(), priv_name.as_ptr(), &mut luid) == 0 {
            eprintln!("Failed to lookup privilege value, error: {}", GetLastError());
            CloseHandle(token_handle);
            CloseHandle(process_handle);
            return false;
        }

        // Настраиваем привилегии
        let mut tp: TOKEN_PRIVILEGES = std::mem::zeroed();
        tp.PrivilegeCount = 1;
        tp.Privileges[0].Luid = luid;
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

        if AdjustTokenPrivileges(token_handle, 0, &mut tp, size_of::<TOKEN_PRIVILEGES>() as u32, null_mut(), null_mut()) == 0 {
            eprintln!("Failed to adjust token privileges, error: {}", GetLastError());
            CloseHandle(token_handle);
            CloseHandle(process_handle);
            return false;
        }

        // Закрываем дескрипторы
        CloseHandle(token_handle);
        CloseHandle(process_handle);
        println!("Privileges elevated successfully for PID: {}", pid);
        true
    }
}




#[cfg(target_os = "linux")]
pub fn elevate_privileges_by_pid(pid: u32) -> bool {
    use std::process::Command;

    let output = Command::new("sudo")
        .arg("prctl")
        .arg("--set-privileges")
        .arg(pid.to_string())
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            println!("Privileges elevated for process with PID: {}", pid);
            return true;
        } else {
            eprintln!(
                "Failed to elevate privileges, error: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            return false;
        }
    }

    eprintln!("Failed to run sudo command.");
    false
}


#[cfg(target_os = "macos")]
pub fn elevate_privileges_by_pid(pid: u32) -> bool {
    use std::process::Command;

    let output = Command::new("sudo")
        .arg("kill")
        .arg("-CONT")
        .arg(pid.to_string())
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            println!("Privileges elevated for process with PID: {}", pid);
            return true;
        } else {
            eprintln!(
                "Failed to elevate privileges, error: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            return false;
        }
    }

    eprintln!("Failed to run sudo command.");
    false
}




#[cfg(target_os = "windows")]
pub fn elevate_privileges(process_name: &str) -> bool {
    use std::ffi::CString;
    use std::ptr::null_mut;
    use winapi::um::errhandlingapi::GetLastError;
    use winapi::um::handleapi::CloseHandle;
    use winapi::um::processthreadsapi::{OpenProcess, OpenProcessToken};
    use winapi::um::securitybaseapi::AdjustTokenPrivileges;
    use winapi::um::tlhelp32::{
        CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS,
    };
    use winapi::um::winbase::LookupPrivilegeValueA;
    use winapi::um::winnt::{
        HANDLE, LUID_AND_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES,
        TOKEN_PRIVILEGES, TOKEN_QUERY,
    };

    // Find process by name
    unsafe {
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snapshot == null_mut() {
            eprintln!("Failed to create process snapshot");
            return false;
        }

        let mut entry: PROCESSENTRY32 = std::mem::zeroed();
        entry.dwSize = size_of::<PROCESSENTRY32>() as u32;

        let mut process_id: u32 = 0;
        if Process32First(snapshot, &mut entry) == 1 {
            loop {
                let process_name_cstr = CStr::from_ptr(entry.szExeFile.as_ptr())
                    .to_string_lossy()
                    .into_owned();
                if process_name_cstr.to_lowercase() == process_name.to_lowercase() {
                    process_id = entry.th32ProcessID;
                    break;
                }
                if Process32Next(snapshot, &mut entry) == 0 {
                    break;
                }
            }
        }

        CloseHandle(snapshot);

        if process_id == 0 {
            eprintln!("Failed to find process: {}", process_name);
            return false;
        }

        // Open process and elevate privileges
        let process_handle = OpenProcess(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, 0, process_id);
        if process_handle.is_null() {
            eprintln!("Failed to open process with PID: {}", process_id);
            return false;
        }

        let mut token_handle: HANDLE = null_mut();
        let mut luid = std::mem::zeroed();

        if OpenProcessToken(
            process_handle,
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
            &mut token_handle,
        ) == 0
        {
            eprintln!("Failed to open process token, error: {}", GetLastError());
            CloseHandle(process_handle);
            return false;
        }

        let privilege_name = CString::new("SeDebugPrivilege").expect("CString::new failed");
        if LookupPrivilegeValueA(null_mut(), privilege_name.as_ptr(), &mut luid) == 0 {
            eprintln!(
                "Failed to lookup privilege value, error: {}",
                GetLastError()
            );
            CloseHandle(process_handle);
            return false;
        }

        let mut tp = TOKEN_PRIVILEGES {
            PrivilegeCount: 1,
            Privileges: [LUID_AND_ATTRIBUTES {
                Luid: luid,
                Attributes: SE_PRIVILEGE_ENABLED,
            }],
        };

        // Attempt to adjust token privileges
        if AdjustTokenPrivileges(
            token_handle,
            0,
            &mut tp as *mut TOKEN_PRIVILEGES,
            0,
            null_mut(),
            null_mut(),
        ) == 0
        {
            let error_code = GetLastError();
            if error_code == 1300 {
                eprintln!("ERROR_NOT_ALL_ASSIGNED (1300): The requested privilege could not be assigned. Ensure the program is running as administrator.");
            } else {
                eprintln!("Failed to adjust token privileges, error: {}", error_code);
            }
            CloseHandle(token_handle);
            CloseHandle(process_handle);
            return false;
        }

        CloseHandle(token_handle);
        CloseHandle(process_handle);

        true
    }
}

#[cfg(target_os = "macos")]
pub fn elevate_privileges(process_name: &str) -> bool {
    use libc::{c_int, getpid, kill};
    use std::ffi::CString;
    use std::process::Command;
    use std::ptr;

    fn find_pid_by_name(process_name: &str) -> Option<i32> {
        let output = Command::new("pgrep")
            .arg(process_name)
            .output()
            .expect("Failed to execute pgrep");

        if output.status.success() {
            if let Ok(pid_str) = String::from_utf8(output.stdout) {
                if let Ok(pid) = pid_str.trim().parse::<i32>() {
                    return Some(pid);
                }
            }
        }

        None
    }

    fn elevate_pid_privileges(pid: i32) -> bool {
        // Try using `sudo` to manipulate process privileges.
        let output = Command::new("sudo")
            .arg("kill")
            .arg("-CONT")
            .arg(format!("{}", pid))
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                println!("Privileges elevated for process with PID: {}", pid);
                return true;
            } else {
                eprintln!(
                    "Failed to elevate privileges, error: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                return false;
            }
        }
        eprintln!("Failed to run sudo command.");
        false
    }

    if let Some(pid) = find_pid_by_name(process_name) {
        if elevate_pid_privileges(pid) {
            println!(
                "Privileges elevated successfully for process: {}",
                process_name
            );
            return true;
        } else {
            eprintln!("Failed to elevate privileges for process: {}", process_name);
            return false;
        }
    } else {
        eprintln!("Process not found: {}", process_name);
        return false;
    }
}

#[cfg(target_os = "linux")]
pub fn elevate_privileges(process_name: &str) -> bool {
    use std::fs::File;
    use std::io::{self, BufRead};
    use std::path::Path;
    use std::process::Command;

    // Find the PID by process name
    fn find_pid_by_name(process_name: &str) -> Option<i32> {
        let proc_dir = Path::new("/proc");
        if let Ok(entries) = proc_dir.read_dir() {
            for entry in entries.flatten() {
                let entry_path = entry.path();
                if entry_path.is_dir() {
                    let status_file = entry_path.join("status");
                    if let Ok(file) = File::open(status_file) {
                        for line in io::BufReader::new(file).lines().flatten() {
                            if line.starts_with("Name:") {
                                let proc_name = line.split_whitespace().nth(1).unwrap_or("");
                                if proc_name == process_name {
                                    let pid_str = entry_path.file_name().unwrap().to_str().unwrap();
                                    if let Ok(pid) = pid_str.parse::<i32>() {
                                        return Some(pid);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    fn elevate_pid_privileges(pid: i32) -> bool {
        // Use `capsh` to elevate privileges using capabilities
        let output = Command::new("capsh")
            .arg("--caps=cap_sys_ptrace+ep")
            .arg("--")
            .arg("sh")
            .arg("-c")
            .arg(format!("kill -0 {}", pid)) // check if the process is accessible
            .output();

        if let Ok(output) = output {
            if output.status.success() {
                return true;
            } else {
                eprintln!(
                    "Failed to elevate privileges, error: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                return false;
            }
        }
        eprintln!("Failed to run capsh command.");
        false
    }

    if let Some(pid) = find_pid_by_name(process_name) {
        if elevate_pid_privileges(pid) {
            println!(
                "Privileges elevated successfully for process: {}",
                process_name
            );
            return true;
        } else {
            eprintln!("Failed to elevate privileges for process: {}", process_name);
            return false;
        }
    } else {
        eprintln!("Process not found: {}", process_name);
        return false;
    }
}

#[cfg(target_os = "windows")]
pub fn get_all_processes() -> Vec<(u32, String)> {
    let mut processes = Vec::new();
    unsafe {
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snapshot == null_mut() {
            return processes;
        }

        let mut entry: PROCESSENTRY32 = std::mem::zeroed();
        entry.dwSize = size_of::<PROCESSENTRY32>() as u32;

        if Process32First(snapshot, &mut entry) == 1 {
            loop {
                let process_name = CStr::from_ptr(entry.szExeFile.as_ptr())
                    .to_string_lossy()
                    .into_owned();
                processes.push((entry.th32ProcessID, process_name));
                if Process32Next(snapshot, &mut entry) == 0 {
                    break;
                }
            }
        }

        CloseHandle(snapshot);
    }
    processes
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_all_processes() -> Vec<(i32, String)> {
    all_processes()
        .filter_map(|process| {
            let process = process.ok()?;
            Some((process.stat.pid, process.stat.comm))
        })
        .collect()
}

#[cfg(target_os = "windows")]
pub fn get_process_cpu_usage(task_name: &str) -> Option<f32> {
    let pid = get_pid(task_name)?;

    unsafe {
        let process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);
        if process_handle.is_null() {
            return None;
        }

        let mut creation_time: FILETIME = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };
        let mut exit_time: FILETIME = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };
        let mut kernel_time: FILETIME = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };
        let mut user_time: FILETIME = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };

        if GetProcessTimes(
            process_handle,
            &mut creation_time,
            &mut exit_time,
            &mut kernel_time,
            &mut user_time,
        ) != 0
        {
            let kernel_time = filetime_to_duration(kernel_time);
            let user_time = filetime_to_duration(user_time);
            let total_time = kernel_time + user_time;

            // Calculate CPU usage as a percentage
            let cpu_usage = total_time.as_secs_f32(); // Adjust as necessary to reflect the total elapsed time since creation
            CloseHandle(process_handle);
            return Some(cpu_usage);
        }

        CloseHandle(process_handle);
        None
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_process_cpu_usage(task_name: &str) -> Option<f32> {
    let pid = get_pid(task_name)?;

    match Process::new(pid) {
        Ok(process) => {
            let cpu_usage = process.stat.utime as f32 + process.stat.stime as f32; // User time + System time
            let total_time =
                process.stat.utime + process.stat.stime + process.stat.cutime + process.stat.cstime;

            if total_time > 0 {
                return Some((cpu_usage / total_time as f32) * 100.0); // CPU usage as a percentage
            }
        }
        Err(_) => return None,
    }

    None
}
#[cfg(target_os = "windows")]
fn filetime_to_duration(filetime: FILETIME) -> Duration {
    let ft = u64::from(filetime.dwHighDateTime) << 32 | u64::from(filetime.dwLowDateTime);
    Duration::from_nanos(ft * 10) // Convert from 100-nanosecond intervals to nanoseconds
}
#[cfg(target_os = "windows")]
pub fn get_process_memory_usage(task_name: &str) -> Option<u64> {
    let pid = get_pid(task_name)?;

    unsafe {
        let process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);
        if process_handle.is_null() {
            return None;
        }

        let mut memory_counters: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
        if GetProcessMemoryInfo(
            process_handle,
            &mut memory_counters,
            size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
        ) != 0
        {
            CloseHandle(process_handle); // Closes a handle
            return Some(memory_counters.WorkingSetSize.try_into().unwrap()); // Convert usize to u64
        }

        CloseHandle(process_handle); // Close the handle in case of an error
        None
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_process_memory_usage(task_name: &str) -> Option<u64> {
    let pid = get_pid(task_name)?;

    match Process::new(pid) {
        Ok(process) => {
            let memory_info = process.stat;
            Some(memory_info.rss as u64) // // Return RSS (Resident Set Size) as the amount of memory used
        }
        Err(_) => None,
    }
}

#[cfg(target_os = "windows")]
pub fn get_pid(task_name: &str) -> Option<u32> {
    unsafe {
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snapshot == null_mut() {
            return None;
        }

        let mut entry: PROCESSENTRY32 = std::mem::zeroed();
        entry.dwSize = size_of::<PROCESSENTRY32>() as u32;

        if Process32First(snapshot, &mut entry) == 1 {
            loop {
                let process_name = CStr::from_ptr(entry.szExeFile.as_ptr())
                    .to_string_lossy()
                    .into_owned();
                if process_name
                    .to_lowercase()
                    .contains(&task_name.to_lowercase())
                {
                    CloseHandle(snapshot);
                    return Some(entry.th32ProcessID);
                }

                if Process32Next(snapshot, &mut entry) == 0 {
                    break;
                }
            }
        }

        CloseHandle(snapshot);
        None
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn get_process_name(pid: i32) -> Option<String> {
    match Process::new(pid) {
        Ok(process) => Some(process.stat.comm),
        Err(_) => None,
    }
}

#[cfg(target_os = "windows")]
pub fn get_process_name(pid: u32) -> Option<String> {
    unsafe {
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snapshot == null_mut() {
            return None;
        }

        let mut entry: PROCESSENTRY32 = std::mem::zeroed();
        entry.dwSize = size_of::<PROCESSENTRY32>() as u32;

        if Process32First(snapshot, &mut entry) == 1 {
            loop {
                if entry.th32ProcessID == pid {
                    let process_name = CStr::from_ptr(entry.szExeFile.as_ptr())
                        .to_string_lossy()
                        .into_owned();
                    CloseHandle(snapshot);
                    return Some(process_name);
                }

                if Process32Next(snapshot, &mut entry) == 0 {
                    break;
                }
            }
        }

        CloseHandle(snapshot);
        None
    }
}