main.py 10.9 KB
Newer Older
putro's avatar
putro committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env python

import os
import sys
import checks
from config import config, nyms, nymList, printNymList, configSection, writeConfig
import traceback
import re
from stats import parse_stats, stats_m, uptime_sort_m, format_stats
from utils import pressKey, validateChoice, chooseList, askPassphrase, askSomething, askYesNo
from utils import chooseSubjType, selectServer, getDomain, validateEmail, isGpg
import gpgfuncts
import easygui as eg
import string
import subprocess




class bcolors:
    """
    Define colors for outputs
    """
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):

        self.GREEN = ''
        self.YELLOW = ''
        self.RED = ''
        self.ENDC = ''


def menu():
    """ Print menu and wait for user choice """
    os.system(['clear', 'cls'][os.name == 'nt'])
    print bcolors.GREEN + "----- NYM HELPER -----" + bcolors.ENDC
    if anym is False:
        print bcolors.RED + "active nym: NONE"
    else:
        print bcolors.GREEN + "active nym: %s " % anym.name
    if re.match("OK", config['last_message']):
        print bcolors.YELLOW + "\ndebug: %s\n" % config['last_message'] + bcolors.ENDC
    else:
        print bcolors.RED + "\ndebug: %s\n" % config['last_message'] + bcolors.ENDC
    #present menu and get selection
    selection = raw_input("Enter\n\
    1 to choose/select active nym\n\
    2 to write a message (as active nym)\n\
    3 to send the message created via local mixmaster\n\
    4 to download fresh remailer stats and keys\n\
    5 to choose remailers chain\n\
    6 to create or update a nym\n\
    8 to create a new secret key\n\
    9 to delete a secret key\n\
    10 to send msg via smtp (NOT ANONYMOUS)\n\
    q to quit\n\n\n")

    #perform actions based on selection above
    if selection == "1":
        askNym()
        menu()
    elif selection == "2":
        writeMessage()
        menu()
    elif selection == "3":
        sendMixMsg()
        menu()
    elif selection == "4":
        download(options.stats_rlist)
        download(options.stats_mlist)
        download(options.keys_file, pgp=True)
        menu()
    elif selection == "5":
        sendMixMsg(dest="drugo@autistici.org", msg="test")
        menu()
    elif selection == "6":
        createNym()
        menu()
    elif selection == "7":
        modifyConfig()
        menu()
    elif selection == "8":
        print "\nsecret keys in your keyring:"
        gpgfuncts.listSecKeys()
        print "\n"
        gpgfuncts.createKey()
        print "key generated, secret keys in your keyring: "
        gpgfuncts.listSecKeys()
        pressKey()
        menu()
    elif selection == "9":
        sk = gpgfuncts.defineSecKey()
        fp = sk["fingerprint"]
        deleteKey(fp)
        msg = "key of %s deleted" % sk["uids"][1]
        config['last_message'] = msg
        menu()
    elif selection == "10":
        sendMsg()
        menu()
    elif selection == "q":
        #f = open(options.message_out, "w")
        # shred messages_out ??
        sys.exit("bye bye")
    else:
        print "wrong selection"
        pressKey()
        menu()

def askNym():
    """ set active nym """
    nymlist = nymList(nyms)
    setActiveNym(chooseList(nymlist))
    return


def createNym():
    name = askSomething('Enter the name of the nym (without domain): ')
    server = selectServer(config)
    email = name + "@" + server

    if not gpgfuncts.selectKey(email):
        print "no key availabke, creating a new one for %s" % email
        gpgfuncts.createKey(email, name)

    subj_type = chooseSubjType(config)
    subject = askSomething('Enter the subject you want to use with this nym: ')

    configSection(email, subject, subj_type)
    writeConfig()
    setActiveNym(email)

    msg = prepareSetupMsg(gpgfuncts.selectSecKey(email), subj_type, subject)
    dest = "config@" + server
    emsg = signCryptMsg(msg, dest, sign=False)
    if not emsg:
        config['last_message'] = "Something went wrong"
        menu()
    sendMixMsg(dest, emsg)
    #return




def prepareSetupMsg(keyid, subj_type, subject):
    key = gpgfuncts.exportPubKey(keyid)
    msg = "%s = %s\n\n" % (subj_type, subject) + key
    return msg


def signCryptMsg(msg, dest, sign):
    msg = gpgfuncts.encrypt(msg, dest, sign=sign)
    return msg


def setActiveNym(nym):
    global anym
    anym = config['nym'][nym]
    anym.domain = getDomain(anym.name)
    anym.fp = gpgfuncts.selectSecKey(anym.name)


class MixError(Exception):
    pass


def sendMixMsg(dest, msg, subj="subject", test=False):
    """ send msg through a local mixmaster client """
    args = [config['options']['mixmaster'], '--mail', '--to=' + dest, '--subject=' + subj, '--copies=1']
    print "\nChoose remailer chain used to send the message to %s\n" % dest
    chooseChain()
    args.append('--chain=' + ','.join(config['remailer_chain']))

    try:
        mix = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = mix.communicate(msg)
        if err.find('Error') >= 0:
            raise MixError('Mixmaster process returned the following error: ' + str(err) + '. Sending failed.')
        config['last_message'] = "OK, succesfully sent email"
    except OSError:    # usally means that mixmaster could not be executed
        raise MixError('Could not find mixmaster binary.')



def writeMessage():
    """
    Create a message to be sent from nym
    The message has to be sent through a remailer chain
    to send@nym-server-address
    """
    if anym.fp is False:
        config['last_message'] = "ERROR - select your nym, actual selection HAS NOT a secret key"
        menu()
    subject = raw_input("Insert message subject: ")

    recipient = raw_input("Insert recipient email address or newsgroup name: ")

    text = eg.textbox(msg='Write your message....', title='Input Box', text='', codebox=0)
    text = filter(lambda x: x in string.printable, text)

    if isGpg(text):
        print "message already encrypted"
        pressKey()
    elif gpgfuncts.encrypt("test", recipient, test=True).status == "encryption ok":
        # barbatrucco veramente infimo per risolvere il problema per cui
        # la prima riga del messaggio viene scartata
        text = "Message:\n" + text
        text = gpgfuncts.encrypt(text, recipient)
        print "message has been encrypted with %s public key" % recipient
        pressKey()
    else:
        print "msg has not been encrypted, public key for %s not found" % recipient
        pressKey()

    msg = "From: %s\n" % anym.name
    if validateEmail(recipient):
        msg = msg + "To: %s\n" % recipient
    else:
        msg = msg + "To: %s\n" % options['mail-to-news']
        msg = msg + "Newsgroups: %s\n" % recipient
    msg = msg + "Subject: %s\n\n" % subject

    if not anym['passphrase']:
        pwd = askPassphrase()
    else:
        pwd = anym['passphrase']

    msg = msg + text
    dest = 'send@' + anym.domain

    emsg = gpgfuncts.stripVersion(str(gpgfuncts.encrypt(msg, dest,
                            sign=anym.fp,
                            passphrase=pwd)))

    sendMixMsg(dest, emsg)


def modifyConfig():
    pass



checks.InitialCheck()

if checks.OptionsCheck(config) == True:
    config['last_message'] = "OK, initial check passed"

if not nyms.sections:
    print "No nyms configured, going to create it..."
    createNym()
else:
    setActiveNym(nyms.sections[0])


def chooseChain():
    """ Print remailer list and prompt for chain choice """
    for remailer in uptime_sort_m():
        print format_stats(remailer)
    chain = raw_input('Choose remailer to be chained (by num), separated by commas, or write "r" for a random chain (3 remailers): ')
    if chain == "r":
        #chooseRandomChain()
        config['remailer_chain'] = ['*','*','*']
    else:
        validateChain(chain)


#def chooseRandomChain():
#    """ Choose a 3 random remailer chain """
#    import random
#    remailers = uptime_sort_m()
#    remailers[:] = [r for r in remailers if stats_m[r].uptime > float(config['stats']['remailer_min_uptime'])]
#    n = len(remailers)
#
#    r1 = str(random.randrange(1, n + 1))
#    r2 = str(random.randrange(1, n + 1))
#    while r2 == r1:
#        r2 = str(random.randrange(1, n + 1))
#    r3 = str(random.randrange(1, n + 1))
#    while r3 == r2:
#        r3 = str(random.randrange(1, n + 1))
#    while True:
#        if checkMiddle(remailers[int(r3) - 1]):
#            r3 = str(random.randrange(1, n + 1))
#        else:
#            break
#    chain = r1 + "," + r2 + "," + r3
#    validateChain(chain, random=True)


def validateChain(chain):
    """
    Validate remailer chain, check the availability of public key of remailers
    and that last remailer of chain is not middleman
    """
    remailer_chain = []
    comma = re.compile(',')

    if len(chain.split(',')) > 1:
        if not comma.search(chain):
            print bcolors.RED + "ERROR - remailer chain selections have to be separated by commas" + bcolors.ENDC
            pressKey()
            return
    a = chain.split(',')
    for n in a:
        if not n.isdigit():
            print bcolors.RED + "ERROR - remailer chain selection cannot contains non-numeric chars" + bcolors.ENDC
            return
        n = int(n)
        n -= 1
        remailer_chain.append(uptime_sort_m()[n])

    # check if last remailer is middleman
    if checkMiddle(remailer_chain[len(remailer_chain)-1]):
        print bcolors.RED + "ERROR - remailer %s is middleman, it cannot be last remailer in chain" % remailer_chain[len(remailer_chain)-1] + bcolors.ENDC
        pressKey()
        chooseChain()
    if checkBrokenChains(remailer_chain):
        print bcolors.RED + "ERROR - broken chain selected, check the breaks in stats last column" + bcolors.ENDC
        pressKey()
        chooseChain()

    config['last_message'] = "OK, remailer chain choosed: %s" % remailer_chain
    config['remailer_chain'] = remailer_chain


def checkMiddle(remailer):
    """ check if a remailer is middleman """
    if stats_m[remailer].middleman:
        return True
    else:
        return False

def checkBrokenChains(remailer_chain):
    """ check for broken remailer chains """
    for i in range(0,len(remailer_chain)-1):
        cur = remailer_chain[i]
        next = remailer_chain[i+1]
        if next in stats_m[cur].broken:
            return True
        else:
            return False

try:
    if checks.opts.nym:
        writeSendMessage()
    else:
        parse_stats()
        #for remailer in uptime_sort_m():
        #    print format_stats(remailer)
        #for property, value in vars(stats_m['austria']).iteritems():
        #    print property, ": ", value
        #pressKey()
        menu()


except KeyboardInterrupt:
    print "program terminated"
except SystemExit:
    print "program terminated, bye"
except:
    print bcolors.RED + "\nAn unhandled exception occured, here's the traceback!\n" + bcolors.ENDC
    traceback.print_exc()
    print bcolors.RED + "\nReport this to putro@autistici.org" + bcolors.ENDC
    sys.exit()