Пример #1
0
def peer_ls():
    'list passwords for inbound connections'
    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)
    c = cjdns.connect(password=conf['admin']['password'])
    for user in c.listPasswords()['users']:
        yield user
    c.disconnect()
Пример #2
0
def tr(target, verify=False):
    'traceroute a node'
    c = cjdns.connect()

    if verify:
        res = c.nodeForAddr()['result']
        lastHop = res['bestParent']['ip']

        yield lastHop

        while True:
            x = c.nextHop(target, lastHop)
            # TODO: implement
            return
    else:
        found = 0
        for route in c.dumpTable():
            if route['ip'] != target:
                continue

            found += 1

            yield '[+] found route #%d' % found
            # TODO: show the route

    c.disconnect()
Пример #3
0
def peer_add(name, addr, pk, password, live=False):
    'add an outbound connection'
    if '/' in name:
        yield 'nope'
        exit(1)

    if not password:
        password = raw_input('Password: '******'type': 'out',
        'name': name,
        'addr': addr,
        'pk': pk,
        'password': password
    }

    if not live:
        with open(path, 'w') as f:
            f.write(json.dumps(info))

    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)

    addr = utils.dns_resolve(addr)

    c = cjdns.connect(password=conf['admin']['password'])
    c.udpBeginConnection(addr, pk, password)
    c.disconnect()
Пример #4
0
def peer_auth(name, live=False, cjdroute=False, yrd=False):
    'add a password for inbound connections'

    if '/' in name:
        yield 'nope'
        exit(1)

    path = os.path.join(YRD_PEERS, name)
    if os.path.exists(path):
        with open(path) as f:
            password = json.load(f)['password']
    else:
        password = utils.generate_key(31)

        info = {'type': 'in', 'name': name, 'password': password}

        if not live:
            with open(path, 'w') as f:
                f.write(json.dumps(info))

    conf = utils.load_conf(CJDROUTE_CONF)
    c = cjdns.connect(password=conf['admin']['password'])
    c.addPassword(name, password)
    c.disconnect()

    publicKey = conf['publicKey']
    port = conf['interfaces']['UDPInterface'][0]['bind'].split(':')[1]

    if (not cjdroute and not yrd) or cjdroute:
        yield utils.to_credstr(utils.get_ip(), port, publicKey, password)
    if not cjdroute and not yrd:
        yield ''
    if (not cjdroute and not yrd) or yrd:
        yield 'yrd peer add namehere %s:%s %s %s' % (utils.get_ip(), port,
                                                     publicKey, password)
Пример #5
0
def start():
    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)

    p = Popen(['cjdroute'], stdin=PIPE)
    p.communicate(json.dumps(conf))

    c = cjdns.connect(password=conf['admin']['password'])

    for peer in os.listdir(YRD_PEERS):
        yield '[*] adding %r' % peer
        try:
            with open(os.path.join(YRD_PEERS, peer)) as f:
                info = json.load(f)
        except ValueError:
            yield '[-] invalid json'
        else:
            if info['type'] == 'in':
                try:
                    c.addPassword(info['name'], info['password'])
                except KeyError:
                    yield '[-] key error'
            elif info['type'] == 'out':
                addr = utils.dns_resolve(info['addr'])
                c.udpBeginConnection(str(addr), str(info['pk']),
                                     str(info['password']))

    c.disconnect()
Пример #6
0
def n(neighbours=False):
    'shows your neighbours'
    conf = utils.load_conf(CJDROUTE_CONF)
    c = cjdns.connect(password=conf['admin']['password'])

    STAT_FORMAT = '%s %19s  v%-2d  %9d %9d  %12s  %d/%d/%d  '
    nodestore = list(c.dumpTable())

    connections = {}

    try:
        for peer in os.listdir(YRD_PEERS):
            with open(os.path.join(YRD_PEERS, peer)) as f:
                info = json.load(f)
                try:
                    connections[info['pk']] = str(info['name'])
                except KeyError:
                    pass
    except OSError:
        pass

    for peer in c.peerStats():
        result = c.nodeForAddr(peer.ip)['result']

        route = utils.grep_ns(nodestore, peer.ip)
        path = utils.get_path(route)

        setattr(peer, 'path', path)

        line = STAT_FORMAT % (peer.ip, peer.path, peer.version, peer.bytesIn,
                              peer.bytesOut, peer.state, peer.duplicates,
                              peer.lostPackets, peer.receivedOutOfRange)

        if hasattr(peer, 'user'):
            line += repr(peer.user)
        elif peer.publicKey in connections:
            line += repr(connections[peer.publicKey])

        yield line

        if neighbours:
            for i in range(result['linkCount']):
                link = c.getLink(peer.ip, i)

                if link and 'child' in link['result']:
                    child = link['result']['child']
                    route = utils.grep_ns(nodestore, child)

                    version = utils.get_version(route)
                    path = utils.get_path(route)

                    yield '   %s   %s  v%s' % (child, path, version)
                else:
                    yield '   -'

    c.disconnect()
Пример #7
0
def connect():
    try:
        if cjdns_use_default:
            print('Connecting using default or ~/.cjdnsadmin credentials...')
            con = cjdns.connectWithAdminInfo()
        else:
            print('Connecting to port {:d}...'.format(cjdns_port))
            con = cjdns.connect(cjdns_ip, cjdns_port, cjdns_password)

        return con

    except:
        print('Connection failed!')
        print(traceback.format_exc())
        sys.exit(1)
Пример #8
0
def connect():
    try:
        if cjdns_use_default:
            print('Connecting using default or ~/.cjdnsadmin credentials...')
            con = cjdns.connectWithAdminInfo()
        else:
            print('Connecting to port {:d}...'.format(cjdns_port))
            con = cjdns.connect(cjdns_ip, cjdns_port, cjdns_password)

        return con

    except:
        print('Connection failed!')
        print(traceback.format_exc())
        sys.exit(1)
Пример #9
0
def peer_remove(user):
    'unpeer a node'
    if '/' in user:
        yield 'nope'
        exit(1)

    path = os.path.join(YRD_PEERS, user)
    if os.path.exists(path):
        os.unlink(path)
    else:
        yield 'user not found'

    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)
    c = cjdns.connect(password=conf['admin']['password'])
    c.removePassword(user)
    c.disconnect()
Пример #10
0
Файл: sGNG.py Проект: kyrias/bin
def connect():
	try:
		if cjdns_use_default:
			print('Connecting using default or ~/.cjdnsadmin credentials...')
			con = cjdns.connectWithAdminInfo()
		else:
			print('Connecting to port %d...' % (cjdns_port))
			con = cjdns.connect(cjdns_ip, cjdns_port, cjdns_password)

		print(admin_tools.whoami(con)['IP'])
		return con

	except:
		print('Failed!')
		print(traceback.format_exc())
		sys.exit(1)
Пример #11
0
def addr():
    'show infos about your node'
    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)
    c = cjdns.connect(password=conf['admin']['password'])

    res = c.nodeForAddr()['result']
    table = list(c.dumpTable())

    yield 'addr\t\t' + res['bestParent']['ip']
    yield 'key\t\t' + res['key']
    yield 'version\t\tv' + str(res['protocolVersion'])
    yield ''
    yield 'links\t\t' + str(res['linkCount'])
    yield 'known routes\t' + str(len(table))

    c.disconnect()
Пример #12
0
def r(follow=False):
    'access the nodestore'
    c = cjdns.connect()

    known = []
    FMT = '%s %s  v%d %11d %7d'

    while True:
        for node in c.dumpTable():
            if node['ip'] not in known:
                yield FMT % (node['ip'], node['path'], node['version'],
                             node['link'], node['time'])

                known.append(node['ip'])

        if not follow:
            break

        time.sleep(3)

    c.disconnect()
Пример #13
0
def uplinks(ip, trace=False):
    'show uplinks of a node'
    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)
    c = cjdns.connect(password=conf['admin']['password'])
    nodestore = list(c.dumpTable())

    result = c.nodeForAddr(ip)['result']
    for i in range(result['linkCount']):
        link = c.getLink(ip, i)

        if link and 'child' in link['result']:
            child = link['result']['child']
            route = utils.grep_ns(nodestore, child)

            version = utils.get_version(route)
            path = utils.get_path(route)

            yield '%s   %s  v%d' % (child, path, version)
        else:
            yield ('-')

    c.disconnect()
Пример #14
0
def ping(ip, count=0, switch=False):
    'ping a node'
    conf = utils.load_conf(CJDROUTE_CONF, CJDROUTE_BIN)
    c = cjdns.connect(password=conf['admin']['password'])

    ping = c.switchPing if switch else c.routerPing

    for _ in xrange(count) if count else itertools.repeat(None):
        try:
            resp = ping(ip)
        except Exception, e:
            resp = {'error': e}

        if 'error' in resp:
            yield 'Error: %s' % resp['error']
        elif resp['result'] == 'pong' and switch:
            yield 'Reply from %s %dms' % (resp['path'], resp['ms'])
        elif resp['result'] == 'pong':
            yield 'Reply from %s %dms' % (resp['from'], resp['ms'])
        elif resp['result'] == 'timeout':
            yield 'Timeout from %s after %dms' % (ip, resp['ms'])

        time.sleep(1)
Пример #15
0
import cjdns
from cjdns import key_utils
import time
import urllib2

nodedb_data_unclean = urllib2.urlopen(
    "https://raw.githubusercontent.com/zielmicha/nodedb/master/nodes")
nodedb_data = nodedb_data_unclean.readlines()
nodedb_data.pop(0)

nodedb_reference_table = {}
for x in nodedb_data:
    nodedb_reference_table[x.split()[0]] = x.split()[1]

cjdns = cjdns.connect("127.0.0.1", 11234, "NONE")

peerStats = cjdns.InterfaceController_peerStats()

list_of_Nodes = []
for x in peerStats['peers']:
    list_of_Nodes.append(key_utils.to_ipv6(x['publicKey']))

Title = "# Virtualhacker - Cjdns public node\n"
date_stamp = "__Last Updated:__ " + time.strftime("%Y-%m-%d, %R")

with open("/var/www/virtualhacker.net/pages/peerstats.md", "w") as handle:
    handle.write(Title)
    handle.write(date_stamp + "  \n")
    handle.write("  \n")
    handle.write(
Пример #16
0
#!/usr/bin/python

import cjdns
from cjdns import key_utils
import time
import urllib2

nodedb_data_unclean = urllib2.urlopen("https://raw.githubusercontent.com/zielmicha/nodedb/master/nodes")
nodedb_data = nodedb_data_unclean.readlines()
nodedb_data.pop(0)

nodedb_reference_table = {}
for x in nodedb_data:
	nodedb_reference_table[x.split()[0]] = x.split()[1]

cjdns = cjdns.connect("127.0.0.1", 11234, "NONE")

peerStats = cjdns.InterfaceController_peerStats()

list_of_Nodes = []
for x in peerStats['peers']:
	list_of_Nodes.append(key_utils.to_ipv6(x['publicKey']))

Title = "# Virtualhacker - Cjdns public node\n"
date_stamp = "__Last Updated:__ " + time.strftime("%Y-%m-%d, %R")

with open("/var/www/virtualhacker.net/pages/peerstats.md","w") as handle:
	handle.write(Title)
	handle.write(date_stamp + "  \n")
	handle.write("  \n")
	handle.write("To join this Node, information can be found [here](/?pages=services#cjdns)  \n")
Пример #17
0
  x /= 8
  u = "K"
  if x > 1024:
    x /= 1024
    u = "M"
    if x > 1024:
      x /= 1024
      u = "G"
  return x, u

def prntbw(tx, rx, name='{}total'.format(' '*49)):
  tx, txu = getxstr(tx)
  rx, rxu = getxstr(rx)
  print('{}↑ %.2f %sBps | ↓ %.2f %sBps'.format(name)%(tx,txu,rx,rxu))

printPeers = len(sys.argv) > 1 and sys.argv[1].lower() == 'peers'
  
s = connect()
ps = s.InterfaceController_peerStats()
tx, rx = 0.0, 0.0
for p in ps['peers']:
  ptx = p['sendKbps']
  prx = p['recvKbps']
  if printPeers:
    pk = '{}.k'.format(p['addr'].split('.')[-2]+": ")
    prntbw(ptx, prx, pk)
  tx += ptx
  rx += prx

prntbw(tx, rx, '')
Пример #18
0
def n(neighbours=False, bw=False):
    'shows your neighbours'
    c = cjdns.connect()

    STAT_FORMAT = '%s %19s  v%-2d  %9s %9s  %12s  %d/%d/%d  '
    nodestore = list(c.dumpTable())

    connections = {}

    try:
        for peer in os.listdir(YRD_PEERS):
            with open(os.path.join(YRD_PEERS, peer)) as f:
                info = json.load(f)
                try:
                    connections[info['pk']] = str(info['name'])
                except KeyError:
                    pass
    except OSError:
        pass

    stats = {}

    while True:
        if bw:
            sys.stderr.write('\x1b[2J\x1b[H')

        for peer in c.peerStats():
            result = c.nodeForAddr(peer.ip)['result']

            route = utils.grep_ns(nodestore, peer.ip)
            path = utils.get_path(route)

            setattr(peer, 'path', path)

            if bw:
                entry = stats.get(peer.ip, (peer.bytesIn, peer.bytesOut))
                stats[peer.ip] = (peer.bytesIn, peer.bytesOut)
                entry = [
                    utils.speed(peer.bytesIn - entry[0]),
                    utils.speed(peer.bytesOut - entry[1])
                ]
            else:
                entry = (peer.bytesIn, peer.bytesOut)

            line = STAT_FORMAT % (peer.ip, peer.path, peer.version, entry[0],
                                  entry[1], peer.state, peer.duplicates,
                                  peer.lostPackets, peer.receivedOutOfRange)

            if hasattr(peer, 'user'):
                line += repr(peer.user)
            elif peer.publicKey in connections:
                line += repr(connections[peer.publicKey])

            yield line

            if neighbours:
                for i in range(result['linkCount']):
                    link = c.getLink(peer.ip, i)

                    if link and 'child' in link['result']:
                        child = link['result']['child']
                        route = utils.grep_ns(nodestore, child)

                        version = utils.get_version(route)
                        path = utils.get_path(route)

                        yield '   %s   %s  v%s' % (child, path, version)
                    else:
                        yield '   -'

        if not bw:
            break

        time.sleep(1)

    c.disconnect()