def term_conn(active_conn): v = vici.Session() for conn in active_conn: try: list(v.terminate({"ike": conn, "force": "true"})) except: pass
def __init__(self): super(IkeAgent, self).__init__(agent.ProcessAgent.AGENTTYPE_IPSEC) self.ike = {} self.vici_sock = socket.socket(socket.AF_UNIX) self.vici_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # self.vici_sock.setblocking(0) try: self.vici_sock.connect(self.VICI) except socket.error as e: self.logger.error( "Cannot connect to the ike server, reason:%s" % str(e)) self.vici_sock.close() sys.exit(0) try: self.cert = open(self.CERT) self.mycert = self.cert.read() except IOError: self.logger.error("Cannot open the certificate:%s", self.CERT) self.vici_sock.close() sys.exit(0) try: self.vici_ses = vici.Session(self.vici_sock) # Get all ike conns and stop them self.stop_legacy_ike_conn() self.vici_ses.register("ike-updown") except Exception, e: self.logger.error("Cannot initiate the vici session: %s" % e) self.vici_sock.close() sys.exit(0)
def _connect_socket(self): try: self.socket = socket.socket(socket.AF_UNIX) self.socket.connect(self.socket_path) self.session = vici.Session(self.socket) except Exception as e: raise ViciSocketException("Vici is not reachable! " + str(e))
class Handler(BaseHTTPRequestHandler): strongswan_session = vici.Session() def _set_headers(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() def _sas_len_iter(self, list_sas): for this_sas in list_sas: ikev2 = this_sas['ikev2'] child_sas = ikev2['child-sas'] yield len(child_sas) def _strongswan_connections_iter(self): list_sas = self.strongswan_session.list_sas() strongswan_connections = sum(self._sas_len_iter(list_sas)) yield '# HELP strongswan_connections Number of strongswan connections.' yield '# TYPE strongswan_connections gauge' yield 'strongswan_connections %s' % strongswan_connections def _messages_iter(self): yield from self._strongswan_connections_iter() def do_GET(self): self._set_headers() for message in self._messages_iter(): self.wfile.write(message.encode()) self.wfile.write(b'\n')
def conn_list(): v = vici.Session() config = vyos.config.Config() config_conns = config.list_effective_nodes("vpn ipsec site-to-site peer") connup = [] v = vici.Session() for conn in v.list_sas(): for key in conn: for c_conn in config_conns: if c_conn in key: if config.return_effective_value( "vpn ipsec site-to-site peer {0} dhcp-interface". format(c_conn)): connup.append(key) return connup
def add_secret(username): s = vici.Session() password = generate_random_string() s.load_shared({'id': username, 'type': 'EAP', 'data': password}) print('added credentials for' + username) print('username: '******'password: ', password) return username, password
def wait_and_remove_credentials(session_name): time.sleep(2 * 60) try: if session_name not in get_active_connections().keys(): s = vici.Session() s.unload_shared({'id': session_name}) print(str(session_name, 'utf-8') + ' is removed') except Exception as err: print(err)
def run(self): for _ in range(10): try: session = vici.Session() break except socket.error, e: time.sleep(1) except Exception as e: sys.exit(1)
def cli(ctx, sock, get_help=False): if get_help: click.echo(pprint.pformat(mapp_g), nl=True) click.echo(pprint.pformat(mapp_l)) return sk = socket.socket(socket.AF_UNIX) sk.connect(sock) ipsec_s = vici.Session(sk) ctx.obj['ipsec_s'] = ipsec_s
def disconnect_client(username, connection_id): s = vici.Session() s.unload_shared({'id': username}) cmd = 'ipsec down [{0}]'.format(str(connection_id)) dc_proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE) dc_proc.wait() if dc_proc.stderr.read(): return False print(str(username, 'utf-8') + ' is disconnected') return True
def setup_vici(): s = socket.socket(socket.AF_UNIX) retry = True while True: try: s.connect("/var/run/charon.vici") break except ConnectionRefusedError as e: if retry: os.system('systemctl restart strongswan.service') retry = False time.sleep(2) else: raise(e) return vici.Session(s)
def get_active_connections(): active_connections = {} s = vici.Session() for conn in s.list_sas(): conn = recursive_ordered_dict_to_dict(conn) conn_path = parse("$..uniqueid") id_path = parse("$..remote-id") bytes_path = parse("$..bytes-in") bytes_out_path = parse("$..bytes-out") for connection_id, remote_id, bytes_in, bytes_out in zip( conn_path.find(conn), id_path.find(conn), bytes_path.find(conn), bytes_out_path.find(conn)): active_connections[remote_id.value] = { 'connection_id': connection_id.value, 'bytes_in': bytes_in.value, 'bytes_out': bytes_out.value } return active_connections
def main(): args = parse_args() # Get all connections and materialize enumerator into a list for later use. sas = list(vici.Session().list_sas()) template = args.prefix + '.{} {} ' + str(int(time())) print(template.format('clients', len(sas))) for client_name, client_data in get_clients_traffic(sas).items(): # For privacy we support hashing client login name. if args.salt: client_hash = binascii.hexlify( pbkdf2_hmac('sha256', client_name.encode(), args.salt.encode(), 100)).decode() else: client_hash = client_name for metric in METRICS: print( template.format( 'clients_traffic.{}.{}'.format(client_hash, metric), client_data[metric]))
def remove_shared(remote_id): s = vici.Session() s.unload_shared({'id': remote_id}) print('removed user ' + remote_id)
def add_secret(username): s = vici.Session() password = generate_random_string() s.load_shared({'id': username, 'type': 'EAP', 'data': password}) return username, password
def get_shared_connections(): s = vici.Session() return recursive_ordered_dict_to_dict(s.get_shared())['keys']
def init_conn(active_conn, updated_conn): v = vici.Session() for conn in active_conn: if conn not in updated_conn: list(v.initiate({"child": conn, "timeout": "10000"}))
def get_session(self): vici_sock = socket.socket(socket.AF_UNIX) vici_sock.connect(self.sock) return vici.Session(vici_sock)
def main(): sess = vici.Session() for metric in _sas(sess): _print_metric(metric) for metric in _pools(sess): _print_metric(metric)
def __init__(self): self.alive = True self.session = vici.Session() self.conns = [] self.active_conns = [] self.target_conns = ['rw-ikev2']
def remove_shared(remote_id): s = vici.Session() s.unload_shared({'id': remote_id})
def install_routes(ike_sa): if_id_out = int(ike_sa['if-id-out'], 16) ifname_out = "xfrm-{}-out".format(if_id_out) child_sa = next(ike_sa["child-sas"].itervalues()) for ts in child_sa['remote-ts']: logger.info("add route to %s via %s", ts, ifname_out) subprocess.call(["ip", "route", "add", ts, "dev", ifname_out]) # daemonize and run parallel to the IKE daemon with daemon.DaemonContext(): logger.debug("starting Python updown listener") try: session = vici.Session() ver = session.version() logger.info("connected to {daemon} {version} ({sysname}, {release}, " "{machine})".format(**ver)) except: logger.error("failed to get status via vici") sys.exit(1) try: for label, event in session.listen(["ike-updown", "child-updown"]): logger.debug("received event: %s %s", label, repr(event)) name = next((x for x in iter(event) if x != "up")) up = event.get("up", "") == "yes" ike_sa = event[name]
def __init__(self, sock='/opt/swan/proc/charon.vici'): vici_sock = socket.socket(socket.AF_UNIX) vici_sock.connect(sock) self.ipsec_s = vici.Session(vici_sock) self.sock = sock self.watchers = []
-------------------------------------------------------------------------------------- disconnect ipsec connection """ import sys import os import subprocess import ujson import vici # parse input parameter conn_id = None if len(sys.argv) > 1: conn_id = sys.argv[1].strip() # validate if SA is active before trying to disconnect, validates input data conn_found = False s = vici.Session() for sas in s.list_sas(): for sa in sas: if sa == conn_id: conn_found = True # terminate connection if found if conn_found: devnull = open(os.devnull, 'w') subprocess.call(['/usr/local/sbin/ipsec', 'down', conn_id], stdin=devnull, stdout=devnull, stderr=devnull)
def __init__(self): self.session = vici.Session()