# MIT License
#
# Copyright (c) 2017 Pietro Ferretti, Danilo Labanca
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from pwn import *
import crypto
import random
import string
import time
import re
import itertools

random.seed(time.time())

words = ['rigors',
 'messengers',
 'devils',
 'beehives',
 'normalizes',
 'rumpus',
 'recruits',
 'absconds',
 'remodels',
 'urns',
 'springiness',
 'acquires',
 'presides',
 'bulkheads',
 'evenness',
 'sinusoids',
 'drunkards',
 'affairs',
 'beakers',
 'lazarus',
 'chubbiness',
 'moons',
 'divergences',
 'ornaments',
 'offenses',
 'aides',
 'sloppiness',
 'reuses',
 'bosoms',
 'corks',
 'tautologies',
 'dopes',
 'completes',
 'rescuers',
 'vicissitudes',
 'pillows',
 'digits',
 'boats',
 'succeeds',
 'thunders',
 'weds',
 'goddess',
 'raters',
 'toads',
 'certainties',
 'goldenness',
 'distinctness',
 'braves',
 'bankrupts',
 'clogs',
 'diggers',
 'lacks',
 'diggings',
 'ballplayers',
 'tardiness',
 'hobbies',
 'sweets',
 'infuses',
 'raisers',
 'withholdings',
 'fearlessness',
 'bottlenecks',
 'badness',
 'recipients',
 'simplifications',
 'eunuchs',
 'tabulators',
 'mourners',
 'prevents',
 'outlines',
 'fears',
 'accesses',
 'subverts',
 'harmlessness',
 'vignettes',
 'begrudges',
 'succubus',
 'anoints',
 'subscribes',
 'electives',
 'sanctimonious',
 'glues',
 'polaris',
 'warships',
 'exhausts',
 'clusterings',
 'monarchies',
 'infiniteness',
 'additives',
 'fliers',
 'treacheries',
 'blowers',
 'improves',
 'precepts',
 'dyes',
 'arrestors',
 'turbans',
 'cursors',
 'tinniness',
 'nervousness',
 'endures',
 'screamers',
 'fits',
 'upholsters',
 'shooters',
 'privates',
 'crutches',
 'eavesdroppers',
 'stores',
 'repetitious',
 'tumors',
 'anomalous',
 'daylights',
 'resoluteness',
 'deceivers',
 'captures',
 'cherishes',
 'curriculums',
 'inferiors',
 'felicities',
 'bijections',
 'lifetimes',
 'antipodes',
 'timings',
 'minerals',
 'northerners',
 'lordosis',
 'collects',
 'rubs',
 'cantors',
 'manometers',
 'athens',
 'cigars',
 'crucifies',
 'beatings',
 'analogues',
 'macromolecules',
 'shortcomings',
 'cleans',
 'stretches',
 'ludicrousness',
 'outrageous',
 'wagers',
 'taboos',
 'morbidness',
 'cliches',
 'sojourners',
 'sweepers',
 'cringes',
 'clasps',
 'blurs',
 'modalities',
 'axolotls',
 'waves',
 'selfishness',
 'wards',
 'intentions',
 'devotions',
 'biases',
 'audits',
 'centralizes',
 'simpleness',
 'oats',
 'consanguineous',
 'nurseries',
 'funds',
 'servings',
 'articulations',
 'infectious',
 'sympathizes',
 'adores',
 'antiquarians',
 'likenesses',
 'recurs',
 'acropolis',
 'installments',
 'highlands',
 'cans',
 'interferences',
 'wrappers',
 'massages',
 'amanuensis',
 'quiets',
 'seekers',
 'coziness',
 'abstractions',
 'naps',
 'wristwatches',
 'talks',
 'cots',
 'dissimilarities',
 'principals',
 'stewards',
 'lingers',
 'icarus',
 'substances',
 'statues',
 'prohibits',
 'senates',
 'pities',
 'herbivorous',
 'possums',
 'analyzes',
 'cons',
 'geniuses',
 'playfulness',
 'dreams',
 'drops',
 'offers',
 'leakages',
 'steepness',
 'chloroplasts',
 'capes',
 'avows',
 'inns',
 'liberates',
 'respectfulness',
 'motionlessness',
 'toothpicks',
 'beds',
 'astounds',
 'borrows',
 'launches',
 'preparations',
 'ampersands',
 'units',
 'surliness',
 'phelps',
 'strives',
 'interns',
 'praises',
 'jungles',
 'begins',
 'aggressions',
 'stupidities',
 'whiteness',
 'narrows',
 'valets',
 'disperses',
 'artisans',
 'guerrillas',
 'misgivings',
 'comparisons',
 'maps',
 'facades',
 'spongers',
 'embroideries',
 'armaments',
 'wholes',
 'legions',
 'psyches',
 'squirms',
 'boastings',
 'obliqueness',
 'briefcases',
 'prowlers',
 'disjunctions',
 'reduces',
 'convents',
 'scares',
 'treatises',
 'submodules',
 'electrophoresis',
 'cosmos',
 'pros',
 'fractures',
 'buildups',
 'earnings',
 'semiramis',
 'adjusts',
 'rattlesnakes',
 'prepositions',
 'pots',
 'brotherliness',
 'troubles',
 'subtasks',
 'aquinas',
 'nationalists',
 'slippers',
 'concentrates',
 'bumptious',
 'vials',
 'psalms',
 'hostesses',
 'flavors',
 'displacements',
 'rolls',
 'whorls',
 'greatness',
 'microwords',
 'indictments',
 'darkness',
 'reads',
 'lowlands',
 'beers',
 'twisters',
 'restorers',
 'disrupts',
 'enjoins',
 'mugs',
 'chalmers',
 'handicaps',
 'dregs',
 'defines',
 'arbutus',
 'slacks',
 'commodores',
 'reexamines',
 'economizers',
 'reiterates',
 'absolutes',
 'helplessness',
 'instabilities',
 'intertwines',
 'journalizes',
 'bungalows',
 'gratuitous',
 'usefulness',
 'parameterizations',
 'entertainers',
 'lasers',
 'trimness',
 'soles',
 'firearms',
 'harness',
 'prestigious',
 'homogeneous',
 'antelopes',
 'describes',
 'spacers',
 'cusps',
 'handiness',
 'alternations',
 'minicomputers',
 'parrots',
 'backstitches',
 'relentlessness',
 'brochures',
 'overprints',
 'blots',
 'centerpieces',
 'bothers',
 'knights',
 'disastrous',
 'smoothes',
 'hoppers',
 'coasters',
 'sorcerers',
 'conservationists',
 'devotes',
 'venturings',
 'terminologies',
 'attendances',
 'wins',
 'supercilious',
 'longs',
 'clutches',
 'captivates',
 'restores',
 'vaporous',
 'abounds',
 'peeks',
 'firings',
 'ferrous',
 'garrulous',
 'decorations',
 'smuggles',
 'bulls',
 'residues',
 'chasms',
 'juices',
 'recognitions',
 'halvers',
 'discoveries',
 'brokenness',
 'directrices',
 'meningitis',
 'screens',
 'backdrops',
 'melodies',
 'lexicons',
 'deserves',
 'matchers',
 'demands',
 'calculus',
 'fabricates',
 'liveness',
 'citadels',
 'relabels',
 'questionings',
 'yelps',
 'exasperates',
 'mandates',
 'messiness',
 'rabies',
 'microprograms',
 'reuters',
 'referents',
 'randomness',
 'driveways',
 'stews',
 'wavers',
 'testers',
 'sanctuaries',
 'permutes',
 'documentaries',
 'accidents',
 'departs',
 'decliners',
 'delegations',
 'explicitness',
 'deals',
 'detections',
 'socks',
 'veterinarians',
 'wolves',
 'checkbooks',
 'pocketbooks',
 'promenades',
 'effects',
 'compromisers',
 'renames',
 'glasses',
 'affiliates',
 'hocus',
 'highlights',
 'vaults',
 'boyishness',
 'instructors',
 'nationals',
 'decimals',
 'terms',
 'specialists',
 'educators',
 'oranges',
 'blockades',
 'includes',
 'alienates',
 'provers',
 'furrows',
 'quarters',
 'drafters',
 'increments',
 'meats',
 'settlements',
 'brutes',
 'damsels',
 'congregates',
 'wades',
 'breakwaters',
 'screams',
 'packs',
 'europeans',
 'attorneys',
 'voicers',
 'hitchhikes',
 'sicknesses',
 'crews',
 'interpolations',
 'stubbornness',
 'sprinters',
 'armpits',
 'permissions',
 'mosses',
 'fragrances',
 'sentiments',
 'fighters',
 'aeolus',
 'offsets',
 'rights',
 'correlations',
 'islets',
 'suiters',
 'majorities',
 'propositions',
 'bans',
 'pliers',
 'hazes',
 'orbiters',
 'keeps',
 'busts',
 'subsets',
 'slops',
 'gleans',
 'bailiffs',
 'depositions',
 'cherubs',
 'digitalis',
 'contemporaneous',
 'bunnies',
 'bunkmates',
 'gradations',
 'fibrosities',
 'attractions',
 'illnesses',
 'airers',
 'gleanings',
 'barbados',
 'jaws',
 'sleepless',
 'brothels',
 'indoors',
 'procurements',
 'relatives',
 'topics',
 'organs',
 'bedspreads',
 'approximations',
 'contents',
 'brambles',
 'multiples',
 'mates',
 'bimonthlies',
 'nonlinearities',
 'trainees',
 'toughness',
 'hendricks',
 'osseous',
 'progresses',
 'guarantees',
 'thieves',
 'orders',
 'monasteries',
 'hails',
 'repeaters',
 'ares',
 'copes',
 'finds',
 'baptizes',
 'censors',
 'exaggerations',
 'underwriters',
 'genuineness',
 'gelatinous',
 'races',
 'noses',
 'confederations',
 'wits',
 'botches',
 'permits',
 'cassius',
 'balks',
 'ideals',
 'appearers',
 'granaries',
 'inhabits',
 'jeres',
 'cries',
 'spacious',
 'cargoes',
 'pappas',
 'perpetrations',
 'mercenaries',
 'variables',
 'acceptances',
 'rockers',
 'edges',
 'sips',
 'foreheads',
 'predictions',
 'visas',
 'contretemps',
 'displays',
 'silences',
 'endlessness',
 'expertness',
 'smells',
 'erectors',
 'elections',
 'buffoons',
 'gangs',
 'bovines',
 'borderings',
 'jerks',
 'trumps',
 'requisitions',
 'ships',
 'ignominious',
 'maidens',
 'ostriches',
 'pruners',
 'abscess',
 'promotes',
 'dismiss',
 'targets',
 'waives',
 'sorters',
 'shouters',
 'formalizes',
 'interrupts',
 'fuses',
 'beginners',
 'facts',
 'babies',
 'ephemeris',
 'regions',
 'confirmations',
 'northwards',
 'excretions',
 'conveniences',
 'tabulations',
 'blips',
 'giggles',
 'reckons',
 'bakes',
 'enrages',
 'contesters',
 'nests',
 'synthesizes',
 'ethics',
 'embarrasses',
 'caucasus',
 'shatters',
 'scatters',
 'habitations',
 'buyers',
 'earmarkings',
 'alkaloids',
 'haplessness',
 'indirects',
 'sonorous',
 'truthfulness',
 'endangers',
 'recesses',
 'mayors',
 'buffetings',
 'boxcars',
 'empires',
 'schizomycetes',
 'advantages',
 'healthiness',
 'sprints',
 'launders',
 'omissions',
 'schemes',
 'marquess',
 'districts',
 'adaptations',
 'hobbyists',
 'sates',
 'jealousies',
 'truncates',
 'resents',
 'depresses',
 'multiprocessors',
 'intercepts',
 'gustavus',
 'antares',
 'assails',
 'quavers',
 'darlings',
 'sympathies',
 'homomorphisms',
 'prisons',
 'indefiniteness',
 'harpers',
 'uprisings',
 'pyrolysis',
 'cowboys',
 'spareness',
 'heels',
 'adopts',
 'parsers',
 'refutes',
 'suppresses',
 'gambles',
 'natures',
 'pares',
 'consciousness',
 'perkins',
 'articles',
 'allocates',
 'flashes',
 'scorings',
 'trickiness',
 'multiplexes',
 'contractors',
 'eccentrics',
 'aquarius',
 'earthquakes',
 'flavorings',
 'tablets',
 'bartenders',
 'circumlocutions',
 'healers',
 'driers',
 'accelerates',
 'marcus',
 'absoluteness',
 'contradictions',
 'contrives',
 'mumbles',
 'sprinkles',
 'contiguous',
 'scoops',
 'processors',
 'procrastinates',
 'confrontations',
 'parades',
 'foes',
 'validates',
 'obscurities',
 'debates',
 'hierarchies',
 'ascends',
 'ties',
 'strings',
 'reunions',
 'shillings',
 'aristocrats',
 'animates',
 'saturates',
 'softness',
 'reparations',
 'leviticus',
 'dims',
 'buffs',
 'enormous',
 'retentions',
 'auspicious',
 'awfulness',
 'blinds',
 'jets',
 'confounds',
 'affiliations',
 'loftiness',
 'fathers',
 'fictions',
 'psychologists',
 'mets',
 'oaths',
 'influences',
 'confesses',
 'allis',
 'places',
 'delusions',
 'tears',
 'comfortabilities',
 'perpetuates',
 'rusts',
 'ascensions',
 'picturesqueness',
 'facets',
 'subscriptions',
 'gayness',
 'hiss',
 'hams',
 'experiments',
 'perils',
 'oscillators',
 'contemplates',
 'gems',
 'chewers',
 'housewares',
 'iciness',
 'pods',
 'equations',
 'stencils',
 'righteousness',
 'managements',
 'camels',
 'caliphs',
 'concentrators',
 'buzzards',
 'coins',
 'migrates',
 'mindfulness',
 'campaigners',
 'laborers',
 'amusers',
 'stipends',
 'battalions',
 'dangles',
 'conspicuous',
 'headquarters',
 'findings',
 'permeates',
 'wills',
 'sizes',
 'receivers',
 'defends',
 'invades',
 'tightenings',
 'goats',
 'volunteers',
 'kilogauss',
 'backyards',
 'stearns',
 'occurs',
 'contemporariness',
 'hands',
 'shores',
 'individuals',
 'refreshments',
 'housewives',
 'improvements',
 'lips',
 'gases',
 'sensitiveness',
 'copiousness',
 'coupons',
 'cultures',
 'ogress',
 'generosities',
 'reprograms',
 'rebates',
 'expanses',
 'augustus',
 'parsings',
 'fierceness',
 'gallus',
 'catalogues',
 'coats',
 'sweetness',
 'pets',
 'camps',
 'zoos',
 'qualifies',
 'anesthetizes',
 'rugs',
 'supposes',
 'disables',
 'intellects',
 'posers',
 'realities',
 'broods',
 'thanks',
 'simplifies',
 'bunches',
 'correctness',
 'footprints',
 'billiards',
 'routings',
 'ermines',
 'relies',
 'guises',
 'prettiness',
 'intruders',
 'coefficients',
 'combings',
 'flinches',
 'cycles',
 'disgraces',
 'jauntiness',
 'chroniclers',
 'expenditures',
 'salters',
 'bituminous',
 'woos',
 'monograms',
 'tilts',
 'slanders',
 'discards',
 'gratuities',
 'suppleness',
 'confronts',
 'voids',
 'audacious',
 'courthouses',
 'canners',
 'appliers',
 'fasts',
 'extracts',
 'talkers',
 'bogus',
 'friendless',
 'arcades',
 'instants',
 'mantis',
 'effectiveness',
 'addis',
 'dollars',
 'naughtiness',
 'skulls',
 'sneaks',
 'matchings',
 'argus',
 'agonies',
 'imperialists',
 'vicious',
 'legislators',
 'kicks',
 'indebtedness',
 'obviates',
 'servants',
 'hermits',
 'underlines',
 'loquacious',
 'blindness',
 'flocks',
 'courtyards',
 'amends',
 'prows',
 'reconstructs',
 'counts',
 'glens',
 'connotes',
 'babbles',
 'postscripts',
 'tablespoons',
 'urges',
 'aerials',
 'consults',
 'booths',
 'switchings',
 'acclimates',
 'deemphasizes',
 'protrudes',
 'falters',
 'fewness',
 'paychecks',
 'lissajous',
 'dazzles',
 'takes',
 'sacks',
 'relocations',
 'sciences',
 'scribners',
 'cottages',
 'fatalities',
 'destinations',
 'dwarves',
 'branches',
 'ministries',
 'revenues',
 'rivets',
 'tends',
 'accreditations',
 'rosebuds',
 'nuts',
 'exposers',
 'alveolus',
 'interests',
 'coverings',
 'imaginings',
 'fedders',
 'actions',
 'friendliness',
 'depots',
 'precariousness',
 'pompous',
 'legalizes',
 'microscopes',
 'shortens',
 'themselves',
 'tanks',
 'lecturers',
 'brutalizes',
 'nonetheless',
 'significants',
 'electricalness',
 'trackers',
 'rascals',
 'animators',
 'appertains',
 'callus',
 'hepatitis',
 'sawmills',
 'larks',
 'pathogenesis',
 'communicates',
 'cartilaginous',
 'nicholas',
 'troubleshoots',
 'relationships',
 'combines',
 'feels',
 'weeds',
 'ulcers',
 'atlantis',
 'interdependencies',
 'exceptions',
 'incubates',
 'breathers',
 'hovers',
 'curries',
 'pyramids',
 'incubators',
 'courtiers',
 'liquifiers',
 'sobers',
 'boatyards',
 'successions',
 'lionesses',
 'repositions',
 'various',
 'sameness',
 'notorious',
 'sours',
 'distinctions',
 'clays',
 'punts',
 'agreeableness',
 'crumbles',
 'perspectives',
 'draughts',
 'consequents',
 'spellers',
 'drowns',
 'bikes']
debug = True
names = ['ponies',
 'rainbows',
 'unicorns',
 'rabbits',
 'piglets',
 'cubs',
 'hamsters',
 'lambs']
MAXWORDINDEX = len(words) - 1
MINVARS = 2
MAXVARS = 3
MINVARVAL = 0
MAXVARVAL = MAXWORDINDEX
MINVERSES = 3
MAXVERSES = 5
MAXLEVELS = 2
DATAPATH = './'
rules = {'c': '',
 'n': '',
 'm': 'with',
 'a': 'and'}
terminals = ('n', 'c')
operators = ('m', 'a')
relations = {'g': 'are sweeter than',
 's': 'are cuddlier than',
 'e': 'are shiny as'}
openpar = ('my',
 'your',
 'their',
 'our')
closepar = (':', ',', ';')


def parser(s):
    elems = s.split(' ')
    expr = []
    new_elems = []

    try:
        elems.remove('are')
        elems.remove('than')
        elems.remove('as')
    except ValueError:
        pass

    for i in range(0,len(elems)): #recupera punteggiatura
        punt = []
        while(any([char in elems[i] for char in closepar]) and len(elems[i])!=1):
            last = elems[i][-1]
            punt.append(last)
            elems[i] = elems[i][:-1]
        
        punt = list(reversed(punt))
        new_elems.append(elems[i])
        for p in punt:
            new_elems.append(p)

    for elem in new_elems:
        if elem in openpar:
            expr.append('(')
        elif elem in closepar:
            expr.append(')')
        elif elem in words:
            expr.append(words.index(elem))
        elif elem in names:
            expr.append(elem)
        elif elem == 'with':
            expr.append('-')
        elif elem == 'and':
            expr.append('+')
        elif elem == 'sweeter':
            expr.append('>')
        elif elem == 'cuddlier':
            expr.append('<')
        elif elem == 'shiny':
            expr.append('=')

    s_expr = ''
    for c in expr:
        s_expr += str(c)

    return parse_to_tree(['('] + expr + [')'])


def split_high_level(expr):
    operators = ['>', '<', '=', '-', '+']

    expr = expr[1:-1]

    level = 0
    left = []
    i = 0
    elem = expr[i]
    while elem not in operators or level != 0:
        if elem == '(':
            level += 1
        elif elem == ')':
            level -= 1
        left.append(elem)
        i += 1
        elem = expr[i]

    if elem == '>':
        op = 'g'
    elif elem == '<':
        op = 's'
    elif elem == '=':
        op = 'e'
    elif elem == '-':
        op = 'm'
    elif elem == '+':
        op = 'a'

    right = []
    for x in expr[i+1:]:
        right.append(x)

    return left, op, right


def parse_to_tree(expr):
    result = dict()
    if len(expr) > 1:
        left, op, right = split_high_level(expr)
        result['t'] = op
        result['o1'] = parse_to_tree(left)
        result['o2'] = parse_to_tree(right)
    elif expr[0] in names:
        result['t'] = 'n'
        result['v'] = expr[0]
    else:
        result['t'] = 'c'
        result['v'] = expr[0]
    return result


def evaluate(e, vals):
    if e['t'] == 'c':
        return e['v']
    if e['t'] == 'n':
        return vals[e['v']]
    if e['t'] in ('m', 'a'):
        v1 = evaluate(e['o1'], vals)
        v2 = evaluate(e['o2'], vals)
        if e['t'] == 'm':
            return v1 - v2
        if e['t'] == 'a':
            return v1 + v2
    else:
        print 'I am terribly sorry, but I see zero teddy bears riding shiny ponies!'


def validate(expressions, vals):
    for e in expressions:
        v1 = evaluate(e['o1'], vals) % MAXVARVAL
        v2 = evaluate(e['o2'], vals) % MAXVARVAL
        if e['t'] == 'e':
            if v1 != v2:
                return False
        elif e['t'] == 'g':
            if v1 <= v2:
                return False
        elif e['t'] == 's':
            if v1 >= v2:
                return False
        else:
            print 'Oh my! I never thing anything like this before! Something is horribly wrong!'
            return False

    return True


def iCTFpwner(ip_address, port, flag_id):

    #filename = '12345'
    filename = 'pp_' + flag_id

    #conn = process(['python', 'ponypoem.py'])
    conn = remote(ip_address, port)

    conn.recvuntil('hear a poem?')
    conn.sendline('y')

    conn.recvuntil('pony poems?')
    conn.sendline('n')

    conn.recvuntil('ultrasweet poem?')
    my_title = ''.join(random.choice(string.ascii_lowercase) for _ in range(20))
    conn.sendline(my_title)

    conn.recvuntil('kingdoms?')
    conn.sendline(''.join(random.choice(string.ascii_lowercase) for _ in range(20)))

    conn.recvuntil('inspiration...')
    conn.sendline(''.join(random.choice(string.ascii_lowercase) for _ in range(20)))

    conn.recvuntil('Characters:')
    characters = conn.recvuntil('\n').strip().split(',')
    print characters

    if characters == ['hamsters', 'unicorns', 'rainbows']:
        ## validate con seed = 0
        # hamsters unicorns rainbows
        # rigors bijections goats
        conn.recvuntil('Tell me the word')
        conn.sendline('rigors')
        
        conn.recvuntil('Tell me the word')
        conn.sendline('bijections')
        
        conn.recvuntil('Tell me the word')
        conn.sendline('goats')

    else:
        # seed random

        verses = []
        conn.recvuntil('\n')
        line = conn.recvuntil('\n').strip()
        while line:
            verses.append(line)
            line = conn.recvuntil('\n').strip()

        expressions = []
        for v in verses:
            expressions.append(parser(v))


        vals = {}
        for char in characters:
            vals[char] = random.randint(1, 1000)
        print validate(expressions, vals)

        if len(characters) == 3:
            # try again for 2 magic words
            return iCTFpwner(ip_address, port, flag_id)

        else:
            for x in itertools.product(range(1000), range(1000)):
                vals[characters[0]] = x[0]
                vals[characters[1]] = x[1]
                if validate(expressions, vals):
                    print vals
                    break
            else:
                print 'no'

        conn.recvuntil('Tell me the word')
        conn.sendline(words[vals[characters[0]]])

        conn.recvuntil('Tell me the word')
        conn.sendline(words[vals[characters[1]]])


    conn.recvuntil('your password?')
    conn.sendline('y')

    conn.recvuntil('my friend?')
    conn.sendline('a'*1000 + filename)

    # parse dopo magic words... 
    # fino a You can come
    conn.recvuntil('magic words...\n')
    cyphertext = conn.recvuntil('\n').strip()

    conn.close()

    # salva in un file
    # decrypt(file, 'hamstersunicornsrainbows' + 'a' *1000 + flag_id)
    f1 = open('file1', 'w')
    f1.write(cyphertext)
    f1.close()
    cypher2 = crypto.decrypt('file1', filename)

    # salva in un file
    # decrypt(file, 'a'*10)
    f2 = open('file2', 'w')
    f2.write(cypher2)
    f2.close()
    plaintext = crypto.decrypt('file2', 'a'*10)

    flag = re.search(r'FLG.{13}', plaintext).group(0)
    print flag
    return flag
