cl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, const size_t *global_work_offset, const size_t *global_work_size, const size_t *local_work_size, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { if(command_queue == NULL || command_queue == (cl_command_queue)0) { return CL_INVALID_COMMAND_QUEUE; } if(kernel == NULL || kernel == (cl_kernel)0) { return CL_INVALID_KERNEL; } PRINT_DEBUG("\n====\tCreating Event \t====\n"); cl_event new_event = createNewEvent(command_queue, CL_COMMAND_NDRANGE_KERNEL, num_events_in_wait_list, event_wait_list); setNDRangeEvent(new_event, kernel, work_dim, global_work_offset, global_work_size, local_work_size); // clReleaseEvent(new_event); // free(new_event); PRINT_DEBUG("\n====\tEnqueuing kernel \t====\n"); //Will only do one dimension if(work_dim != 1) { return CL_INVALID_WORK_DIMENSION; } cl_program program = kernel->kernel_program; PRINT_DEBUG("NDRange: Program location %p\n", program); PRINT_DEBUG("NDRange: Program elefs location %p\n", program->program_elfs); addEventToCommandQueue(new_event, command_queue); if(num_events_in_wait_list > 0) { // Do appropriate stuff here for event wait list } PRINT_DEBUG("\n====\tKernel Enqueued \t====\n"); return CL_SUCCESS; }
/** * Prepares the stack for a 64-bit guest and places the arguments in the correct * register / stack locations. * * Arguments on 64-bit systems: * 1st ARG: %RDI * 2nd ARG: %RSI * 3rd ARG: %RDX * 4th ARG: %RCX * 5th ARG: %R8 * 6th ARG: %R9 * 7th ARG - nth ARG: on stack from right to left * * @param inject The injection structure of the module that is injected. * @param virt_stack A pointer to the virtual address of the memory area * that was reserved for the stack of the module. */ void prepareStack64(struct kvm_vcpu *vcpu, struct injection *inject, u64 *virt_stack) { u64 phys_stack = 0; struct x86_exception error; struct injection_arg *arg = NULL; unsigned int i = 0; int ret = 0; enum kvm_reg reg; // Do we actually have arguments? if (inject->args) { // Move all data to the stack that cannot be directly passed as an argument // such as strings and structures. for (i = 0; i < inject->args->argc; ++i) { arg = get_next_arg(inject, arg); if (!is_immediate(arg)) { // Copy the data to the stack PRINT_DEBUG("Writing data of argument %d with type %d and size %d to 0x%llx\n", i, arg->type, arg->size, *virt_stack - arg->size); // Update address (*virt_stack) -= arg->size; arg->data_on_stack = (void *)(*virt_stack); // Write phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, (*virt_stack), 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, get_arg_data(inject, arg), arg->size); if(ret < 0) { PRINT_ERROR("An error (code: %d) occurred while writing the argument %d to memory!\n", ret, i); return; } } } // Place arguments into the correct register / stack locations arg = NULL; for (i = inject->args->argc; i > 0 ; --i) { arg = get_prev_arg(inject, arg); if (i >= 7) { // Arg goes on the stack // ToDo: We just fix this to 8 byte here, but the size of the arg // may actually be shorter (*virt_stack) -= 8; phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, (*virt_stack), 0, &error); if (is_immediate(arg)) { PRINT_DEBUG("Writing argument %d with type %d and size %d to the stack 0x%llx\n", i, arg->type, arg->size, *virt_stack); ret = kvm_write_guest(vcpu->kvm, phys_stack, get_arg_data(inject, arg), arg->size); } else { PRINT_DEBUG("Writing pointer 0x%lx to argument %d with type %d and size %d to the stack 0x%llx\n", (unsigned long)arg->data_on_stack, i, arg->type, arg->size, *virt_stack); ret = kvm_write_guest(vcpu->kvm, phys_stack, &arg->data_on_stack, 8); } if(ret < 0) { PRINT_ERROR("An error (code: %d) occurred while writing the argument %d " "to the stack!\n", ret, i); return; } } else { // Arg goes into a register switch (i) { case 1: reg = VCPU_REGS_RDI; break; case 2: reg = VCPU_REGS_RSI; break; case 3: reg = VCPU_REGS_RDX; break; case 4: reg = VCPU_REGS_RCX; break; case 5: reg = VCPU_REGS_R8; break; case 6: reg = VCPU_REGS_R9; break; default: PRINT_ERROR("Argument is not between one and six!\n"); } if (is_immediate(arg)) { PRINT_DEBUG("Writing argument %d with value 0x%lx, type %d, and size %d to register %d\n", i, (unsigned long)arg->data, arg->type, arg->size, reg); kvm_register_write(vcpu, reg, *((unsigned long *)get_arg_data(inject, arg))); } else { PRINT_DEBUG("Writing pointer 0x%lx to argument %d with type %d and size %d to register %d\n", (unsigned long)arg->data_on_stack, i, arg->type, arg->size, reg); kvm_register_write(vcpu, reg, (unsigned long)arg->data_on_stack); } } } } // Add Offset to stack so the shellcode can operate (*virt_stack) -= STACK_AREA_SC ; // Place the original kernel pointer on the stack (*virt_stack) -= 8; // Write address of the original kernel stack on the new stack phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, (*virt_stack), 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.regs.rsp, 8); kvm_register_write(vcpu, VCPU_REGS_RSP, (*virt_stack)); }
/* * Handle a halt instruction that can indicate that the executing code just finished. */ int XTIER_inject_handle_hlt(struct kvm_vcpu *vcpu) { // Stop execution time XTIER_inject_end_time_measurement(&_starttime, &_XTIER_performance.total_module_exec_time); // Get Time XTIER_inject_begin_time_measurement(&_starttime); PRINT_INFO("Handling HLT Exit...\n"); //PRINT_DEBUG("RAX: 0x%llx\n", kvm_register_read(vcpu, VCPU_REGS_RAX)); // Remove Mappings XTIER_memory_remove_mappings_pid(vcpu, XTIER_INJECTION_PID); // Disable Exit XTIER_disable_hlt_exiting(); // Disable Exception Exiting XTIER_disable_interrupt_exiting(vcpu); // Restore state restoreVMState(vcpu); // Reset Reinjection _XTIER_inject.reinject = 0; // Reset faults if(!_XTIER_inject.injection_fault) _injection_faults = 0; // Set Mode if(!_XTIER_inject.event_based) { _XTIER.mode &= ~((u64)XTIER_CODE_INJECTION); } else { // Reenable hook if the was no injection fault if(!_XTIER_inject.injection_fault) XTIER_inject_enable_hook(vcpu, &_XTIER_inject_current_injection); } // Get Removal Time XTIER_inject_end_time_measurement(&_starttime, &_XTIER_performance.total_module_unload_time); // Pause execution ? if(_XTIER_inject.exit_after_injection && !_XTIER_inject_current_injection.auto_inject && !_XTIER_inject_current_injection.time_inject && !_XTIER_inject_current_injection.event_based) { PRINT_DEBUG("Exit after injection is set! Returning to userspace...\n"); vcpu->run->exit_reason = XTIER_EXIT_REASON_INJECT_FINISHED; return 0; } else { //vcpu->run->exit_reason = XTIER_EXIT_REASON_INJECT_FINISHED; //return 0; PRINT_DEBUG("Exit after injection is _NOT_ set! Resuming...\n"); return 1; } }
rp_frame * frame_read (char *str, rp_screen *screen) { Window w = 0L; rp_window *win; rp_frame *f; char *tmp, *d; int s_width = -1; int s_height = -1; /* Create a blank frame. */ f = xmalloc (sizeof (rp_frame)); init_frame(f); PRINT_DEBUG(("parsing '%s'\n", str)); d = xstrdup(str); tmp = strtok_ws (d); /* Verify it starts with '(frame ' */ if (strcmp(tmp, "(frame")) { PRINT_DEBUG(("Doesn't start with '(frame '\n")); free (d); free (f); return NULL; } /* NOTE: there is no check to make sure each field was filled in. */ tmp = strtok_ws(NULL); while (tmp) { if (!strcmp(tmp, ":number")) read_slot(f->number); else if (!strcmp(tmp, ":x")) read_slot(f->x); else if (!strcmp(tmp, ":y")) read_slot(f->y); else if (!strcmp(tmp, ":width")) read_slot(f->width); else if (!strcmp(tmp, ":height")) read_slot(f->height); else if (!strcmp(tmp, ":screenw")) read_slot(s_width); else if (!strcmp(tmp, ":screenh")) read_slot(s_height); else if (!strcmp(tmp, ":window")) read_slot(w); else if (!strcmp(tmp, ":last-access")) read_slot(f->last_access); else if (!strcmp(tmp, ":dedicated")) { /* f->dedicated is unsigned, so read into local variable. */ long dedicated; read_slot(dedicated); if (dedicated <= 0) f->dedicated = 0; else f->dedicated = 1; } else if (!strcmp(tmp, ")")) break; else PRINT_ERROR(("Unknown slot %s\n", tmp)); /* Read the next token. */ tmp = strtok_ws(NULL); } if (tmp) PRINT_ERROR(("Frame has trailing garbage\n")); free (d); /* adjust x, y, width and height to a possible screen size change */ if (s_width > 0) { f->x = (f->x*screen->width)/s_width; f->width = (f->width*screen->width)/s_width; } if (s_height > 0) { f->y = (f->y*screen->height)/s_height; f->height = (f->height*screen->height)/s_height; } /* Perform some integrity checks on what we got and fix any problems. */ if (f->number <= 0) f->number = 0; if (f->x <= 0) f->x = 0; if (f->y <= 0) f->y = 0; if (f->width <= defaults.window_border_width*2) f->width = defaults.window_border_width*2 + 1; if (f->height <= defaults.window_border_width*2) f->height = defaults.window_border_width*2 + 1; if (f->last_access < 0) f->last_access = 0; /* Find the window with the X11 window ID. */ win = find_window_in_list (w, &rp_mapped_window); if (win) f->win_number = win->number; else f->win_number = EMPTY; return f; }
void core_tests(void) { int i = 0; while (1) { PRINT_IMPORTANT("waiting..."); //sleep(10); //char recv_data[4000]; //gets(recv_data); fgetc(stdin); //wait until user enters PRINT_IMPORTANT("active"); i++; if (i == 1) { metadata *meta = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta); uint32_t host_ip = IP4_ADR_P2H(192,168,1,8); uint32_t host_port = 55454; uint32_t dst_ip = IP4_ADR_P2H(192,168,1,3); uint32_t dst_port = 44444; uint32_t ttl = 64; uint32_t tos = 64; secure_metadata_writeToElement(meta, "send_src_ip", &host_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_src_port", &host_port, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_dst_ip", &dst_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_dst_port", &dst_port, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_ttl", &ttl, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_tos", &tos, META_TYPE_INT32); uint32_t src_index = 1; uint32_t dst_index = 2; struct finsFrame *ff = (struct finsFrame *) secure_malloc(sizeof(struct finsFrame)); ff->dataOrCtrl = FF_DATA; ff->destinationID = dst_index; ff->metaData = meta; ff->dataFrame.directionFlag = DIR_UP; ff->dataFrame.pduLength = 10; ff->dataFrame.pdu = (uint8_t *) secure_malloc(10); PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[src_index]->name, overall->modules[dst_index]->name); module_to_switch(overall->modules[src_index], ff); } if (0) { PRINT_DEBUG("Sending ARP req"); metadata *meta_req = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta_req); uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //uint32_t dst_ip = IP4_ADR_P2H(172, 31, 54, 169); uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 20); //uint32_t src_ip = IP4_ADR_P2H(172, 31, 50, 160); secure_metadata_writeToElement(meta_req, "dst_ip", &dst_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta_req, "src_ip", &src_ip, META_TYPE_INT32); struct finsFrame *ff_req = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame)); ff_req->dataOrCtrl = FF_CONTROL; ff_req->destinationID = 1; //arp ff_req->metaData = meta_req; ff_req->ctrlFrame.sender_id = 4; //ipv4 ff_req->ctrlFrame.serial_num = gen_control_serial_num(); ff_req->ctrlFrame.opcode = CTRL_EXEC; ff_req->ctrlFrame.param_id = 0; //EXEC_ARP_GET_ADDR; ff_req->ctrlFrame.data_len = 0; ff_req->ctrlFrame.data = NULL; PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff_req, meta_req, overall->modules[0]->name, overall->modules[1]->name); module_to_switch(overall->modules[0], ff_req); } if (i == 2) { PRINT_DEBUG("Sending data"); metadata *meta_req = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta_req); uint32_t ether_type = 0x0800; //ipv4 int32_t if_index = 3; //wlan0 uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 5); //wlan0 uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //gw uint32_t src_index = 2; uint32_t dst_index = 1; secure_metadata_writeToElement(meta_req, "send_ether_type", ðer_type, META_TYPE_INT32); secure_metadata_writeToElement(meta_req, "send_if_index", &if_index, META_TYPE_INT32); secure_metadata_writeToElement(meta_req, "send_src_ipv4", &src_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta_req, "send_dst_ipv4", &dst_ip, META_TYPE_INT32); struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame)); ff->dataOrCtrl = FF_DATA; ff->destinationID = dst_index; //arp ff->metaData = meta_req; ff->dataFrame.directionFlag = DIR_DOWN; ff->dataFrame.pduLength = 100; ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength); memset(ff->dataFrame.pdu, 59, ff->dataFrame.pduLength); PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta_req, overall->modules[src_index]->name, overall->modules[dst_index]->name); module_to_switch(overall->modules[src_index], ff); } if (0) { PRINT_DEBUG("Sending data"); metadata *meta = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta); uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 4); //wlan0 uint32_t src_port = 6666; uint32_t dst_ip = IP4_ADR_P2H(192, 168, 1, 1); //gw uint32_t dst_port = 5555; secure_metadata_writeToElement(meta, "send_src_ipv4", &src_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_src_port", &src_port, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_dst_ipv4", &dst_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_dst_port", &dst_port, META_TYPE_INT32); uint32_t dst_index = 8; struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame)); ff->dataOrCtrl = FF_DATA; ff->destinationID = dst_index; //arp ff->metaData = meta; ff->dataFrame.directionFlag = DIR_DOWN; ff->dataFrame.pduLength = 10; ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength); memset(ff->dataFrame.pdu, 65, ff->dataFrame.pduLength); PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[0]->name, overall->modules[dst_index]->name); module_to_switch(overall->modules[0], ff); } if (0) { PRINT_DEBUG("Sending data"); metadata *meta = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta); uint32_t family = AF_INET; uint32_t src_ip = IP4_ADR_P2H(192, 168, 1, 15); //wlan0 uint32_t dst_ip = IP4_ADR_P2H(172, 168, 1, 1); //gw secure_metadata_writeToElement(meta, "send_family", &family, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_src_ipv4", &src_ip, META_TYPE_INT32); secure_metadata_writeToElement(meta, "send_dst_ipv4", &dst_ip, META_TYPE_INT32); uint32_t dst_index = 4; struct finsFrame *ff = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame)); ff->dataOrCtrl = FF_DATA; ff->destinationID = dst_index; ff->metaData = meta; ff->dataFrame.directionFlag = DIR_DOWN; ff->dataFrame.pduLength = 10; ff->dataFrame.pdu = (uint8_t *) secure_malloc(ff->dataFrame.pduLength); memset(ff->dataFrame.pdu, 65, ff->dataFrame.pduLength); PRINT_IMPORTANT("sending: ff=%p, meta=%p, src='%s' to dst='%s'", ff, meta, overall->modules[0]->name, overall->modules[dst_index]->name); module_to_switch(overall->modules[0], ff); } //break; } }
// Request a checkpoint of the local process // The return value is // - negative in case of error // - zero when successfully resuming after the checkpoint // - positive when restarting from the checkpoint static int request_checkpoint( const char* filename ) { cr_checkpoint_args_t cr_file_args; cr_checkpoint_handle_t cr_handle; int cr_fd = -1; int return_code = 0; // Check current state CR_state_lock(); if ( cr_state != CR_READY ) { switch( cr_state ) { case CR_REQUEST_CHECKPOINT: case CR_CHECKPOINT: { PRINT_ERROR("Error: Already checkpointing... (cr_state=%d)\n", cr_state); return_code = -10; break; } default: { PRINT_ERROR("Error: Not ready to checkpoint... (cr_state=%d)\n", cr_state); return_code = -11; break; } } CR_state_unlock(); goto error; } else { // All is ok, proceed to checkpoint request CR_state_transition_nolock( CR_REQUEST_CHECKPOINT ); } CR_state_unlock(); cr_fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0600); if ( cr_fd < 0 ) { PRINT_ERROR_ERRNO("Failed to open checkpoint file '%s'", errno, filename); return_code = -1; goto error; } int ret = cr_initialize_checkpoint_args_t(&cr_file_args); if (ret < 0) { PRINT_ERROR("BLCR call cr_initialize_checkpoint_args_t() failed\n"); return_code = -2; goto error; } cr_file_args.cr_scope = CR_SCOPE_PROC; cr_file_args.cr_target = getpid(); cr_file_args.cr_fd = cr_fd; cr_file_args.cr_signal = 0; cr_file_args.cr_timeout = 0; cr_file_args.cr_flags &= ~CR_CHKPT_DUMP_ALL; // Save None // Request a checkpoint PRINT_DEBUG( DEBUG_FT_verbose, "cr_request_checkpoint() with file '%s'\n", filename ); ret = cr_request_checkpoint(&cr_file_args, &cr_handle); PRINT_DEBUG( DEBUG_FT_verbose>1, "cr_request_checkpoint() returned %d\n", ret ); if (ret < 0) { PRINT_ERROR("BLCR call cr_request_checkpoint() failed with error %d: %s\n", errno, cr_strerror(errno)); return_code = -3; goto error; } // Wait for the end of the checkpoint, and retry while interrupted PRINT_DEBUG( DEBUG_FT_verbose, "cr_poll_checkpoint()\n" ); do { ret = cr_poll_checkpoint(&cr_handle, NULL); } while (ret == CR_POLL_CHKPT_ERR_PRE && errno == EINTR); PRINT_DEBUG( DEBUG_FT_verbose>1, "cr_poll_checkpoint() returned %d\n", ret ); // Check the result of the checkpoint if (ret == CR_POLL_CHKPT_ERR_POST && errno == CR_ERESTARTED) { // We are restarting, ignore this error code // The checkpoint file is not opened at restart cr_fd = -1; // Positive value means restart return_code = 1; return return_code; } else if (ret < 0) { // Checkpoint failed PRINT_ERROR("BLCR call cr_poll_checkpoint() failed with error %d: %s\n", errno, cr_strerror(errno)); // Negative value for failure return_code = -4; goto error; } else if (ret == 0) { // 0 means that the checkpoint is in progress // It should never happen because we don't specify any timeout when calling cr_poll_checkpoint() ASSERT_MSG( 0==1, "Internal error\n"); } // Close the checkpoint file ASSERT_MSG( cr_fd>=0, "Internal error\n"); ret = close(cr_fd); cr_fd = -1; PRINT_DEBUG( DEBUG_FT_verbose, "close() returned %d\n", ret ); if (ret < 0) { PRINT_ERROR_ERRNO("Failed to close file '%s'", errno, filename); return_code = -5; goto error; } // If we are here, it means that everything went good ASSERT_MSG( return_code==0, "Internal error\n"); return return_code; error: // An error happened, cleanup and return properly if ( cr_fd >= 0 ) { close( cr_fd ); cr_fd = -1; } // If the request failed, ie not the checkpoint itself // Restore the CR_READY state CR_state_lock(); if ( cr_state == CR_REQUEST_CHECKPOINT ) { CR_state_transition_nolock( CR_READY ); } CR_state_unlock(); return return_code; }
struct ip4_routing_table * IP4_get_routing_table() { int nlmsg_len; struct nlmsghdr* msg; char receive_buffer[IP4_NETLINK_BUFF_SIZE]; char * receive_ptr; unsigned int sock; struct ip4_route_request route_req; struct ip4_routing_table * routing_table; struct ip4_routing_table * current_table_entry; unsigned int pid = (uint32_t) getpid(); unsigned int seq = (uint32_t) getppid(); if ((sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) == -1) { PRINT_DEBUG("couldn't open NETLINK_ROUTE socket"); return NULL; } /* prepare netlink message header*/ route_req.msg.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); route_req.msg.nlmsg_type = RTM_GETROUTE; route_req.msg.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; route_req.msg.nlmsg_seq = seq; route_req.msg.nlmsg_pid = pid; route_req.rt.rtm_family = AF_INET; route_req.rt.rtm_dst_len = IP4_ALEN * 8;// must be supplied in bits route_req.rt.rtm_src_len = 0; route_req.rt.rtm_table = RT_TABLE_MAIN; route_req.rt.rtm_protocol = RTPROT_UNSPEC; route_req.rt.rtm_scope = RT_SCOPE_UNIVERSE; route_req.rt.rtm_type = RTN_UNSPEC; route_req.rt.rtm_flags = 0; // write the message to our netlink socket int result = send(sock, &route_req, sizeof(route_req), 0); if (result < 0) { PRINT_ERROR("Routing table request send error."); return NULL; } memset(receive_buffer, 0, IP4_NETLINK_BUFF_SIZE); receive_ptr = receive_buffer; nlmsg_len = 0; while (1) { int msg_len = recv(sock, receive_ptr, IP4_NETLINK_BUFF_SIZE, 0); if (msg_len < 0) { PRINT_ERROR("recv() error."); return NULL; //ERROR } msg = (struct nlmsghdr *) receive_ptr; if (msg->nlmsg_type == NLMSG_DONE) { break; } for (; 0 != NLMSG_OK(msg, msg_len); msg = NLMSG_NEXT(msg, msg_len)) { if (msg->nlmsg_seq == seq) { if (routing_table == NULL) { routing_table = current_table_entry = parse_nlmsg(msg); } else { current_table_entry->next_entry = parse_nlmsg(msg); if (current_table_entry->next_entry != NULL) { current_table_entry = current_table_entry->next_entry; } } } receive_ptr = receive_ptr + msg_len; nlmsg_len = nlmsg_len + msg_len; } } return routing_table; }
/** * Funkcja pobiera certyfikat z formularza wczytanego do struktury xmlDocPtr i * zapisuje go do bufora generycznego. * \param document Sparsowany formularz XML. * \param certyfikat Wskaźnik na bufor generyczny. Pod wskazanym adresem zapisany * zostanie zdekodowany certyfikat. Potrzebna pamięc zostanie zaalokowana. * * \retval 0 Wszystko OK. * \retval -1 Nie można pobrać z formularza certyfikatu. Może podano zły formularz? * \retval -2 Nie można zdekodować certyfikatu. * */ long _getCertificateFromXML(xmlDocPtr *document, GenBuf_t ** certyfikat) { long status = 0; int si_temp = 0; char *xpath = NULL; /*ściezka xpath do certyfikatu*/ char *node_value = NULL; /*zawartość taga ze zbejzowanym certem*/ size_t dlugosc_bufora=0; /*długość rozbejzowanego certyfikatu*/ /*sprawdzamy wywolanie*/ if (document == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (certyfikat == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*certyfikat != NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg; } /*pobieramy certyfikat*/ #ifdef CASA_XADES asprintf(&xpath, "//ds:X509Certificate"); #else asprintf(&xpath, "//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate"); #endif status = bmdxml_get_node_value_by_xpath (*document, (const char *) xpath, &node_value); if (status < 0) { PRINT_DEBUG("Unable to get certificate from the form!\n"); return -1; } /*dodajemy go do genbufa*/ (*certyfikat) = (GenBuf_t*) malloc (sizeof(GenBuf_t)); (*certyfikat)->buf = (char *)spc_base64_decode((unsigned char *)node_value, &dlugosc_bufora, 0, &si_temp); if (si_temp != 0) { PRINT_DEBUG("Error while decoding certificate!\n"); return -2; } if (dlugosc_bufora <= 5) { PRINT_DEBUG("Decoded buffer has %li length!\n", (long)dlugosc_bufora); return -2; } (*certyfikat)->size = (long)dlugosc_bufora; /*sprzatamy*/ free(xpath); free(node_value); return 0; }
/** * Funkcja porównuje numery seryjne z certyfikatu i z formularza * */ long _compareSerials(char **cert, char **form) { BIGNUM *certGigant = NULL; /*serial z certyfikatu*/ BIGNUM *formGigant = NULL; /*serial z formularza*/ BN_CTX *ctx = NULL; /*kontekst dla numerków*/ char *castrate = NULL; /*serial cert. pozbawiony spacji*/ long equal = -13; long i, j; long len = 0; /*długość numeru seryjnego*/ /*wywolanie funkcji*/ if (cert == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (*cert == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (form == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*form == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } /*kastracja cert*/ len = (long)strlen(*cert); castrate = (char*) malloc (sizeof(char) * len); if (castrate == NULL) { PRINT_ERROR("No memory!\n"); return -13; } for (i = 0, j = 0; i < len; i++) { if ((*cert)[i] != ' ') { castrate[j] = (*cert)[i]; j++; } } castrate[j] = '\0'; /*inicjaliacja numerków*/ certGigant = BN_new(); formGigant = BN_new(); /*ładujemy numerki do BN*/ BN_hex2bn(&certGigant, castrate); BN_dec2bn(&formGigant, *form); /*porównujemy seriale*/ equal = BN_cmp(certGigant, formGigant); /*inicjalizujemy kontekst do BN*/ ctx = BN_CTX_new(); /*sprzatamy*/ free(castrate); BN_CTX_free(ctx); BN_free(certGigant); BN_free(formGigant); return equal; }
/** * Funkcja pobiera numer seryjny i wystawcę certyfikatu z formularza. * \param document Wskaźnik na sparsowany dokument xml. * \param FormSerialNumber Wskaźnik na numer seryjny. String pod ten numer * zostanie zaalokowany, należy go potem zwolnić. * \param FormIssuerName Wskaźnik na nazwę wystawcy. String pod tę nazwę * zostanie zaalokowany, nalezy go potem zwolnić. * * \retval 0 Wszystko OK. * \retval -1 Nie można pobrać numeru seryjnego z formularza. * \retval -2 Nie można pobrać imienia wystawcy z formularza. * */ long _getInfoFromXML(const xmlDocPtr *document, char **FormSerialNumber, char **FormIssuerName) { long status; char *xpath = NULL; /*ściezka xpath do certyfikatu*/ char *node_value = NULL; /*zawartość taga ze zbejzowanym certem*/ if (document == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (FormSerialNumber == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*FormSerialNumber != NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (FormIssuerName == NULL) { PRINT_DEBUG("Wrong argument 3\n"); return ERR_arg+3; } if (*FormIssuerName != NULL) { PRINT_DEBUG("Wrong argument 3\n"); return ERR_arg+3; } /*pobieramy serial*/ #ifdef CASA_XADES asprintf(&xpath, "//X509SerialNumber"); #else asprintf(&xpath, "//ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:IssuerSerial/ds:X509SerialNumber"); #endif status = bmdxml_get_node_value_by_xpath (*document, xpath, &node_value); if (status < 0) { PRINT_DEBUG("Unable to get serial number from the form!\n"); return -1; } asprintf(FormSerialNumber, "%s", node_value); free(node_value); node_value = NULL; free(xpath); xpath = NULL; /*pobieramy IssuerName*/ #ifdef CASA_XADES asprintf(&xpath, "//X509IssuerName"); #else asprintf(&xpath, "//ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:IssuerSerial/ds:X509IssuerName"); #endif status = bmdxml_get_node_value_by_xpath (*document, (const char *) xpath, &node_value); if (status < 0) { PRINT_DEBUG("Unable to get issuer name from the form!\n"); return -2; } asprintf(FormIssuerName, "%s", node_value); free(node_value); node_value = NULL; free(xpath); xpath = NULL; return 0; }
/** * Funkcja dokonuje weryfikacji poprawności złożonego podpisu pod formularzem. * \param[in] mngr Zainicjalizowany menedżer kluczy. * \param[in] buffer Formularz do zweryfikowania. * \param[in] buffer_len Długość weryfikowanego formularza. * * \retval 0 Podpis poprawny. * \retval 1 Podpis niepoprawny. * \retval -1 Nie można przeparsować dokumentu. * \retval -2 Nie znaleziono startowego węzła. * \retval -3 Nie dało się utworzyć kontekstu podpisu. * \retval -4 Nie dało rady zweryfikować podpisu. * */ static long verify_memory(xmlSecKeysMngrPtr mngr, const char* buffer, const long buffer_len) { xmlDocPtr doc = NULL; xmlNodePtr node = NULL; xmlSecDSigCtxPtr dsigCtx = NULL; long ret = -99; assert(mngr); /* load file */ doc = xmlParseMemory(buffer,buffer_len); if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){ PRINT_DEBUG("UNABLE TO PARSE DOCUMENT\n"); ret = -1; goto done; } /* find start node */ node = xmlSecFindNode(xmlDocGetRootElement(doc), xmlSecNodeSignature, xmlSecDSigNs); if(node == NULL) { PRINT_DEBUG("Start node %s not found\n",xmlSecNodeSignature); ret = -2; goto done; } /* create signature context */ dsigCtx = xmlSecDSigCtxCreate(mngr); if(dsigCtx == NULL) { PRINT_DEBUG("Failed to create signature context\n"); ret = -3; goto done; } /* Verify signature */ if(xmlSecDSigCtxVerify(dsigCtx, node) < 0) { PRINT_DEBUG("Error: signature verify failed\n"); ret = -4; goto done; } /* print verification result to stdout */ if(dsigCtx->status == xmlSecDSigStatusSucceeded) { ret = 0; PRINT_DEBUG("XAdES: Signature is OK\n"); } else { ret = 1; PRINT_DEBUG("XAdES: Signature is INVALID\n"); } done: /* cleanup */ if(dsigCtx != NULL) { xmlSecDSigCtxDestroy(dsigCtx); } if(doc != NULL) { xmlFreeDoc(doc); } return(ret); }
/**Funkcja sprawdza, czy certyfikat jest ważny w danym momencie oznaczonym przez timestamp. * \param certyfikat Certyfikat do sprawdzenia. * \param timestamp Znacznik czasu. * */ long isCertificateValid(GenBuf_t **certyfikat, GenBuf_t *timestamp) { long status = -1; char *validNB = NULL;/*początek okresu wazności*/ char *validNA = NULL;/*koniec okresu ważności*/ char *today = NULL;/*dzisiejsza data*/ GenBuf_t *PlainData = NULL; time_t tNB, tNA, tToday; if (certyfikat == NULL || *certyfikat == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (timestamp == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } /*poczatek waznosci*/ status = GetValidityNBFromX509Certificate_time(*certyfikat, &tNB); if (status < 0) { PRINT_DEBUG("Couldn't get validity not before\n"); return -1; } /*koniec waznosci*/ status = GetValidityNAFromX509Certificate_time(*certyfikat, &tNA); if (status < 0) { PRINT_DEBUG("Couldn't get validity not after\n"); return -2; } PRINT_VDEBUG("Getting current date from timestamp...\n"); status = GetGenerationTimeFromTimestamp_time(timestamp, &tToday); if (status < 0) { PRINT_DEBUG("Couldn't get current date and time\n"); return -3; } /*ewentualne wydruki*/ /*PRINT_VDEBUG("Valid not before: %s\n", validNB); PRINT_VDEBUG("Valid not after: %s\n", validNA); PRINT_VDEBUG("Today is: %s\n", today);*/ /*konieczne porównania*/ /*tNB = _to_seconds(validNB); tNA = _to_seconds(validNA); tToday = _to_seconds(today);*/ if (tToday < tNB) { PRINT_DEBUG("Certificate not valid before %s!\n", validNB); return -4; } else if (tToday > tNA) { PRINT_DEBUG("Certificate not valid after %s!\n", validNA); return -5; } free(validNB); free(validNA); free(today); free_gen_buf(&PlainData); return 0; }
/** * Funkcja porównuje zawartość pól X509IssuerName, X509SerialNumber i CertDigest * w certyfikacie i w formularzu. * \retval -1 Nie można przeparsować dokumentu. * \retval -2 Nie można pobrać info certyfikatu z formularza. * \retval -3 Nie można pobrać info z formularza. * \retval -4 Niezgodne numery seryjne. * \retval -5 Niezgodne nazwy wystawców. * \retval -6 Nie można utworzyć skrótu z certyfikatu. * \retval -7 Nie można pobrać skrótu certyfikatu z formularza. * \retval -8 Niezgodne skróty z certyfikatów. * \retval -9 Certyfikat przeterminowany. * */ long verify_fields(const char *buffer, const long buffer_len, GenBuf_t *timestamp) { xmlDocPtr document = NULL; char *CertSerialNumber = NULL; /*serial sczytany z certyfikatu*/ char *FormSerialNumber = NULL; /*serial sczytany z formularza*/ char *CertIssuerName = NULL; /*wystawca sczytany z certyfikatu*/ char *FormIssuerName = NULL; /*wystawca sczytany z formularza*/ char *CertDigest = NULL; /*digest w base64 do porównania*/ char *FormDigest = NULL; /*digest z formularza*/ GenBuf_t *certyfikat = NULL; /*genbuf z certyfikatem*/ LIBBMDXADES_DIGEST_METHOD_t metoda; long status; /*kontrola poprawnosci parametrow*/ if (buffer == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (buffer_len == 0) { PRINT_DEBUG("Wrong argument 2 (too short!)\n"); return ERR_arg+2; } /* load file */ document = xmlParseMemory(buffer,buffer_len); if ((document == NULL) || (xmlDocGetRootElement(document) == NULL)) { PRINT_DEBUG("UNABLE TO PARSE DOCUMENT\n"); return -1; } /* pobieramy certyfikat*/ status = _getCertificateFromXML(&document, &certyfikat); if (status < 0) { PRINT_DEBUG("Error while getting certificate.\n"); return -2; } /*pobieramy date waznosci*/ status = isCertificateValid(&certyfikat, timestamp); if (status < 0) { PRINT_DEBUG("Error - certificate not valid!\n"); return -9; } /* get Serial and IssuerName from certificate in the form*/ status = _getInfoFromCertificate(&certyfikat, &CertSerialNumber, &CertIssuerName); if (status < 0) { PRINT_DEBUG("Error while getting info from X509 Certificate.\n"); return -2; } PRINT_VDEBUG("Form signed by certificate issued by %s, serial: %s\n", CertIssuerName, CertSerialNumber); /* get Serial and IssuerName from the form*/ _getInfoFromXML(&document, &FormSerialNumber, &FormIssuerName); if (status < 0) { PRINT_DEBUG("Error while getting info from the form.\n"); return -3; } /*porównujemy seriale*/ status = _compareSerials(&CertSerialNumber, &FormSerialNumber); if (status != 0) { PRINT_DEBUG("Bad serial number.\n"); return -4; } /*porównujemy wystawcow*/ status = _compareIssuerNames(&CertIssuerName, &FormIssuerName); if (status != 0) { PRINT_DEBUG("Bad issuer name.\n"); return -5; } /*sprawdzamy digest*/ status = _getDigestAndMethod(&document, &FormDigest, &metoda); if (status < 0) { PRINT_DEBUG("Cannot get digests from XML!\n"); return -7; } _getCertificateDigest(&certyfikat, metoda, &CertDigest); if (status < 0) { PRINT_DEBUG("Error while digesting certificate!\n"); return -6; } if (strcmp(FormDigest, CertDigest)!= 0) { PRINT_DEBUG("Digests in cert and XML vary!\n"); return -8; } /*sprzatamy*/ free(CertIssuerName); free(CertSerialNumber); free(FormIssuerName); free(FormSerialNumber); free(CertDigest); free(FormDigest); free_gen_buf(&certyfikat); xmlFreeDoc(document); return 0; }
void *switch_loop(void *local) { struct fins_module *module = (struct fins_module *) local; PRINT_DEBUG("Entered: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name); struct switch_data *md = (struct switch_data *) module->data; uint32_t i; int ret; //int32_t val; struct finsFrame *ff; //uint8_t index; int counter = 0; while (module->state == FMS_RUNNING) { secure_sem_wait(module->event_sem); //TODO uncomment, for testing //secure_sem_wait(module->input_sem); secure_sem_wait(&md->overall->sem); for (i = 0; i < MAX_MODULES; i++) { if (md->overall->modules[i] != NULL) { //helgrind says is race condition, though there will always be FF when post to event_sem if (!IsEmpty(md->overall->modules[i]->output_queue)) { //added as optimization /* //can possibly cause switch to be "behind" ret = sem_getvalue(md->overall->modules[i]->output_sem, &val); if (ret) { PRINT_ERROR("sem get value prob: src module_index=%u, ret=%d", i, ret); exit(-1); } //*/ //if (val != 0) { while ((ret = sem_wait(md->overall->modules[i]->output_sem)) && errno == EINTR) ; if (ret != 0) { PRINT_ERROR("sem wait prob: src module_index=%u, ret=%d", i, ret); exit(-1); } ff = read_queue(md->overall->modules[i]->output_queue); sem_post(md->overall->modules[i]->output_sem); //if (ff != NULL) { //shouldn't occur counter++; //index = ff->destinationID; if (ff->destinationID < 0 || ff->destinationID > MAX_MODULES) { PRINT_ERROR("dropping ff: illegal destination: src module_index=%u, dst module_index=%u, ff=%p, meta=%p", i, ff->destinationID, ff, ff->metaData); //TODO if FCF set ret_val=0 & return? or free or just exit(-1)? freeFinsFrame(ff); } else { //if (i != id) //TODO add this? if (md->overall->modules[ff->destinationID] != NULL) { PRINT_DEBUG("Counter=%d, from='%s', to='%s', ff=%p, meta=%p", counter, md->overall->modules[i]->name, md->overall->modules[ff->destinationID]->name, ff, ff->metaData); //TODO decide if should drop all traffic to switch input queues, or use that as linking table requests if (ff->destinationID == module->index) { switch_process_ff(module, ff); } else { while ((ret = sem_wait(md->overall->modules[ff->destinationID]->input_sem)) && errno == EINTR) ; if (ret != 0) { PRINT_ERROR("sem wait prob: dst index=%u, ff=%p, meta=%p, ret=%d", ff->destinationID, ff, ff->metaData, ret); exit(-1); } if (write_queue(ff, md->overall->modules[ff->destinationID]->input_queue)) { sem_post(md->overall->modules[ff->destinationID]->event_sem); sem_post(md->overall->modules[ff->destinationID]->input_sem); } else { sem_post(md->overall->modules[ff->destinationID]->input_sem); PRINT_ERROR("Write queue error: dst index=%u, ff=%p, meta=%p", ff->destinationID, ff, ff->metaData); freeFinsFrame(ff); } } } else { PRINT_ERROR("dropping ff: destination not registered: src index=%u, dst index=%u, ff=%p, meta=%p", i, ff->destinationID, ff, ff->metaData); print_finsFrame(ff); //TODO if FCF set ret_val=0 & return? or free or just exit(-1)? freeFinsFrame(ff); } //} //} } } } } //sem_post(module->input_sem); sem_post(&md->overall->sem); } PRINT_DEBUG("Exited: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name); return NULL; }
//RTM's main function //Gets information from RTM_IN pipe //Is started as a thread in core.c void rtm_init(pthread_attr_t *fins_pthread_attr) { PRINT_IMPORTANT("RTM has started"); /* //added to include code from fins_daemon.sh -- mrd015 !!!!! //TODO move this to RTM module if (mkfifo(RTM_PIPE_IN, 0777) != 0) { if (errno == EEXIST) { PRINT_DEBUG("mkfifo(" RTM_PIPE_IN ", 0777) already exists."); } else { PRINT_ERROR("mkfifo(" RTM_PIPE_IN ", 0777) failed."); exit(-1); } } if (mkfifo(RTM_PIPE_OUT, 0777) != 0) { if (errno == EEXIST) { PRINT_DEBUG("mkfifo(" RTM_PIPE_OUT ", 0777) already exists."); } else { PRINT_ERROR("mkfifo(" RTM_PIPE_OUT ", 0777) failed."); exit(-1); } } */ //int datalen; int numBytes; //int val_len; int temp_serial_cntr = 0; unsigned char* serialized_FCF = NULL; int length_serialized_FCF; //create a finsframe to be sent tover the queue struct finsFrame *fins_frame = (struct finsFrame *) secure_malloc(sizeof(struct finsFrame)); fins_frame->dataOrCtrl = CONTROL; //opens the pipe from clicomm (or wherever) rtm_in_fd = open(RTM_PIPE_IN, O_RDWR); if (rtm_in_fd == -1) { PRINT_DEBUG("rtm_in_fd Pipe failure "); exit(EXIT_FAILURE); } fflush(stdout); while (1) { temp_serial_cntr++; //used as a temporary serial_number generator //READ FROM PIPE RTM_IN numBytes = 0; numBytes += read(rtm_in_fd, &length_serialized_FCF, sizeof(int)); //length of incoming serialized FCF numBytes += read(rtm_in_fd, serialized_FCF, length_serialized_FCF); //incoming serialized FCF fins_frame = unserializeCtrlFrame(serialized_FCF, length_serialized_FCF); //value, Assumption was made, notice the size PRINT_DEBUG("received data"); numBytes = 0; //ERROR Message fflush(stdout); if (numBytes >= 0) { PRINT_DEBUG("numBytes written %d", numBytes); } //CHANGE SenderID and SerialNum fins_frame->ctrlFrame.senderID = RTM_ID; fins_frame->ctrlFrame.serial_num = temp_serial_cntr; //SEND TO QUEUE secure_sem_wait(&RTM_to_Switch_Qsem); write_queue(fins_frame, RTM_to_Switch_Queue); sem_post(&RTM_to_Switch_Qsem); PRINT_DEBUG("sent data "); //READ FROM QUEUE rtm_get_ff(); } }
/** * Funkcja porównuje nazwy wystawców z certyfikatu i z formularza. * */ long _compareIssuerNames(char **cert, char **form) { #define ILESKROTOW 8 char skroty[8][10] = {"CN=", "SN=", "C=", "L=", "S=", "O=", "OU=", "G="}; /*skroty poszczegolnych pol certyfikatu*/ long i; char *formwsk = NULL; /*wskaznik na pole w wystawcy wg formularza*/ char *certwsk = NULL; /*wskaznik na pole w wystawcy wg certyfikatu*/ char *tmpwsk = NULL; /*do obliczen na wskaznikach*/ long dlugosc; long status; /*wywolanie funkcji*/ if (cert == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (*cert == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (form == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*form == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } /*sprawdzamy czy w formularzu pojawiaja sie poszczegolne skroty*/ for (i = 0; i < ILESKROTOW; i++) { formwsk = strstr(*form, skroty[i]); if (formwsk != NULL)/*znaleziono dane pole w formularzu*/ { certwsk = strstr(*cert, skroty[i]); if (certwsk != NULL) /*znaleziono tez w certyfikacie*/ { /*porownujemy zawartosc*/ dlugosc = (long)strlen(skroty[i]); formwsk += dlugosc; certwsk += (dlugosc+1); tmpwsk = strchr(certwsk, '>'); dlugosc = (long)(tmpwsk - certwsk); status = strncmp(certwsk, formwsk, dlugosc); if (status != 0) { return -1; } } } #undef ILESKROTOW } return 0; }
int main(int argc, char *argv[]) { bmd_conf *konfiguracja=NULL; struct soap soap; char *serverURL = NULL; char *host = NULL; long int ssl_enabled=0; long int authenticate=0; char *keyfile=NULL; char *keyfile_passwd=NULL; char *keyfile_ssl=NULL; char *keyfile_passwd_ssl=NULL; char *cacert=NULL; char *capath=NULL; int status = 0; struct bmd230__mtdsInfo *userMtds = NULL; struct bmd230__searchResults *searchResults = NULL; struct xsd__base64Binary *base64Cert = NULL; char *serverResponse = NULL; int *result = NULL; int id=0; int i=0; int j=0; _GLOBAL_debug_level=0; if (argc==5) { for (i=1; i<argc; i++) { if (strcmp(argv[i],"-d")==0) { if (argc>i+1) _GLOBAL_debug_level=atoi(argv[i+1]); } if (strcmp(argv[i],"-p")==0) { if (argc>i+1) id=atoi(argv[i+1]); } } } else { printf("%s\n",argv[0]); printf("\nniepoprawne wywołanie\n\nuzyj ponizszych parametrow\n"); printf("-------------------------------------------------------\n"); printf("\t-d liczba\tpoziom logowania\n"); printf("\t-p liczba\tid usuwanego pliku\n"); printf("-------------------------------------------------------\n"); return -1; } /*załadowanie bibliotek ssl-owych*/ SSL_load_error_strings(); SSL_library_init(); /*funkcje konfiguracyjne*/ load_soap_configuration(&konfiguracja); configuration(konfiguracja,&host,&keyfile,&keyfile_passwd,&keyfile_ssl,&keyfile_passwd_ssl,&cacert,&capath,&ssl_enabled); /*funkcja ustanowienia połaczenia z serwerem*/ status=connection(&soap,ssl_enabled,authenticate,keyfile_ssl,keyfile_passwd_ssl,cacert,capath); if (status!=SOAP_OK) { PRINT_DEBUG("SOAPCLIENTERR Connection error\n"); return 0; } /*przygotowanie danych niezbędnych do uruchomienia funkcji web-owej*/ GenBuf_t *cert_pem=NULL; struct bmd230__fileInfo *fileResponse = NULL; base64Cert = (struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); status = bmd_load_binary_content(keyfile,&cert_pem); if (status != BMD_OK) { PRINT_DEBUG("SOAPCLIENTERR Error while reading certificate file\n"); return 0; } base64Cert->__ptr=cert_pem->buf; base64Cert->__size=cert_pem->size; /*****************************************************************************************************************/ /*****************************************************************************************************************/ /*****************************************************************************************************************/ /*****************************************************************************************************************/ struct bmd230__bmdListDatagram *request = NULL; struct bmd230__bmdListDatagram *response = NULL; /******************************************/ /* alokacja pamieci na datagramset */ /******************************************/ request=(struct bmd230__bmdListDatagram *)malloc(sizeof (struct bmd230__bmdListDatagram )); /************************************/ /* alokacja pamieci na datagram */ /************************************/ request->__size=5; request->__ptr=(struct bmd230__bmdSingleDatagram *)malloc(sizeof (struct bmd230__bmdSingleDatagram )*request->__size); for (i=0; i<request->__size; i++) { request->__ptr[i].randId = 666; request->__ptr[i].filesRemaining = i; request->__ptr[i].datagramStatus = i*i; request->__ptr[i].datagramType = i*i +8; request->__ptr[i].actionMetaData=(struct bmd230__bmdListMetadata *)malloc(sizeof(struct bmd230__bmdListMetadata)); /* request->__ptr[i].sysMetaData=(struct bmd230__bmdListMetadata *)malloc(sizeof(struct bmd230__bmdListMetadata)); request->__ptr[i].pkiMetaData=(struct bmd230__bmdListMetadata *)malloc(sizeof(struct bmd230__bmdListMetadata)); request->__ptr[i].additionalMetaData=(struct bmd230__bmdListMetadata *)malloc(sizeof(struct bmd230__bmdListMetadata)); */ request->__ptr[i].actionMetaData->__size=3; /* request->__ptr[i].sysMetaData->__size=3; request->__ptr[i].pkiMetaData->__size=3; request->__ptr[i].additionalMetaData->__size=3; */ request->__ptr[i].actionMetaData->__ptr=(struct bmd230__bmdSingleMetadata *)malloc(sizeof(struct bmd230__bmdSingleMetadata) * request->__ptr[i].actionMetaData->__size); /* request->__ptr[i].sysMetaData->__ptr=(struct bmd230__bmdSingleMetadata *)malloc(sizeof(struct bmd230__bmdSingleMetadata) * request->__ptr[i].sysMetaData->__size); request->__ptr[i].pkiMetaData->__ptr=(struct bmd230__bmdSingleMetadata *)malloc(sizeof(struct bmd230__bmdSingleMetadata) * request->__ptr[i].pkiMetaData->__size); request->__ptr[i].additionalMetaData->__ptr=(struct bmd230__bmdSingleMetadata *)malloc(sizeof(struct bmd230__bmdSingleMetadata) * request->__ptr[i].additionalMetaData->__size); */ request->__ptr[i].protocolData=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].protocolData->__size=0; request->__ptr[i].protocolData->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].protocolDataFilename=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].protocolDataFilename->__size=0; request->__ptr[i].protocolDataFilename->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].protocolDataFileId=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].protocolDataFileId->__size=0; request->__ptr[i].protocolDataFileId->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].protocolDataOwner=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].protocolDataOwner->__size=0; request->__ptr[i].protocolDataOwner->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); for (j=0; j<request->__ptr[i].actionMetaData->__size; j++) { request->__ptr[i].actionMetaData->__ptr[j].myId = i; request->__ptr[i].actionMetaData->__ptr[j].ownerId = j; request->__ptr[i].actionMetaData->__ptr[j].oid=(xsd__string)malloc(sizeof(xsd__string) * strlen("1.2.3.21.32423.12.32.3")); memset(request->__ptr[i].actionMetaData->__ptr[j].oid, 0, strlen("1.2.3.21.32423.12.32.3")); memcpy(request->__ptr[i].actionMetaData->__ptr[j].oid, "1.2.3.21.32423.12.32.3", strlen("1.2.3.21.32423.12.32.3")); request->__ptr[i].actionMetaData->__ptr[j].value=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].actionMetaData->__ptr[j].value->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].actionMetaData->__ptr[j].value->__size=0; } /* for (j=0; j<request->__ptr[i].sysMetaData->__size; j++) { request->__ptr[i].sysMetaData->__ptr[j].myId = i; request->__ptr[i].sysMetaData->__ptr[j].ownerId = j; request->__ptr[i].sysMetaData->__ptr[j].value=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].sysMetaData->__ptr[j].value->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].sysMetaData->__ptr[j].value->__size=0; } for (j=0; j<request->__ptr[i].pkiMetaData->__size; j++) { request->__ptr[i].pkiMetaData->__ptr[j].myId = i; request->__ptr[i].pkiMetaData->__ptr[j].ownerId = j; request->__ptr[i].pkiMetaData->__ptr[j].value=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].pkiMetaData->__ptr[j].value->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].pkiMetaData->__ptr[j].value->__size=0; } for (j=0; j<request->__ptr[i].additionalMetaData->__size; j++) { request->__ptr[i].additionalMetaData->__ptr[j].myId = i; request->__ptr[i].additionalMetaData->__ptr[j].ownerId = j; request->__ptr[i].additionalMetaData->__ptr[j].value=(struct xsd__base64Binary *)malloc(sizeof(struct xsd__base64Binary)); request->__ptr[i].additionalMetaData->__ptr[j].value->__ptr=(unsigned char *)malloc(sizeof(unsigned char)); request->__ptr[i].additionalMetaData->__ptr[j].value->__size=0; }*/ } /************************************/ /* alokacja pamieci na metadane */ /************************************/ soap_set_namespaces(&soap, bmd230_namespaces); /*********************************************************************************/ /************************ funkcja testowa ****************************************/ status=soap_call_bmd230__bmdSendBMDRequest(&soap, host, NULL, request, &response); /*********************************************************************************/ /*********************************************************************************/ if (status == SOAP_OK) { /*********************************************************************************/ /************************ funkcja odpowiedź ****************************************/ printf("Plik usunięty z archiwum; result %i\n",result); /*********************************************************************************/ /*********************************************************************************/ } else { soap_print_fault(&soap, stderr); soap_end(&soap); soap_done(&soap); free(serverURL); return -1; } soap_end(&soap); soap_done(&soap); free(serverURL); return 0; }
/** * Funkcja generuje skrót z certyfikatu wykorzystując podaną w drugim parametrze * metodę. * \param certyfikat Bufor generyczny ze zdekodowanym certyfikatem. * \param method Metoda generowania skrótu. W chwili obecnej do wyboru: * - LIBBMDXADES_DIGEST_METHOD_SHA1 * - LIBBMDXADES_DIGEST_METHOD_MD5 * \param basedHash Skrót zakodowany do base64. * \retval 0 Wszystko OK. * \retval -1 Nieznana metoda. * \retval -2 Brak pamięci. * */ long _getCertificateDigest(GenBuf_t **certyfikat, LIBBMDXADES_DIGEST_METHOD_t method, char **basedHash) { EVP_MD_CTX mdctx; /*kontekst digesta*/ const EVP_MD *md; /*metoda skrotu*/ char md_value[EVP_MAX_MD_SIZE]; /*otrzymany skrot*/ long md_len = 0; /*dlugosc skrotu*/ unsigned int ui_temp = 0; if (certyfikat == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (*certyfikat == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (basedHash == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*basedHash != NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } OpenSSL_add_all_digests(); switch (method) { case LIBBMDXADES_DIGEST_METHOD_SHA1: md = EVP_get_digestbyname("sha1"); break; case LIBBMDXADES_DIGEST_METHOD_MD5: md = EVP_get_digestbyname("md5"); break; default: PRINT_DEBUG("UNKNOWN DIGEST METHOD!\n"); return -1; } EVP_MD_CTX_init(&mdctx); /*inicjalizacja kontekstu*/ EVP_DigestInit_ex(&mdctx, md, NULL); /*ustawiamy odpowiednia metode liczenia skrotu*/ EVP_DigestUpdate(&mdctx, (*certyfikat)->buf, (*certyfikat)->size);/*dodajemy tekst*/ ui_temp = md_len; EVP_DigestFinal_ex(&mdctx, (unsigned char*)md_value, &ui_temp); md_len = ui_temp; EVP_MD_CTX_cleanup(&mdctx); (*basedHash) = (char *) spc_base64_encode((unsigned char *)md_value, md_len, 0); if (*basedHash == NULL) { PRINT_ERROR("NO MEMORY!\n"); return -2; } return 0; }
static void *CR_Loop(void *arg) { #ifdef CR_FTB if (cr_ftb_init(nprocs)) exit(EXIT_FAILURE); #else char cr_msg_buf[MAX_CR_MSG_LEN]; char valstr[CRU_MAX_VAL_LEN]; fd_set set; int i, n, nfd = 0, ret; if (USE_LINEAR_SSH) { if (!show_on) { // This call is blocking (in case of error) // It must be kept in the CR thread int rv = accept_connections(); if ( rv != 0 ) { m_state_fail(); pthread_exit(NULL); } } } #endif CR_state_transition( CR_READY ); #ifdef CR_FTB // The main thread of mpirun_rsh is waiting for the CR thread to connect to FTB // before starting the mpispawn processes // Make the transition to the M_LAUNCH state // Use to signal the main thread of mpirun_rsh // This should be removed once we remove the use of FTB for this if (M_LAUNCH != m_state_transition(M_INITIALIZE|M_RESTART, M_LAUNCH)) { PRINT_ERROR("Internal error: transition failed\n"); m_state_fail(); pthread_exit(NULL); } #endif if ( checkpoint_interval > 0 ) { PRINT_DEBUG( DEBUG_FT_verbose, "Checkpoint interval = %d s\n", checkpoint_interval ); } while (1) { // Check if CR_thread_stop() has been called CR_state_lock(); if (cr_state == CR_STOPPED) { CR_state_unlock(); PRINT_DEBUG( DEBUG_FT_verbose, "Exit CR thread\n" ); pthread_exit(NULL); } CR_state_unlock(); #ifdef CR_FTB sleep(1); if (cr_ftb_app_ckpt_req || cr_ftb_finalize_ckpt) #else nfd = 0; FD_ZERO(&set); for (i = 0; i < nspawns; i++) { FD_SET(mpirun_fd[i], &set); nfd = (nfd >= mpirun_fd[i]) ? nfd : mpirun_fd[i]; } nfd += 1; struct timeval tv; do { tv.tv_sec = 1; tv.tv_usec = 0; ret = select(nfd, &set, NULL, NULL, &tv); } while ( ret==-1 && errno==EINTR ); if (ret < 0) { PRINT_ERROR_ERRNO("select(nfd=%d, set, NULL, NULL, tv={%lu,%lu}) failed", errno, nfd, tv.tv_sec, tv.tv_usec); return ((void *) -1); } else if (ret > 0) #endif { // Do not go further if not ready // This avoid bad interactions on file descriptors with the CR_Callback thread CR_state_lock(); if (cr_state != CR_READY) { CR_state_unlock(); continue; } CR_state_unlock(); #ifdef CR_FTB if (cr_ftb_app_ckpt_req) #else for (i = 0; i < nspawns; i++) { if (!FD_ISSET(mpirun_fd[i], &set)) continue; n = CR_MPDU_readline(mpirun_fd[i], cr_msg_buf, MAX_CR_MSG_LEN); if (n == 0) continue; if (CR_MPDU_parse_keyvals(cr_msg_buf) < 0) break; CR_MPDU_getval("cmd", valstr, CRU_MAX_VAL_LEN); if (strcmp(valstr, "app_ckpt_req") == 0) #endif { #ifdef CR_FTB cr_ftb_app_ckpt_req = 0; #endif unsigned int current_version = checkpoint_version; char buf[CR_MAX_FILENAME]; sprintf(buf, "%s.%d.sync", ckpt_filename, current_version); PRINT_DEBUG( DEBUG_FT_verbose, "Checkpoint request from the application\n" ); int rv = request_checkpoint( buf ); if ( rv < 0 ) { PRINT_ERROR( "Checkpoint failed\n" ); } else if ( rv > 0 ) { PRINT_DEBUG( DEBUG_FT_verbose, "Restarting from checkpoint\n" ); // Terminate the thread pthread_exit(NULL); } } #ifdef CR_FTB else if (cr_ftb_finalize_ckpt) #else else if (strcmp(valstr, "finalize_ckpt") == 0) #endif { // One process called MPI_finalize() #ifdef CR_FTB cr_ftb_finalize_ckpt = 0; #endif // Terminate the CR_thread CR_state_transition( CR_STOPPED ); pthread_exit(NULL); } #ifndef CR_FTB } #endif } else {
/** * Funkcja pobiera z formularza skrót certyfikatu i metodę generowania tego skrótu. * \param document Przeparsowany formularz XML. * \param hash Tutaj zostanie zaalokowany string ze skrótem pobranym z formularza. * \param metoda Tutaj zostanie zapisana metoda generowania skrótu. * */ long _getDigestAndMethod(const xmlDocPtr *document, char **hash, LIBBMDXADES_DIGEST_METHOD_t *metoda) { long status; char *xpath = NULL; /*ściezka xpath do digesta/metody*/ char *node_value = NULL; /*zawartość taga z metoda / digestem*/ char *tmpwsk = NULL; /*do wybierania metody*/ /*argumenty wywolania*/ if (document == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return ERR_arg+1; } if (hash == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } if (*hash != NULL) { PRINT_DEBUG("Wrong argument 2\n"); return ERR_arg+2; } /*pobieramy metode*/ #ifdef CASA_XADES asprintf(&xpath, "//ds:Object//CertDigest[1]/DigestMethod/@Algorithm"); #else asprintf(&xpath, "//ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest[1]/ds:DigestMethod/@Algorithm"); #endif status = bmdxml_get_node_value_by_xpath (*document, xpath, &node_value); if (status < 0) { PRINT_DEBUG("Unable to get serial number from the form!\n"); return -1; } if (strstr(node_value, "http://www.w3.org/2000/09/xmldsig#sha1") != NULL) { tmpwsk = strstr(node_value, "#sha1"); if (tmpwsk != NULL && strlen(tmpwsk) == 5) { *metoda = LIBBMDXADES_DIGEST_METHOD_SHA1; } } else if(strstr(node_value, "http://www.w3.org/2000/09/xmldsig#md5") != NULL) { tmpwsk = strstr(node_value, "#md5"); if (tmpwsk != NULL && strlen(tmpwsk) == 4) { *metoda = LIBBMDXADES_DIGEST_METHOD_MD5; } } free(node_value); node_value = NULL; free(xpath); xpath = NULL; /*pobieramy digest*/ #ifdef CASA_XADES asprintf(&xpath, "//ds:Object//CertDigest[1]/DigestValue"); #else asprintf(&xpath, "//ds:Signature/ds:Object/xades:QualifyingProperties/xades:SignedProperties/xades:SignedSignatureProperties/xades:SigningCertificate/xades:Cert/xades:CertDigest[1]/ds:DigestValue"); #endif status = bmdxml_get_node_value_by_xpath (*document, (const char *) xpath, &node_value); if (status < 0) { PRINT_DEBUG("Unable to get digest value from the form!\n"); return -1; } asprintf(hash, "%s", node_value); free(node_value); node_value = NULL; free(xpath); xpath = NULL; return 0; }
struct ip4_routing_table * parse_nlmsg(struct nlmsghdr* msg) { char dst_temp[IP4_ALEN]; char gw_temp[IP4_ALEN]; unsigned int priority; unsigned int interface; struct ip4_routing_table *table_pointer = NULL; switch (msg->nlmsg_type) { case NLMSG_ERROR: { struct nlmsgerr* errorMsg = (struct nlmsgerr*) NLMSG_DATA(msg); PRINT_DEBUG("\nrecvd NLMSG_ERROR error seq:%d code:%d...", msg->nlmsg_seq, errorMsg->error); break; } case RTM_NEWROUTE: { struct rtmsg* rtm = (struct rtmsg*) NLMSG_DATA(msg); struct rtattr* rta = RTM_RTA(rtm); int rtaLen = msg->nlmsg_len - NLMSG_LENGTH(sizeof(struct rtmsg)); if (rtm->rtm_type == RTN_UNICAST) // don't consider local, broadcast and unreachable routes { table_pointer = (struct ip4_routing_table*) malloc( sizeof(struct ip4_routing_table)); memset(table_pointer, 0, sizeof(struct ip4_routing_table)); // zero the routing table entry data for (; RTA_OK(rta, rtaLen); rta = RTA_NEXT(rta, rtaLen)) { switch (rta->rta_type) { case RTA_DST: //destination table_pointer->mask = rtm->rtm_dst_len; memcpy(dst_temp, RTA_DATA(rta), IP4_ALEN); PRINT_DEBUG("received RTA_DST"); PRINT_DEBUG("dst_str = %u.%u.%u.%u", dst_temp[0]&0xFF, dst_temp[1]&0xFF, dst_temp[2]&0xFF, dst_temp[3]&0xFF); table_pointer->dst = IP4_ADR_P2N(dst_temp[0]&0xFF, dst_temp[1]&0xFF, dst_temp[2]&0xFF, dst_temp[3]&0xFF); break; case RTA_GATEWAY: //next hop table_pointer->mask = rtm->rtm_dst_len; memcpy(gw_temp, RTA_DATA(rta), IP4_ALEN); PRINT_DEBUG("received RTA_GATEWAY"); PRINT_DEBUG("gw_str = %u.%u.%u.%u",gw_temp[0]&0xFF, gw_temp[1]&0xFF, gw_temp[2]&0xFF, gw_temp[3]&0xFF); table_pointer->gw = IP4_ADR_P2N(gw_temp[0]&0xFF, gw_temp[1]&0xFF, gw_temp[2]&0xFF, gw_temp[3]&0xFF); break; case RTA_OIF: //interface memcpy(&table_pointer->interface, RTA_DATA(rta), sizeof(interface)); PRINT_DEBUG("interface:%u",table_pointer->interface); break; case RTA_PRIORITY: //metric memcpy(&table_pointer->metric, RTA_DATA(rta), sizeof(priority)); PRINT_DEBUG("metric:%u",table_pointer->metric); break; } //switch(rta->) }// for() } // if RTN_UNICAST return (table_pointer); } } //switch (msg->nlmsg_type) return (NULL); }
void server_session::do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(buf_.data(), buf_.capacity()), [this, self](boost::system::error_code ec, std::size_t length) { if (ec) { if (!id_.empty()) { rooms_.erase(id_); } socket_.close(); return; } auto r = buf_.consume(length); if (r == buffer_t::intermediate) { do_read(); } else if (r == buffer_t::ok) { if (state_ == accept_request) { connect_req req; if (decode_connect_req(buf_, req)) { connect_res res {0}; auto found = rooms_.find(req.room) != rooms_.end(); auto& room = rooms_[req.room]; if (found) { PRINT_DEBUG ("Room %s found\n", req.room.c_str()); res.host = room.host; state_ = close_connection; } else { PRINT_DEBUG ("Room %s created\n", req.room.c_str()); state_ = accept_info; id_ = req.room; room.host_id = req.from; room.host = req.host; } res.host_id = room.host_id; // send response buf_.reset(); if (encode_connection_res(res, buf_)) { do_write(); } } else { socket_.close(); } } else if (state_ == accept_info) { // todo: handle history here } } else { socket_.close(); } }); }
void core_main(uint8_t *envi_name, uint8_t *stack_name, uint32_t seed) { PRINT_IMPORTANT("Core Initiation: Starting ************"); #ifdef BUILD_FOR_ANDROID library_dummies(); #endif register_to_signal(SIGRTMIN); if (seed == DEFAULT_SEED_NUM) { srand((unsigned int) time(NULL)); } else { srand(seed); } sem_init(&global_control_serial_sem, 0, 1); //TODO remove after gen_control_serial_num() converted to RNG signal(SIGINT, core_termination_handler); //register termination handler int status; int i, j, k; metadata_element *list_elem; int list_num; metadata_element *elem; metadata_element *ip_elem; uint32_t ip_num; //###################################################################### overall = (struct fins_overall *) secure_malloc(sizeof(struct fins_overall)); sem_init(&overall->sem, 0, 1); //###################################################################### overall->envi = (struct envi_record *) secure_malloc(sizeof(struct envi_record)); PRINT_IMPORTANT("########################## loading environment: '%s'", (char *) envi_name); metadata *meta_envi = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta_envi); status = config_read_file(meta_envi, (char *) envi_name); if (status == META_FALSE) { PRINT_ERROR("file='%s', %s:%d - %s\n", envi_name, config_error_file(meta_envi), config_error_line(meta_envi), config_error_text(meta_envi)); metadata_destroy(meta_envi); PRINT_ERROR("todo error"); exit(-1); } //############# if_list PRINT_IMPORTANT("############# Configuring List of Interfaces"); overall->envi->if_list = list_create(MAX_INTERFACES); list_elem = config_lookup(meta_envi, "environment.interfaces"); if (list_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } list_num = config_setting_length(list_elem); int32_t if_index; uint8_t *name; uint64_t mac; uint32_t mode; uint32_t mtu; uint32_t flags; struct if_record *ifr; for (i = 0; i < list_num; i++) { elem = config_setting_get_elem(list_elem, i); if (elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "index", (int *) &if_index); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_string(elem, "name", (const char **) &name); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int64(elem, "mac", (long long *) &mac); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "mode", (int *) &mode); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "mtu", (int *) &mtu); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "flags", (int *) &flags); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } //############# ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index); if (ifr == NULL) { ifr = (struct if_record *) secure_malloc(sizeof(struct if_record)); ifr->index = if_index; strcpy((char *) ifr->name, (char *) name); ifr->mac = mac; ifr->mode = (uint8_t) mode; ifr->mtu = mtu; ifr->flags = flags; ifr->addr_list = list_create(MAX_FAMILIES); if (list_has_space(overall->envi->if_list)) { PRINT_IMPORTANT("Adding interface: ifr=%p, index=%u, name='%s', mac=0x%012llx", ifr, ifr->index, ifr->name, ifr->mac); list_append(overall->envi->if_list, ifr); } else { //TODO error PRINT_ERROR("todo error"); exit(-1); } if (flags & IFF_LOOPBACK) { overall->envi->if_loopback = ifr; } } else { PRINT_ERROR("todo error"); exit(-1); } } PRINT_IMPORTANT("if_list: list=%p, max=%u, len=%u", overall->envi->if_list, overall->envi->if_list->max, overall->envi->if_list->len); //############# if_loopback PRINT_IMPORTANT("############# Configuring Loopback Interface"); if (overall->envi->if_loopback != NULL) { PRINT_IMPORTANT("loopback: name='%s', addr_list->len=%u", overall->envi->if_loopback->name, overall->envi->if_loopback->addr_list->len); } else { PRINT_WARN("todo error"); } //############# if_main PRINT_IMPORTANT("############# Configuring Main Interface"); uint32_t if_main; status = config_lookup_int(meta_envi, "environment.main_interface", (int *) &if_main); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } overall->envi->if_main = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_main); if (overall->envi->if_main != NULL) { PRINT_IMPORTANT("main interface: name='%s', addr_list->len=%u", overall->envi->if_main->name, overall->envi->if_main->addr_list->len); if (!ifr_running_test(overall->envi->if_main)) { PRINT_WARN("!!!!Selected main interface is NOT running: name='%s', flagx->len=0x%x", overall->envi->if_main->name, overall->envi->if_main->flags); } } else { PRINT_WARN("todo error"); } //############# addr_list PRINT_IMPORTANT("############# Configuring List of Host Addresses"); //overall->envi->addr_list = list_create(MAX_INTERFACES * MAX_FAMILIES); //TODO use? list_elem = config_lookup(meta_envi, "environment.addresses"); if (list_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } list_num = config_setting_length(list_elem); uint32_t family; //atm only AF_INET, but eventually also AF_INET6 uint32_t ip[4]; //SIOCGIFADDR //ip uint32_t mask[4]; //SIOCGIFNETMASK //mask uint32_t gw[4]; //? //(ip & mask) | 1; uint32_t bdc[4]; //SIOCGIFBRDADDR //(ip & mask) | ~mask uint32_t dst[4]; //SIOCGIFDSTADDR //dst struct addr_record *addr; for (i = 0; i < list_num; i++) { elem = config_setting_get_elem(list_elem, i); if (elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "if_index", (int *) &if_index); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "family", (int *) &family); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } ip_elem = config_setting_get_member(elem, "ip"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { ip[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "mask"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "gw"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "bdc"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { bdc[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "dst"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } //############ ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index); if (ifr != NULL) { if (ifr_running_test(ifr)) { if (family == AF_INET) { addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v4); } else { addr = (struct addr_record *) list_find(ifr->addr_list, addr_is_v6); } if (addr == NULL) { addr = (struct addr_record *) secure_malloc(sizeof(struct addr_record)); addr->if_index = if_index; addr->family = AF_INET; if (family == AF_INET) { addr4_set_ip(&addr->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3])); addr4_set_ip(&addr->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3])); addr4_set_ip(&addr->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3])); addr4_set_ip(&addr->bdc, IP4_ADR_P2H(bdc[0], bdc[1], bdc[2], bdc[3])); addr4_set_ip(&addr->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3])); } else if (family == AF_INET6) { //TODO //addr_set_addr6(&addr->ip, ip); PRINT_WARN("todo"); } else { //TODO error? PRINT_ERROR("todo error"); exit(-1); } if (list_has_space(ifr->addr_list)) { PRINT_IMPORTANT( "Adding address: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'", if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]); list_append(ifr->addr_list, addr); } else { //TODO error PRINT_ERROR("todo error"); exit(-1); } } else { //TODO error PRINT_ERROR("todo: previous address found, replace or add new?"); } } else { if (family == AF_INET) { PRINT_WARN( "Ignoring address, no active interface: if_index=%d, family=%u, ip='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', bdc='%u.%u.%u.%u', dst='%u.%u.%u.%u'", if_index, family, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], bdc[0], bdc[1], bdc[2], bdc[3], dst[0], dst[1], dst[2], dst[3]); } else if (family == AF_INET6) { //TODO PRINT_WARN("todo"); } else { //TODO error? PRINT_ERROR("todo error"); exit(-1); } } } else { //TODO error PRINT_ERROR("todo error"); exit(-1); } } //############# route_list PRINT_IMPORTANT("############# Configuring List of Routes"); overall->envi->route_list = list_create(MAX_ROUTES); list_elem = config_lookup(meta_envi, "environment.routes"); if (list_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } list_num = config_setting_length(list_elem); uint32_t metric; //SIOCGIFMETRIC uint32_t timeout; //struct timeval route_stamp; struct route_record *route; for (i = 0; i < list_num; i++) { elem = config_setting_get_elem(list_elem, i); if (elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "if_index", (int *) &if_index); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "family", (int *) &family); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } ip_elem = config_setting_get_member(elem, "dst"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { dst[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "mask"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { mask[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } ip_elem = config_setting_get_member(elem, "gw"); if (ip_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } ip_num = config_setting_length(ip_elem); for (j = 0; j < ip_num; j++) { gw[j] = (uint32_t) config_setting_get_int_elem(ip_elem, j); } status = config_setting_lookup_int(elem, "metric", (int *) &metric); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(elem, "timeout", (int *) &timeout); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } //############ ifr = (struct if_record *) list_find1(overall->envi->if_list, ifr_index_test, &if_index); if (ifr != NULL) { if (ifr_running_test(ifr)) { route = (struct route_record *) secure_malloc(sizeof(struct route_record)); route->if_index = if_index; route->family = family; if (family == AF_INET) { addr4_set_ip(&route->dst, IP4_ADR_P2H(dst[0], dst[1], dst[2], dst[3])); addr4_set_ip(&route->mask, IP4_ADR_P2H(mask[0], mask[1], mask[2],mask[3])); addr4_set_ip(&route->gw, IP4_ADR_P2H(gw[0], gw[1], gw[2], gw[3])); //addr4_set_addr(&route->ip, IP4_ADR_P2H(ip[0], ip[1], ip[2],ip[3])); } else if (family == AF_INET6) { //TODO //addr_set_addr6(&route->ip, ip); } else { //TODO error? } route->metric = metric; route->timeout = timeout; if (list_has_space(overall->envi->route_list)) { PRINT_IMPORTANT( "Adding route: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u", route->if_index, route->family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout); list_append(overall->envi->route_list, route); } else { //TODO error PRINT_ERROR("todo error"); exit(-1); } } else { if (family == AF_INET) { PRINT_WARN( "Ignoring route, no active interface: if_index=%d, family=%u, dst='%u.%u.%u.%u', mask='%u.%u.%u.%u', gw='%u.%u.%u.%u', metric=%u, timeout=%u", if_index, family, dst[0], dst[1], dst[2], dst[3], mask[0], mask[1], mask[2], mask[3], gw[0], gw[1], gw[2], gw[3], metric, timeout); } else if (family == AF_INET6) { //TODO PRINT_WARN("todo"); } else { //TODO error? PRINT_ERROR("todo error"); } } } } PRINT_IMPORTANT("route_list: list=%p, max=%u, len=%u", overall->envi->route_list, overall->envi->route_list->max, overall->envi->route_list->len); metadata_destroy(meta_envi); //###################################################################### PRINT_IMPORTANT("########################## loading stack: '%s'", (char *) stack_name); metadata *meta_stack = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta_stack); status = config_read_file(meta_stack, (char *) stack_name); if (status == META_FALSE) { PRINT_ERROR("file='%s', %s:%d - %s\n", stack_name, config_error_file(meta_stack), config_error_line(meta_stack), config_error_text(meta_stack)); metadata_destroy(meta_stack); PRINT_ERROR("todo error"); exit(-1); } //############# module_list PRINT_IMPORTANT("############# Configuring List of Modules"); overall->lib_list = list_create(MAX_MODULES); memset(overall->modules, 0, MAX_MODULES * sizeof(struct fins_module *)); overall->admin_list = list_create(MAX_MODULES); struct linked_list *mt_list = list_create(MAX_MODULES); uint8_t base_path[100]; memset((char *) base_path, 0, 100); #ifdef BUILD_FOR_ANDROID strcpy((char *) base_path, FINS_TMP_ROOT); //strcpy((char *) base_path, "."); #else strcpy((char *) base_path, "."); #endif metadata_element *mods_elem = config_lookup(meta_stack, "stack.modules"); if (mods_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } int mods_num = config_setting_length(mods_elem); metadata_element *mod_elem; uint32_t mod_id; uint8_t *mod_lib; uint8_t *mod_name; metadata_element *flows_elem; uint32_t mod_flows[MAX_MOD_FLOWS]; uint32_t mod_flows_num; metadata_element *mod_params; metadata_element *mod_admin; struct fins_library *library; struct fins_module *module; struct fins_module_table *mt; for (i = 0; i < mods_num; i++) { mod_elem = config_setting_get_elem(mods_elem, i); if (mod_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(mod_elem, "id", (int *) &mod_id); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_string(mod_elem, "lib", (const char **) &mod_lib); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_string(mod_elem, "name", (const char **) &mod_name); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } flows_elem = config_setting_get_member(mod_elem, "flows"); if (flows_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } mod_flows_num = config_setting_length(flows_elem); for (j = 0; j < mod_flows_num; j++) { mod_flows[j] = (uint32_t) config_setting_get_int_elem(flows_elem, j); } mod_params = config_setting_get_member(mod_elem, "params"); if (mod_params == NULL) { PRINT_ERROR("todo error"); exit(-1); } mod_admin = config_setting_get_member(mod_elem, "admin"); PRINT_DEBUG("admin=%u", mod_admin != NULL); //############ library = (struct fins_library *) list_find1(overall->lib_list, library_name_test, mod_lib); if (library == NULL) { #ifdef BUILD_FOR_ANDROID library = library_fake_load(mod_lib, base_path); #else //library = library_load(mod_lib, base_path); library = library_fake_load(mod_lib, base_path); #endif if (library == NULL) { PRINT_ERROR("Failed in loading library: lib='%s', base_path='%s'", mod_lib, base_path); exit(-1); } if (list_has_space(overall->lib_list)) { PRINT_IMPORTANT("Adding library: library=%p, name='%s'", library, library->name); list_append(overall->lib_list, library); } else { PRINT_ERROR("Failed in init sequence, too many libraries: lib_list->len=%u", overall->lib_list->len); exit(-1); } } module = library->create(i, mod_id, mod_name); if (module == NULL) { //TODO error PRINT_ERROR("Failed to create module: library=%p, index=%u, id=%u, name='%s'", library, i, mod_id, mod_name); exit(-1); } library->num_mods++; //TODO move flow to update? or links here? status = module->ops->init(module, mod_params, overall->envi); //TODO merge init into create? if (status != 0) { overall->modules[i] = module; if (module->flows_max < mod_flows_num) { PRINT_ERROR("Loading module parameters failed, too many flows for this library: specified=%u, max=%u", mod_flows_num, module->flows_max); exit(-1); } mt = (struct fins_module_table *) secure_malloc(sizeof(struct fins_module_table)); mt->flows_num = mod_flows_num; for (j = 0; j < mt->flows_num; j++) { mt->flows[j].link_id = mod_flows[j]; } list_append(mt_list, mt); if (mod_admin != NULL) { PRINT_IMPORTANT("Adding admin module: module=%p, lib='%s', name='%s', id=%d, index=%u", module, module->lib, module->name, module->id, module->index); list_append(overall->admin_list, module); } else { PRINT_IMPORTANT("Adding module: module=%p, lib='%s', name='%s', id=%d, index=%u", module, module->lib, module->name, module->id, module->index); } } else { PRINT_ERROR("Initialization of module failed: module=%p, lib='%s', name='%s', flows_num=%u, flows=%p, params=%p, envi=%p", module, module->lib, module->name, mod_flows_num, mod_flows, mod_params, overall->envi); exit(-1); } //free(mod_lib); //don't free, string from libconfig points to metadata memory //free(mod_name); } //############# admin_list //TODO change to admin_list? list_for_each1(overall->admin_list, assign_overall, overall); //############# linking_list PRINT_IMPORTANT("############# Configuring Linking Table"); overall->link_list = list_create(MAX_TABLE_LINKS); metadata_element *links_elem = config_lookup(meta_stack, "stack.links"); if (links_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } int links_num = config_setting_length(links_elem); metadata_element *link_elem; uint32_t link_id; uint32_t link_src; metadata_element *dsts_elem; uint32_t link_dsts[MAX_MODULES]; int link_dsts_num; struct link_record *link; for (i = 0; i < links_num; i++) { link_elem = config_setting_get_elem(links_elem, i); if (link_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(link_elem, "id", (int *) &link_id); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } status = config_setting_lookup_int(link_elem, "src", (int *) &link_src); if (status == META_FALSE) { PRINT_ERROR("todo error"); exit(-1); } dsts_elem = config_setting_get_member(link_elem, "dsts"); if (dsts_elem == NULL) { PRINT_ERROR("todo error"); exit(-1); } link_dsts_num = config_setting_length(dsts_elem); for (j = 0; j < link_dsts_num; j++) { link_dsts[j] = (uint32_t) config_setting_get_int_elem(dsts_elem, j); } //############ link = (struct link_record *) secure_malloc(sizeof(struct link_record)); link->id = link_id; //module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_src); link->src_index = -1; for (j = 0; j < MAX_MODULES; j++) { if (overall->modules[j] != NULL && overall->modules[j]->id == link_src) { link->src_index = overall->modules[j]->index; } } if (link->src_index == -1) { PRINT_ERROR("todo error"); exit(-1); } link->dsts_num = link_dsts_num; for (j = 0; j < link_dsts_num; j++) { //module = (struct fins_module *) list_find1(overall->envi->module_list, mod_id_test, &link_dsts[j]); link->dsts_index[j] = -1; for (k = 0; k < MAX_MODULES; k++) { if (overall->modules[k] != NULL && overall->modules[k]->id == link_dsts[j]) { link->dsts_index[j] = overall->modules[k]->index; } } if (link->dsts_index[j] == (uint32_t) -1) { PRINT_ERROR("todo error"); exit(-1); } } if (list_has_space(overall->link_list)) { uint8_t buf[1000]; uint8_t *pt = buf; int ret; int i; for (i = 0; i < link->dsts_num; i++) { ret = sprintf((char *) pt, "%u, ", link->dsts_index[i]); pt += ret; } *pt = '\0'; PRINT_IMPORTANT("Adding link: link=%p, id=%u, src_index=%u, dsts_num=%u, ['%s']", link, link->id, link->src_index, link->dsts_num, buf); list_append(overall->link_list, link); } else { //TODO error PRINT_ERROR("todo error"); exit(-1); } } metadata_destroy(meta_stack); //###################################################################### PRINT_IMPORTANT("############# Updating modules with correct flows & links"); //send out subset of linking table to each module as update //TODO table subset update metadata *meta_update; struct finsFrame *ff_update; for (i = 0; i < MAX_MODULES; i++) { if (overall->modules[i] != NULL) { mt = (struct fins_module_table *) list_remove_front(mt_list); mt->link_list = list_filter1(overall->link_list, link_src_test, &overall->modules[i]->index, link_clone); //was link_involved_test, decide which better? PRINT_IMPORTANT("Module link table subset: name='%s' index=%d, link_list=%p, len=%d", overall->modules[i]->name, i, mt->link_list, mt->link_list->len); for (j = 0; j < mt->flows_num; j++) { mt->flows[j].link = (struct link_record *) list_find1(mt->link_list, link_id_test, &mt->flows[j].link_id); } //#ifdef DEBUG uint8_t buf[1000]; uint8_t *pt = buf; int ret; for (j = 0; j < mt->flows_num; j++) { ret = sprintf((char *) pt, "%u (%p), ", mt->flows[j].link_id, mt->flows[j].link); pt += ret; } *pt = '\0'; PRINT_IMPORTANT("Module flows: num=%u, ['%s']", mt->flows_num, buf); list_for_each(mt->link_list, link_print); //#endif meta_update = (metadata *) secure_malloc(sizeof(metadata)); metadata_create(meta_update); ff_update = (struct finsFrame*) secure_malloc(sizeof(struct finsFrame)); ff_update->dataOrCtrl = FF_CONTROL; ff_update->destinationID = i; ff_update->metaData = meta_update; ff_update->ctrlFrame.sender_id = 0; ff_update->ctrlFrame.serial_num = gen_control_serial_num(); ff_update->ctrlFrame.opcode = CTRL_SET_PARAM; ff_update->ctrlFrame.param_id = MOD_SET_PARAM_DUAL; ff_update->ctrlFrame.data_len = sizeof(struct fins_module_table); ff_update->ctrlFrame.data = (uint8_t *) mt; module_to_switch(overall->modules[0], ff_update); //module_set_param_dual(overall->modules[i], ff_update); } } list_free(mt_list, free); //############ say by this point envi var completely init'd //assumed always connect/init to switch first pthread_attr_init(&overall->attr); pthread_attr_setdetachstate(&overall->attr, PTHREAD_CREATE_JOINABLE); PRINT_IMPORTANT("############# Calling run() for modules"); for (i = 0; i < MAX_MODULES; i++) { if (overall->modules[i] != NULL) { overall->modules[i]->ops->run(overall->modules[i], &overall->attr); } } PRINT_IMPORTANT("Core Initiation: Finished ************"); }
void main() { pid_t pID; char device[20]; strcpy(device, "lo"); //strcpy(device, "eth0"); /** Time to split into two processes * 1. the child Process is for capturing (incoming) * 2. the parent process is for injecting frames (outgoing) */ pID = fork(); if (pID == 0) // child -- Capture process { // Code only executed by child process PRINT_DEBUG("child started to capture \n"); //sleep(2); capture_init(device); } else if (pID < 0) // failed to fork { PRINT_DEBUG ("Failed to Fork \n"); exit(1); } else // parent { // Code only executed by parent process /** inject handler is supposed to be initialized earlier to make sure that forwarding * feature is able to work even if the parent process did not start injecting yet * we fix this by sleeping the capturing process for a while. To give the injection * process a lead */ PRINT_DEBUG("parent started to Inject \n"); inject_init(device); // while (1); } /** if (inject_handle != NULL); pcap_close(inject_handle); if (capture_handle != NULL); pcap_close(capture_handle); */ return; }
u64 XTIER_inject_reserve_additional_memory(struct kvm_vcpu *vcpu, u32 size) { PRINT_DEBUG("Trying to reserve addition memory of %u bytes!\n", size); return XTIER_memory_establish_mapping(vcpu, XTIER_INJECTION_PID, _XTIER_inject.sregs.cr3, size); }
/*by AK*/ long set_mail_send_info(mail_send_info_t **mi, char *_server_port, char *_recipient_to, char *_recipient_cc, char*_recipient_bcc, char *_mail_body, long _with_auth, char *_user, char* _password, char *_reverse_path) { if (mi == NULL) { PRINT_DEBUG("Wrong argument 1\n"); return BMD_ERR_PARAM1; } if (*mi != NULL) { PRINT_DEBUG("Wrong argument 1\n"); return BMD_ERR_PARAM1; } if (_server_port == NULL) { PRINT_DEBUG("Wrong argument 2\n"); return BMD_ERR_PARAM2; } if (_recipient_to == NULL) { PRINT_DEBUG("Wrong argument 3\n"); return BMD_ERR_PARAM3; } if (_reverse_path == NULL) { PRINT_DEBUG("Wrong argument 10\n"); return BMD_ERR_PARAM10; } if (_mail_body == NULL) { PRINT_DEBUG("Warning: no mail body given (param 6).\n"); } if (_with_auth == BMD_MAIL_WITH_AUTH) { if (_user == NULL) { PRINT_DEBUG("Wrong argument 8\n"); return BMD_ERR_PARAM8; } if (_password == NULL) { PRINT_DEBUG("Wrong argument 9\n"); return BMD_ERR_PARAM9; } } (*mi) = (mail_send_info_t*) calloc (1, sizeof(mail_send_info_t)); if (*mi == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } (*mi)->server_port = strdup(_server_port); if ((*mi)->server_port == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } (*mi)->recipient_to = strdup(_recipient_to); if ((*mi)->recipient_to == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } (*mi)->reverse_path = strdup(_reverse_path); if ((*mi)->reverse_path == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } if (_recipient_cc != NULL) { (*mi)->recipient_cc= strdup(_recipient_cc); if ((*mi)->recipient_cc == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } } if (_recipient_bcc != NULL) { (*mi)->recipient_bcc= strdup(_recipient_bcc); if ((*mi)->recipient_bcc == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } } if (_mail_body) { (*mi)->mail_body= strdup(_mail_body); if ((*mi)->mail_body == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } } if (_with_auth == BMD_MAIL_WITH_AUTH) { (*mi)->with_auth=BMD_MAIL_WITH_AUTH; (*mi)->auth_data.username = strdup(_user); if ((*mi)->auth_data.username == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } (*mi)->auth_data.password = strdup(_password); if ((*mi)->auth_data.password == NULL) { PRINT_ERROR("No memory!\n"); return BMD_ERR_MEMORY; } } return 0; }
/** * Inject the given code into the VM. * * @param inject A pointer to the XTIER_inject structure used for injection. * It contains a pointer to the code and the length of the code. */ void XTIER_inject_code(struct kvm_vcpu *vcpu, struct injection *inject) { u64 virt_code = 0; u64 virt_stack = 0; u64 phys_code = 0; u64 phys_stack = 0; struct x86_exception error; int ret = 0; u32 state = 0; PRINT_DEBUG("Injecting code...\n"); // Get Time XTIER_inject_begin_time_measurement(&_starttime); if(_XTIER_inject.new_module) { // This is the first injection, reset the timer XTIER_inject_init_performance_struct(); // Reset _XTIER_inject.new_module = 0; } // Reduce auto injection if enabled if(inject->auto_inject > 0) inject->auto_inject--; // Disable hooks to avoid exceptions during injection if(inject->event_based) XTIER_inject_disable_hook(vcpu); // Reset the fault variable _XTIER_inject.injection_fault = 0; // Save VM state saveVMState(vcpu); // Get a mapping // We currently can only reserve space for a little less than 4MB. if(inject->code_len > (512 * 4096)) { /* virt_code = XTIER_memory_establish_mapping(vcpu, XTIER_INJECTION_PID, _XTIER_inject.sregs.cr3, 512 * 4096); XTIER_memory_establish_mapping(vcpu, XTIER_INJECTION_PID, _XTIER_inject.sregs.cr3, inject->code_len - (512 * 4096)); */ PRINT_ERROR("The module that should be injected is to large!\n"); return; } // Code virt_code = XTIER_memory_establish_mapping(vcpu, XTIER_INJECTION_PID, _XTIER_inject.sregs.cr3, inject->code_len); // Stack // Do NOT modify the stack pointer in case of event based injection if(!inject->event_based) { // Reserve space for the args and the stack itself virt_stack = XTIER_memory_establish_mapping(vcpu, XTIER_INJECTION_PID, _XTIER_inject.sregs.cr3, inject->args_size + 4096); if (virt_stack) { // Currently virt_stack points to the end of the stack // Fix that virt_stack += inject->args_size + 4000; // We leave 96 bytes free // Prepare Stack switch(_XTIER.os) { case XTIER_OS_UBUNTU_64: prepareStack64(vcpu, inject, &virt_stack); break; case XTIER_OS_WINDOWS_7_32: /* Fall through*/ case XTIER_OS_UBUNTU_32: virt_stack -= 4; // Write address of the original kernel stack on the new stack phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, virt_stack, 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.regs.rsp, 4); kvm_register_write(vcpu, VCPU_REGS_RSP, virt_stack); if(inject->args_size > 0) PRINT_WARNING("Module arguments for 32-bit OSs are currently not supported!\n"); break; default: PRINT_ERROR("OS type is unknown! Cannot inject module!\n"); XTIER_memory_remove_mappings_pid(vcpu, XTIER_INJECTION_PID); return; } } } else { // Event based injection // Set the stack to the original stack - The SC offset virt_stack = _XTIER_inject.regs.rsp - STACK_AREA_SC; // Prepare Stack switch(_XTIER.os) { case XTIER_OS_UBUNTU_64: // Place the original kernel pointer on the stack virt_stack -= 8; // Write address of the original kernel stack on the new stack phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, virt_stack, 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.regs.rsp, 8); kvm_register_write(vcpu, VCPU_REGS_RSP, virt_stack); break; case XTIER_OS_WINDOWS_7_32: /* Fall through*/ case XTIER_OS_UBUNTU_32: virt_stack -= 4; // Write address of the original kernel stack on the new stack phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, virt_stack, 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.regs.rsp, 4); kvm_register_write(vcpu, VCPU_REGS_RSP, virt_stack); break; default: PRINT_ERROR("OS type is unknown! Cannot inject module!\n"); XTIER_memory_remove_mappings_pid(vcpu, XTIER_INJECTION_PID); return; } if(inject->args_size > 0) PRINT_WARNING("Module arguments are not supported in the case of event-based injection!\n"); } // Verify that the memory was reserved if(virt_code == 0 || virt_stack == 0) { PRINT_ERROR("Could not establish the mappings for code injection. Aborting.\n"); return; } // Get Physical address phys_code = vcpu->arch.mmu.gva_to_gpa(vcpu, virt_code, 0, &error); // Write Data ret = kvm_write_guest(vcpu->kvm, phys_code, inject->code, inject->code_len); if(ret < 0) { PRINT_ERROR("An error (code: %d) occurred while writing the binary to memory!\n", ret); // Remove Mappings XTIER_memory_remove_mappings_pid(vcpu, XTIER_INJECTION_PID); // Reenable hook if(inject->event_based) XTIER_inject_enable_hook(vcpu, inject); return; } // Set params _XTIER_inject.event_based = inject->event_based; _XTIER_inject.exit_after_injection = inject->exit_after_injection; // Increase injections _XTIER_performance.injections++; PRINT_INFO("Running shellcode @ 0x%llx (ESP: 0x%llx, KERNEL ESP: 0x%llx, SEIP: 0x%llx, CR3: 0x%llx)\n", virt_code, virt_stack, _XTIER_inject.regs.rsp, _XTIER_inject.regs.rip, _XTIER_inject.sregs.cr3); // Set Mode _XTIER.mode |= XTIER_CODE_INJECTION; // Set HALT Exiting XTIER_enable_hlt_exiting(); // Set Exception Exiting XTIER_enable_interrupt_exiting(vcpu); // Set EIP kvm_rip_write(vcpu, virt_code); // Flush TLB //kvm_x86_ops->tlb_flush(vcpu); // Get Time XTIER_inject_end_time_measurement(&_starttime, &_XTIER_performance.total_module_load_time); // Take Time for execution just before we enter the VM XTIER_take_time_on_entry(&_starttime); // Make sure the VM is not halted XTIER_read_vmcs(GUEST_ACTIVITY_STATE, &state); if(state == GUEST_ACTIVITY_HLT) XTIER_write_vmcs(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE); }
int main( int argc, char *argv[] ){ struct sockaddr_un addr; int optchar, debug; unsigned int timeout = 0; ssize_t numRead; char buf[BUF_SIZE], sockPathBuffer[ PATH_MAX ]; enum BINARY_MODE clientMode = COMMANDLINE; pthread_t THreaderSocket, THwriterSocket; memset( sockPathBuffer, NUL_BYTE, sizeof( sockPathBuffer ) ); strncpy( sockPathBuffer, MSCANGTWYD_UXDOSOCK_PATH, sizeof( MSCANGTWYD_UXDOSOCK_PATH ) ); /* command line args parsing - getopt */ while( ( optchar = getopt( argc, argv, "chs:t:v" ) ) != -1 ){ switch( optchar ){ /* console mode */ case 'c': PRINT_DEBUG( "getopt: %c\n", optchar ); clientMode = CONSOLE; break; /* show help or usage */ case 'h': PRINT_DEBUG( "getopt: %c\n", optchar ); usage( argv[0] ); exit( EXIT_FAILURE ); break; /* unix domain socket path */ case 's': PRINT_DEBUG( "getopt: %c: %s\n", ( char )optchar, optarg ); if( PATH_MAX < strlen( optarg ) ){ PRINT_DEBUG( "Path longer than %d\n", PATH_MAX ); usage( argv[0] ); exit( EXIT_FAILURE ); } memset( sockPathBuffer, NUL_BYTE, sizeof( sockPathBuffer ) ); strncpy( sockPathBuffer, optarg, ( size_t )( PATH_MAX - 1 ) ); PRINT_DEBUG( "%s\n", sockPathBuffer ); break; /* timeout in seconds */ case 't': PRINT_DEBUG( "getopt: %c: %s\n", ( char )optchar, optarg ); timeout = atoi( optarg ); if( ( TIMEOUT_MAX < timeout ) || ( TIMEOUT_MIN > timeout ) ){ fprintf( stderr, "Invaid timeout duration specified\n" ); usage( argv[0] ); exit( EXIT_FAILURE ); } break; case 'v': PRINT_DEBUG( "getopt: %c: %s\n", ( char )optchar, optarg ); fprintf( stderr, "%s %.2f\n", argv[0], SOFTWARE_VERSION ); exit( EXIT_SUCCESS ); break; default: usage( argv[0] ); exit( EXIT_FAILURE ); } } /* catch none or non-valid cmdline options in console mode */ if( CONSOLE == clientMode ){ PRINT_DEBUG( "optind: %d argc: %d\n", optind, argc ); if( ( 1 == argc ) || ( optind != argc ) ){ usage( argv[0] ); exit( EXIT_FAILURE ); } if( 0 != timeout ){ fprintf( stderr, "Timeout is an invalid option in console mode\n" ); usage( argv[0] ); exit( EXIT_FAILURE ); } } if( COMMANDLINE == clientMode ){ PRINT_DEBUG( "optind: %d argc: %d\n", optind, argc ); if( ( 1 == argc ) || ( optind == argc ) ){ usage( argv[0] ); exit( EXIT_FAILURE ); } if( 0 == timeout ){ fprintf( stderr, "Timeout must be specified in command line mode\n" ); usage( argv[0] ); exit( EXIT_FAILURE ); } } PRINT_DEBUG( "optind: %d argc: %d\n", optind, argc ); /* Create client unix domain socket */ sfd = socket(AF_UNIX, SOCK_STREAM, 0); if( -1 == sfd ){ perror("socket"); exit( EXIT_FAILURE ); } /* Construct server address, and make the connection */ memset( &addr, 0, sizeof( struct sockaddr_un ) ); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, MSCANGTWYD_UXDOSOCK_PATH, sizeof( addr.sun_path ) - 1 ); if( connect( sfd, ( struct sockaddr * )&addr, sizeof( struct sockaddr_un ) ) == -1){ perror( "connect" ); exit( EXIT_FAILURE ); } pthread_create( &THwriterSocket, NULL, &socketWriter, NULL); pthread_create( &THreaderSocket, NULL, &socketReader, NULL); if( CONSOLE == clientMode ){ pthread_join( THwriterSocket, NULL); pthread_cancel( THreaderSocket ); pthread_join( THreaderSocket, NULL); } close( sfd ); /* Closes our socket; server sees EOF */ exit( EXIT_SUCCESS ); }
/* * Take care of an external function call. */ int XTIER_inject_temporarily_remove_module(struct kvm_vcpu *vcpu) { int ret = 0; u64 phys_stack = 0; struct kvm_regs regs; struct x86_exception error; struct timespec begin; PRINT_INFO("The injected module will be temporarily removed due to an external function call!\n"); // Take time // Since the execution is still running we do not use starttime! XTIER_inject_begin_time_measurement(&begin); // Increase the number of removals _XTIER_performance.temp_removals++; // Get registers kvm_arch_vcpu_ioctl_get_regs(vcpu, ®s); // Protect module from read and write access XTIER_memory_remove_access(vcpu); // Disable Exit XTIER_disable_hlt_exiting(); // Disable Exception Exiting XTIER_disable_interrupt_exiting(vcpu); //disable_if(vcpu); // Save the old RIP such that it points to the next instruction after // the interrupt _XTIER_inject.external_function_return_rip = kvm_rip_read(vcpu); // RBX contains the target instruction address PRINT_DEBUG("RET EIP will be set to 0x%llx\n", _XTIER_inject.external_function_return_rip); PRINT_DEBUG("CURRENT EIP will be set to 0x%llx\n", regs.rbx); PRINT_DEBUG("CR3: 0x%lx\n", kvm_read_cr3(vcpu)); kvm_rip_write(vcpu, regs.rbx); // Push the Return Address on stack switch(_XTIER.os) { case XTIER_OS_UBUNTU_64: // Get stack addresses PRINT_DEBUG("RSP will be set to 0x%llx\n", regs.rsp - 8); phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, regs.rsp - 8, 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.external_function_return_rip, 8); kvm_register_write(vcpu, VCPU_REGS_RSP, (regs.rsp - 8)); break; case XTIER_OS_WINDOWS_7_32: /* Fall through*/ case XTIER_OS_UBUNTU_32: // Get stack addresses PRINT_DEBUG("RSP will be set to 0x%llx\n", regs.rsp - 4); phys_stack = vcpu->arch.mmu.gva_to_gpa(vcpu, regs.rsp - 4, 0, &error); ret = kvm_write_guest(vcpu->kvm, phys_stack, &_XTIER_inject.external_function_return_rip, 4); kvm_register_write(vcpu, VCPU_REGS_RSP, (regs.rsp - 4)); break; default: PRINT_ERROR("OS type is unknown! Cannot remove module!\n"); return -1; } if(ret < 0) { PRINT_ERROR("An error (code: %d) occurred while pushing the return address!\n", ret); PRINT_ERROR("GVA to GPA resolution returned error code %u\n", error.error_code); return -1; } // Take time XTIER_inject_end_time_measurement(&begin, &_XTIER_performance.total_module_temp_removal_time); return 1; }
static int allocate_ud_vbuf_region(int nvbufs) { struct vbuf_region *reg = NULL; void *mem = NULL; int i = 0; vbuf *cur = NULL; void *vbuf_dma_buffer = NULL; int alignment_vbuf = 64; int alignment_dma = getpagesize(); int result = 0; PRINT_DEBUG(DEBUG_UD_verbose>0,"Allocating a UD buf region.\n"); if (ud_free_vbuf_head != NULL) { ibv_error_abort(GEN_ASSERT_ERR, "free_vbuf_head = NULL"); } reg = (struct vbuf_region *) MPIU_Malloc (sizeof(struct vbuf_region)); if (NULL == reg) { ibv_error_abort(GEN_EXIT_ERR, "Unable to malloc a new struct vbuf_region"); } if (rdma_enable_hugepage) { result = alloc_hugepage_region (®->shmid, &vbuf_dma_buffer, &nvbufs, rdma_default_ud_mtu); } /* do posix_memalign if enable hugepage disabled or failed */ if (rdma_enable_hugepage == 0 || result != 0 ) { reg->shmid = -1; result = posix_memalign(&vbuf_dma_buffer, alignment_dma, nvbufs * rdma_default_ud_mtu); } if ((result!=0) || (NULL == vbuf_dma_buffer)) { ibv_error_abort(GEN_EXIT_ERR, "unable to malloc vbufs DMA buffer"); } if (posix_memalign( (void**) &mem, alignment_vbuf, nvbufs * sizeof(vbuf))) { fprintf(stderr, "[%s %d] Cannot allocate vbuf region\n", __FILE__, __LINE__); return -1; } MPIU_Memset(mem, 0, nvbufs * sizeof(vbuf)); MPIU_Memset(vbuf_dma_buffer, 0, nvbufs * rdma_default_ud_mtu); ud_vbuf_n_allocated += nvbufs; ud_num_free_vbuf += nvbufs; reg->malloc_start = mem; reg->malloc_buf_start = vbuf_dma_buffer; reg->malloc_end = (void *) ((char *) mem + nvbufs * sizeof(vbuf)); reg->malloc_buf_end = (void *) ((char *) vbuf_dma_buffer + nvbufs * rdma_default_ud_mtu); reg->count = nvbufs; ud_free_vbuf_head = mem; reg->vbuf_head = ud_free_vbuf_head; PRINT_DEBUG(DEBUG_UD_verbose>0, "VBUF REGION ALLOCATION SZ %d TOT %d FREE %ld NF %ld NG %ld\n", rdma_default_ud_mtu, ud_vbuf_n_allocated, ud_num_free_vbuf, ud_num_vbuf_freed, ud_num_vbuf_get); /* region should be registered for both of the hca */ for (; i < rdma_num_hcas; ++i) { reg->mem_handle[i] = ibv_reg_mr( ptag_save[i], vbuf_dma_buffer, nvbufs * rdma_default_ud_mtu, IBV_ACCESS_LOCAL_WRITE ); if (!reg->mem_handle[i]) { fprintf(stderr, "[%s %d] Cannot register vbuf region\n", __FILE__, __LINE__); return -1; } } /* init the free list */ for (i = 0; i < nvbufs; ++i) { cur = ud_free_vbuf_head + i; cur->desc.next = ud_free_vbuf_head + i + 1; if (i == (nvbufs -1)) cur->desc.next = NULL; cur->region = reg; cur->head_flag = (VBUF_FLAG_TYPE *) ((char *)vbuf_dma_buffer + (i + 1) * rdma_default_ud_mtu - sizeof * cur->head_flag); cur->buffer = (unsigned char *) ((char *)vbuf_dma_buffer + i * rdma_default_ud_mtu); cur->eager = 0; cur->content_size = 0; cur->coalesce = 0; } /* thread region list */ reg->next = vbuf_region_head; vbuf_region_head = reg; return 0; }