Пример #1
0
def dosSmilator():
    conf.verb = 0

    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']

    print("\033[33m[!] Client Interface: {0}".format(str(
        conf.iface))) + "\033[0m"
    print("\033[33m[!] Client IP: {0} ".format(str(client_ip))) + "\033[0m"

    print "\033[94m[!] DoS attack simulation process started. \033[0m"

    utilities.promisc("on", conf.iface)

    i = 0
    while i < int(options.counter):
        try:

            toUser = random.choice(
                [line.rstrip('\n') for line in open(options.to_user)])
            fromUser = random.choice(
                [line.rstrip('\n') for line in open(options.from_user)])
            spUser = random.choice(
                [line.rstrip('\n') for line in open(options.sp_user)])
            userAgent = random.choice(
                [line.rstrip('\n') for line in open(options.user_agent)])

            pkt = IP(dst=options.dest_ip)
            client = pkt.src

            if options.random and not options.library:
                client = utilities.randomIPAddress()
            if options.manual and not options.library:
                client = random.choice([
                    line.rstrip('\n') for line in open(options.manual_ip_list)
                ])
            if options.subnet and not options.library:
                client = utilities.randomIPAddressFromNetwork(
                    client_ip, client_netmask)
            send_protocol = "scapy"
            if options.library:
                send_protocol = "socket"

            sip = sip_packet.sip_packet(str(options.dos_method),
                                        str(options.dest_ip),
                                        str(options.dest_port), str(client),
                                        str(fromUser), str(toUser),
                                        str(userAgent), str(spUser),
                                        send_protocol)
            sip.generate_packet()
            i += 1
            utilities.printProgressBar(i, int(options.counter), "Progress: ")
        except (KeyboardInterrupt):
            utilities.promisc("off", conf.iface)
            print("Exiting traffic generation...")
            raise SystemExit

    print "\033[31m[!] DoS simulation finished and {0} packet sent to {1}...".format(
        str(i), str(options.dest_ip)) + "\033[0m"
    utilities.promisc("off", conf.iface)
Пример #2
0
def dosSmilator():
    conf.verb = 0
    os.system("toilet SIP-DAS")
    
    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']
    
    print ("[!] Client Interface: {0}".format(str(conf.iface)))
    print ("[!] Client IP: {0} ".format(str(client_ip)))
    
    utilities.promisc("on")

    i = 0
    while i <= int(options.counter):
        try:
            
            toUser = random.choice([line.rstrip('\n') for line in open(options.to_user)])
            fromUser = random.choice([line.rstrip('\n') for line in open(options.from_user)])
            spUser = random.choice([line.rstrip('\n') for line in open(options.sp_user)])
            userAgent = random.choice([line.rstrip('\n') for line in open(options.user_agent)])
            
            pkt= IP(dst=options.server)
            client = pkt.src
            
            if options.random and not options.tcp:
                client = utilities.randomIPAddress()
            if options.manual and not options.tcp:
                client = random.choice([line.rstrip('\n') for line in open(options.manual_ip_list)])
            if options.subnet and not options.tcp:
                client = utilities.randomIPAddressFromNetwork(client_ip, client_netmask)
            send_protocol = "udp"
            if options.tcp_protocol:
                send_protocol = "tcp"
                
            SipPacket(str(options.dos_method), str(options.dest_ip), str(options.dest_port), str(client), str(fromUser), str(toUser), str(userAgent), str(spUser), send_protocol)
            
            i += 1
            utilities.printProgressBar(i,int(options.counter),"Progress: ")
        except (KeyboardInterrupt):
            utilities.promisc("off")
            print("Exiting traffic generation...")
            raise SystemExit
    
    print "[!] DoS simulation finished and {0} packet sent to {1}...".format(str(i),str(options.dest_ip))
    utilities.promisc("off")
    
Пример #3
0
def dosSmilator():
    conf.verb = 0
    
    client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
    client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']
    
    print ("[!] Client Interface: {0}".format(str(conf.iface)))
    print ("[!] Client IP: {0} ".format(str(client_ip)))
    
    utilities.promisc("on",conf.iface)

    i = 0
    while i < int(options.counter):
        try:
            
            toUser = random.choice([line.rstrip('\n') for line in open(options.to_user)])
            fromUser = random.choice([line.rstrip('\n') for line in open(options.from_user)])
            spUser = random.choice([line.rstrip('\n') for line in open(options.sp_user)])
            userAgent = random.choice([line.rstrip('\n') for line in open(options.user_agent)])
            
            pkt= IP(dst=options.dest_ip)
            client = pkt.src
            
            if options.random and not options.library:
                client = utilities.randomIPAddress()
            if options.manual and not options.library:
                client = random.choice([line.rstrip('\n') for line in open(options.manual_ip_list)])
            if options.subnet and not options.library:
                client = utilities.randomIPAddressFromNetwork(client_ip, client_netmask)
            send_protocol = "scapy"
            if options.library:
                send_protocol = "socket"
                
            sip = sip_packet.sip_packet(str(options.dos_method), str(options.dest_ip), str(options.dest_port), str(client), str(fromUser), str(toUser), str(userAgent), str(spUser), send_protocol)
            sip.generate_packet()
            i += 1
            utilities.printProgressBar(i,int(options.counter),"Progress: ")
        except (KeyboardInterrupt):
            utilities.promisc("off",conf.iface)
            print("Exiting traffic generation...")
            raise SystemExit
    
    print "[!] DoS simulation finished and {0} packet sent to {1}...".format(str(i),str(options.dest_ip))
    utilities.promisc("off",conf.iface)
Пример #4
0
def dosSmilator():
    value_errors = []
    conf.verb = 0

    try:
        client_ip = netifaces.ifaddresses(conf.iface)[2][0]['addr']
        client_netmask = netifaces.ifaddresses(conf.iface)[2][0]['netmask']
    except ValueError:
        value_errors.append(
            'Please specify a valid interface name with --if option.')
    message_type = options.message_type.lower(
    ) if options.message_type else "invite"

    utilities.check_value_errors(value_errors)
    utilities.promisc("on", conf.iface)
    utilities.printInital("DoS attack simulation", conf.iface, client_ip)

    i = 0
    while i < int(options.counter):
        try:
            toUser = random.choice(
                [line.rstrip('\n') for line in open(options.to_user)])
            fromUser = random.choice(
                [line.rstrip('\n') for line in open(options.from_user)])
            spUser = random.choice(
                [line.rstrip('\n') for line in open(options.sp_user)])
            userAgent = random.choice(
                [line.rstrip('\n') for line in open(options.user_agent)])

            pkt = IP(dst=options.target_network)
            client = pkt.src

            if options.random and not options.library:
                client = utilities.randomIPAddress()
            if options.manual and not options.library:
                client = random.choice([
                    line.rstrip('\n') for line in open(options.manual_ip_list)
                ])
            if options.subnet and not options.library:
                client = utilities.randomIPAddressFromNetwork(
                    client_ip, client_netmask, False)
            send_protocol = "scapy"
            if options.library:
                send_protocol = "socket"

            sip = sip_packet.sip_packet(str(message_type),
                                        str(options.target_network),
                                        str(options.dest_port), str(client),
                                        str(fromUser), str(toUser),
                                        str(userAgent), str(spUser),
                                        send_protocol)
            sip.generate_packet()
            i += 1
            utilities.printProgressBar(i, int(options.counter), "Progress: ")
        except (KeyboardInterrupt):
            utilities.promisc("off", conf.iface)
            print("Exiting traffic generation...")
            raise SystemExit

    print((
        "\033[31m[!] DoS simulation finished and {0} packet sent to {1}...\033[0m"
        .format(str(i), str(options.target_network))))
    utilities.promisc("off", conf.iface)
from time import sleep
from utilities import printProgressBar
import sys

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=50)
for i, item in enumerate(items):
    # Do stuff...
    sleep(0.1)
    # Update Progress Bar
    printProgressBar(i + 1,
                     l,
                     prefix='Progress:',
                     suffix='Complete',
                     length=50)
    sys.stdout.flush()
Пример #6
0
def track(image_dir_path, s_initial):

    image_name = "trackedFrame_"

    # SET NUMBER OF PARTICLES
    N = 100

    # CREATE INITIAL PARTICLE MATRIX 'S' (SIZE 6xN)
    S_temp = (s_initial) * np.ones((N, 1))
    S = predict_particles(np.transpose(S_temp))

    # LOAD FIRST IMAGE
    I = cv2.imread(image_dir_path + os.sep + "frame_001.jpg")

    # COMPUTE NORMALIZED HISTOGRAM
    q = comp_norm_hist(I, s_initial)

    # COMPUTE NORMALIZED WEIGHTS (W) AND PREDICTOR CDFS (C)
    W = np.zeros(shape=(N, 1))
    C = np.zeros(shape=(N, 1))

    for i in range(N):
        W[i] = comp_bat_dist(comp_norm_hist(I, S[:, i]), q)

    W = W / np.sum(W)
    C[0] = W[0]
    for i in range(1, N):
        C[i] = C[i - 1] + W[i]

    images_processed = 1

    # MAIN TRACKING LOOP
    image_name_list = os.listdir(image_dir_path)
    length = len(image_name_list)

    for index, image_name in enumerate(image_name_list[1:]):

        printProgressBar(index, length)

        S_prev = S

        # LOAD NEW IMAGE FRAME
        image_path = image_dir_path + os.sep + image_name
        I = cv2.imread(image_path)

        # plt.imshow(I)
        # plt.show()

        # SAMPLE THE CURRENT PARTICLE FILTERS
        S_next_tag = sample_particles(S_prev, C)

        # PREDICT THE NEXT PARTICLE FILTERS (YOU MAY ADD NOISE)
        S = predict_particles(S_next_tag)

        # COMPUTE NORMALIZED WEIGHTS (W) AND PREDICTOR CDFS (C)

        W = np.zeros(shape=(N, 1))
        C = np.zeros(shape=(N, 1))

        for k in range(N):
            W[k] = comp_bat_dist(comp_norm_hist(I, S[:, k]), q)

        W = W / np.sum(W)
        C[0] = W[0]
        for k in range(1, N):
            C[k] = C[k - 1] + W[k]

        # CREATE DETECTOR PLOTS
        images_processed += 1
        show_particles(I, S, W, images_processed, image_name)

    comp_norm_hist(I, s_initial)
Пример #7
0
def trimap(video_input):
    cap = cv2.VideoCapture(video_input)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    output_file = "binary.avi"
    frame_num = 0
    if not os.path.exists(frames_folder):
        os.makedirs(frames_folder)

    while cap.isOpened():  # play the video by reading frame by frame
        ret, frame = cap.read()

        printProgressBar(frame_num, total_frames)

        if (ret == True):
            frame1 = frame
            image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            ret, thresh = cv2.threshold(image, 145, 255, cv2.THRESH_BINARY_INV)
            kernel1 = np.ones((12, 12), np.uint8)
            erosion = cv2.erode(thresh, kernel1, iterations=1)
            # cv2.imshow("AfterErosion", erosion)

            kernel2 = np.ones((3, 3), np.uint8)
            dilation = cv2.dilate(erosion, kernel2, iterations=2)
            # cv2.imshow("AfterDilation", dilation)

            image, contours, hierarchy = cv2.findContours(
                dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
            # plt.imshow(image)
            # plt.show()

            #sort contours
            sorted_ctrs = sorted(contours,
                                 key=lambda ctr: cv2.boundingRect(ctr)[1])

            mask = np.zeros_like(
                frame1
            )  # Create mask where white is what we want, black otherwise
            cv2.drawContours(mask, sorted_ctrs, 0, (255, 255, 255),
                             -1)  # Draw filled contour in mask
            out = np.zeros_like(
                frame1)  # Extract out the object and place into output image
            out[mask == 255] = [255]

            image1 = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY)

            # noise removal
            kernel = np.ones((5, 5), np.uint8)
            opening = cv2.morphologyEx(image1,
                                       cv2.MORPH_OPEN,
                                       kernel,
                                       iterations=1)

            # sure background area
            sure_bg = cv2.dilate(opening, kernel, iterations=1)

            # Finding sure foreground area
            sure_fg = cv2.erode(opening, kernel, iterations=1)
            # cv2.imshow("foreground", sure_fg)

            # Finding unknown region
            sure_fg = np.uint8(sure_fg)
            unknown = cv2.subtract(sure_bg, sure_fg)
            ret, thresh = cv2.threshold(unknown, 240, 255, cv2.THRESH_BINARY)

            unknown[thresh == 255] = 127
            #cv2.imshow("unknown", unknown)

            final_mask = sure_fg + unknown
            # cv2.imshow("final_mask", final_mask)
            plt.imsave(f"{frames_folder}/trimap_mask_{frame_num+1:03d}",
                       final_mask,
                       cmap="gray")

            frame_num += 1

            if cv2.waitKey(1) & 0xFF == ord('q'):  # press q to quit
                break
        else:
            break
            if cv2.waitKey(1) == ord('q'): break

    plt.imsave(f"{frames_folder}/trimap_mask_{frame_num+1:03d}",
               final_mask,
               cmap="gray")
    cap.release()
    cv2.destroyAllWindows

    # create the video from the new trimap frames
    create_video_from_image_folder(frames_folder,
                                   output_file,
                                   shape=(1280, 720))

    return frames_folder, output_file
Пример #8
0
def main():
    """ Main function """

    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-td',
                            action='append',
                            dest='tempdirs',
                            default=[],
                            required=True,
                            help="Paths to template directories")
    arg_parser.add_argument("-v",
                            action='store',
                            dest="videofile",
                            required=False,
                            help="Path to the video file")
    args = arg_parser.parse_args()

    check.check_init(args)

    DetectorD.item_types = len(args.tempdirs)

    for i in range(0, DetectorD.item_types):
        obj_name = args.tempdirs[i].split('/')
        DetectorD.item_list.append(Item(obj_name[2], 1))
        DetectorD.item_list[i].template_processing(args.tempdirs[i])

    Config.number_of_frame = 0
    Config.frame_count = 0
    fvs = None

    if args.videofile is None:
        fvs = WebcamVideoStream(src=0).start()
    else:
        fvs = FileVideoStream(args.videofile).start()
        time.sleep(1.0)
        cap = cv2.VideoCapture(args.videofile)
        Config.number_of_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        try:
            fvs = FileVideoStream(args.videofile).start()
            time.sleep(1.0)

            Config.number_of_frame = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        except BaseException:
            print("Error in checking the path to the video file.")
            print("Please check the path to the video file.")
            return

    frame = fvs.read()
    hheight, wwidth, _ = frame.shape
    writer = cv2.VideoWriter(Config.OUTPUT_FILE,
                             cv2.VideoWriter_fourcc(*'PIM1'), 25,
                             (wwidth, hheight), True)

    if args.videofile is not None:
        printProgressBar(0,
                         0,
                         Config.number_of_frame,
                         prefix='Progress:',
                         suffix='Complete',
                         length=50)

    total_frames = 0

    vidflag = False
    webflag = True
    if args.videofile is None:
        vidflag = True
        webflag = True
    else:
        vidflag = fvs.more()
        webflag = False

    while vidflag:
        total_frames += 1
        if total_frames % 2 == 0:
            # taking every other frame
            pass

        #### LIST RESET ####
        DetectorD.reset_max_loc_val()

        WindowW.reset_cartesian_list()

        WindowW.reset_is_drawn()
        WindowW.reset_pixel_pos()

        frame = fvs.read()
        frame = rescale_frame(frame, Config.degradation_percent)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.medianBlur(gray, 5)

        for i in range(0, DetectorD.item_types):
            DetectorD.item_list[i].found = []
            for j in range(len(DetectorD.item_list[i].templates)):
                DetectorD.item_list[i].found.append(None)

        for scale in np.linspace(0.2, 1.0, 20)[::-1]:

            resized = imutils.resize(gray, width=int(gray.shape[1] * scale))
            ratio = gray.shape[1] / float(resized.shape[1])

            break_flag = 0

            for i in range(0, DetectorD.item_types):
                for j in range(len(DetectorD.item_list[i].templates)):
                    if (resized.shape[0] < DetectorD.item_list[i].height[j]
                            or resized.shape[1] <
                            DetectorD.item_list[i].width[j]):
                        break_flag = 1

            if break_flag == 1:
                break

            edged = cv2.Canny(resized, 50, 100)
            edged = cv2.dilate(edged, None, iterations=1)
            edged = cv2.erode(edged, None, iterations=1)

            cv2.imshow('Edge Template', edged)

            DetectorD.reset_max_loc_val()
            DetectorD.reset_item_threads()
            for i in range(0, DetectorD.item_types):
                DetectorD.max_val.append(1)
                DetectorD.max_loc.append(1)
                DetectorD.item_threads.append(
                    threading.Thread(target=DetectorD.item_threading,
                                     args=(
                                         ratio,
                                         edged,
                                         DetectorD.item_list[i].templates,
                                         DetectorD.item_list[i].found,
                                         i,
                                     )))

            DetectorD.spawn_item_threads()

        for i in range(0, DetectorD.item_types):
            (ret_startx, ret_starty,
             ret_endx, ret_endy) = WindowW.localise_match(
                 DetectorD.item_list[i].found, DetectorD.max_loc[i],
                 DetectorD.item_list[i].found, DetectorD.item_list[i].height,
                 DetectorD.item_list[i].width, ratio)
            WindowW.startx_coord.append(ret_startx)
            WindowW.starty_coord.append(ret_starty)
            WindowW.endx_coord.append(ret_endx)
            WindowW.endy_coord.append(ret_endy)

        ret_frame = None
        for i in range(0, DetectorD.item_types):
            ret_isdrawn, index_of_max, ret_frame = WindowW.draw_match(
                frame, DetectorD.max_val[i], Config.thresh_max, i,
                DetectorD.item_list[i].article)
            WindowW.is_drawn.append(ret_isdrawn)
            WindowW.pixel_pos.append(index_of_max)

        ret_frame = rescale_frame(ret_frame, Config.restoration_percent)
        writer.write(ret_frame)

        for i in range(0, DetectorD.item_types):
            if WindowW.is_drawn[i]:
                DetectorD.item_list[i].x_abscissa = (
                    WindowW.startx_coord[i][WindowW.pixel_pos[i]] +
                    WindowW.endx_coord[i][WindowW.pixel_pos[i]]) / 2
                DetectorD.item_list[i].y_ordinate = (
                    WindowW.starty_coord[i][WindowW.pixel_pos[i]] +
                    WindowW.endy_coord[i][WindowW.pixel_pos[i]]) / 2
            else:
                DetectorD.item_list[i].x_abscissa = None
                DetectorD.item_list[i].y_ordinate = None

        for i in range(0, DetectorD.item_types):
            DetectorD.item_list[i].log_position()

        Config.frame_count += 1
        fps = Config.fps.fps()
        if args.videofile is not None:
            printProgressBar(fps,
                             Config.frame_count + 1,
                             Config.number_of_frame,
                             prefix='Progress:',
                             suffix='Complete',
                             length=50)

        Config.fps.update()

        if webflag is False:
            vidflag = fvs.more()

        if cv2.waitKey(1) == 27:
            break

    Config.fps.stop()
    cap.release()
    writer.release()
    cv2.destroyAllWindows()

    if fvs:
        fvs.stop()
Пример #9
0
def add_background_image(trimap_folder, input_vid_path, background_image_path):
    im_shape = (720, 1280, 3)
    output_file_path = "matted.avi"
    input_cap = cv2.VideoCapture(input_vid_path)
    bg_image = cv2.imread(background_image_path)
    bg_image = cv2.resize(bg_image,
                          dsize=(1280, 720),
                          interpolation=cv2.INTER_CUBIC)

    alpha = 0.75

    # plt.imshow(bg_image)
    # plt.show()

    fouorcc = cv2.VideoWriter_fourcc(*"MJPG")

    image_name_list = os.listdir(trimap_folder)
    length = len(image_name_list)

    input_ret, input_frame = input_cap.read()
    vid_writer = cv2.VideoWriter(output_file_path, fouorcc, 30,
                                 (input_frame.shape[1], input_frame.shape[0]))

    frame_num = 0
    total_frames = int(input_cap.get(cv2.CAP_PROP_FRAME_COUNT))

    while input_cap.isOpened():
        trimap_frame = cv2.imread(trimap_folder + '/' +
                                  image_name_list[frame_num])

        if (input_ret):

            ut.printProgressBar(frame_num + 1, total_frames)

            # initialize new image to be written
            out_frame = np.zeros(im_shape, dtype=np.uint8)

            # iterate over all pixels
            for row in range(out_frame.shape[0]):
                for col in range(out_frame.shape[1]):
                    if trimap_frame[row, col].max() > 200:
                        out_frame[row, col] = input_frame[row, col]
                    elif 100 < np.average(trimap_frame[row, col]) < 150:
                        out_frame[row, col] = alpha * bg_image[row, col] + (
                            1 - alpha) * input_frame[row, col]
                    else:
                        out_frame[row, col] = bg_image[row, col]
                    # print("d")
            #     check if binary mask value is 0, if it is take the value from the background image,
            #     otherwise from the frame

            # cv2.imshow('BGSUB', out_frame)
            # plt.imshow(out_frame)
            # plt.show()
            vid_writer.write(out_frame)
            # plt.imshow(out_frame)
            # plt.show()
            frame_num += 1

            input_ret, input_frame = input_cap.read()

            if cv2.waitKey(1) & 0xFF == ord('q'):  # press q to quit
                break
        else:
            break

    vid_writer.release()
    input_cap.release()
    cv2.destroyAllWindows()

    return output_file_path