Skip to content

Instantly share code, notes, and snippets.

@baderj
Last active January 12, 2016 13:02
Show Gist options
  • Save baderj/477f04c2c6f11661f403 to your computer and use it in GitHub Desktop.
Save baderj/477f04c2c6f11661f403 to your computer and use it in GitHub Desktop.
"""
generate domains according to:
- https://www.endgame.com/blog/malware-with-a-personal-touch.html
- http://www.rsaconference.com/writable/presentations/file_upload/br-r01-end-to-end-analysis-of-a-domain-generating-algorithm-malware-family.pdf
requires words1.txt and words2.txt
"""
import time
from datetime import datetime
import argparse
def generate_domains(time_, word_list):
with open("words{}.txt".format(word_list), "r") as r:
words = [w.strip() for w in r.readlines()]
if not time_:
time_ = time.time()
seed = int(time_) >> 9
for c in range(85):
nr = seed
res = 16*[0]
shuffle = [3, 9, 13, 6, 2, 4, 11, 7, 14, 1, 10, 5, 8, 12, 0]
for i in range(15):
res[shuffle[i]] = nr % 2
nr = nr >> 1
first_word_index = 0
for i in range(7):
first_word_index <<= 1
first_word_index ^= res[i]
second_word_index = 0
for i in range(7,15):
second_word_index <<= 1
second_word_index ^= res[i]
second_word_index += 0x80
first_word = words[first_word_index]
second_word = words[second_word_index]
tld = ".net"
print("{}{}{}".format(first_word, second_word, tld))
seed += 1
if __name__=="__main__":
parser = argparse.ArgumentParser()
datefmt = "%Y-%m-%d %H:%M:%S"
parser.add_argument('set', choices=[1,2], type=int, help="word list")
parser.add_argument('-t', '--time',
help="time (default is now: %(default)s)",
default=datetime.now().strftime(datefmt))
args = parser.parse_args()
time_ = time.mktime(datetime.strptime(args.time, datefmt).timetuple())
generate_domains(time_, args.set)
"""
check if domain is generated by DGA described here:
- https://www.endgame.com/blog/malware-with-a-personal-touch.html
- http://www.rsaconference.com/writable/presentations/file_upload/br-r01-end-to-end-analysis-of-a-domain-generating-algorithm-malware-family.pdf
requires words1.txt and words2.txt
"""
import time
from datetime import datetime
import argparse
def find_timerange(domain):
word_sets = {}
for i in [1,2]:
filename = "words{}.txt".format(i)
with open(filename, "r") as r:
words = [w.strip() for w in r.readlines()]
word_sets[filename] = words
second_level = domain.split('.')[-2]
for word_set, words in word_sets.items():
first_w_matches = []
second_w_matches = []
for word in words[:128]:
if second_level.startswith(word):
first_w_matches.append(word)
for word in words[128:]:
if second_level.endswith(word):
second_w_matches.append(word)
found = False
for first_w in first_w_matches:
for second_w in second_w_matches:
if first_w and second_w and first_w + second_w == second_level:
found = True
if found:
break
else:
print("ERROR: can't find words in word lists")
return
first_w_index = word_sets[word_set].index(first_w)
second_w_index = word_sets[word_set].index(second_w)
shuffle = [3, 9, 13, 6, 2, 4, 11, 7, 14, 1, 10, 5, 8, 12, 0]
reverse_shuffle = 15*[None]
for i, s in enumerate(shuffle):
reverse_shuffle[s] = i
res = (first_w_index << 8) + ((second_w_index - 0x80))
res_bin = [int(x) for x in list('{0:0b}'.format(res))]
res_bin = (15-len(res_bin))*[0] + res_bin
res_bin_shuffled = 15*[0]
for i, x in enumerate(res_bin[:15]):
res_bin_shuffled[reverse_shuffle[i]] = x
seed = 0
for x in res_bin_shuffled[::-1]:
seed <<= 1
seed += x
seed <<= 9
datefmt = "%Y-%m-%d %H:%M:%S"
n = (int(time.mktime(datetime(2012,1,1).timetuple())) >> 24) << 24
seed += n
for i in range(10):
first_time = datetime.fromtimestamp(seed - 84*512)
last_time = datetime.fromtimestamp(seed + 511)
print("Wordlist {}, active between {} - {}".format(
word_set,
first_time.strftime(datefmt),
last_time.strftime(datefmt)))
seed += (1 << 24)
if __name__=="__main__":
parser = argparse.ArgumentParser()
datefmt = "%Y-%m-%d %H:%M:%S"
parser.add_argument('domain', help="domain, e.g, deepeight.net")
args = parser.parse_args()
find_timerange(args.domain)
journey
destroy
against
night
within
effort
street
better
husband
little
doub
decide
suffer
through
trade
gather
ridden
chair
large
record
forget
would
flier
quiet
belong
those
captain
electric
increase
remember
bread
season
degree
answer
think
chief
order
leader
rather
strange
forward
glass
present
college
require
heaven
morning
history
difficult
pleasant
often
middle
heavy
various
amount
thick
heard
necessary
alone
twelve
gentle
return
weather
class
movement
building
fresh
gentleman
fellow
broken
summer
thought
outside
evening
experience
already
double
result
crowd
water
store
doctor
follow
begin
prepare
strength
woman
party
might
pretty
member
known
desire
still
smoke
fight
expect
person
severa
simple
figure
picture
winter
finish
because
machine
laugh
mother
though
cigarette
subject
leave
sudden
whether
mountain
perhaps
children
either
sweet
several
foreign
right
possible
window
family
english
probably
material
shore
welcome
dollar
proud
should
industry
opinion
contain
character
nature
board
enough
supply
settle
office
device
beyond
silver
forever
valley
matter
school
together
question
flower
bring
special
demand
father
hunger
built
storm
written
around
realize
complete
short
became
promise
basket
ladder
needle
enter
govern
distance
language
arrive
before
being
sister
bottom
labor
spent
while
control
therefore
minute
listen
corner
shout
apple
training
carry
thrown
length
laughter
indeed
consider
almost
attempt
orderly
neighbor
clear
smell
include
safety
chance
market
twenty
beauty
clean
ready
course
people
understand
succeed
behind
produce
stream
nation
bottle
please
dried
round
angry
likely
notice
fancy
during
friend
reason
square
value
spread
general
early
north
future
meeting
report
understood
garden
paint
brown
women
daughter
broad
between
butter
student
nothing
soldier
divide
condition
fifteen
glossary
article
worth
except
further
bicycle
become
strong
found
president
success
wagon
until
kitchen
shoulder
continue
airplane
wonder
guard
advance
station
goodbye
object
measure
choose
afraid
period
escape
space
problem
yellow
wheat
single
always
difference
bridge
cover
whose
company
trouble
spring
caught
banker
without
above
probable
finger
master
straight
discover
fence
stranger
third
fortieth
childhood
dinner
although
circle
however
animal
travel
modern
close
anger
charge
forest
every
branch
separate
receive
clothes
borrow
toward
electricity
million
honor
catch
system
public
number
heart
strike
mayor
manner
century
business
power
mister
method
service
direct
instead
surprise
bright
letter
nearly
speak
shake
write
believe
health
quarter
distant
train
pleasure
delight
white
neither
eearly
trust
dress
position
perfect
partial
battle
another
famous
appear
country
suppose
action
river
brought
explain
beside
inside
different
happen
niece
share
oclock
milk
with
arive
upon
quick
sunday
equal
spoke
tried
duty
south
which
then
most
group
visit
these
case
spot
glad
meat
cloud
watch
dream
sight
head
salt
taken
sick
dark
fair
this
know
pick
human
yard
hill
felt
hang
join
able
song
hair
music
whom
look
september
wish
room
move
went
front
three
drink
dead
wrong
sign
jump
spend
offer
lord
wife
rock
made
sorry
their
long
wheel
point
none
mouth
shall
fifty
likr
soil
said
call
liar
till
deep
fear
table
stick
enemy
well
ring
push
along
west
lead
ball
life
nose
favor
friday
december
tries
lrstn
field
both
tore
week
story
after
your
view
queen
gain
fall
very
weak
force
plant
sense
least
month
piece
wait
sell
drive
fill
learn
face
walk
much
take
wednesday
nail
stood
shoe
first
moon
ride
lift
ought
sound
taste
show
allow
rule
them
happy
considerable
since
wash
sleep
talk
held
fruit
than
noise
mile
sure
hello
shot
live
threw
saturday
shade
loud
kill
october
guess
outer
small
green
marry
hand
earth
hunt
gives
hear
best
heat
easy
page
below
height
shirt
rain
rise
read
pull
king
cause
mine
back
serve
cross
thousand
floor
tree
cloth
dare
august
body
blood
about
lose
into
price
feel
raise
color
hold
never
ocean
start
grow
wild
thank
began
step
feet
grown
yesterday
pure
boat
dish
rest
form
gray
touch
army
paid
dance
born
tell
daily
child
full
place
croud
high
reach
only
second
nine
have
sing
tear
june
city
kind
plain
each
black
wedge
march
press
july
open
agree
april
word
edge
weight
under
come
feed
goes
voice
light
eight
iron
world
roll
octover
road
aunt
wore
great
slept
house
prove
tuesday
usual
stock
teach
reply
fine
home
else
grain
state
cold
mark
bone
took
monday
nerve
lend
fool
five
gone
they
build
enjoy
deal
horse
mail
scene
where
dont
hers
gift
break
peace
could
throw
grave
whole
nice
over
important
gold
broke
wrote
news
fire
neck
half
food
guide
there
tall
stone
next
some
wing
today
lady
lower
again
wide
sugar
compe
told
fell
wear
hard
uncle
make
loss
hope
slow
thirteen
help
fifth
free
done
other
shown
name
meet
late
arms
cook
side
been
seven
past
such
fish
tomorrow
pass
kiss
stand
hour
find
count
hurt
clock
study
rush
once
left
february
hurry
november
shine
forty
knew
wall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment