class Device: def __init__(self, name, ip_address, mac_address, ): self.name = name self.ip = ip_address self.mac = MAC(mac_address) def __str__(self): return str(self.__dict__) def change_mac(self): self.stop() self.mac.reset_mac() command = ['ifconfig', self.name, 'hw', 'ether', str(self.mac)] code = call(command, stdout=DEVNULL, stderr=STDOUT) if code > 1: self.change_mac() self.start() def stop(self): command = ['ifconfig', self.name, "down"] code = call(command) if code > 1: raise CalledProcessError(code, command) def start(self): command = ['ifconfig', self.name, "up"] code = call(command) if code > 1: raise CalledProcessError(code, command)
def generate_response(self): (request, _) = netstring.consume_netstring(self.readbuf) (sig, request) = netstring.consume_netstring(request) sig = base64.standard_b64decode(sig) mysig = hmac.new(ACCESSKEY, request, hashlib.sha256).digest() if sig != mysig: self.writebuf = b"ERROR Bad signature" return (action, request) = netstring.consume_netstring(request) (mac, request) = netstring.consume_netstring(request) (time, request) = netstring.consume_netstring(request) if len(request) > 0: raise Exception("Invalid request: too long: " + repr(self.readbuf)) mac = MAC(mac.decode("ascii")) time = datetime.datetime.strptime(time.decode("ascii"), "%Y-%m-%dT%H:%M:%S") now = datetime.datetime.utcnow() if time < (now - TIMEWINDOW) or time > (now + TIMEWINDOW): self.writebuf = b"ERROR Time out of sync" return if action not in (b"grant", b"revoke"): self.writebuf = b"ERROR Invalid action" return LOGGER.info("Valid request to {0!r} {1!s}".format(action, mac)) if action == b"grant": print("grant", str(mac)) elif action == b"revoke": print("revoke", str(mac)) sys.stdout.flush() resp = sys.stdin.readline().strip() if resp == "OK": self.writebuf = netstring.encode_netstring(b"OK") else: self.writebuf = netstring.encode_netstring(b"ERROR " + resp.encode("ascii"))
def generate_response(self): (request, _) = netstring.consume_netstring(self.readbuf) (sig, request) = netstring.consume_netstring(request) sig = base64.standard_b64decode(sig) mysig = hmac.new(ACCESSKEY, request, hashlib.sha256).digest() if sig != mysig: self.writebuf = b'ERROR Bad signature' return (action, request) = netstring.consume_netstring(request) (mac, request) = netstring.consume_netstring(request) (time, request) = netstring.consume_netstring(request) if len(request) > 0: raise Exception('Invalid request: too long: ' + repr(self.readbuf)) mac = MAC(mac.decode('ascii')) time = datetime.datetime.strptime(time.decode('ascii'), '%Y-%m-%dT%H:%M:%S') now = datetime.datetime.utcnow() if time < (now - TIMEWINDOW) or time > (now + TIMEWINDOW): self.writebuf = b'ERROR Time out of sync' return if action not in (b'grant', b'revoke'): self.writebuf = b'ERROR Invalid action' return LOGGER.info('Valid request to {0!r} {1!s}'.format(action, mac)) if action == b'grant': print('grant', str(mac)) elif action == b'revoke': print('revoke', str(mac)) sys.stdout.flush() resp = sys.stdin.readline().strip() if resp == 'OK': self.writebuf = netstring.encode_netstring(b'OK') else: self.writebuf = netstring.encode_netstring(b'ERROR ' + resp.encode('ascii'))
def getHardwareAddress(self): """ Provides the client's MAC address. :return: The client's MAC address. """ length = self.getOption(FIELD_HLEN)[0] full_hw = self.getOption(FIELD_CHADDR) if length and length < len(full_hw): return MAC(full_hw[0:length]) return MAC(full_hw)
class artifact_removal_with_MAC: def __init__(self, th = 0.1): self.th = th return def get_params(self, deep=True): return {"th": self.th} def set_params(self, **parameters): for parameter, value in parameters.items(): setattr(self, parameter, value) return self def fit(self,X,y): from mac import MAC self.mac = MAC(th=self.th) self.mac.fit(X,y) return def transform(self, X): return self.__noise_removal(X) def predict(self, X): return self.transform(X) def fit_transform(self, X, y): self.fit(X,y) return self.transform(X) def __noise_removal(self, X_true): import numpy as np from tqdm import tqdm from mac import MAC noise_est = self.mac.transform(X_true) return np.array([[self.__ch_noise_removal(rnc, Xnc) for rnc, Xnc in zip(rn,Xn)] for rn, Xn in tqdm(zip(noise_est ,X_true))]) def __ch_noise_removal(self, noise_true, X_true): import numpy as np signalEmbedding = 5 noise_em = np.array([noise_true[i-signalEmbedding:i] for i in range(signalEmbedding,len(noise_true))]) X_em = np.array([X_true[i] for i in range(signalEmbedding,len(noise_true))]).reshape(-1,1) if np.sum(noise_em) != 0.0: from KAF import QKLMS f = QKLMS(epsilon = 0) noise_pred = f.evaluate(noise_em,X_em) return X_em.ravel() - noise_pred.ravel() else: return X_em.ravel()
def session(self, action=None, source=None, mac=None, ipv4=None, ipv6=None, time=None): if cherrypy.request.method != 'POST': return "Invalid request method" if source not in ('arp', 'nd', 'radius', 'dhcp'): return "Invalid source" self.authenticate_session_request() mac = MAC(mac) if ipv4: ipv4 = ipaddr.IPv4Address(ipv4) if ipv6: ipv6 = ipaddr.IPv6Address(ipv6) time = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S") if action == 'start': sessions.session_started(source, mac, time, ipv4, ipv6) elif action == 'end': sessions.session_ended(source, mac, time, ipv4, ipv6) else: return "Invalid action" return "Success"
def find_mac_in_db(self, address): candidates = [] for row in self.db: vendoraddress = MAC.standarize_address(row['oui']) if address.startswith(vendoraddress): candidates.append(row) return candidates
def __init__(self, name=None, mac=None, cable=None): if not mac: self.mac = MAC() else: self.mac = mac self.name = name if cable: self.connectCable(cable)
def login(self, user=None, mac=None, origurl=None): if cherrypy.request.method != 'POST': return self.splash(mac, origurl) mac = MAC(mac) sessions.user_logged_in(user, mac) params = {'user': user} if origurl: params['origurl'] = origurl url = '{0}/welcome?{1}'.format(cherrypy.request.base, urllib.parse.urlencode(params)) raise cherrypy.HTTPRedirect(url)
def splash(self, mac=None, origurl=None): macval = MAC(mac) # Ensures mac is a safe string yield """<html> <head><title>Wifi Login</title></head> <body> <form action="/login" method="POST"> <input type="hidden" name="mac" value="{mac}"/> """.format(mac=mac) if origurl: yield ' <input type="hidden" name="origurl" value={0}/>'.format( xml.sax.saxutils.quoteattr(origurl)) yield """
def parse_ipneigh_line(line, cons): try: tokens = line.split() state = tokens[-1] if state not in VALID_STATES: return None ip = cons(tokens[0]) mac = MAC(tokens[tokens.index('lladdr') + 1]) return (mac, ip) except: LOGGER.exception("Failed to parse line {0!r}".format(line)) return None
def all_sessions(con): # KLUDGE: This function is entirely too view-oriented, and it's a bad view # at that. There should be a more abstract session model, but I needed # something quick-n-dirty to see what sessions there were. cur = con.execute('''SELECT user_sessions.user, addr_sessions.mac, user_sessions.start, user_sessions.end, addr_sessions.source, addr_sessions.ipv4, addr_sessions.ipv6, addr_sessions.start, addr_sessions.end FROM addr_sessions LEFT OUTER JOIN user_sessions ON addr_sessions.user_session = user_sessions.id ORDER BY addr_sessions.start DESC''') # KLUDGE: This should be a generator, but since the generator gets passed # back up out of the with_dbconn decorator, the connection is closed before # the generator is evaluated. return [(row[0], MAC(row[1]), row[2], row[3], row[4], common.bytes_to_ipv4(row[5]), common.bytes_to_ipv6(row[6]), row[7], row[8]) for row in cur]
def read_OUIs_from_file(filename): macs = [] lines = open(filename).readlines() for line in lines: line = line.strip() if not line: continue if line[0] == '#': # skip line that is comment only continue line_parts = filter(lambda s: s, line.split('\t')) line_parts = list(map(lambda s: s.strip(), line_parts)) if len(line_parts) < 2: # we need [mac] and [vendor] continue line_OUI_part = line_parts[0] if line_OUI_part.find('/') > -1: # TODO: I don't know how to read this yes. continue line_vendor_part = line_parts[1] if len(line_parts) >= 3: line_full_vendor_part = line_parts[2] if len(line_parts) >= 4: line_comment_part = line_parts[3] if len(line_parts) > 4: line = line.replace('\t', '\\t') print(f'Discarding [{" ".join(line_parts[4:])}] ' f'from [{line}]') else: line_comment_part = None else: line_full_vendor_part = None line_comment_part = None mac = MAC(line_OUI_part, line_vendor_part, line_full_vendor_part, line_comment_part) macs.append(mac) return macs
def end_user_session(con, sessid): """Close the user session, revoking access. Not for external use, only called from session_ended """ # Pseudocode # UPDATE user_sessions SET end = datetime('now') WHERE id = ? # (sessid) # SELECT mac FROM user_sessions WHERE id = ? # (sessid) # access_control.revoke(mac) con.execute('UPDATE user_sessions SET end = datetime(\'now\')' ' WHERE id = ?', (sessid,)) cur = con.execute('SELECT mac FROM user_sessions WHERE id = ?', (sessid,)) mac = MAC(cur.fetchone()[0]) try: access_control.revoke(mac) except: logger().exception('Failed to revoke mac {0!s}'.format(mac))
def run_server(): global HOST global PORT s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(10) while True: conn, addr = s.accept() print("{0} - ".format(get_counter()) + 'Connection from : {0}'.format(addr)) data_recv=conn.recv(1024) data=bytearray() conn.settimeout(1) while len(data_recv)>0: data.extend(data_recv) if len(data_recv) < 1024: break try: data_recv=conn.recv(1024) except socket.timeout: break data=str(data) if data=="1": message=get_message1() conn.sendall(message) elif data=="2": global ifname current_mac= MAC.get_local_mac(ifname) conn.sendall(current_mac) conn.close()
def main(): args = get_argparse() MAC.set_macs(read_OUIs_from_file(args.file)) MAC.set_levenshtein_max_dist_allowed(args.max_levenshtein_distance) if args.vendor is None: mac = MAC.get_any() else: macs = MAC.find_by_vendor(args.vendor, args.no_levenshtein) if args.lucky: mac = secrets.choice(macs) else: for i, _mac in enumerate(macs): print(f'{str(i).zfill(2)} - {_mac.OUI}: {_mac.vendor}') choice = read_choice(i) mac = macs[choice] for _ in range(args.count): output = '' if args.print_vendor: output += (mac.full_vendor_name or mac.vendor) + ': ' output += mac.generate_random_mac(args.separator) print(output)
def fit(self,X,y): from mac import MAC self.mac = MAC(th=self.th) self.mac.fit(X,y) return
y_train = data['labels'].reshape(-1, ) fs = int(data['fs'].reshape(-1, )) print('Loading', filetrain, 'with sampling frequency of', fs, 'Hz.') X_train = np.transpose(X_train, (2, 1, 0)) #trials x ch x time print(X_train.shape, y_train.shape) # 2. Parameter selection parameters = pd.read_csv(params) bp = parameters[parameters.mean_test_score == parameters.mean_test_score.max()].iloc[0] # AMK parameters # 3. Pipeline definition and trainnig steps = [('artifact_removal', MAC(th=0.668963518761388)), ('extract', FBCSP(fs, 4, 40, 4, 4, n_components=4)), ('select', SelectKBest(score_func=mutual_info_classif, k=bp.param_select__k)), ('classify', SVC(kernel='linear', C=bp.param_classify__C))] # ('artifact_removal', ar(th=0.890070294773727)) pipeline = Pipeline(steps=steps) pipeline.fit(X_train, y_train) # 4. Prediction data = sio.loadmat(filetest) X_test = data['X'] y_test = data['labels'].reshape(-1, )
def __init__(self, name, ip_address, mac_address, ): self.name = name self.ip = ip_address self.mac = MAC(mac_address)
###Paths for testing only #filename = r'G:\Shared drives\datasets\BCI\Competition IV\dataset 2a\Trials\NEW_22ch_A01.mat' #filename = r'G:\My Drive\Students\vigomez\Code_A1_Application\data_4C\BCI_s02train.mat' #filename = '..\data_4C\BCI_s01train.mat' data = sio.loadmat(filename) Xdata = data['X'] Xdata = np.transpose(Xdata, (2, 1, 0)) labels = data['labels'].reshape(-1, ) fs = 250 print('Loading', filename, 'with sampling frequency of', fs, 'Hz.') # 2. Artifacts removal stage - Noise Estimation from mac import MAC mac_ = MAC(th=args.th) noise_est = mac_.fit_transform(Xdata, labels) Noise_sum = np.array([np.sum(noise) for noise in noise_est]) noise_index = np.where(Noise_sum != 0.0)[0] Xdata = Xdata[noise_index] Noise = noise_est[noise_index] labels = labels[noise_index] #3. Parameter Grid for AMK AF param_dist = { 'embedding': randint(5, 10), 'eta': loguniform(1e-2, 0.5), 'epsilon': uniform(1e-1, 2), 'mu': uniform(1e-2, 1),
args = parser.parse_args() filename = args.input savename = args.out filename = "../../data_4C/BCI_s01train.mat" data = sio.loadmat(filename) Xdata = data['X'] labels = data['labels'].reshape(-1, ) fs = int(data['fs'].reshape(-1, )) print('Loading', filename, 'with sampling frequency of', fs, 'Hz.') Xdata = np.transpose(Xdata, (2, 1, 0)) #trials x ch x time steps = [ ('preproc', MAC()), ('extract', FBCSP(fs, 4, 40, 4, 4, n_components=4)), #('select', SelectKBest()), ('classify', LDA()) ] pipeline = Pipeline(steps=steps) param_dist = { 'extract__n_components': [4], 'extract__fs': [fs], 'extract__f_low': [4], 'extract__f_high': [40], 'extract__bandwidth': [4], 'extract__step': [4], #'select__score_func':[mutual_info_classif],
def fit(self, X, y): from mac import MAC mac_ = MAC(th=self.th) self.noise_est = mac_.fit_transform(X, y) return
# weight input interface in_W = m.Array(y, m.Array(x, TIN)) # Top level module: line buffer input, MAC output args = ['I0', in_LB, 'I1', in_W, 'WE', m.BitIn, 'O', out_MAC, 'V', m.Out(m.Bit)] + \ m.ClockInterface(False, False) conv = m.DefineCircuit('Convolution', *args) # Line buffer declaration lb = Linebuffer(cirb, in_LB, out_LB, imgType, True) m.wire(conv.I0, lb.I) m.wire(conv.WE, lb.wen) # MAC declaration mac = MAC(x * y) # connect up linebuffer and weights to MAC input k = 0 for i in range(y): for j in range(x): m.wire(lb.out[i][j][0], mac.I0[k]) m.wire(conv.I1[i][j][0], mac.I1[k]) k += 1 m.wire(conv.O, mac.O) m.wire(conv.V, lb.valid) m.EndCircuit() module = GetCoreIRModule(cirb, conv)