Skip to content

Instantly share code, notes, and snippets.

@lrvick
Created October 6, 2022 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lrvick/4657fb0a1f9498c14cc10868a000e3cd to your computer and use it in GitHub Desktop.
Save lrvick/4657fb0a1f9498c14cc10868a000e3cd to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/vm_sockets.h>
#include <poll.h>
int main() {
mount("dev", "/dev", "devtmpfs", MS_NOSUID | MS_NOEXEC, NULL);
const char *console_path = "/dev/console";
freopen(console_path, "r", stdin);
freopen(console_path, "w", stdout);
freopen(console_path, "w", stderr);
int socket_fd;
struct sockaddr_vm sa = {
.svm_family = AF_VSOCK,
.svm_cid = 3,
.svm_port = 9000,
.svm_reserved1 = 0,
};
uint8_t buf[1];
buf[0] = 0xB7;
socket_fd = socket(AF_VSOCK, SOCK_STREAM, 0);
connect(socket_fd, (struct sockaddr*) &sa, sizeof(sa));
write(socket_fd, buf, 1);
read(socket_fd, buf, 1);
close(socket_fd);
puts("\nHello World from C init!\n");
reboot(RB_AUTOBOOT);
}
extern crate libc;
use libc::mount;
use libc::read;
use libc::write;
use libc::close;
use libc::reboot;
use libc::socket;
use libc::connect;
use libc::freopen;
use libc::c_void;
use libc::sockaddr;
use libc::sockaddr_vm;
use libc::SOCK_STREAM;
use libc::AF_VSOCK;
use libc::MS_NOSUID;
use libc::MS_NOEXEC;
use libc::RB_AUTOBOOT;
use std::mem::zeroed;
use std::mem::size_of;
fn main() {
unsafe {
mount(
b"devtmpfs\0".as_ptr() as _,
b"/dev\0".as_ptr() as _,
b"devtmpfs\0".as_ptr() as _,
MS_NOSUID | MS_NOEXEC,
b"mode=0755\0".as_ptr() as *const c_void,
);
freopen(
b"/dev/console\0".as_ptr() as _,
b"r\0".as_ptr() as _,
b"stdin\0".as_ptr() as _,
);
freopen(
b"/dev/console\0".as_ptr() as _,
b"w\0".as_ptr() as _,
b"stdout\0".as_ptr() as _,
);
freopen(
b"/dev/console\0".as_ptr() as _,
b"w\0".as_ptr() as _,
b"stderr\0".as_ptr() as _,
);
let mut sa: sockaddr_vm = zeroed();
sa.svm_family = AF_VSOCK as _;
sa.svm_port = 9000;
sa.svm_cid = 3;
let fd = socket(AF_VSOCK, SOCK_STREAM, 0);
connect(
fd,
&sa as *const _ as *mut sockaddr,
size_of::<sockaddr_vm>() as _,
);
let mut buf: [u8; 1] = [0; 1];
buf[0] = 0xB7;
write(fd, buf.as_ptr() as _, 1);
read(fd, buf.as_ptr() as _, 1);
close(fd);
println!("Hello World from Rust init!");
reboot(RB_AUTOBOOT);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment