Playing around with XOR (my fav operation) during the holidays

# cipher design notes:
## purpose?
### cheap single byte keyed stream cipher
### cheaply obfuscate data based on a simple password
### use a simple language with as few lines & dependencies as possible
## internal key setup:
### produce a random byte for every pw byte (KEY IV)
### generate a secret internal state byte for every pw byte (KEY HASH):
#### loop through the each pw byte & mix together its random byte & a counter value
#### set the final looped result as the state byte for that key byte
#### order the operations used to try & reduce getting a null byte output
#### end the internal state byte with the current counter value mixed in (CBC MODE)
## message cipher steps:
### use the looped key counter above as an index to get a key list item
### XOR the message byte with each byte in key item: random byte, pwd byte, state byte
### mix the cipher byte in with the internal state byte (new secret internal state)
### XOR the prior internal state byte with the cipher byte (cipher output)
## notes:
### this does not prevent or detect bit-flipping (integrity with a hash function)
import sys, random
def h(n):
  sys.stdout.write(hex(n).replace("x","")[-2:])
i=0xff; j=0x00; l=len(sys.argv[1]); s=sys.stdin.read()
if (s[:2]=="ff"):
  r=s[2:2+(l*2)]; t=s[2+(l*2):].strip()
  s="".join([chr(int(t[x:x+2],16)) for x in range(0,len(t),2)])
  k=[[int(r[x*2:(x*2)+2],16), ord(sys.argv[1][x])] for x in range(0,l)]
else:
  k=[[random.randint(0x00, 0xff), ord(d)] for d in sys.argv[1]]
  h(i); z=[h(d[0]) for d in k]; r=""
for e in k:
  for d in k:
    i=(((i+j)*(d[0]^d[1]))%256); j=((j+1)%256)
  e.append(i); i=((i+j)%256); j=((j+1)%256)
j=0
for c in s:
  p=ord(c); m=k[j%l]; o=(((p^m[0])^m[1])^m[2]); j=(j+1); n=(j%256)
  if (r==""):
    t=i; i=((k[o%l][0]+o+n)%256); o=(o^t); h(o)
  else:
    d=(p^i); t=i; i=((k[d%l][0]+d+n)%256); o=(o^t); sys.stdout.write(chr(o))

Cipher testing output (Message: 000000, Key: 000000):

a=$(echo '000000' | python ~/tmp/en.py "000000") ; echo "Cipher-Out: [$a]" ; \
k="000000" ; echo -n "Decrypt-Test[$k]: " ; echo "$a" | tr -d '|' | python ~/tmp/en.py "$k" ; \
for x in 1 2 3 ; do
k="00000$x" ; echo -n "Bad-Key-Test[$k]: "
echo "$a" | tr -d '|' | python ~/tmp/en.py "$k" | xxd | sed -e 's/^[^ ]* //' | sed -e 's/  [ ]*/|/g' | sed -e 's/\(..[ |]\)/ \1/g' | tr -s ' '
done
Cipher-Out: [ff372f4ca01971de08925718521c]
Decrypt-Test[000000]: 000000
Bad-Key-Test[000001]: 70 b0 bf f0 cc 98 0e|p......
Bad-Key-Test[000002]: 6c e0 ac c5 9d 59 54|l....YT
Bad-Key-Test[000003]: 5c 50 e0 c3 da a8 1f|\P.....
Playing around with XOR (my fav operation) during the holidays

Python: Layer-3 tunnel device traffic under client & server TCP sockets

# notes: PoC, single threaded, single client, single interface, single address, ipv4 over tcp
# 
# server: python tun.py -s 0.0.0.0 31337 key
#   ('[conn]:new', [socket._socketobject object at 0xb6b20c00], ('192.168.160.241', 64227))
#   ('[auth]:good', [socket._socketobject object at 0xb6b20c00])
# 
# client: python tun.py -c 1.2.3.4 31337 key
#   client: route add -host 1.2.3.4 [real gateway]
#   client: route add -net 0.0.0.0/0 10.0.0.1
#   client: host yahoo.com 4.2.2.1
#!/usr/bin/python

import os, sys
import ctypes, fcntl, struct
import select, socket, subprocess
import time, random, hashlib

def tclose(sobj):
	try:
		sobj.close()
	except:
		pass

def ksa4(k):
	s = []
	for i in range(0, 256):
		s.append(i)
	j = 0
	l = len(k)
	for i in range(0, 256):
		j = ((j + s[i] + ord(k[i % l])) % 256)
		t = s[i]; s[i] = s[j]; s[j] = t
	return (s, 0, 0)

def arc4(m, k):
	(s, i, j) = k
	l = len(m)
	o = ""
	for x in range(0, l):
		i = ((i + 1) % 256)
		j = ((j + s[i]) % 256)
		t = s[i]; s[i] = s[j]; s[j] = t
		c = s[(s[i] + s[j]) % 256]
		o += chr(ord(m[x]) ^ c)
	k = (s, i, j)
	return (o, k)

def set4(n, k):
	if (n == ""):
		n = (str(time.time()) + ":" + str(random.random()) + "-")
	s = ksa4(n + "s" + k)
	r = ksa4(n + "r" + k)
	(null, s) = arc4("x"*4096, s)
	(null, r) = arc4("x"*4096, r)
	return (n, s, r)

def client(h, p, n, k):
	f = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	f.connect((h, p))
	(enc, k) = arc4(n, k)
	f.send(n + enc)
	return (f, k)

# initialize some common variables
BUFFER_SIZE = 2000
PR_MODE = "client"
PR_HOST = "1.2.3.4"
PR_PORT = 31337
PR_SKEY = "key"
OS_TYPE = sys.platform
IF_CMD = ["/sbin/ifconfig", "tun0", "10.0.0.1", "10.0.0.2", "up"]

# process command line args usage: tun.py mode:[-c,-s] ip:[0.0.0.0] port:[4321] secret:[key]
if (sys.argv[1] == "-s"):
	PR_MODE = "server"
PR_HOST = sys.argv[2]
PR_PORT = int(sys.argv[3])
PR_SKEY = sys.argv[4]

# initialize the clients secret key state
last = 0
(nonce, skey, rkey) = set4("", PR_SKEY)

# define the remote connection socket descriptors - tcp client or tcp server
srv_fd = None
net_fd = None
if (PR_MODE == "client"):
	tmp = IF_CMD[2]
	IF_CMD[2] = IF_CMD[3]
	IF_CMD[3] = tmp
	(net_fd, skey) = client(PR_HOST, PR_PORT, nonce, skey)
else:
	srv_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	srv_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	srv_fd.bind(("0.0.0.0", PR_PORT))
	srv_fd.listen(1)

# determine how to bring up the tun0 interface - mac or linux
if (OS_TYPE == "darwin"):
	tun_fd = os.open("/dev/tun0", os.O_RDWR)
else:
	TUNSETIFF = 0x400454ca
	IFF_TUN = 0x0001
	IFF_TAP = 0x0002
	IFF_NO_PI = 0x1000
	
	tun_fd = os.open("/dev/net/tun", os.O_RDWR)
	ifr = struct.pack("16sH", "tun0", IFF_TUN | IFF_NO_PI)
	fcntl.ioctl(tun_fd, TUNSETIFF, ifr)
	
	IF_CMD.insert(3, "pointopoint")
subprocess.call(IF_CMD)

# main processing loop for network traffic tunneling
conns = []
while (1):
	#print("loop")
	
	# set the list of available socket descriptors to listen for
	fd_list = [tun_fd]
	if (srv_fd):
		fd_list.append(srv_fd)
	if (net_fd):
		fd_list.append(net_fd)
	for conn in conns:
		fd_list.append(conn)
	
	# select the available fds ready for reading
	rd = select.select(fd_list, [], [])
	
	# loop through each socket now to process each action
	for ready_fd in rd[0]:
		# if we are reading from our tun device then encrypt the message and write it to the network socket
		if (ready_fd == tun_fd):
			packet = os.read(tun_fd, BUFFER_SIZE)
			plen = len(packet)
			if ((plen > 0) and (net_fd)):
				(enc, skey) = arc4(packet, skey)
				smac = str(skey)
				hmac = hashlib.sha256(smac + enc + smac).digest()
				net_fd.send(enc + hmac)
		
		# if the server gets a new client connection then add it to a list to be authenticated next
		if (ready_fd == srv_fd):
			(conn, addr) = srv_fd.accept()
			print("[conn]:new",conn,addr)
			conns.append(conn)
		
		# if we get a network message decrypted and authenticated then write it to our tunnel device
		if (ready_fd == net_fd):
			data = net_fd.recv(BUFFER_SIZE)
			dlen = len(data)
			if (dlen > 0):
				try:
					temp = data[:-32]
					(dec, tkey) = arc4(temp, rkey)
					tmac = str(tkey)
					hmac = hashlib.sha256(tmac + temp + tmac).digest()
					if (hmac == data[-32:]):
						rkey = tkey
						os.write(tun_fd, dec)
					else:
						print("[hmac]:fail",hmac,data[-32:])
				except:
					dlen = 0
			if (dlen < 1):
				tclose(net_fd)
				net_fd = None
		
		# loop through any unauthenticated clients who have sent us data
		tmps = []
		conl = (len(conns) - 1)
		while (conl > -1):
			conn = conns[conl]
			
			# if the connection is ready
			if (ready_fd == conn):
				data = conn.recv(BUFFER_SIZE)
				dlen = len(data)
				indx = data.find("-")
				
				# if they sent us some actual data
				if ((dlen > 0) and (indx > -1)):
					# try to decrypt the nonce and verify an increase in the time
					try:
						temp = float(data.split(":")[0])
					except:
						temp = 0
					(tnonce, trkey, tskey) = set4(data[:indx+1], PR_SKEY)
					(dec, trkey) = arc4(data[indx+1:], trkey)
					
					# if the auth succeeds then setup the new key state and set the new client socket
					if ((temp > last) and (tnonce == dec)):
						print("[auth]:good",conn)
						
						nonce = tnonce
						skey = tskey
						rkey = trkey
						
						tclose(net_fd)
						net_fd = conn
						
						last = temp
						conns[conl] = None
					else:
						dlen = 0
				else:
					dlen = 0
				
				# if the auth failed then remove the client now
				if (dlen < 1):
					print("[auth]:fail",conns[conl])
					tclose(conns[conl])
					conns[conl] = None
			
			if (conns[conl]):
				tmps.append(conns[conl])
			conl -= 1
		
		conns = tmps[:]

Python: Layer-3 tunnel device traffic under client & server TCP sockets

Agile development w/ CI/CD – Automated cloud building & deployment (from scratch)

So I went to an interview recently and I was asked on the spot how I would implement an entire agile development platform, end-to-end, with specific details, (no requirements listed) – and it had to be cloud friendly/scalable! I was running different ideas through my head because it was a fairly open ended question and I felt like it deserved more thought than I could provide in just the 30 minutes given to me…

There are a dozen different ways this can be achieved but I wanted to post an example proof-of-concept of the essential steps needed to accomplish something like this. There are basically 5 different pieces to this puzzle that need to be solved:

  1. The developers need a central repository with local branching capabilities so they can test different versions of their changes on demand
  2. They need to be able to take an automatic snapshot of their code base that they are currently working on so they can specify which change they want to test
  3. They need a simple mechanism, which when triggered, takes that code-change snapshot and sends it to a build server for compilation
  4. The build server, when finished, should deploy and run their compiled test code, usually in a temporary, clean, isolated environment like a vm
  5. The build server returns a simple and unique URL pointing to their new test instance so the developer can easily see and test their desired changes

Example Tech Env: GIT, SSH, NetCat, Bash Scripts, Java

Components Workflow:

  • Developer (java)
  • Central Repo (git/ssh)
  • Automatic Snapshot Transfer (netcat)
  • Automatic Building (javac)
  • Automatic Deployment (bash script)
  • Temporary Test Instance (netcat website)

 

[devops engineer setup]

git init
git add project
git commit -a

# setup initial supporting scripts

 

[developer]

# get the code
git clone ssh://[email protected]:/home/git/projects

# make a change
cd project/
vim src/program.java
# @@ -11,5 +11,6 @@ public class program {
#  			System.out.println(x+": "+resList.get(x));
#  		}
# +		System.out.println("Changed!");
#  	}
#  }

./make.sh # magic!
# this script tar's up the current code and connects to the server to run an init.sh bootstrap script
# the init.sh script chooses an initial random port and calls the deploy.sh script
#   to perform the snapshot code transfer
# the deploy.sh script opens a netcat port to receive the snapshot'd code
#   and then runs build.sh on the result (port is closed after)
# the build.sh script opens a netcat port to communicate the build results
#   and then runs a http netcat instance of the executed code for the developer to test/visit

 

[automated build, deploy, test instance]

Extracting build...
./src/
./src/dep.java
./src/program.java
Extraction completed!

Building started...
Build completed!


Visit the build URL below:
http://192.168.161.2:29792/testing

[example web change test output]

Fri Nov 11 05:22:10 UTC 2016

0: [A, D]
1: [B, E]
2: [C, F]
Changed!

Completed!

 

[project file tree layout]

project/
|-- make.sh
|-- init.sh
|-- deploy.sh
|-- build.sh
`-- src
    |-- dep.java
    |-- lib
    `-- program.java

 

[script source code]

[make.sh]

#!/bin/bash
tar -czf snapshot.tgz ./src
USRN=`git config --get remote.origin.url | sed -e 's/@.*$//' -e '[email protected]^.*/@@'`
REPO=`git config --get remote.origin.url | sed -e 's/^.*://'`
PROJ="project"
PORT=`ssh "${USRN}@buildsrv" "${REPO}/${PROJ}/init.sh"`
false
while [ $? -ne 0 ] ; do
	sleep 1
	nc buildsrv "$PORT" < snapshot.tgz
done
rm snapshot.tgz
let PORT="$PORT + 1"
false
while [ $? -ne 0 ] ; do
	sleep 1
	nc buildsrv "$PORT"
done

[init.sh]

#!/bin/bash

DIR=$(dirname "$0")
let PORT="1028 + ( $RANDOM % 64000 )"

nohup "$DIR/deploy.sh" "$PORT" > /dev/null 2> /dev/null < /dev/null &
echo "$PORT"

[deploy.sh]

#!/bin/bash

DIR=$(dirname "$0")
PORT="$1"

TMP="/tmp/build.`date '+%s'`"

mkdir -p "$TMP/"
nc -l -p "$PORT" -w 30 > "$TMP/src.tgz"

if [ -s "$TMP/src.tgz" ] ; then
	let PORT="$PORT + 1"
	"$DIR/build.sh" "$PORT" "$TMP" | nc -l -p "$PORT" -w 30 -q 1
fi

[build.sh]

#!/bin/bash

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

let PORT="$1 + 1"
TMP="$2"

echo
echo "Extracting build..."
cd "$TMP/"
tar -xzvf "src.tgz"
cd src/
echo "Extraction completed!"
echo
echo "Building started..."
javac -d . dep.java 2>&1
javac -cp . program.java 2>&1
echo "Build completed!"
echo

GW=`netstat -nr | grep -i '^0.0.0.0' | awk '{ print $2 }' | cut -c 1-4`
IP=`ifconfig | grep -i "inet addr:$GW" | awk '{ print $2 }' | sed -e 's/^[^:]*://'`

echo
echo "Visit the build URL below:"
echo "http://${IP}:${PORT}/testing"
echo

( echo -e 'HTTP/1.1 200 OK\r\n\r\n' ; date ; echo ; java program ; echo ; echo 'Completed!' ) | nohup nc -l -p "$PORT" -w 60 -q 1 > /dev/null 2> /dev/null &

[src/dep.java]

package lib;
import java.util.*;
public class dep {
	public dep() {
	}
	public static ArrayList merge(ArrayList listA, ArrayList listB) {
		ArrayList outList = new ArrayList();
		for (int x = 0; x < listA.size(); ++x) {
			ArrayList tmpList = new ArrayList();
			tmpList.add(listA.get(x));
			tmpList.add(listB.get(x));
			outList.add(tmpList);
		}
		return outList;
	}
}

[src/program.java]

import java.util.*;
import lib.dep;
public class program {
	public static void main(String[] args) {
		ArrayList inA = new ArrayList();
		ArrayList inB = new ArrayList();
		inA.add("A"); inA.add("B"); inA.add("C");
		inB.add("D"); inB.add("E"); inB.add("F");
		dep help = new dep();
		ArrayList resList = help.merge(inA, inB);
		for (int x = 0; x < resList.size(); ++x) {
			System.out.println(x+": "+resList.get(x));
		}
	}
}
Agile development w/ CI/CD – Automated cloud building & deployment (from scratch)

OpenWRT dhcp-lease file arping-based host-removal (dnsmasq)

To help prevent DHCP starvation DoS attacks (not fool-proof though if you can fake ARP replies back)

rm /tmp/arp.*
cat /tmp/dhcp.leases | awk '{ print $3 }' | while read a ; do
  ( arping -f -q -c 1 -w 1 -I br-lan "$a" ; if [ $? -ne 0 ] ; then echo "$a" > /tmp/arp.host."$a" ; fi ) &
done
sleep 3
cat /tmp/arp.host.* | while read a ; do
  sed "/^.*$a.*$/d" -i /tmp/dhcp.leases
  touch /tmp/arp.run
done
if [ -f /tmp/arp.run ] ; then
  kill `ps | grep -i 'dnsmasq' | grep -iv 'grep' | awk '{ print $1 }'`
  /usr/sbin/dnsmasq -C /var/etc/dnsmasq.conf -k -x /var/run/dnsmasq/dnsmasq.pid &
fi
rm /tmp/arp.*
OpenWRT dhcp-lease file arping-based host-removal (dnsmasq)

Having fun with numbers & Python – Randomization & Shuffling – Stream Cipher

import sys,time
def hexs(s):
	o = ""
	for c in s:
		h = hex(ord(c))[2:]
		if (len(h) < 2):
			h = ("0" + h)
		if (o != ""):
			o += ":"
		o += h
	return o
def nice(s):
	o = ""
	for i in range(0, len(s)):
		if (i > 0):
			if ((i % 16) == 0):
				o += "\n  "
			else:
				o += ":"
		t = str(s[i])
		while (len(t) < 3):
			t = ("0" + t)
		o += t
	return o
def rnds():
	n = 2; s = ""
	while ((int(time.time()) % n) != 0):
		pass
	while (len(s) != 32):
		time.sleep(1)
		r = 0
		while ((int(time.time()) % n) != 0):
			r = (r + 1)
		#sys.stderr.write("r="+str(r)+"\n");break
		s = (s + chr((r >> 8) & 0xff) + chr(r & 0xff))
	return s
if (len(sys.argv) < 2):
	h = rnds()
	sys.stderr.write("k="+hexs(h)+"\n")
else:
	def keys(k):
		s = []
		for x in range(0, 256):
			s.append(x)
		for y in range(0, len(k)):
			l = ord(k[y])
			for x in range(0, 256):
				t = s[x] ; s[x] = s[l] ; s[l] = t
				l = ((l + x) % 256)
		return s
	s = keys(sys.argv[1])
	if (len(sys.argv) > 2):
		sys.stderr.write("s="+nice(s)+"\n\n")
	def ciph(m, s, z):
		j = 0; o = ""
		for y in range(0, len(m)):
			l = ord(m[y])
			c = (l ^ s[y % 256])
			o += chr(c)
			i = l
			if (z == "d"):
				i = c
			j = ((j ^ i) % 256)
			for x in range(0, 256):
				t = s[x] ; s[x] = s[j] ; s[j] = t
				j = ((j + x) % 256)
		return o
	if (len(sys.argv) < 3):
		m = sys.stdin.read()
		z = "d"
	else:
		m = sys.argv[2]
		z = "e"
	o = ciph(m, s, z)
	if (len(sys.argv) > 2):
		sys.stderr.write("m="+hexs(o)+"\n")
	sys.stdout.write(o)

$ clear ; echo ; python fun.py ; python fun.py ; echo ; python fun.py key msg | python fun.py key ; echo

k=74:ed:3c:1d:62:72:92:61:3c:27:f8:7c:c4:98:92:47:0d:18:c0:47:a6:44:b6:13:19:5c:90:30:4b:23:cf:12
k=fd:e7:4d:1d:c7:b0:a6:d9:45:0e:c9:68:95:35:46:e9:08:e9:8c:4f:53:42:9d:29:7b:30:65:f6:cd:00:ae:f6

s=054:166:020:190:252:207:029:030:042:098:156:055:041:108:058:032
  073:208:253:242:115:250:053:106:192:168:087:173:045:161:124:186
  163:049:162:067:040:096:086:039:057:023:100:216:203:123:217:175
  248:107:224:131:038:172:014:011:085:003:214:149:110:215:159:129
  046:125:144:043:077:126:150:167:200:169:097:153:188:201:071:254
  246:244:080:184:232:010:006:176:241:183:019:027:118:090:104:065
  000:033:210:220:236:234:063:205:048:155:095:133:218:050:022:158
  130:068:221:170:202:079:213:101:164:111:099:074:034:239:082:238
  031:181:092:230:088:017:007:251:083:193:051:245:237:209:064:070
  016:139:013:037:113:180:119:009:191:148:026:189:136:059:142:233
  056:160:243:135:076:165:012:035:222:212:231:084:249:061:152:093
  255:015:174:178:223:102:052:177:021:062:117:028:225:105:025:069
  121:002:227:122:143:047:134:137:146:219:194:060:005:089:044:140
  182:247:147:145:179:198:075:081:138:094:109:141:151:116:187:127
  103:128:001:132:036:154:066:112:078:196:229:004:226:211:206:199
  091:072:171:008:114:228:197:157:240:120:185:235:018:204:195:024

m=5b:c4:90
msg

Having fun with numbers & Python – Randomization & Shuffling – Stream Cipher

Basic HTTPS TLS Proxy Server In Python

#!/usr/bin/python
# Usage: ./net.py
# Description: Proof-of-concept HTTPS proxy script to hide the domain name in a TLS connection
#              so that firewalling appliances can't see who you are trying to connect to.
# Example setup: Edit ../hosts to include "127.0.0.1 imgur.com"
# Browser: http://imgur.com
#          -> TCP 127.0.0.1 80 (Python is listening & reads headers "GET / && Host imgur.com")
#          -> UDP 4.2.2.1 53 (Python performs DNS query on "imgur.com" [non-hosts file lookup])
#          -> TCP 1.2.3.4 443 (Python connects to TLS server & sends headers over encrypted channel [non-cert verify])
#          -> HTTPS response data is proxied back to browser localhost connection
# Warning: This script is very slow and insecure

import re
import socket
import ssl
import subprocess
import SocketServer

resolv = {}

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        global resolv
        
        heads = self.request.recv(10024).strip().split("\n")
        
        page = ""; host = ""
        for head in heads:
            match = re.match("^get ([^ ]+).*$", head.strip(), re.I)
            if (match):
                page = match.group(1)
            match = re.match("^host: ([^ ]+).*$", head.strip(), re.I)
            if (match):
                host = match.group(1)
        
        if ((not page) or (not host)):
            print("err",heads)
        else:
            addr = ""
            if (host in resolv.keys()):
                addr = resolv[host]
            else:
                looks = subprocess.check_output(["nslookup", host]).split("\n")
                for look in looks:
                    match = re.match("^address:[ ]+([^ ]+).*$", look.strip(), re.I)
                    if (match):
                        addr = match.group(1)
                resolv[host] = addr
            
            print(page,host,addr)
            
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            context.verify_mode = ssl.CERT_NONE
            context.check_hostname = False
            conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=addr)
            conn.connect((addr, 443))
            conn.sendall("GET "+page+" HTTP/1.1\r\n"+"Host: "+host+"\r\n"+"Connection: close\r\n"+"\r\n")
            
            resp = "";
            while (1):
                temp = conn.recv(10024)
                if (not temp):
                    break
                resp += temp
            self.request.sendall(resp)

if (__name__ == "__main__"):
    (HOST, PORT) = ("127.0.0.1", 80)
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

Basic HTTPS TLS Proxy Server In Python

A cool SSH auto password program – sshpass – for sys admin remote automation (probably should use keys instead tho)

#!/usr/bin/python
# Usage: ./sshpw.py <password> ssh user@host date
# Description: This is a demo SSH auto password login script via a pseudo tty device (stolen from sshpass - not recommended obviously!)
# Note: This is a rough example script which assumes you have already accepted the fingerprint & have the right password

import os, sys, time

import glob, struct, termios, fcntl, pty

from ctypes import *

try:
	libc = cdll.LoadLibrary(glob.glob("/lib/*-linux-gnu/libc-*.so")[0])
except:
	libc = cdll.LoadLibrary(glob.glob("/usr/lib/libc.dylib")[0])

(master, slave) = pty.openpty()
#fcntl.fcntl(master, fcntl.F_SETFL, os.O_NONBLOCK)

libc.ptsname.restype = c_char_p
name = libc.ptsname(c_int(master))
slavept = -10

ourtty = os.open("/dev/tty", 0)

s = struct.pack("HHHH", 0, 0, 0, 0)
t = fcntl.ioctl(ourtty, termios.TIOCGWINSZ, s)
fcntl.ioctl(master, termios.TIOCSWINSZ, t)

pidn = os.fork()

if (pidn == 0):
	os.setsid()
	slavept = os.open(name, os.O_RDWR)
	os.close(slavept)
	os.close(master)
	os.execvp(sys.argv[2], sys.argv[2:])
	os._exit(0)

else:
	slavept = os.open(name, os.O_RDWR | os.O_NOCTTY)
	print("["+os.read(master, 128)+"]")
	os.write(master, sys.argv[1] + "\r\n")
	print("["+os.read(master, 8)+"]")
	os.wait()

A cool SSH auto password program – sshpass – for sys admin remote automation (probably should use keys instead tho)

Simple LinkedIn Resume Generator (js)

LinkedIn recently disabled it’s third party APIs which took out an auto-resume builder service based on my public profile. I wrote some JS to try and at least generate a basic resume from my LinkedIn profile now:

From LinkedIn Profile -to- a simple clean resume! with just a little bit of effort! (done in Safari with print-to-PDF graphics enabled & headers disabled):

var s = 0, q = 0;
function y() {
  if (s < document.body.scrollHeight) {
    // scroll
    window.scrollBy(0, 125); s += 125;
    setTimeout(y, 0.125 * 1000);
  } else {
    if (q == 0) { q = 1; w(); }
    else { window.scrollTo(0, 0); }
  }
}

function w() {
  var s = 0, m = ["pv-profile-section__see-more-inline", "inline-show-more-text__button"];
  for (var j = 0; j < m.length; ++j) {
    var l = document.getElementsByClassName(m[j]);
    for (var i = 0; (i < l.length) && (s == 0); ++i) {
      try {
        // click
        var t = l[i].innerText; if (!t) { t = ""; }
        if (t.match(/^.*(see|show).*(more).*$/mi)) { l[i].click(); s = 1; }
        else if (t.match(/^.*(see|show).*(few|less)*$/mi)) { l[i].innerText = "x"; l[i].style.display = "none"; s = 1; }
        //console.log(i,t,l[i]);
      } catch(e) { /* no-op */ }
    }
  }
  if (s == 1) { setTimeout(w, 0.521 * 1000); } else { v(); z(); }
}

function v() {
  var u = (location.href.replace(/^.*\.com/, "") + "detail/contact-info/");
  var xttp = new XMLHttpRequest();
  xttp.onreadystatechange = function() {
    var r = this.responseText, l = []; if (r) { l = r.replace(/[ \t\r\n]/mig, " ").split(" "); }
    for (var i = 0; i < l.length; ++i) {
      // extra
      if (l[i] && l[i].match(/^.*emailaddr.*$/mig)) { pi(l[i]); }
    }
  }
  xttp.open("GET", u, true);
  xttp.send();
}

function pi(rr) {
  var p = "", q = "";
  var d = document.createElement("div");
  d.innerHTML = rr;
  var j = JSON.parse(d.innerText)["data"];
  console.log("ajax",j);
  p = j["emailAddress"];
  var l = j["websites"];
  for (var i = 0; l && (i < l.length); ++i) {
    if (q != "") { q += " | "; }
    q += l[i]["url"].replace(/^https?:../,"");
  }
  if (j["address"] && (j["address"].length > 0)) {
    if (q != "") { q += " | "; }
    q += j["address"];
  }
  if ((!p) || (!q)) { return ""; }
  var n = document.getElementsByClassName("pb2")[0];
  n.getElementsByTagName("a")[0].innerHTML = p;
  if (!document.getElementById("info")) {
    d = document.createElement("div");
    d.setAttribute("id", "info");
    d.setAttribute("class", "text-body-small");
    d.setAttribute("style", "font-family: monospace; padding-top: 5px;");
    d.innerHTML = q;
    n.parentNode.appendChild(d);
  }
}

function u() {
  // hide
  var l = [
    "msg-overlay", "global-nav", "global-footer", "scaffold-layout__aside", "artdeco-carousel__content", "artdeco-toasts",
    "pv-profile-sticky-header", "pv-top-card--photo", "pv-top-card__badge-wrap", "profile-topcard-background-image-edit__icon", "pv-open-to-carousel__navigation-button", "pv-text-details__right-panel",
    "pv-top-card--list", "pv-top-card-v2-ctas", "pv-entity__add-action", "pv-entity__edit-action", "pv-profile-section__header-add-action", "pv-profile-section__header-edit-action", "pv-profile-section__add-action", "pv-profile-section__edit-action"];
  for (var i in l) {
    var a = document.getElementById(l[i]);
    var b = document.getElementsByClassName(l[i]);
    try { a.setAttribute("style", "display: none !important;"); } catch(e) { /* no-op */ }
    for (var j in b) { try { b[j].setAttribute("style", "display: none !important;"); } catch(e) { /* no-op */ } }
  }

  // info
  var n = document.getElementsByClassName("pb2")[0];
  var h = n.innerHTML;
  var p = n.parentNode.children[0].children[1];
  p.innerHTML += ('<span class="pv-text-details__separator"></span>' + h);
  n.setAttribute("style", "display: none !important;");
  p.style.fontSize = "12px";
  var l = p.getElementsByTagName("*");
  for (var i = 0; i < l.length; ++i) { l[i].style.fontSize = "12px"; }
  n.parentNode.parentNode.parentNode.style.paddingBottom = "10px";
  document.getElementsByClassName("live-video-hero-image")[0].style.minHeight = "25px";
  document.getElementsByClassName("live-video-hero-image")[0].style.maxHeight = "25px";
}

function z() {
  // misc
  var l = ["profile-views", "pv-accomplishments-section", "pv-interests-section", "pv-recommendations-section", "pv-skill-categories-section", "pv-recent-activity-section-v2__headline"];
  for (var i = 0; i < l.length; ++i) {
    var p = document.getElementsByClassName(l[i]);
    if (p.length > 0) { p = p[0].parentNode; } else { p = null; }
    while (p) {
      if ((p.nodeName.toLowerCase() == "div") && p.id.startsWith("ember")) {
        if ((p.className == "ember-view") || p.className.includes("pv-deferred-area")) {
          p.style.display = "none"; break;
        }
      }
      p = p.parentNode;
    }
  }

  // high
  try {
    document.getElementsByClassName("authentication-outlet")[0].style.background = "white";
    document.getElementsByClassName("authentication-outlet")[0].style.paddingTop = "5px";
    document.getElementsByClassName("authentication-outlet")[0].style.paddingBottom = "256px";
    document.getElementsByClassName("live-video-hero-image")[0].style.width = "100.3%";
    document.getElementsByClassName("live-video-hero-image")[0].style.left = "-1px";
  } catch(e) { /* no-op */ }

  // wide
  try {
    document.getElementsByClassName("scaffold-layout__main")[0].style.width = "125%";
    document.getElementsByClassName("scaffold-layout__main")[0].style.background = "white";
    document.getElementsByClassName("scaffold-layout")[0].style.setProperty("--scaffold-layout-gutter", "0px");
    document.getElementsByClassName("scaffold-layout")[0].style.background = "white";
    document.getElementsByClassName("scaffold-layout-container")[0].style.margin = "0px";
    document.getElementsByClassName("scaffold-layout-container")[0].style.paddingLeft = "5px";
    document.getElementsByClassName("scaffold-layout-container")[0].style.background = "white";
  } catch(e) { /* no-op */ }

  // dots
  var l = document.getElementsByClassName("pv-entity__description");
  for (var i = 0; i < l.length; ++i) {
    var f = 1;
    while (f == 1) {
      f = 0;
      var h = l[i].innerHTML; if (!h) { h = ""; }
      h = h.replace(/\*/mig, "•")
      var m = h.match(/^(.*[^•])([•]+)([^&][^<]+)(.*)$/mi);
      if (m) {
        h = (m[1] + "<table style='display:inline;'><tr><td style='padding-left:"+(25*(m[2].length-1))+"px;white-space:nowrap;'><b style='font-size:16px;'>"+m[2][0]+"&nbsp;</b></td><td>" + m[3] + "</td></tr></table>" + m[4]);
        f = 1;
      }
      l[i].innerHTML = h;
    }
  }

  // imgs
  var l = document.getElementsByClassName("pv-entity__logo-img");
  for (var i = 0; i < l.length; ++i) {
    l[i].style.position = "relative"; l[i].style.transform = "none";
    l[i].style.top = "0px"; l[i].style.left = "0px";
  }

  // fixs
  var l = document.getElementsByClassName("pv-entity__extra-details");
  for (var i = 0; i < l.length; ++i) {
    l[i].style.paddingBottom = "25px";
    var p = l[i].parentNode;
    while (1) {
      //console.log(i,p);
      var m = p.classList.length;
      for (var j = 0; j < m; ++j) {
        p.classList.forEach(n => { if (!n.includes("pv-entity")) { p.classList.remove(n); } });
      }
      p.style.display = "block";
      p.style.padding = "0px"; p.style.margin = "0px";
      if (p.nodeName.toLowerCase() == "ul") {
        p.style.backgroundColor = "white";
      }
      if (p.nodeName.toLowerCase() == "section") {
        p.style.padding = "25px 25px 0px 5px";
        if (p.childNodes[0].nodeName.toLowerCase() == "header") {
          p.childNodes[0].style.padding = "0px 0px 25px 0px";
        }
        break;
      }
      p = p.parentNode;
    }
  }

  // find
  try {
    var l = document.getElementsByTagName("div");
    for (var i = 0; i < l.length; ++i) {
      var o = window.getComputedStyle(l[i], null).getPropertyValue("margin-left");
      var n = parseInt(o), s = "margin: 0px 0px 0px 65px !important;";
      if (n > 65) {
        console.log(l[i],n);
        l[i].setAttribute("style", s);
      }
    }
    var m = [document.getElementsByTagName("section"), document.getElementsByClassName("pv-profile-section__card-header")];
    for (var j = 0; j < m.length; ++j) {
      var l = m[j];
      for (var i = 0; i < l.length; ++i) {
        var o = window.getComputedStyle(l[i], null).getPropertyValue("padding-left");
        var n = parseInt(o), s = "padding: 25px 5px 5px 5px !important;";
        if (n > 15) {
          console.log(l[i],n);
          l[i].setAttribute("style", s);
        }
        if (j == 0) {
          var f = l[i], p = f.parentNode;
          while (p) {
            if (p.nodeName.toLowerCase() == "section") { f = p; }
            p = p.parentNode;
          }
          if (f != l[i]) { s = ""; }
          if (f.children.length < 1) { s = "display: none;"; }
          s += "box-shadow: 0px 0px 0px 0px !important;";
          s += "border-bottom: 1px solid rgba(0, 0, 0, 0.11) !important;";
          f.setAttribute("style", s);
        }
        if (l[i].innerHTML.match(/^.*cares about.*$/mig)) {
          l[i].style.display = "none";
        }
      }
    }
    document.getElementsByTagName("h1")[0].parentNode.parentNode.parentNode.parentNode.setAttribute("style", "padding-left: 5px !important;");
  } catch(e) { /* no-op */ }

  // font
  var m = ["inline-show-more-text", "pv-entity__description"];
  for (var j = 0; j < m.length; ++j) {
    var l = document.getElementsByClassName(m[j]);
    for (var i = 0; i < l.length; ++i) {
      l[i].style.fontSize = "10px"; l[i].style.paddingTop = "10px"; l[i].style.paddingBottom = "10px";
    }
  }
  var l = document.getElementsByTagName("h2");
  for (var i = 0; i < l.length; ++i) {
    l[i].setAttribute("style", "line-height: 0px !important;");
  }

  // fill
  var l = document.getElementsByClassName("pv-entity__description");
  for (var i = 0; i < l.length; ++i) {
    l[i].onclick = function() { this.innerHTML += "<br/> &nbsp; "; };
  }

  // mini
  var m = ["pv-entity__summary-info", "pv-entity__summary-info-v2"];
  for (var j = 0; j < m.length; ++j) {
    var l = document.getElementsByClassName(m[j]);
    for (var i = 0; i < l.length; ++i) {
      var n = l[i].getElementsByClassName("display-flex")[0];
      var h = l[i].children[l[i].children.length-1].innerHTML;
      if (!n) { console.log(j,i,l[i]); continue; }
      n.innerHTML += ('<h4 class="t-14 t-black--light t-normal"><span class="pv-entity__bullet-item-v2">' + h + '</span></h4>');
      l[i].children[l[i].children.length-1].setAttribute("style", "display: none !important;");
      var c = n.children;
      for (var k = 0; k < c.length; ++k) { c[k].style.fontSize = "10px"; }
      var k = (l[i].children.length - 3);
      while (k > 0) { l[i].children[k].style.fontSize = "12px"; --k; }
      l[i].children[0].style.fontSize = "14px";
    }
  }

  // end!
  setTimeout(u, 5 * 1000);
  window.scrollTo(0, 0);
  s = 0; y();
}

s = 0; y();

Simple LinkedIn Resume Generator (js)

Using a good Curve (25519) to implement a Dual_EC_DRBG based PRNG (bad) in Py

('(secret)', 'e=17211717500188099600568359980754843411619158773615107210604175251693280840607')

('(pub)', 'P', [15395204427582176828288140787842485523287609441875116301821962120815246523165L, 50972925492742860438904710940702337165443708937045978727200475339385656596802L])
('(pub)', 'Q', [54379753906375494870435841730857804485220282788952166778590221998932647140003L, 10542862410506568609831388869015874299228416047841839543681429954753256816461L])

Running first 3 prng outputs:
(1, '(pub)', 'rQ', [35085355371653225423586630859880842591953206407407058841980055259804158729190L, 17642611272178418467727837731595189739886826601909812633308152323681611088547L])
(2, '(pub)', 'rQ', [49239914602839976828302644790025511534554523065665058491590572885136905915179L, 8379389248907743775496938151971165397933498701999710225313910125914506554304L])
(3, '(pub)', 'rQ', [46183005535555809253746127552459776700939930656325949263490016267446108722393L, 39473869171813125431282259087083131250343325900631309529780555199432408899154L])

Predicting next prng output:
(4, '(pub)', 'sQ', [41709487842035263418257031106229715942424730101066821754384094668791902320545L, 47532264341329149594994883777108416347984877171111029279692175022666589952933L])
Running next prng output:
(4, '(pub)', 'rQ', [41709487842035263418257031106229715942424730101066821754384094668791902320545L, 47532264341329149594994883777108416347984877171111029279692175022666589952933L])
import sys
import random

def egcd(a, b):
	s = 0; news = 1
	r = b; newr = a
	while r != 0:
		quot = (newr / r)
		prev = s
		s = (news - (quot * prev))
		news = prev
		prev = r
		r = (newr - (quot * prev))
		newr = prev
	if (news < 0):
		news += b
	return news

def dub(p, a, b, n):
	# l = 3*x^2 + 2*a*x + 1 / 2*b*y
	xx = pow(p[0], 2, n)
	ya = (((3 * xx) + (2 * a * p[0]) + 1) % n)
	yd = ((2 * b * p[1]) % n)
	l = ((ya * egcd(yd, n)) % n)
	# xr = b*l^2 - a - 2*x
	ll = pow(l, 2, n)
	newx = (((b * ll) - a - (2 * p[0])) % n)
	# yr = ((3*x + a) * l) - b*l^3 - y
	yb = (((3 * p[0]) + a) % n)
	newy = (((yb * l) - (b * ll * l) - p[1]) % n)
	return [newx, newy]

def add(p, q, a, b, n):
	# l = (Qy - Py) / (Qx - Px)
	ya = ((q[1] - p[1]) % n)
	yd = ((q[0] - p[0]) % n)
	l = ((ya * egcd(yd, n)) % n)
	# xr = b*l^2 - a - Px - Qx
	ll = pow(l, 2, n)
	newx = (((b * ll) - a - p[0] - q[0]) % n)
	# yr = ((2*Px + Qx + a) * l) - b*l^3 - Py
	yb = (((2 * p[0]) + q[0] + a) % n)
	yc = ((b * ll * l) % n)
	newy = ((((yb * l) % n) - yc - p[1]) % n)
	return [newx, newy]

def mul(m, p, a, b, n):
	r = None
	while (m > 0):
		if ((m % 2) == 1):
			if (r == None):
				r = p
			else:
				r = add(r, p, a, b, n)
		p = dub(p, a, b, n)
		m = (m >> 1)
	return r

a = 486662
b = 1
n = 57896044618658097711785492504343953926634992332820282019728792003956564819949
try:
	p = [int(sys.argv[2]), int(sys.argv[3])]
except:
	p = [9, 43114425171068552920764898935933967039370386198203806730763910166200978582548]

# e is our secret key here
d = random.randint(3, n - 3)
e = random.randint(3, n - 3)
print("(secret)","e=%d"%e)
print("")

# let G = any base point
# calculate public point constants: P = edG & Q = dG
g = mul(d, p, a, b, n)
g = mul(e, g, a, b, n)
print("(pub)","P",g)
h = mul(d, p, a, b, n)
print("(pub)","Q",h)
print("")

# multiply random seed with the points: P' = rP & Q' = rQ
# these then equate to: P' = redG & Q' = rdG
# the 'key' to this is basing the next r' off of the output of P' and publishing the point info of Q' and repeat
r = random.randint(3, n - 3)
print("Running first 3 prng outputs:")
for x in range(1, 4):
	t = mul(r, g, a, b, n)
	u = mul(r, h, a, b, n)
	print(x,"(pub)","rQ",u)
	r = ((t[0] + t[1]) % n)
print("")

# to predict the next output then multiply: eQ' == erdQ == erdG == redG == P'
# you can now get r' and calculate the next P'' & Q''
print("Calculating next prng output (using e & latest Q):")
z = mul(e, [u[0], u[1]], a, b, n)
s = ((z[0] + z[1]) % n)
v = mul(s, z, a, b, n)
w = mul(s, h, a, b, n)
print(x+1,"(pub)","sQ",w)

# just to be sure
print("Running next prng output:")
for y in range(0, 1):
	t = mul(r, g, a, b, n)
	u = mul(r, h, a, b, n)
	print(x+1,"(pub)","rQ",u)
	r = ((t[0] + t[1]) % n)
print("")

Using a good Curve (25519) to implement a Dual_EC_DRBG based PRNG (bad) in Py

Secure Message iOS App in Swift

Using: Curve25519-ECDH, SHA256-HMAC, AES256-CBC — [Link to the GitHub Project Repo]

 
tcpdump pcap

01:07:18.371915 IP 192.168.1.171.64115 > 31.170.162.63.80: Flags [P.], seq 258:712, ack 1, win 8192, length 454: HTTP
mode=mesg&user=bob&rcpt=jon&mesg=key,31237969521267061265339920357754601118035663355449910125550985699827426505154,7903087581924324533759768883989441673564165222638106623548350836149345932721
--
01:07:18.783449 IP 31.170.162.63.80 > 192.168.1.171.64116: Flags [P.], seq 1:353, ack 539, win 250, length 352: HTTP: HTTP/1.1 200 OK
1450084038.47668400.66932:bob:key,31237969521267061265339920357754601118035663355449910125550985699827426505154,7903087581924324533759768883989441673564165222638106623548350836149345932721
--
01:07:19.547229 IP 192.168.1.171.64117 > 31.170.162.63.80: Flags [P.], seq 258:712, ack 1, win 8192, length 454: HTTP
mode=mesg&user=jon&rcpt=bob&mesg=key,20845162869924781138108110300526986101524551329253196414272755241823588505763,3845740679180735844612211279137657051909097428357280103024866020367868787613
--
01:07:20.637809 IP 31.170.162.63.80 > 192.168.1.171.64118: Flags [P.], seq 1:353, ack 539, win 250, length 352: HTTP: HTTP/1.1 200 OK
1450084039.65591500.56627:jon:key,20845162869924781138108110300526986101524551329253196414272755241823588505763,3845740679180735844612211279137657051909097428357280103024866020367868787613
--
01:07:30.861632 IP 192.168.1.171.64123 > 31.170.162.63.80: Flags [P.], seq 258:672, ack 1, win 8192, length 414: HTTP
mode=mesg&user=bob&rcpt=jon&mesg=msg,471776850.748092,8017053b9ea82e9d52e41052cc3518cd,8bd681694098a46a6ffbb01158672929d1fc5f3859f3fc5cc5030de8e4ed6d6e
--
01:07:33.788855 IP 31.170.162.63.80 > 192.168.1.171.64124: Flags [P.], seq 1:313, ack 539, win 250, length 312: HTTP: HTTP/1.1 200 OK
1450084050.96252100.73649:bob:msg,471776850.748092,8017053b9ea82e9d52e41052cc3518cd,8bd681694098a46a6ffbb01158672929d1fc5f3859f3fc5cc5030de8e4ed6d6e

/* c helper swift functions */

bnum *getx(ecc *e) { return e->x; }
bnum *gety(ecc *e) { return e->y; }

ecc *eccryp()
{
	char *a = "486662", *b = "1", *p = "57896044618658097711785492504343953926634992332820282019728792003956564819949";
	char *x = "9", *y = "43114425171068552920764898935933967039370386198203806730763910166200978582548";
	bnum *t, *u, *v, *w;
	ecc *e;
	
	t = bndec(p);
	u = bninit(t->size); w = bndec(x); bncopy(w, u); bnfree(w);
	v = bninit(t->size); w = bndec(y); bncopy(w, v); bnfree(w);
	e = ecinit(bndec(a), bndec(b), t, u, v);
	
	return e;
}

bnum *bnrnd(int size)
{
	FILE *f;
	bnum *r;
	
	r = bninit(size);
	f = fopen("/dev/urandom", "r");
	fread(r->nums, sizeof(unsigned int), size - 1, f);
	fclose(f);
	r->leng = size;
	while ((r->leng > 1) && (r->nums[r->leng - 1] == 0)) { r->leng -= 1; }
	
	return r;
}

/*
 Curve25519: a=486662, b=1, p=2^255 - 19
 ECC DH: o * (n * P) == onP == noP == n * (o * P)
 */

char *ecdh(ecc *e, const char *n)
{
	char *r = (char *)n;
	bnum *m;
	ecc *f;
	
	if (r == NULL)
	{
		m = bnrnd((e->p)->size);
		r = bnstr(m);
	}
	
	else
	{
		m = bndec((char *)n);
	}
	
	f = ecdup(e);
	pmul(m, e, f);
	
	(f->x)->leng = min((f->x)->leng, (e->p)->size); bncopy(f->x, e->x);
	(f->y)->leng = min((f->y)->leng, (e->p)->size); bncopy(f->y, e->y);
	bnfree(m);
	ecfree(f);
	
	return r;
}

void setexy(ecc *e, const char *x, const char *y)
{
	bnum *t;
	t = bndec((char *)x); t->leng = min(t->leng, (e->p)->size);
	bncopy(t, e->x); bnfree(t);
	t = bndec((char *)y); t->leng = min(t->leng, (e->p)->size);
	bncopy(t, e->y); bnfree(t);
}

char *shash(const char *m)
{
	char *o = malloc(256);
	sha256 hobj;
	sha256init(&hobj);
	sha256update(&hobj, (unsigned char *)m, (unsigned int)strlen(m));
	sha256final(&hobj, o);
	return o;
}

char *sencr(const char *i, const char *m, const char *k, int d)
{
	int x, y, w, z = 0;
	unsigned long ilen = strlen(i), mlen = strlen(m), klen = strlen(k);
	unsigned char tmp[16], ivn[16], msg[16], key[256];
	char *hex = "0123456789abcdef";
	char *enc = malloc(3 * strlen(m));
	
	bzero(key, 256);
	for (x = 0; ((x + 1) < 64) && ((x + 1) < klen); x += 2)
	{
		for (y = 0; y < 16; ++y)
		{
			if (k[x] == hex[y]) { key[x / 2] |= (y << 4); }
			if (k[x + 1] == hex[y]) { key[x / 2] |= y; }
		}
	}
	aes256keys(key);
	
	for (x = 0; x < 16; ++x)
	{
		ivn[x] = 0;
		if (x < ilen) { ivn[x] = i[x]; }
	}
	
	x = 0;
	while (x < mlen)
	{
		if (d == 0)
		{
			for (y = 0; y < 16; ++y)
			{
				msg[y] = 0;
				if (x < mlen) { msg[y] = m[x]; ++x; }
				msg[y] ^= ivn[y];
			}
		}
		else
		{
			for (y = 0; y < 16; ++y)
			{
				msg[y] = 0;
				if ((x + 1) < mlen)
				{
					for (w = 0; w < 16; ++w)
					{
						if (m[x] == hex[w]) { msg[y] |= (w << 4); }
						if (m[x + 1] == hex[w]) { msg[y] |= w; }
					}
					x += 2;
				}
				tmp[y] = msg[y];
			}
		}
		
		aes256core(msg, key, d);
		
		if (d == 0)
		{
			for (y = 0; y < 16; ++y)
			{
				enc[z] = hex[(msg[y] >> 4) & 0xf]; ++z;
				enc[z] = hex[msg[y] & 0xf]; ++z;
				ivn[y] = msg[y];
			}
		}
		else
		{
			for (y = 0; y < 16; ++y)
			{
				enc[z] = (msg[y] ^ ivn[y]); ++z;
				ivn[y] = tmp[y];
			}
		}
	}
	enc[z] = 0;
	
	return enc;
}

char *hmac(const char *m, const char *k)
{
	int x, y, i, j, bs = 64;
	unsigned long mlen = strlen(m), klen = strlen(k);
	char *hex = "0123456789abcdef", *hmout = malloc(256);
	unsigned char key[bs], ipad[bs], opad[bs];
	sha256 hobj;
	
	bzero(key, bs);
	for (x = 0; ((x + 1) < 64) && ((x + 1) < klen); x += 2)
	{
		for (y = 0; y < 16; ++y)
		{
			if (k[x] == hex[y]) { key[x / 2] |= (y << 4); }
			if (k[x + 1] == hex[y]) { key[x / 2] |= y; }
		}
	}
	
	for (x = 0; x < bs; ++x)
	{
		ipad[x] = (0x36 ^ key[x]);
		opad[x] = (0x5C ^ key[x]);
	}
	
	sha256init(&hobj);
	sha256update(&hobj, ipad, bs);
	sha256update(&hobj, (unsigned char *)m, (unsigned int)mlen);
	sha256final(&hobj, hmout);
	
	for (x = 0; x < 8; ++x)
	{
		for (y = 0; y < 4; ++y)
		{
			i = ((x * 4) + y);
			j = (24 - (y * 8));
			key[i] = ((hobj.h[x] >> j) & 0xff);
		}
	}
	
	sha256init(&hobj);
	sha256update(&hobj, opad, bs);
	sha256update(&hobj, key, 32);
	sha256final(&hobj, hmout);
	
	return hmout;
}

//
//  ViewController.swift
//  smsg
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

	let userText: UITextField = UITextField(frame: CGRect(x: 10.00, y: 32.00, width: 200.00, height: 30.00))
	let passText: UITextField = UITextField(frame: CGRect(x: 10.00, y: 64.00, width: 200.00, height: 30.00))
	let authButn: UIButton = UIButton(frame: CGRect(x: 225.00, y: 64.00, width: 100.00, height: 30.00))
	
	let frndText: UITextField = UITextField(frame: CGRect(x: 10.00, y: 96.00, width: 200.00, height: 30.00))
	let frndButn: UIButton = UIButton(frame: CGRect(x: 225.00, y: 96.00, width: 100.00, height: 30.00))
	let seckText: UILabel = UILabel(frame: CGRect(x: 10.00, y: 128.00, width: 300.00, height: 30.00))
	
	var mesgList: [String] = ["line 1", "line 2", "line 3"]
	let mesgHist: UITableView = UITableView(frame: CGRect(x: 10.00, y: 160.00, width: 300.00, height: 120.00))
	let mesgText: UITextView = UITextView(frame: CGRect(x: 10.00, y: 284.00, width: 200.00, height: 60.00))
	let mesgButn: UIButton = UIButton(frame: CGRect(x: 225.00, y: 284.00, width: 100.00, height: 30.00))
	
	let vers = "1.9.9.1"
	let serv = "http://smsg.site88.net"
	var authkey: String = ""
	var dhkey: String = ""
	var dhx: String = ""
	var dhy: String = ""
	var skey: String = ""
	var tkey: String = ""
	var ecobj = eccryp()
	
	func readReply(mode: Int, response: String) {
		if (response != "") { print("r>"+response) }
		
		if (response.characters.count > 5)
		{
			if (mode == 0)
			{
				self.authkey = response.substringWithRange(Range<String.Index>(start:response.startIndex.advancedBy(5), end:response.endIndex))
				
				dispatch_async(dispatch_get_main_queue()) { self.seckText.text = (" " + self.authkey) }
			}
			
			else if (mode == 3)
			{
				let linelist = response.characters.split{$0 == "\n"}.map(String.init)
				for line in linelist
				{
					let readlist = line.characters.split{$0 == ":"}.map(String.init)
					if (readlist.count > 2)
					{
						let infolist = readlist[2].characters.split{$0 == ","}.map(String.init)
						
						if (infolist.count == 3)
						{
							if ((readlist[1] == frndText.text) && (infolist[0] == "key"))
							{
								if (self.dhkey == "")
								{
									self.dhkey = String.fromCString(ecdh(self.ecobj, nil))!
									self.dhx = String.fromCString(bnstr(getx(self.ecobj)))!
									self.dhy = String.fromCString(bnstr(gety(self.ecobj)))!
									self.sendMesg(1, mesg: self.dhx+","+self.dhy)
								}
								
								setexy(self.ecobj, infolist[1], infolist[2])
								ecdh(self.ecobj, self.dhkey)
								let tdhx = String.fromCString(bnstr(getx(self.ecobj)))
								let tdhy = String.fromCString(bnstr(gety(self.ecobj)))
								
								print("d>"+tdhx!+","+tdhy!)
								self.skey = String.fromCString(shash(tdhx!+","+tdhy!))!
								self.tkey = String.fromCString(shash(self.skey))!
								print("k>"+self.skey+","+self.tkey)
								dispatch_async(dispatch_get_main_queue()) { self.seckText.text = (" " + self.skey) }
							}
						}
						
						else if (infolist.count == 4)
						{
							if ((readlist[1] == frndText.text) && (infolist[0] == "msg"))
							{
								let smac = String.fromCString(hmac(infolist[1]+","+infolist[2], self.tkey))
								print("v>"+smac!+"=="+infolist[3])
								if (smac == infolist[3])
								{
									let smesg = String.fromCString(sencr(infolist[1], infolist[2], self.skey, 1))
									self.mesgList.append(smesg!)
									dispatch_async(dispatch_get_main_queue()) { self.mesgHist.reloadData() }
								}
							}
						}
					}
				}
			}
		}
	}
	
	func sendMesg(mode: Int, mesg: String) {
		var postdata: String = ""
		
		if (mode == 0)
		{
			postdata = ("mode=auth&user="+self.userText.text!+"&pass="+self.passText.text!)
		}
		
		else if (mode == 1)
		{
			postdata = ("mode=mesg&user="+self.userText.text!+"&auth="+self.authkey+"&rcpt="+self.frndText.text!+"&mesg=key,"+mesg)
		}
		
		else if (mode == 2)
		{
			postdata = ("mode=mesg&user="+self.userText.text!+"&auth="+self.authkey+"&rcpt="+self.frndText.text!+"&mesg=msg,"+mesg)
		}
		
		else if (mode == 3)
		{
			postdata = ("mode=read&user="+self.userText.text!+"&auth="+self.authkey)
		}
		
		let request = NSMutableURLRequest(URL: NSURL(string: self.serv)!)
		request.HTTPMethod = "POST"
		request.HTTPBody = postdata.dataUsingEncoding(NSUTF8StringEncoding)
		let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
			data, response, error in
			let reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
			self.readReply(mode, response: reply as! String)
		}
		task.resume()
	}
	
	func butnPress(butn: UIButton) {
		if (butn.titleLabel?.text == "Login") { self.sendMesg(0, mesg: "") }
		if (butn.titleLabel?.text == "Add")
		{
			if (self.dhkey == "")
			{
				self.dhkey = String.fromCString(ecdh(self.ecobj, nil))!
				self.dhx = String.fromCString(bnstr(getx(self.ecobj)))!
				self.dhy = String.fromCString(bnstr(gety(self.ecobj)))!
			}
			self.sendMesg(1, mesg: self.dhx+","+self.dhy)
		}
		if (butn.titleLabel?.text == "Send")
		{
			if (self.skey != "")
			{
				let stime = String(NSDate.timeIntervalSinceReferenceDate())
				let smesg = String.fromCString(sencr(stime, self.mesgText.text, self.skey, 0))
				let smac = String.fromCString(hmac(stime+","+smesg!, self.tkey))
				self.sendMesg(2, mesg: stime+","+smesg!+","+smac!)
			}
		}
	}
	
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return self.mesgList.count
	}
	
	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
		cell.textLabel!.text = self.mesgList[indexPath.row]
		cell.textLabel!.font = cell.textLabel!.font.fontWithSize(10)
		return cell
	}
	
	func backFunc(timer: NSTimer) {
		self.sendMesg(3, mesg: "")
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		
		print("i>draw init")
		
		/* login elements */
		
		let userPadd = UIView(frame: CGRectMake(0, 0, 5, self.userText.frame.size.height))
		self.userText.leftView = userPadd
		self.userText.leftViewMode = UITextFieldViewMode.Always
		self.userText.layer.cornerRadius = 2.0
		self.userText.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.userText.layer.borderWidth = 2.0
		self.userText.autocorrectionType = UITextAutocorrectionType.No
		self.userText.autocapitalizationType = UITextAutocapitalizationType.None
		self.view.addSubview(self.userText)
		
		let passPadd = UIView(frame: CGRectMake(0, 0, 5, self.passText.frame.size.height))
		self.passText.leftView = passPadd
		self.passText.leftViewMode = UITextFieldViewMode.Always
		self.passText.layer.cornerRadius = 2.0
		self.passText.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.passText.layer.borderWidth = 2.0
		self.passText.secureTextEntry = true
		self.view.addSubview(self.passText)
		
		self.authButn.layer.cornerRadius = 2.0
		self.authButn.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.authButn.layer.borderWidth = 2.0
		self.authButn.setTitle("Login", forState: UIControlState.Normal)
		self.authButn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
		self.authButn.addTarget(self, action: "butnPress:", forControlEvents: UIControlEvents.TouchUpInside)
		self.view.addSubview(self.authButn)
		
		/* friend elements */
		
		let frndPadd = UIView(frame: CGRectMake(0, 0, 5, self.userText.frame.size.height))
		self.frndText.leftView = frndPadd
		self.frndText.leftViewMode = UITextFieldViewMode.Always
		self.frndText.layer.cornerRadius = 2.0
		self.frndText.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.frndText.layer.borderWidth = 2.0
		self.frndText.autocorrectionType = UITextAutocorrectionType.No
		self.frndText.autocapitalizationType = UITextAutocapitalizationType.None
		self.view.addSubview(self.frndText)
		
		self.frndButn.layer.cornerRadius = 2.0
		self.frndButn.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.frndButn.layer.borderWidth = 2.0
		self.frndButn.setTitle("Add", forState: UIControlState.Normal)
		self.frndButn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
		self.frndButn.addTarget(self, action: "butnPress:", forControlEvents: UIControlEvents.TouchUpInside)
		self.view.addSubview(self.frndButn)
		
		self.seckText.layer.cornerRadius = 2.0
		self.seckText.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.seckText.layer.borderWidth = 2.0
		self.seckText.font = self.seckText.font.fontWithSize(8)
		self.seckText.text = (" v" + self.vers)
		self.view.addSubview(self.seckText)
		
		/* message elements */
		
		self.mesgHist.layer.cornerRadius = 2.0
		self.mesgHist.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.mesgHist.layer.borderWidth = 2.0
		self.mesgHist.rowHeight = 20.0
		self.mesgHist.delegate = self
		self.mesgHist.dataSource = self
		self.view.addSubview(self.mesgHist)
		
		self.mesgText.layer.cornerRadius = 2.0
		self.mesgText.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.mesgText.layer.borderWidth = 2.0
		self.mesgText.autocorrectionType = UITextAutocorrectionType.No
		self.mesgText.autocapitalizationType = UITextAutocapitalizationType.None
		self.mesgText.text = "message string"
		self.view.addSubview(self.mesgText)
		
		self.mesgButn.layer.cornerRadius = 2.0
		self.mesgButn.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
		self.mesgButn.layer.borderWidth = 2.0
		self.mesgButn.setTitle("Send", forState: UIControlState.Normal)
		self.mesgButn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
		self.mesgButn.addTarget(self, action: "butnPress:", forControlEvents: UIControlEvents.TouchUpInside)
		self.view.addSubview(self.mesgButn)
		
		/* background reader */
		
		NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "backFunc:", userInfo: nil, repeats: true)
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}

}

Secure Message iOS App in Swift