Beispiel #1
0
/*
 * Check username part in To header field
 */
int check_to(struct sip_msg* _m, char* _s1, char* _s2)
{
	if (!_m->to && ((parse_headers(_m, HDR_TO, 0) == -1) || (!_m->to))) {
		LOG(L_ERR, "check_to(): Error while parsing To header field\n");
		return -1;
	}
	return check_username(_m, &get_to(_m)->uri);
}
Beispiel #2
0
/*
 * Check username part in From header field
 */
int check_from(struct sip_msg* _m, char* _s1, char* _s2)
{
	if (parse_from_header(_m) < 0) {
		LOG(L_ERR, "check_from(): Error while parsing From header field\n");
		return -1;
	}

	return check_username(_m, &get_from(_m)->uri);
}
Beispiel #3
0
/*
 * Check username part in From header field
 */
int check_from(struct sip_msg* _m, char* _s1, char* _s2)
{
	if (parse_from_header(_m) < 0) {
		LM_ERR("Error while parsing From header field\n");
		return ERR_INTERNAL;
	}
	if(parse_from_uri(_m)==NULL) {
		LM_ERR("Error while parsing From header URI\n");
		return ERR_INTERNAL;
	}

	return check_username(_m, &get_from(_m)->parsed_uri);
}
Beispiel #4
0
/*
 * Check username part in To header field
 */
int check_to(struct sip_msg* _m, char* _s1, char* _s2)
{
	if (!_m->to && ((parse_headers(_m, HDR_TO_F, 0) == -1) || (!_m->to))) {
		LM_ERR("Error while parsing To header field\n");
		return ERR_INTERNAL;
	}
	if(parse_to_uri(_m)==NULL) {
		LM_ERR("Error while parsing To header URI\n");
		return ERR_INTERNAL;
	}

	return check_username(_m, &get_to(_m)->parsed_uri);
}
Beispiel #5
0
int preparing_hash_aut(FILE *faut, hashTable_t **hashaut,
		pthread_mutex_t mtx_autor) {
	char *username;
	username = calloc(sizeof(char), MAXLENGTHUSER);
	if (if_null_char(username,
			"ERROR : msgserv : username = calloc(sizeof(char), MAXLENGTHUSER).\n")
			== 1) {
		fclose(faut);
		pthread_mutex_lock(&mtx_autor);
		if (*hashaut != NULL)
			free_hashTable(&(*hashaut));
		free(*hashaut);
		pthread_mutex_unlock(&mtx_autor);
		return 1;
	}

	while (fscanf(faut, "%s\n", username) != EOF) {
		int *fd_skt = malloc(sizeof(int));
		*fd_skt = -1;/*Utente disconnesso*/
		if (check_username(username) == 1) {
			fclose(faut);
			free(fd_skt);
			free(username);
			pthread_mutex_lock(&mtx_autor);
			if (*hashaut != NULL)
				free_hashTable(&(*hashaut));
			free(*hashaut);
			fprintf(stderr, "ERROR : faut non valido\n");
			return 1;
		}
		if (add_hashElement(*hashaut, username, fd_skt) == -1) {
			fclose(faut);
			free(fd_skt);
			free(username);
			pthread_mutex_lock(&mtx_autor);
			if (*hashaut != NULL)
				free_hashTable(&(*hashaut));
			free(*hashaut);
			fprintf(
					stderr,
					"ERROR : msgserv : utente : %s , addhashelement non riuscita, free_all e free usernanme e fd_skt riuscite.\n",
					username);
			return 1;
		}
		free(fd_skt);
	}
	fclose(faut);
	free(username);
	return 0;
}
Beispiel #6
0
void bank_balance(Bank* bank, char* name) {
   if (!name || check_username(name)) {
       printf("Usage: balance <user-name>\n");
       return;
   }

   char* balance;
   balance = (char*)hash_table_find(bank->user_balance_ht, name);
   if (!balance) {
      printf("No such user\n");
      return;
   }

   printf("$%s\n", balance);
   return;
}
Beispiel #7
0
static inline int check_to(struct sip_msg *_m, str *_username)
{
	if (!_m->to && ((parse_headers(_m, HDR_TO_F, 0) == -1) || (!_m->to)))
	{
		LM_ERR("parsing To: header\n");
		return CHECK_ERROR;
	}

	if (parse_to_uri(_m) == NULL)
	{
		LM_ERR("parsing To: URI\n");
		return CHECK_ERROR;
	}

	return check_username(_username, &get_to(_m)->parsed_uri);
}
Beispiel #8
0
static inline int check_from(struct sip_msg *_m, str *_username)
{
	if (parse_from_header(_m) < 0)
	{
		LM_ERR("parsing From: header\n");
		return CHECK_ERROR;
	}

	if (parse_from_uri(_m) == NULL)
	{
		LM_ERR("parsing From: URI\n");
		return CHECK_ERROR;
	}

	return check_username(_username, &get_from(_m)->parsed_uri);
}
Beispiel #9
0
void bank_create_user(Bank* bank, char* args1, char* args2, char* args3) {	
	if (!args1 || !args2 || !args3) {
      printf("Usage: create-user <user-name> <pin> <balance>\n");
		return;		
	}
	
	if (check_username(args1) != 0 || check_pin(args2) != 0 
		|| check_balance(args3) != 0) {
   	printf("Usage: create-user <user-name> <pin> <balance>\n");
		return;	
	} 
	 
   if ((char*)hash_table_find(bank->user_balance_ht, args1) != NULL) {
       printf("Error: user %s already exists\n", args1);
       return;
   }

	FILE *fp;
	char card_name[MAX_CARD_NAME_SIZE + 1];
	
	memset(card_name, 0, MAX_CARD_NAME_SIZE);
   strcat(card_name, args1);
   strcat(card_name, ".card");

   fp = fopen(card_name, "w");
   if (!fp) {
       printf("Error creating card file for user %s\n", args1);
       return;
   }

	printf("Created user %s\n", args1);

	/* write to card*/
   fprintf(fp, "%s\n", args1);
   fprintf(fp, "%s\n", args2);
   fclose(fp);

 	char* tmp;
   tmp = (char*)malloc(64);
	int len = strlen(args3);
	if (len > 64) {
		printf("Usage: create-user <user-name> <pin> <balance>\n");
		return;
	}
   strncpy(tmp, args3, len);
   hash_table_add(bank->user_balance_ht, args1, tmp);
}
Beispiel #10
0
void bank_deposit(Bank* bank, char* name, char* amt) {
    if (!name || !amt) {
        printf("Usage: deposit <user-name> <amt>\n");
        return;
    }
   if (check_username(name) || check_amt(amt)) {
        printf("Usage: deposit <user-name> <amt>\n");
        return;
    }
   if (!hash_table_find(bank->user_balance_ht, name)) {
       printf("No such user\n");
       return;
   }
	
	// handle name
	char card_name[MAX_CARD_NAME_SIZE + 1];
   memset(card_name, 0, MAX_CARD_NAME_SIZE);
   strcat(card_name, name);
   strcat(card_name, ".card");


	// handle balance
	int amount = 0; 
	int balance = 0;   
	sscanf(amt, "%d", &amount);		
   sscanf((char*)hash_table_find(bank->user_balance_ht, name), "%d", &balance);

    if (balance + amount < 0) {
        printf("Too rich for this program\n");
        return;
    }

    balance += amount;
	 char* tmp;
    tmp = (char*)malloc(64);
    sprintf(tmp, "%d", balance);
    hash_table_del(bank->user_balance_ht, name);
    hash_table_add(bank->user_balance_ht, name, tmp);

    printf("$%d added to %s's account\n", amount, name);
}
Beispiel #11
0
/* Process the SPA packet data
*/
void
incoming_spa(fko_srv_options_t *opts)
{
    /* Always a good idea to initialize ctx to null if it will be used
     * repeatedly (especially when using fko_new_with_data()).
    */
    fko_ctx_t       ctx = NULL;

    char            *spa_ip_demark, *raw_digest = NULL;
    int             res, enc_type, stanza_num=0;
    int             added_replay_digest = 0;
    int             is_err, cmd_exec_success = 0, attempted_decrypt = 0;
    int             conf_pkt_age = 0;
    char            dump_buf[CTX_DUMP_BUFSIZE];

    spa_pkt_info_t *spa_pkt = &(opts->spa_pkt);

    /* This will hold our pertinent SPA data.
    */
    spa_data_t spadat;

    /* Loop through all access stanzas looking for a match
    */
    acc_stanza_t        *acc = opts->acc_stanzas;

    inet_ntop(AF_INET, &(spa_pkt->packet_src_ip),
        spadat.pkt_source_ip, sizeof(spadat.pkt_source_ip));

    inet_ntop(AF_INET, &(spa_pkt->packet_dst_ip),
        spadat.pkt_destination_ip, sizeof(spadat.pkt_destination_ip));

    /* At this point, we want to validate and (if needed) preprocess the
     * SPA data and/or to be reasonably sure we have a SPA packet (i.e
     * try to eliminate obvious non-spa packets).
    */
    if(!precheck_pkt(opts, spa_pkt, &spadat, &raw_digest))
        return;

    if(strncasecmp(opts->config[CONF_ENABLE_SPA_PACKET_AGING], "Y", 1) == 0)
    {
        conf_pkt_age = strtol_wrapper(opts->config[CONF_MAX_SPA_PACKET_AGE],
                0, RCHK_MAX_SPA_PACKET_AGE, NO_EXIT_UPON_ERR, &is_err);
        if(is_err != FKO_SUCCESS)
        {
            log_msg(LOG_ERR, "[*] [%s] invalid MAX_SPA_PACKET_AGE", spadat.pkt_source_ip);
            return;
        }
    }

    /* Now that we know there is a matching access.conf stanza and the
     * incoming SPA packet is not a replay, see if we should grant any
     * access
    */
    while(acc)
    {
        res = FKO_SUCCESS;
        cmd_exec_success  = 0;
        attempted_decrypt = 0;
        stanza_num++;

        /* Start access loop with a clean FKO context
        */
        if(ctx != NULL)
        {
            if(fko_destroy(ctx) == FKO_ERROR_ZERO_OUT_DATA)
                log_msg(LOG_WARNING,
                    "[%s] (stanza #%d) fko_destroy() could not zero out sensitive data buffer.",
                    spadat.pkt_source_ip, stanza_num
                );
            ctx = NULL;
        }

        /* Check for a match for the SPA source and destination IP and the access stanza
        */
        if(! src_dst_check(acc, spa_pkt, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        log_msg(LOG_INFO, "(stanza #%d) SPA Packet from IP: %s received with access source match",
            stanza_num, spadat.pkt_source_ip);

        log_msg(LOG_DEBUG, "SPA Packet: '%s'", spa_pkt->packet_data);

        /* Make sure this access stanza has not expired
        */
        if(! check_stanza_expiration(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Get encryption type and try its decoding routine first (if the key
         * for that type is set)
        */
        enc_type = fko_encryption_type((char *)spa_pkt->packet_data);

        if(! handle_rijndael_enc(acc, spa_pkt, &spadat, &ctx,
                    &attempted_decrypt, &cmd_exec_success, enc_type,
                    stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        if(! handle_gpg_enc(acc, spa_pkt, &spadat, &ctx, &attempted_decrypt,
                    cmd_exec_success, enc_type, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        if(! check_mode_ctx(&spadat, &ctx, attempted_decrypt,
                    enc_type, stanza_num, res))
        {
            acc = acc->next;
            continue;
        }

        /* Add this SPA packet into the replay detection cache
        */
        if(! add_replay_cache(opts, acc, &spadat, raw_digest,
                    &added_replay_digest, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        /* At this point the SPA data is authenticated via the HMAC (if used
         * for now). Next we need to see if it meets our access criteria which
         * the server imposes regardless of the content of the SPA packet.
        */
        log_msg(LOG_DEBUG, "[%s] (stanza #%d) SPA Decode (res=%i):",
            spadat.pkt_source_ip, stanza_num, res);

        res = dump_ctx_to_buffer(ctx, dump_buf, sizeof(dump_buf));
        if (res == FKO_SUCCESS)
            log_msg(LOG_DEBUG, "%s", dump_buf);
        else
            log_msg(LOG_WARNING, "Unable to dump FKO context: %s", fko_errstr(res));

        /* First, if this is a GPG message, and GPG_REMOTE_ID list is not empty,
         * then we need to make sure this incoming message is signer ID matches
         * an entry in the list.
        */

        if(! handle_gpg_sigs(acc, &spadat, &ctx, enc_type, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        /* Populate our spa data struct for future reference.
        */
        res = get_spa_data_fields(ctx, &spadat);

        if(res != FKO_SUCCESS)
        {
            log_msg(LOG_ERR, "[%s] (stanza #%d) Unexpected error pulling SPA data from the context: %s",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));

            acc = acc->next;
            continue;
        }

        /* Figure out what our timeout will be. If it is specified in the SPA
         * data, then use that.  If not, try the FW_ACCESS_TIMEOUT from the
         * access.conf file (if there is one).  Otherwise use the default.
        */
        set_timeout(acc, &spadat);

        /* Check packet age if so configured.
        */
        if(! check_pkt_age(opts, &spadat, stanza_num, conf_pkt_age))
        {
            acc = acc->next;
            continue;
        }

        /* At this point, we have enough to check the embedded (or packet source)
         * IP address against the defined access rights.  We start by splitting
         * the spa msg source IP from the remainder of the message.
        */
        spa_ip_demark = strchr(spadat.spa_message, ',');
        if(spa_ip_demark == NULL)
        {
            log_msg(LOG_WARNING, "[%s] (stanza #%d) Error parsing SPA message string: %s",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));

            acc = acc->next;
            continue;
        }

        if((spa_ip_demark-spadat.spa_message) < MIN_IPV4_STR_LEN-1
                || (spa_ip_demark-spadat.spa_message) > MAX_IPV4_STR_LEN)
        {
            log_msg(LOG_WARNING, "[%s] (stanza #%d) Invalid source IP in SPA message, ignoring SPA packet",
                spadat.pkt_source_ip, stanza_num);
            break;
        }

        strlcpy(spadat.spa_message_src_ip,
            spadat.spa_message, (spa_ip_demark-spadat.spa_message)+1);

        if(! is_valid_ipv4_addr(spadat.spa_message_src_ip))
        {
            log_msg(LOG_WARNING, "[%s] (stanza #%d) Invalid source IP in SPA message, ignoring SPA packet",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));
            break;
        }

        strlcpy(spadat.spa_message_remain, spa_ip_demark+1, MAX_DECRYPTED_SPA_LEN);

        /* If use source IP was requested (embedded IP of 0.0.0.0), make sure it
         * is allowed.
        */
        if(! check_src_access(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* If REQUIRE_USERNAME is set, make sure the username in this SPA data
         * matches.
        */
        if(! check_username(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Take action based on SPA message type.
        */
        if(! check_nat_access_types(opts, acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Command messages.
        */
        if(spadat.message_type == FKO_COMMAND_MSG)
        {
            if(process_cmd_msg(opts, acc, &spadat, stanza_num, &res))
            {
                /* we processed the command on a matching access stanza, so we
                 * don't look for anything else to do with this SPA packet
                */
                break;
            }
            else
            {
                acc = acc->next;
                continue;
            }
        }

        /* From this point forward, we have some kind of access message. So
         * we first see if access is allowed by checking access against
         * restrict_ports and open_ports.
         *
         *  --DSS TODO: We should add BLACKLIST support here as well.
        */
        if(! check_port_proto(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* At this point, we process the SPA request and break out of the
         * access stanza loop (first valid access stanza stops us looking
         * for others).
        */
        if(opts->test)  /* no firewall changes in --test mode */
        {
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) --test mode enabled, skipping firewall manipulation.",
                spadat.pkt_source_ip, stanza_num
            );
            acc = acc->next;
            continue;
        }
        else
        {
            process_spa_request(opts, acc, &spadat);
        }

        /* If we made it here, then the SPA packet was processed according
         * to a matching access.conf stanza, so we're done with this packet.
        */
        break;
    }

    if (raw_digest != NULL)
        free(raw_digest);

    if(ctx != NULL)
    {
        if(fko_destroy(ctx) == FKO_ERROR_ZERO_OUT_DATA)
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) fko_destroy() could not zero out sensitive data buffer.",
                spadat.pkt_source_ip, stanza_num
            );
        ctx = NULL;
    }

    return;
}
Beispiel #12
0
/* Process the SPA packet data
*/
void
incoming_spa(fko_srv_options_t *opts)
{
    /* Always a good idea to initialize ctx to null if it will be used
     * repeatedly (especially when using fko_new_with_data()).
    */
    fko_ctx_t       ctx = NULL;

    char            *spa_ip_demark, *raw_digest = NULL;
    int             res, enc_type, stanza_num=0;
    int             added_replay_digest = 0;
    int             cmd_exec_success = 0, attempted_decrypt = 0;
    char            dump_buf[CTX_DUMP_BUFSIZE];

    spa_pkt_info_t *spa_pkt = &(opts->spa_pkt);

    /* This will hold our pertinent SPA data.
    */
    spa_data_t spadat;

    /* Loop through all access stanzas looking for a match
    */
    //²éÕÒËùÓеÄstanzas£¬Æ¥ÅäÏàÓ¦Ïî¡£
    acc_stanza_t        *acc = opts->acc_stanzas;

    inet_ntop(AF_INET, &(spa_pkt->packet_src_ip),
        spadat.pkt_source_ip, sizeof(spadat.pkt_source_ip));	//»ñÈ¡Êý¾Ý±¨À´Ô´µØÖ·¡£

    inet_ntop(AF_INET, &(spa_pkt->packet_dst_ip),
        spadat.pkt_destination_ip, sizeof(spadat.pkt_destination_ip));	//»ñÈ¡Êý¾Ý±¨Ä¿µÄµØÖ·¡£

    /* At this point, we want to validate and (if needed) preprocess the
     * SPA data and/or to be reasonably sure we have a SPA packet (i.e
     * try to eliminate obvious non-spa packets).
    */
    //ÔÚÕâÀÎÒÃÇÒªÑéÖ¤ºÍÔ¤´¦ÀíSPAÊý¾Ý£¬ÌÞ³ýÃ÷ÏÔ²»ÊÇSPAµÄÊý¾Ý°ü¡£
    //ͨ¹ý±È¶ÔÕªÒª¼ì²éÊý¾ÝÍêÕûÐÔºÍÊÇ·ñÊܵ½ÖطŹ¥»÷¡£
    //¼ÆËãctx->encrypted_msgµÄSHA256ÕªÒªÊý¾Ý£¬´æÔÚraw_digest¡£
    if(!precheck_pkt(opts, spa_pkt, &spadat, &raw_digest))
        return;

    /* Now that we know there is a matching access.conf stanza and the
     * incoming SPA packet is not a replay, see if we should grant any
     * access
    */
    while(acc)
    {
        res = FKO_SUCCESS;
        cmd_exec_success  = 0;
        attempted_decrypt = 0;
        stanza_num++;

        /* Start access loop with a clean FKO context
        */
        //¶Ôÿһ¸östanza½øÐÐÆ¥Å䣬ֱµ½Æ¥Åä³É¹¦ÎªÖ¹¡£
        if(ctx != NULL)
        {
            if(fko_destroy(ctx) == FKO_ERROR_ZERO_OUT_DATA)
                log_msg(LOG_WARNING,
                    "[%s] (stanza #%d) fko_destroy() could not zero out sensitive data buffer.",
                    spadat.pkt_source_ip, stanza_num
                );
            ctx = NULL;
        }

        /* Check for a match for the SPA source and destination IP and the access stanza
        */
        //Æ¥ÅästanzaÖеÄÔ´µØÖ·ºÍÄ¿µÄµØÖ·¡£
        if(! src_dst_check(acc, spa_pkt, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        log_msg(LOG_INFO,
            "(stanza #%d) SPA Packet from IP: %s received with access source match",
            stanza_num, spadat.pkt_source_ip);

        log_msg(LOG_DEBUG, "SPA Packet: '%s'", spa_pkt->packet_data);

        /* Make sure this access stanza has not expired
        */
        //È·±£Õâ¸östanzaûÓйýÆÚ¡£
        if(! check_stanza_expiration(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Get encryption type and try its decoding routine first (if the key
         * for that type is set)
        */
        //¼ì²â´Ë¶ÎÃÜÎĵļÓÃÜÀàÐÍ¡£
        enc_type = fko_encryption_type((char *)spa_pkt->packet_data);

		//»¹Ô­¼ÓÑÎÃÜÎÄ£¬Í¨¹ýHMACժҪУÑéÊý¾Ý°üµÄÍêÕûÐÔ£¬½âÃÜencrypted_msg¡£
        if(acc->use_rijndael)
            handle_rijndael_enc(acc, spa_pkt, &spadat, &ctx,
                        &attempted_decrypt, &cmd_exec_success, enc_type,
                        stanza_num, &res);

        if(! handle_gpg_enc(acc, spa_pkt, &spadat, &ctx, &attempted_decrypt,
                    cmd_exec_success, enc_type, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        if(! check_mode_ctx(&spadat, &ctx, attempted_decrypt,
                    enc_type, stanza_num, res))
        {
            acc = acc->next;
            continue;
        }

        /* Add this SPA packet into the replay detection cache
        */
        //¼ì²âÖطŹ¥»÷¡£
        if(! add_replay_cache(opts, acc, &spadat, raw_digest,
                    &added_replay_digest, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        /* At this point the SPA data is authenticated via the HMAC (if used
         * for now). Next we need to see if it meets our access criteria which
         * the server imposes regardless of the content of the SPA packet.
        */
        log_msg(LOG_DEBUG, "[%s] (stanza #%d) SPA Decode (res=%i):",
            spadat.pkt_source_ip, stanza_num, res);

        res = dump_ctx_to_buffer(ctx, dump_buf, sizeof(dump_buf));
        if (res == FKO_SUCCESS)
            log_msg(LOG_DEBUG, "%s", dump_buf);
        else
            log_msg(LOG_WARNING, "Unable to dump FKO context: %s", fko_errstr(res));

        /* First, if this is a GPG message, and GPG_REMOTE_ID list is not empty,
         * then we need to make sure this incoming message is signer ID matches
         * an entry in the list.
        */

        if(! handle_gpg_sigs(acc, &spadat, &ctx, enc_type, stanza_num, &res))
        {
            acc = acc->next;
            continue;
        }

        /* Populate our spa data struct for future reference.
        */
        //ÏòspadatÖÐÌî³ä×ֶΡ£
        res = get_spa_data_fields(ctx, &spadat);

        if(res != FKO_SUCCESS)
        {
            log_msg(LOG_ERR,
                "[%s] (stanza #%d) Unexpected error pulling SPA data from the context: %s",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));

            acc = acc->next;
            continue;
        }

        /* Figure out what our timeout will be. If it is specified in the SPA
         * data, then use that.  If not, try the FW_ACCESS_TIMEOUT from the
         * access.conf file (if there is one).  Otherwise use the default.
        */
        //²é¿´ÔÚSPAÖÐÓÐûÓÐÉèÖó¬Ê±×ֶΣ¬·ñÔò¾ÍÓÃaccess.confÖÐÉèÖõÄ×ֶΡ£
        set_timeout(acc, &spadat);

        /* Check packet age if so configured.
        */
        //²é¿´Êý¾Ý°üÖеÄʱ¼ä´ÁÊÇ·ñ¹ýʱ¡£
        if(! check_pkt_age(opts, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* At this point, we have enough to check the embedded (or packet source)
         * IP address against the defined access rights.  We start by splitting
         * the spa msg source IP from the remainder of the message.
        */
        spa_ip_demark = strchr(spadat.spa_message, ',');
        if(spa_ip_demark == NULL)
        {
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) Error parsing SPA message string: %s",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));

            acc = acc->next;
            continue;
        }

        if((spa_ip_demark-spadat.spa_message) < MIN_IPV4_STR_LEN-1
                || (spa_ip_demark-spadat.spa_message) > MAX_IPV4_STR_LEN)
        {
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) Invalid source IP in SPA message, ignoring SPA packet",
                spadat.pkt_source_ip, stanza_num);
            break;
        }

        strlcpy(spadat.spa_message_src_ip,
            spadat.spa_message, (spa_ip_demark-spadat.spa_message)+1);

        if(! is_valid_ipv4_addr(spadat.spa_message_src_ip))
        {
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) Invalid source IP in SPA message, ignoring SPA packet",
                spadat.pkt_source_ip, stanza_num, fko_errstr(res));
            break;
        }

        strlcpy(spadat.spa_message_remain, spa_ip_demark+1, MAX_DECRYPTED_SPA_LEN);

        /* If use source IP was requested (embedded IP of 0.0.0.0), make sure it
         * is allowed.
        */
        if(! check_src_access(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* If REQUIRE_USERNAME is set, make sure the username in this SPA data
         * matches.
        */
        //Èç¹ûREQUIRE_USERNAME ×ֶα»ÉèÖã¬È·±£Óû§ÃûÔÚSPAÖпɱ»Æ¥Åä¡£
        if(! check_username(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Take action based on SPA message type.
        */
        if(! check_nat_access_types(opts, acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* Command messages.
        */
        if(acc->cmd_cycle_open != NULL)
        {
            if(cmd_cycle_open(opts, acc, &spadat, stanza_num, &res))
                break; /* successfully processed a matching access stanza */
            else
            {
                acc = acc->next;
                continue;
            }
        }
        else if(spadat.message_type == FKO_COMMAND_MSG)
        {
            if(process_cmd_msg(opts, acc, &spadat, stanza_num, &res))
            {
                /* we processed the command on a matching access stanza, so we
                 * don't look for anything else to do with this SPA packet
                */
                break;
            }
            else
            {
                acc = acc->next;
                continue;
            }
        }

        /* From this point forward, we have some kind of access message. So
         * we first see if access is allowed by checking access against
         * restrict_ports and open_ports.
         *
         *  --DSS TODO: We should add BLACKLIST support here as well.
        */
        if(! check_port_proto(acc, &spadat, stanza_num))
        {
            acc = acc->next;
            continue;
        }

        /* At this point, we process the SPA request and break out of the
         * access stanza loop (first valid access stanza stops us looking
         * for others).
        */
        if(opts->test)  /* no firewall changes in --test mode */
        {
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) --test mode enabled, skipping firewall manipulation.",
                spadat.pkt_source_ip, stanza_num
            );
            acc = acc->next;
            continue;
        }
        else
        {
            if(acc->cmd_cycle_open != NULL)
            {
            		//Ö´ÐÐiptablesµÄCMD¡£
                if(cmd_cycle_open(opts, acc, &spadat, stanza_num, &res))
                    break; /* successfully processed a matching access stanza */
                else
                {
                    acc = acc->next;
                    continue;
                }
            }
            else
            {
                process_spa_request(opts, acc, &spadat);
            }
        }

        /* If we made it here, then the SPA packet was processed according
         * to a matching access.conf stanza, so we're done with this packet.
        */
        break;
    }

    if (raw_digest != NULL)
        free(raw_digest);

    if(ctx != NULL)
    {
        if(fko_destroy(ctx) == FKO_ERROR_ZERO_OUT_DATA)
            log_msg(LOG_WARNING,
                "[%s] (stanza #%d) fko_destroy() could not zero out sensitive data buffer.",
                spadat.pkt_source_ip, stanza_num
            );
        ctx = NULL;
    }

    return;
}
Beispiel #13
0
int afp_parse_url(struct afp_url * url, const char * toparse, int verbose)
{
	char firstpart[255],secondpart[2048];
	char *p, *q;
	int firstpartlen;
	int skip_earliestpart=0;
	int skip_secondpart=0;
	char * lastchar;
	int foundv6literal=0;

	if (verbose) printf("Parsing %s\n",toparse);

	url->username[0]='\0';
	url->servername[0]='\0';
	url->uamname[0]='\0';
	url->password[0]='\0';
	url->volumename[0]='\0';
	url->path[0]='\0';

	/* The most complex URL is:
 
	afp://user;AUTH=authType:password@server-name:port/volume-name/path 

	where the optional parms are user, password, AUTH and port, so the
	simplest is:

	afp://server-name/volume-name/path 

	*/

	/* if there is a ://, make sure it is preceeded by afp */

	if ((p=strstr(toparse,"://"))!=NULL) {
		q=p-3;
		if (p<toparse) {
			if (verbose) printf("URL does not start with afp://\n");
			return -1;
		}

		if (strncmp(q,"afp",3)!=0) {
			if (verbose) printf("URL does not start with afp://\n");
			return -1;
		}
		p+=3;
	} else {
		if (verbose) printf("This isn't a URL at all.\n");
		return -1;

	}
	if (p==NULL) p=(char *)toparse;

	/* Now split on the first / */
	if (sscanf(p,"%[^/]/%[^$]",

		firstpart, secondpart)!=2) {
		/* Okay, so there's no volume. */
		skip_secondpart=1;
	}

	firstpartlen=strlen(firstpart);

	lastchar=firstpart+firstpartlen-1;

	/* First part could be something like:
		user;AUTH=authType:password

	   We'll assume that the breakout is:
                user;  optional user name
	        AUTH=authtype:
	*/

	/* Let's see if there's a ';'.  q is the end of the username */

	if ((p=escape_strchr(firstpart,'@',"@"))) {
		*p='\0';
		p++; 
	} else {
		skip_earliestpart=1;
		p=firstpart;
	}
	/* p now points to the start of the server name*/

	/* square brackets denote a literal ipv6 address */
	if (*p == '[' && 
		(q=strchr(p,']'))) {
		foundv6literal = 1;
		p++;
		*q = '\0';
		q++;
	}

	/* see if we have a port number */

	if ((foundv6literal && (q=strchr(q,':'))) ||
			(!foundv6literal && (q=strchr(p,':'))) ) {
		*q='\0';
		q++;
		if (check_port(q)) return -1;
		if ((url->port=atoi(q))==0) {
			if (verbose) printf("Port appears to be zero\n");
			return -1;
		}
	}

	snprintf(url->servername,strlen(p)+1,"%s", p);
	if (check_servername(url->servername)) {
			if (verbose) printf("This isn't a valid servername\n");
			return -1;
	}

	if ((p==NULL) || ((strlen(p)+p-1)==lastchar)) {
		/* afp://server */
	}

	if ((q) && ((strlen(q)+q-1)==lastchar)) {
		/* afp://server:port */
	}


	/* Earliest part */

	if (skip_earliestpart) {
		p+=strlen(p);
		goto parse_secondpart;
	}
	p=firstpart;

	/* Now we're left with something like user[;AUTH=uamname][:password] */

	/* Look for :password */

	if ((q=escape_strrchr(p,':',":"))) {
		*q='\0';
		q++;
		snprintf(url->password,strlen(q)+1, "%s", q);
		if (check_password(url->password)) {
			if (verbose) printf("This isn't a valid passwd\n");
			return -1;
		}
	}

	/* Now we're down to user[;AUTH=uamname] */
	p=firstpart;

	if ((q=strstr(p,";AUTH="))) {
		*q='\0';
		q+=6;
		snprintf(url->uamname,strlen(q)+1,"%s", q);
		if (check_uamname(url->uamname)) {
			if (verbose) printf("This isn't a valid uamname\n");
			return -1;
		}
	}

	if (strlen(p)>0) {
		snprintf(url->username,strlen(p)+1,"%s", p);
		if (check_username(url->username)) {
			if (verbose) printf("This isn't a valid username\n");
			return -1;
		}
	}


parse_secondpart:
	if (skip_secondpart) goto done;
	if (strlen(secondpart)==0) goto done;

	if (secondpart[strlen(secondpart)]=='/') 
		secondpart[strlen(secondpart)]='\0';

	p=secondpart;
	if ((q=strchr(p,'/'))) {
		*q='\0';
		q++;
	}
	snprintf(url->volumename,strlen(p)+1,"%s", p);


	if (q) {
		url->path[0]='/';
		snprintf(url->path+1,strlen(q)+1, "%s", q);
	}

done:
	escape_url(url);
	if (verbose) printf("Successful parsing of URL\n");
	return 0;
}
Beispiel #14
0
int main(int argc, char** argv) {

  int i,j;
  int caller = getuid();
  int status;

  char   *trac_script;
  char   **trac_script_args;
  struct passwd *TRAC; 
  struct passwd *MTA;
  struct stat script_attrs;
 
  trac_script = malloc((strlen(TRAC_SCRIPT_PATH) 
	+ strlen(TRAC_SCRIPT_NAME) + 10) * sizeof(char));

  strncat(trac_script,TRAC_SCRIPT_PATH, strlen(TRAC_SCRIPT_PATH));
  strcat(trac_script,"/");
  strncat(trac_script,TRAC_SCRIPT_NAME, strlen(TRAC_SCRIPT_NAME));

  /*
  printf("trac_script = %s\n", trac_script);
  */

  /* First copy arguments passed to the wrapper as scripts arguments
     after filtering out some of the possible script options */
  trac_script_args = (char**) malloc((argc+1)*sizeof(char*));
  trac_script_args[0] = TRAC_SCRIPT_NAME;
  for (i=j=1; i<argc; i++) {
    if ( (strcmp(argv[i],"--file") == 0) || 
	 (strcmp(argv[i],"-f") == 0) ) {
      i++;
      continue;
    }
    
    trac_script_args[j] = argv[i];
    j++;
  }
  trac_script_args[j] = NULL;

  
  /* Check caller */


  check_username(MTA_USER);
  MTA = getpwnam(MTA_USER);

  if ( MTA == NULL ) {
    if ( DEBUG ) printf("Invalid MTA user (%s)\n", MTA_USER);
    return -3;     /* 253 : MTA user not found */
  }

  if ( caller !=  MTA->pw_uid ) {
    if ( DEBUG ) printf("Invalid caller UID (%d)\n",caller);
    return -2;     /* 254 : Invalid caller */
  }
  
  
  /* set UID/GID to Trac (or apache) user */
  check_username(TRAC_USER);
  if ( TRAC = getpwnam(TRAC_USER) ) {
    setuid(TRAC->pw_uid);
    setgid(TRAC->pw_gid);
  } else {
    if ( DEBUG ) printf("Invalid Trac user (%s)\n",TRAC_USER);
    return -3;     /* 253 : Trac user not found */
  }
	 
  /* Check that script exists */
  if ( stat(trac_script,&script_attrs) ) {
    if ( DEBUG ) printf("Script not found (%s)\n",trac_script);
    return -4;    /* 252 : script not found */
  }
 
  /* Execute script */
  status = execv(trac_script, trac_script_args);
  if ( DEBUG ) printf("Script %s execution failure (error=%d). Check permission and interpreter path.\n",trac_script,status);
  return -1;     /* 255 : should never reach this point */

}
Beispiel #15
0
Datei: bank.c Projekt: evanqi/atm
void bank_process_local_command(Bank *bank, char *command, size_t len)
{

    char *comm = (char *)calloc(MAX_COMMAND_SIZE, sizeof(char));
    char *name = (char *)calloc(MAX_COMMAND_SIZE, sizeof(char));
    char *misc = (char *)calloc(MAX_COMMAND_SIZE, sizeof(char));
    char *misc_two = (char *)calloc(MAX_COMMAND_SIZE, sizeof(char));

    char temp_comm[MAX_LINE_SIZE];
    char temp_name[MAX_LINE_SIZE];
    char temp_misc[MAX_LINE_SIZE];
    char temp_misc_two[MAX_LINE_SIZE];

    if(strlen(command) >= MAX_LINE_SIZE)
    {
        printf("Invalid command\n");
        return;
    }

    sscanf(command, "%s %s %s %s", temp_comm,temp_name,temp_misc,temp_misc_two);
    
    if(strlen(temp_comm) < 1 || strlen(temp_comm) >= MAX_COMMAND_SIZE)
    {
        printf("Invalid command\n");
        return;
    }

    strncpy(comm, temp_comm, strlen(temp_comm) + 1);

    if(strcmp(comm, "create-user") == 0)
    {
        if(strlen(temp_name) < 1 || strlen(temp_misc) < 1 || strlen(temp_misc_two) < 1 || strlen(temp_name) >= MAX_NAME_SIZE)
        {
            printf("Usage: create-user <user-name> <pin> <balance>\n");
            return;
        }

        strncpy(name, temp_name, strlen(temp_name) + 1);

        if(check_username(name) == 0)
        {
            printf("Usage: create-user <user-name> <pin> <balance>\n");
            return;
        }

        if(hash_table_find(bank->user_bal, name) != NULL)
        {
            printf("%s already exists\n", name);
            return;
        }

        if(strlen(temp_misc) != 4 || strlen(temp_misc_two) > 10)
        {
            printf("Usage: create-user <user-name> <pin> <balance>\n");
            return;
        }

        strncpy(misc, temp_misc, strlen(temp_misc) + 1);
        if(check_pin(misc) == 0)
        {
            printf("Usage: create-user <user-name> <pin> <balance>\n");
            return;
        }

        strncpy(misc_two, temp_misc_two, strlen(temp_misc_two) + 1);
        if(check_bal(misc_two) == 0)
        {
            printf("Usage: create-user <user-name> <pin> <balance>\n");
            return;
        }

         // create card
         int filelen = strlen(name) + 6;
         char cardfile[filelen];
         memset(cardfile, '\0', filelen);
         strncpy(cardfile, name, strlen(name));
         strncat(cardfile, ".card", 5);
         FILE *card = fopen(cardfile, "w");
         if(card == NULL){
             printf("Error creating card file for user %s\n", name);
             remove(cardfile);
             return;
        }
	unsigned char *buff = (unsigned char *)calloc(BLOCK_SIZE+1, sizeof(char));
	do_crypt(bank, (unsigned char *)misc, buff, 1);
	fputs((char *)buff, card);
        fclose(card);

        hash_table_add(bank->user_bal, name, misc_two); //username balance
        hash_table_add(bank->user_pin, name, misc);	//username pin

        printf("Created user %s\n", name);
        return;
    } 
    else if(strcmp(comm, "deposit") == 0)
    {
        if(strlen(temp_name) < 1 || strlen(temp_misc) < 1 || strlen(temp_name) >= MAX_NAME_SIZE)
        {
            printf("Usage: deposit <user-name> <amt>\n");
            return;
        }

        strncpy(name, temp_name, strlen(temp_name) + 1);
        if(check_username(name) != 1 || strlen(temp_misc) > 10)
        {
            printf("Usage: deposit <user-name> <amt>\n");
            return;
        }

        if(hash_table_find(bank->user_bal, name) == NULL)
        {
            printf("No such user\n");
            return;
        }

        strncpy(misc, temp_misc, strlen(temp_misc) + 1);
        if(check_bal(misc) == 0)
        {
            printf("Usage: deposit <user-name> <amt>\n");
            return;
        }
       	char *ptr;
        char* curr_bal = (char*) hash_table_find(bank->user_bal, name);
        
        unsigned int curr_bal_int = (unsigned int)strtoul(curr_bal, &ptr, 10);
    	unsigned int amt = (unsigned int)strtoul(misc, &ptr, 10);
   
        unsigned int new_bal = (unsigned int)amt + (unsigned int)curr_bal_int;  

        //checks if new_bal was capped
        if( new_bal > UINT_MAX || (new_bal - amt) != curr_bal_int || new_bal < curr_bal_int){
            printf("Too rich for this program\n");
            return;   
        }       

        char *new_bal_char = (char *)calloc(MAX_MISC_SIZE, sizeof(char));

        sprintf(new_bal_char, "%u", new_bal);

        hash_table_del(bank->user_bal, name);
        hash_table_add(bank->user_bal, name, new_bal_char);

        printf("$%s added to %s's account\n", misc, name);
        return;

    }
    else if(strcmp(comm, "balance") == 0)
    {
        if(strlen(temp_name) < 1)
        {
            printf("Usage: balance <user-name>\n");
            return;
        }

        if(strlen(temp_name) >= MAX_NAME_SIZE)
        {
            printf("Usage: balance <user-name>\n");
            return;
        }

        strncpy(name, temp_name, strlen(temp_name) + 1);
        if(check_username(name) != 1)
        {
            printf("Usage: balance <user-name>\n");
            return;
        }

        char *curr_bal = (char *) hash_table_find(bank->user_bal, name);
        if(curr_bal == NULL)
        {
            printf("No such user\n");
            return;
        }

        printf("$%s\n", curr_bal);
        return;

    }
    else
    {
        printf("Invalid command\n");
        return;
    }
}
Beispiel #16
0
int main(int argc, char *argv[]) {
   static char argv0[] = "login";
   int argn, i, j;
   const char *rh = NULL;
   char **envs = environ;

   /* first, make sure our stdin/stdout/stderr are aimed somewhere */
   i = open("/", O_RDONLY);
   if (i<3) {
      /* Oops. Can't even print an error message... */
      exit(100);
   }
   close(i);

   /* check args */
   argn=1;
   if (argc<1) {
      die("Illegal args: argc < 1");
   }
   if (argn < argc && !strcmp(argv[argn], "-h")) {
      argn++;
      if (argn==argc) die("Illegal args: -h requires argument");
      if (check_a_hostname(argv[argn])) die("Illegal remote host specified");
      rh = argv[argn];
      argn++;
   }
   if (argn < argc && !strcmp(argv[argn], "-p")) {
      argn++;
   }
   if (argn < argc && !strcmp(argv[argn], "-f")) {
      argn++;
      if (argn==argc) die("Illegal args: -f requires argument");
      if (check_username(argv[argn])) die("Illegal remote username specified");
      argn++;
   }
   if (argn < argc && argv[argn][0] != '-') {
      argn++;
   }
   if (argn < argc) die("Illegal args: too many args");
   argv[0] = argv0;

   /* check environment */
   if (envs) for (i=0; envs[i]; i++) {
      char *testenv = envs[i];
      size_t testlen = strlen(testenv);
      for (j=0; legal_envs[j].name; j++) {
	 const char *okenv = legal_envs[j].name;
	 size_t oklen = strlen(okenv);
	 int sign;

	 if (testlen < oklen) continue;
	 if (testenv[oklen]!='=') continue;
	 if ((sign = memcmp(testenv, okenv, oklen)) < 0) {
	    continue;
	 } else if (sign > 0) {
	    break;
	 }
	 if (legal_envs[j].validator(testenv+oklen+1)) {
	    die("Invalid environment: bad value for %s", okenv);
	 }
	 break;
      }
   }

   /* unignore all signals so they get cleared at exec time */
   for (i=1; i<NSIG; i++) {
      signal(i, SIG_DFL);
   }

   /* just in case */
   if (chdir("/")) die("chdir to / failed");

   /* 
    * don't do anything with uids and gids, as login is normally meant
    * to be able to take care of them.  
    * 
    * but, should we insist that ruid==nobody?
    */

#ifdef debian
   /*
    * Debian's /bin/login doesn't work properly unless we're really root.
    */
   setuid(0);
#endif

   /*
    * don't do anything with limits, itimers, or process priority either
    */

   /*
    * should we check to make sure stdin=stdout=stderr and they're a tty
    * and it's our controlling tty [hard] and we're the leader of the 
    * foreground process group?
    *
    * Yeah, we should.
    */
   validate_tty();

   /*
    * now exec login
    * argv[0] was set up above.
    */
   execve(_PATH_LOGIN, argv, envs);
   exit(255);
}