Ejemplo n.º 1
0
def test_mail(mails, bilateral):
    import email.mime.text
    from kryptomime import create_mail, protect_mail
    from kryptomime.pgp import find_gnupg_key
    server, imapsend, imaprecv = mails
    id1, id2 = bilateral['id1'], bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'], sender)
    key2 = find_gnupg_key(bilateral['gpg2'], receiver)
    assert not len(imapsend) and not len(imaprecv)
    attachment = email.mime.text.MIMEText('some\nattachment')
    msg = create_mail(sender,
                      receiver,
                      'subject',
                      'body\nmessage',
                      attach=[attachment])
    #msg = protect_mail(msg,linesep='\r\n')

    enc, _ = id1.encrypt(msg, sign=True, inline=False)
    assert enc and id2.analyze(enc) == (True, None)
    assert server.send(enc)
    assert not len(imapsend) and len(imaprecv) == 1
    for mail, flags in imaprecv:
        mail, verified, result = id2.decrypt(mail)
        assert mail and verified and result
        assert result['encrypted'] and result['signed'] and result[
            'fingerprints'] == [key1]
        compare_mail(msg, mail)
    assert not len(imapsend) and not len(imaprecv)

    msg = create_mail(receiver,
                      sender,
                      'subject',
                      'body\nmessage',
                      attach=[attachment])
    msg = protect_mail(msg, linesep='\r\n')
    sgn, _ = id2.sign(msg, inline=True, verify=True)
    assert sgn and id1.analyze(sgn) == (False, True)

    dec, verified, result = id1.decrypt(sgn, strict=True)
    assert dec and verified and result
    assert not result['encrypted'] and result['signed'] and result[
        'fingerprints'] == [key2]
    compare_mail(msg, dec)

    assert server.send(sgn)
    assert len(imapsend) == 1 and not len(imaprecv)

    for mail, flags in imapsend:
        mail = protect_mail(mail, linesep='\r\n')
        dec, verified, result = id1.decrypt(mail, strict=True)
        assert dec and verified and result
        assert not result['encrypted'] and result['signed'] and result[
            'fingerprints'] == [key2]
        compare_mail(msg, dec)
    assert not len(imapsend) and not len(imaprecv)
Ejemplo n.º 2
0
def keys(request):
    import os, gnupg, logging
    from kryptomime.pgp import GPGMIME, find_gnupg_key
    from ekklesia.data import tmpfname
    #generate = verbose = False
    generate = request.config.getoption('generate',False)
    verbose = request.config.getoption('gpglog',False)
    if verbose: gnupg._logger.create_logger(10)
    else:
        log = logging.getLogger('gnupg')
        log.setLevel(logging.CRITICAL)
    if generate: # pragma: no cover
        keyrings = [tmpfname() for i in range(3)]
        secrings = [tmpfname() for i in range(3)]
    else:
        home = os.path.dirname(os.path.abspath(__file__))
        keyrings = [os.path.join(home,'keyring%i.gpg'%i) for i in range(3)]
        secrings = [os.path.join(home,'secring%i.gpg'%i) for i in range(3)]
        pubring = os.path.join(home,'pubring.gpg')
    keygen = generate
    if not keygen:
        for fname in keyrings+secrings:
            if os.path.exists(fname): continue
            keygen = True
            break
    if keygen: # pragma: no cover
        for fname in keyrings+secrings:
            if os.path.exists(fname): os.unlink(fname)
    gpg1 = gnupg.GPG(keyring=keyrings[0],secring=secrings[0],verbose=verbose)
    gpg2 = gnupg.GPG(keyring=keyrings[1],secring=secrings[1],verbose=verbose)
    gpg3 = gnupg.GPG(keyring=keyrings[2],secring=secrings[2],verbose=verbose)
    if keygen: # pragma: no cover
        key1 = gpg1.gen_key(gpg1.gen_key_input(name_email=sender,key_length=1024,
            passphrase=passphrase,expire_date='2030-01-01')).fingerprint
        key2 = gpg2.gen_key(gpg2.gen_key_input(name_email=receiver,key_length=1024,
            expire_date='2030-01-01')).fingerprint
        key3 = gpg3.gen_key(gpg3.gen_key_input(name_email=third,key_length=1024,
            expire_date='2030-01-01')).fingerprint
    else:
        key1 = find_gnupg_key(gpg1,sender)
        key2 = find_gnupg_key(gpg2,receiver)
        key3 = find_gnupg_key(gpg3,third)
    pubkey1= gpg1.export_keys(key1)
    pubkey2= gpg2.export_keys(key2)
    pubkey3= gpg3.export_keys(key3)
    if not generate and not os.path.exists(pubring): # pragma: no cover
        gpg = gnupg.GPG(keyring=pubring,verbose=verbose)
        gpg.import_keys(pubkey1)
        gpg.import_keys(pubkey2)
        gpg.import_keys(pubkey2)
    def fin():
        for tmp in keyrings+secrings: os.unlink(tmp)
    if generate: request.addfinalizer(fin)
    return {'gpg1':gpg1, 'gpg2':gpg2, 'gpg3':gpg3, 'pubkey1':pubkey1, 'pubkey2':pubkey2, 'pubkey3':pubkey3, 'secrings':secrings, 'fingerprints':[key1,key2,key3]}
Ejemplo n.º 3
0
def keys(request):
    import os
    generate = request.config.getoption('generate')
    verbose = request.config.getoption('gpglog')
    if verbose: gnupg._logger.create_logger(10)
    keyrings = [tmpfname() for i in range(2)]
    secrings = [tmpfname() for i in range(2)]
    home = os.path.dirname(os.path.abspath(__file__))
    fpubkey = [os.path.join(home,'pubkey%i.asc'%(i+1)) for i in range(2)]
    fseckey = [os.path.join(home,'seckey%i.asc'%(i+1)) for i in range(2)]
    keygen = generate
    if not keygen:
        for fname in fpubkey+fseckey:
            if os.path.exists(fname): continue
            keygen = True
            break
    if keygen:
        for fname in fpubkey+fseckey:
            if os.path.exists(fname): os.unlink(fname)
    gpg1 = gnupg.GPG(keyring=keyrings[0],secring=secrings[0],verbose=verbose,use_agent=False)
    gpg2 = gnupg.GPG(keyring=keyrings[1],secring=secrings[1],verbose=verbose,use_agent=False)
    if keygen:
        print ('generating keys')
        key1 = gpg1.gen_key(gpg1.gen_key_input(name_email=sender,key_length=1024,
            passphrase=passphrase,expire_date='0'))
        key2 = gpg2.gen_key(gpg2.gen_key_input(name_email=receiver,key_length=1024,
            expire_date='0'))
        assert key1 and key2
        key1, key2 = key1.fingerprint, key2.fingerprint
        pubkey1= gpg1.export_keys(key1)
        pubkey2= gpg2.export_keys(key2)
        open(fpubkey[0],'wt').write(pubkey1)
        open(fpubkey[1],'wt').write(pubkey2)
        seckey1= gpg1.export_keys(key1,secret=True)
        seckey2= gpg2.export_keys(key2,secret=True)
        open(fseckey[0],'wt').write(seckey1)
        open(fseckey[1],'wt').write(seckey2)
    else:
        pubkey1 = open(fpubkey[0],'rt').read()
        pubkey2 = open(fpubkey[1],'rt').read()
        gpg1.import_keys(pubkey1)
        gpg2.import_keys(pubkey2)
        seckey1 = open(fseckey[0],'rt').read()
        seckey2 = open(fseckey[1],'rt').read()
        gpg1.import_keys(seckey1)
        gpg2.import_keys(seckey2)
        key1 = find_gnupg_key(gpg1,sender)
        key2 = find_gnupg_key(gpg2,receiver)
        assert key1 and key2
    def fin():
        for tmp in keyrings+secrings: os.unlink(tmp)
    if generate: request.addfinalizer(fin)
    return {'gpg1':gpg1, 'gpg2':gpg2, 'pubkey1':pubkey1, 'pubkey2':pubkey2, 'secrings':secrings}
Ejemplo n.º 4
0
def test_send(request, empty_db, havesmtp, bilateral):
    "unsent/retry -> sent/failed"
    from ekklesia.mail import VirtualMailServer
    from kryptomime.pgp import find_gnupg_key
    import tempfile, shutil
    db = empty_db
    db.gpg = bilateral['id1']
    id2 = bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'], sender)
    input = remove_email(inv_pre) if db.member_class else inv_pre
    db.import_invitations(input, allfields=True, format='json')

    tmpdir = tempfile.mkdtemp()
    server = VirtualMailServer(tmpdir)

    def fin():
        server.finish()
        shutil.rmtree(tmpdir, ignore_errors=True)

    request.addfinalizer(fin)
    accounts = {}
    if havesmtp:
        for i in range(1, 12):
            accounts['uid%02i' % i] = server.add_account("inv%i@localhost" % i,
                                                         keep=False)
    db.send_invitations(debug_smtp=server)
    changed = ['uid04', 'uid05', 'uid07', 'uid08']
    post = {}
    db.export_invitations(post, allfields=True, format='json')
    field_uuid = post['fields'].index('uuid')
    field_sent = post['fields'].index('sent')
    ofield_sent = input['fields'].index('sent')
    field_lchange = post['fields'].index('lastchange')
    field_senttime = post['fields'].index('senttime')
    for i, inv in enumerate(post['data']):
        orig = input['data'][i]
        mod = list(orig)
        assert inv[field_lchange]
        inv[field_lchange] = None  # delete lastchange
        assert inv[field_sent] == 'unsent' or inv[field_senttime]
        if inv[field_sent] != 'unsent':
            inv[field_senttime] = None if mod[
                ofield_sent] == 'unsent' else some_time
        if not inv[field_uuid] in changed:
            assert inv == orig, "unexpected change"
            continue
        mod[ofield_sent] = 'sent' if havesmtp else 'failed'
        assert inv == mod, "invalid change"
        if not havesmtp: continue
        imap = accounts[inv[field_uuid]]
        assert len(imap) == 1
        for mail, flags in imap:
            mail, verified, result = id2.decrypt(mail, strict=False)
            assert mail and result
            assert not result['encrypted'] and result['signed'] and result[
                'fingerprints'] == [key1]
Ejemplo n.º 5
0
def test_send(request, empty_db, havesmtp, bilateral):
    "unsent/retry -> sent/failed"
    from ekklesia.mail import VirtualMailServer
    from kryptomime.pgp import find_gnupg_key
    import tempfile, shutil
    db = empty_db
    db.gpg = bilateral['id1']
    id2 = bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'],sender)
    input = remove_email(inv_pre) if db.member_class else inv_pre
    db.import_invitations(input,allfields=True,format='json')

    tmpdir = tempfile.mkdtemp()
    server = VirtualMailServer(tmpdir)
    def fin():
        server.finish()
        shutil.rmtree(tmpdir,ignore_errors=True)
    request.addfinalizer(fin)
    accounts = {}
    if havesmtp:
        for i in range(1,12):
            accounts['uid%02i'%i] = server.add_account("inv%i@localhost" % i,keep=False)
    db.send_invitations(debug_smtp=server)
    changed = ['uid04','uid05','uid07','uid08']
    post = {}
    db.export_invitations(post,allfields=True,format='json')
    field_uuid = post['fields'].index('uuid')
    field_sent = post['fields'].index('sent')
    ofield_sent = input['fields'].index('sent')
    field_lchange = post['fields'].index('lastchange')
    field_senttime = post['fields'].index('senttime')
    for i,inv in enumerate(post['data']):
        orig = input['data'][i]
        mod = list(orig)
        assert inv[field_lchange]
        inv[field_lchange] = None # delete lastchange
        assert inv[field_sent] == 'unsent' or inv[field_senttime]
        if inv[field_sent] != 'unsent':
            inv[field_senttime] = None if mod[ofield_sent] == 'unsent' else some_time
        if not inv[field_uuid] in changed:
            assert inv == orig, "unexpected change"
            continue
        mod[ofield_sent] = 'sent' if havesmtp else 'failed'
        assert inv == mod, "invalid change"
        if not havesmtp: continue
        imap = accounts[inv[field_uuid]]
        assert len(imap)==1
        for mail, flags in imap:
            mail, verified, result = id2.decrypt(mail,strict=False)
            assert mail and result
            assert not result['encrypted'] and result['signed'] and result['fingerprints']==[key1]
Ejemplo n.º 6
0
def keys(request):
    import os
    generate = request.config.getoption('generate')
    verbose = request.config.getoption('gpglog')
    if verbose: gnupg._logger.create_logger(10)
    keyrings = [tmpfname() for i in range(2)]
    secrings = [tmpfname() for i in range(2)]
    home = os.path.dirname(os.path.abspath(__file__))
    fpubkey = [os.path.join(home, 'pubkey%i.asc' % (i + 1)) for i in range(2)]
    fseckey = [os.path.join(home, 'seckey%i.asc' % (i + 1)) for i in range(2)]
    keygen = generate
    if not keygen:
        for fname in fpubkey + fseckey:
            if os.path.exists(fname): continue
            keygen = True
            break
    if keygen:
        for fname in fpubkey + fseckey:
            if os.path.exists(fname): os.unlink(fname)
    gpg1 = gnupg.GPG(keyring=keyrings[0],
                     secring=secrings[0],
                     verbose=verbose,
                     use_agent=False)
    gpg2 = gnupg.GPG(keyring=keyrings[1],
                     secring=secrings[1],
                     verbose=verbose,
                     use_agent=False)
    if keygen:
        print('generating keys')
        key1 = gpg1.gen_key(
            gpg1.gen_key_input(name_email=sender,
                               key_length=1024,
                               passphrase=passphrase,
                               expire_date='0'))
        key2 = gpg2.gen_key(
            gpg2.gen_key_input(name_email=receiver,
                               key_length=1024,
                               expire_date='0'))
        assert key1 and key2
        key1, key2 = key1.fingerprint, key2.fingerprint
        pubkey1 = gpg1.export_keys(key1)
        pubkey2 = gpg2.export_keys(key2)
        open(fpubkey[0], 'wt').write(pubkey1)
        open(fpubkey[1], 'wt').write(pubkey2)
        seckey1 = gpg1.export_keys(key1, secret=True)
        seckey2 = gpg2.export_keys(key2, secret=True)
        open(fseckey[0], 'wt').write(seckey1)
        open(fseckey[1], 'wt').write(seckey2)
    else:
        pubkey1 = open(fpubkey[0], 'rt').read()
        pubkey2 = open(fpubkey[1], 'rt').read()
        gpg1.import_keys(pubkey1)
        gpg2.import_keys(pubkey2)
        seckey1 = open(fseckey[0], 'rt').read()
        seckey2 = open(fseckey[1], 'rt').read()
        gpg1.import_keys(seckey1)
        gpg2.import_keys(seckey2)
        key1 = find_gnupg_key(gpg1, sender)
        key2 = find_gnupg_key(gpg2, receiver)
        assert key1 and key2

    def fin():
        for tmp in keyrings + secrings:
            os.unlink(tmp)

    if generate: request.addfinalizer(fin)
    return {
        'gpg1': gpg1,
        'gpg2': gpg2,
        'pubkey1': pubkey1,
        'pubkey2': pubkey2,
        'secrings': secrings
    }
Ejemplo n.º 7
0
def test_registerkey(request,accounts,mails,bilateral,defect):
    from accounts.models import Account
    from idapi.models import Message, PublicKey
    from idapi.mails import gnupg_init, get_mails, send_mails, update_keyrings, process_register
    import email.mime.text
    from kryptomime import create_mail
    from kryptomime.pgp import find_gnupg_key
    import tempfile
    home = tempfile.mkdtemp()
    gpg = gnupg_init(home)
    update_keyrings(debug_gpg=gpg,debug_import=bilateral['gpg1'])

    user = accounts['member1']
    id1, id2 = bilateral['id1'], bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'],sender)
    key2 = find_gnupg_key(bilateral['gpg2'],receiver)
    server, imapsend, imaprecv = mails
    # id1=register, id2=member1

    if defect=='unknown':
        # unknown sender, should be rejected
        unknown = 'unknown@localhost'
        imapbad = server.add_account(unknown,keep=False)
        msg = create_mail(unknown,sender,'register','register')
    elif defect=='nokey':
        # known sender, but forget key/signing
        msg = create_mail(receiver,sender,'register','register')
    else:
        # known sender, return confirmation request
        attach = id2.pubkey_attachment(key2)
        msg = create_mail(receiver,sender,'register','register',attach=[attach])

    assert server.send(msg)
    assert len(imapsend)==1
    get_mails(joint=True,debug=server,debug_gpg=gpg,keep=False)
    process_register(debug_gpg=gpg)
    send_mails(joint=True,debug=server,debug_gpg=gpg)

    if defect=='unknown':
        assert len(imapbad)==1
        for mail, flags in imapbad:
            mail, verified, result = id2.decrypt(mail,strict=False)
            assert mail and result
            assert not result['encrypted'] and result['signed'] and result['fingerprints']==[key1]
            #print mail
            # assert key1 attached
        return

    return #FIXME
    assert len(imaprecv)==1
    msg = None
    for mail, flags in imaprecv:
        mail, verified, result = id2.decrypt(mail,strict=False)
        assert mail and result
        assert result['signed'] and result['fingerprints']==[key1]
        assert bool(result['encrypted']) == (defect!='nokey')
        #print mail
        msg = mail
        # assert key1 attached
    if defect=='nokey':
        return

    if defect=='badcode':
        reply = create_mail(receiver,sender,'confirmation','bad code')
    else:
        body = msg.get_payload()
        reply = '> '+'> '.join(body.splitlines(True))
        reply = create_mail(receiver,sender,'Re: '+mail['subject'],reply)
        reply = id2.encrypt(reply,sign=True)
    assert server.send(reply)
    assert len(imapsend)==1
    get_mails(joint=True,debug=server,debug_gpg=gpg,keep=False)
    process_register(debug_gpg=gpg)
    send_mails(joint=True,debug=server,debug_gpg=gpg)
    assert len(imaprecv)==1
    for mail, flags in imaprecv:
        mail, verified, result = id2.decrypt(mail,strict=False)
        assert mail and result
        assert result['encrypted'] and result['signed'] and result['fingerprints']==[key1]
        #print mail
        msg = mail
        # assert key1 attached

    if defect=='badcode':
        return

    if defect!='unverified':
        key = user.publickeys.get(active=True)
        key.trust=PublicKey.TRUSTED
        key.save()
    msg = create_mail(receiver,sender,'test','test')
    msg = id2.encrypt(msg,sign=True)
    assert server.send(reply)
    assert len(imapsend)==1
    get_mails(joint=True,debug=server,debug_gpg=gpg,keep=False)

    # check verified = CONFIRMED/TRUST/...
    # verifiyed key, receive
    return
Ejemplo n.º 8
0
def test_receive(request, accounts, tokens, mails, bilateral, client, defect):
    from accounts.models import Account
    from idapi.models import Message, PublicKey
    from idapi.mails import get_mails, update_keyrings
    import email.mime.text, six
    from kryptomime import create_mail, protect_mail
    from kryptomime.pgp import find_gnupg_key

    user = accounts['member1']
    token = tokens['member1']
    #update_keyrings()
    id1, id2 = bilateral['id1'], bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'], sender)
    key2 = find_gnupg_key(bilateral['gpg2'], receiver)
    livemail = request.config.getoption('livemail')
    if livemail: server = mails
    else: server, imapsend, imaprecv = mails
    if not livemail: assert not len(imapsend) and not len(imaprecv)

    user.publickeys.create(active=True,
                           keytype=PublicKey.PGP,
                           trust=PublicKey.TRUSTED)

    key1 = find_gnupg_key(bilateral['gpg1'], sender)
    key2 = find_gnupg_key(bilateral['gpg2'], receiver)
    attachment = email.mime.text.MIMEText('some\nattachment')
    msg = create_mail(receiver,
                      sender,
                      'subject',
                      'body\nmessage',
                      attach=[attachment])
    msg = protect_mail(msg, linesep='\r\n')

    assert server.send(msg)
    if not livemail: assert len(imapsend) == 1 and not len(imaprecv)

    sgn, _ = id2.sign(msg, inline=True, verify=True)
    assert sgn and id1.analyze(sgn) == (False, True)
    assert server.send(sgn)
    if not livemail: assert len(imapsend) == 2 and not len(imaprecv)

    enc, _ = id2.encrypt(msg, sign=True, inline=False)
    assert enc and id1.analyze(enc) == (True, None)
    assert server.send(enc)
    if not livemail: assert len(imapsend) == 3 and not len(imaprecv)
    """
    for mail, flags in imapsend:
        mtype = id1.analyze(mail)
        if mtype != (False,False):
            if mtype == (False,True):
                verified, result = id1.verify(mail)
                mail = id1.strip_signature(mail)[0]
                mail = protect_mail(mail,linesep='\r\n')
            else: #if mtype == (True,None):
                mail, verified, result = id1.decrypt(mail)
            assert mail and verified and result
            assert result['signed'] and result['fingerprints']==[key2]
            assert result['encrypted']==(mtype != (False,True))
        else: mail = protect_mail(mail,linesep='\r\n')
        compare_mail(msg,mail)
    assert not len(imapsend) and not len(imaprecv)
    """
    get_mails(joint=True,
              debug=None if livemail else server,
              debug_gpg=bilateral['gpg1'],
              keep=False)
    if not livemail: assert not len(imapsend) and not len(imaprecv)

    response, out = api(client, 'user/mails/', token=token)
    assert response.status_code == 200
    todo = [(False, False), (True, False), (True, True)]
    for mid in out['items']:
        response, out = api(client, 'user/mails/%i/' % mid, token=token)
        assert response.status_code == 200
        parts = out['parts']
        assert out['subject'] == 'subject' and len(parts) == 2
        signed, encrypted = out['signed'], out['encrypted']
        contents = ['body\r\nmessage', 'some\r\nattachment']
        assert parts[0] == {
            'content': contents[0],
            'content-charset': 'us-ascii',
            'content-type': 'text/plain',
            'content-encoding': '7bit'
        }
        assert parts[1] == {
            'content': contents[1],
            'content-charset': 'us-ascii',
            'content-type': 'text/plain',
            'content-encoding': '7bit'
        }
        todo.remove((signed, encrypted))
        if signed: assert out['verified'] == 'trusted'
        #print out
    assert not todo

    if livemail: server.close()
Ejemplo n.º 9
0
def test_send(request, accounts, tokens, mails, bilateral, client, defect):
    from accounts.models import Account
    from idapi.models import Message, PublicKey
    from idapi.mails import send_mails, update_keyrings
    from kryptomime.pgp import find_gnupg_key
    user = accounts['member1']
    token = tokens['member1']
    #update_keyrings()
    id1, id2 = bilateral['id1'], bilateral['id2']
    key1 = find_gnupg_key(bilateral['gpg1'], sender)
    key2 = find_gnupg_key(bilateral['gpg2'], receiver)
    livemail = request.config.getoption('livemail')
    if livemail: server = None
    else: server, imapsend, imaprecv = mails

    user.publickeys.create(active=True,
                           keytype=PublicKey.PGP,
                           trust=PublicKey.TRUSTED)

    data = {
        'identity': 'portal',
        'content': {
            'subject': 'hallo1',
            'body': 'foö'
        }
    }
    response, out = api(client, 'user/mails/', 'post', data, token=token)
    assert response.status_code == 200
    data = {
        'identity': 'portal',
        'content': {
            'subject': 'hallo2',
            'body': 'foo'
        },
        'sign': True
    }
    response, out = api(client, 'user/mails/', 'post', data, token=token)
    assert response.status_code == 200
    data = {
        'identity': 'portal',
        'content': {
            'subject': 'hallo3',
            'body': 'foo'
        },
        'sign': True,
        'encrypt': True
    }
    response, out = api(client, 'user/mails/', 'post', data, token=token)
    assert response.status_code == 200

    send_mails(joint=True, debug=server, debug_gpg=bilateral['gpg1'])
    if livemail:
        server.close()
        return
    assert not len(imapsend) and len(imaprecv) == 3
    for mail, flags in imaprecv:
        mail, verified, result = id2.decrypt(mail)
        assert mail and result
        subj = mail.get('subject')
        if subj == 'hallo1':
            assert not result['encrypted'] and not result['signed']
        else:
            assert result['encrypted'] == (
                subj == 'hallo3'
            ) and result['signed'] and result['fingerprints'] == [key1]