Ejemplo n.º 1
0
Archivo: mcp.c Proyecto: hyena/fuzzball
int
mcp_frame_process_input(McpFrame * mfr, const char *linein, char *outbuf, int bufsize)
{
	if (!strncmp_nocase(linein, MCP_MESG_PREFIX, 3)) {
		/* treat it as an out-of-band message, and parse it. */
		if (mfr->enabled || !strncmp_nocase(MCP_INIT_MESG, linein + 3, 4)) {
			if (!mcp_internal_parse(mfr, linein + 3)) {
				strncpy(outbuf, linein, bufsize);
				outbuf[bufsize - 1] = '\0';
				return 1;
			}
			return 0;
		} else {
			strncpy(outbuf, linein, bufsize);
			outbuf[bufsize - 1] = '\0';
			return 1;
		}
	} else if (mfr->enabled && !strncmp_nocase(linein, MCP_QUOTE_PREFIX, 3)) {
		/* It's quoted in-band data.  Strip the quoting. */
		strncpy(outbuf, linein + 3, bufsize);
	} else {
		/* It's in-band data.  Return it raw. */
		strncpy(outbuf, linein, bufsize);
	}
	outbuf[bufsize - 1] = '\0';
	return 1;
}
Ejemplo n.º 2
0
ngram_file_type_t
ngram_file_name_to_type(const char *file_name)
{
    const char *ext;

    ext = strrchr(file_name, '.');
    if (ext == NULL) {
        return NGRAM_INVALID;
    }
    if (0 == strcmp_nocase(ext, ".gz")) {
        while (--ext >= file_name) {
            if (*ext == '.')
                break;
        }
        if (ext < file_name) {
            return NGRAM_INVALID;
        }
    }
    else if (0 == strcmp_nocase(ext, ".bz2")) {
        while (--ext >= file_name) {
            if (*ext == '.')
                break;
        }
        if (ext < file_name) {
            return NGRAM_INVALID;
        }
    }
    /* We use strncmp because there might be a .gz on the end. */
    if (0 == strncmp_nocase(ext, ".ARPA", 5))
        return NGRAM_ARPA;
    if (0 == strncmp_nocase(ext, ".DMP", 4)
        || 0 == strncmp_nocase(ext, ".BIN", 4))
        return NGRAM_BIN;
    return NGRAM_INVALID;
}
Ejemplo n.º 3
0
char * PKI_HTTP_get_header_txt (const char * orig_data,
		                        const char * header) {

	char *tk = NULL, *pnt = NULL;
	char *ret = NULL;

	char *data = NULL;
	int found = 0;

	if( !orig_data || !header || !strlen(orig_data) || !strlen(header))
	{
		PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
		return NULL;
	}

	if ((data = strdup(orig_data)) == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		return NULL;
	}

	for (tk = strtok_r ( data, "\r\n", &pnt ); tk; tk = strtok_r(NULL, "\r\n", &pnt)) 
	{
		if ( tk == NULL ) break;

		if (strncmp_nocase(tk, header, (int) strlen(header)) == 0)
		{
			found = 1;
			break;
		}
	}

	if (!found)
	{
		PKI_Free ( data );
		return NULL;
	}

	if ((pnt = strchr( tk, ':' )) == NULL)
	{
		PKI_Free ( data );
		return NULL;
	}
	pnt++;

	while ((pnt != NULL ) && (*pnt == ' ' )) {
			pnt++;
	}

	if (pnt) ret = strdup( pnt );

	PKI_Free ( data );

	return ret;
}
Ejemplo n.º 4
0
/*! \brief Returns the type of DNS records identified by the passed char * arg */
int URL_get_dns_type(char *str) {

	int ret = -1;
	if (!str) return ret;

#ifdef HAVE_LIBRESOLV

	if (strncmp_nocase(str, "AAAA", 4) == 0) {
		ret = T_AAAA;
	} else if (strncmp_nocase(str, "A", 1) == 0) {
		ret = T_A;
	} else if (strncmp_nocase(str, "NS", 2) == 0) {
		ret = T_NS;
	} else if (strncmp_nocase(str, "MX", 2) == 0) {
		ret = T_MX;
	} else if (strncmp_nocase(str, "CNAME", 5) == 0) {
		ret = T_CNAME;
	} else if (strncmp_nocase(str, "SRV", 3) == 0) {
		ret = T_SRV;
	} else if (strncmp_nocase(str, "TXT", 3) == 0) {
		ret = T_TXT;
	} else if (strncmp_nocase(str, "CERT", 4) == 0) {
		ret = T_CERT;
	} else if (strncmp_nocase(str, "ANY", 3) == 0) {
		ret = T_ANY;
	} else if (atoi(str) > 0) {
		ret = atoi(str);
	} else {
		PKI_log_err("DNS URI: record type (%s) not supported.", str);
	}

	PKI_log_debug("DNS URI: record type (%s=%d) parsed", str, ret);
#else
  PKI_log_debug("DNS URI: dns support disabled at compile time");
#endif
	return ret;
}
Ejemplo n.º 5
0
char *pkcs11_parse_url_getval ( URL * url, char *keyword ) {

	char * ret = NULL;
	char * tmp_s = NULL;
	char * tmp_s2 = NULL;

	char *col = NULL;
	char *val = NULL;

	if( !url || !url->path ) return( NULL );

	tmp_s = url->path;

	while((tmp_s2 = strchr(tmp_s, '/')) != NULL ) {
		tmp_s2++;
		tmp_s = tmp_s2;
	}

	if((col = PKI_Malloc( 1024 )) == NULL ) {
		return( NULL );
	}

	if((val = PKI_Malloc( 1024 )) == NULL ) {
		PKI_Free( col );
		return (NULL);
	}

	while( sscanf(tmp_s, "(%[^=]=\"%[^\"])", col, val) > 1 ) {

		if( (strlen(col) == strlen(keyword)) && 
			(strncmp_nocase( col,keyword,(int)strlen(keyword)) ) == 0 ) {
			ret = strdup( val );
			goto end;
		}

		/* The tmp_s should point to the next token */
		tmp_s += strlen(col) + strlen(val) + 3;
	}
end:
	if( col ) PKI_Free ( col );
	if( val ) PKI_Free ( val );

	return( ret );
}
Ejemplo n.º 6
0
PKI_STACK *PKI_X509_CERT_get_cdp (const PKI_X509_CERT *x) {

  STACK_OF(DIST_POINT) *sk_cdp = NULL;
        DIST_POINT *cdp = NULL;

        STACK_OF(CONF_VALUE) *sk_val = NULL;
        CONF_VALUE *v = NULL;

        PKI_STACK *ret = NULL;
  PKI_X509_CERT_VALUE *cert = NULL;

  char *tmp_s = NULL;

        int k = -1;
  int i = 0;

  if ( !x || !x->value ) return NULL;

  cert = (PKI_X509_CERT_VALUE *) x->value;

        if(( sk_cdp = X509_get_ext_d2i(cert, 
        NID_crl_distribution_points,
                                                NULL, NULL)) == NULL ) {
                return NULL;
        }

  /* Should we go through the whole stack ? Maybe, now we just
     take the first value... */
  if ( sk_DIST_POINT_num ( sk_cdp ) < 1 ) {
    return NULL;
  }

  for ( i = 0 ; i < sk_DIST_POINT_num ( sk_cdp ); i++ ) {

    cdp = sk_DIST_POINT_value ( sk_cdp, i );

    if( cdp->distpoint ) {
                  if(cdp->distpoint->type == 0) {
                          if( cdp->distpoint->name.fullname ) {
                                  sk_val = i2v_GENERAL_NAMES(NULL,
                                          cdp->distpoint->name.fullname,
                                                  sk_val);
                                k=0;
                                for( ;; ) {
                                        v = sk_CONF_VALUE_value( sk_val, k++ );
                                        if( v == NULL ) break;

                                        if( strncmp_nocase("URI",
                                                        v->name, 3) == 0 ) {
                                                PKI_log_debug( "INFO::Found "
              "CDP in cert %s:%s", 
              v->name, v->value );

            if (!ret) {
              ret = PKI_STACK_new_null ();
              if (!ret) return NULL;
            }

                                                tmp_s = strdup( v->value );
            PKI_STACK_push ( ret, tmp_s );
                                        }
                                }

        // sk_CONF_VALUE_free(sk_val);
                          }
                  } // else {
                   //        DIST_POINT_free( cdp );
                   //        sk_DIST_POINT_free( sk_cdp );
                   //}
          }
  }

        return ret;
}
Ejemplo n.º 7
0
Archivo: mcp.c Proyecto: hyena/fuzzball
int
mcp_intern_is_mesg_start(McpFrame * mfr, const char *in)
{
	char mesgname[128];
	char authkey[128];
	char *subname = NULL;
	McpMesg *newmsg = NULL;
	McpPkg *pkg = NULL;
	int longlen = 0;

	if (!mcp_intern_is_ident(&in, mesgname, sizeof(mesgname)))
		return 0;
	if (strcmp_nocase(mesgname, MCP_INIT_PKG)) {
		if (!isspace(*in))
			return 0;
		while (isspace(*in))
			in++;
		if (!mcp_intern_is_unquoted(&in, authkey, sizeof(authkey)))
			return 0;
		if (strcmp(authkey, mfr->authkey))
			return 0;
	}

	if (strncmp_nocase(mesgname, MCP_INIT_PKG, 3)) {
		for (pkg = mfr->packages; pkg; pkg = pkg->next) {
			int pkgnamelen = strlen(pkg->pkgname);

			if (!strncmp_nocase(pkg->pkgname, mesgname, pkgnamelen)) {
				if (mesgname[pkgnamelen] == '\0' || mesgname[pkgnamelen] == '-') {
					if (pkgnamelen > longlen) {
						longlen = pkgnamelen;
					}
				}
			}
		}
	}
	if (!longlen) {
		int neglen = strlen(MCP_NEGOTIATE_PKG);

		if (!strncmp_nocase(mesgname, MCP_NEGOTIATE_PKG, neglen)) {
			longlen = neglen;
		} else if (!strcmp_nocase(mesgname, MCP_INIT_PKG)) {
			longlen = strlen(mesgname);
		} else {
			return 0;
		}
	}
	subname = mesgname + longlen;
	if (*subname) {
		*subname++ = '\0';
	}

	newmsg = (McpMesg *) malloc(sizeof(McpMesg));
	mcp_mesg_init(newmsg, mesgname, subname);
	while (*in) {
		if (!mcp_intern_is_keyval(newmsg, &in)) {
			mcp_mesg_clear(newmsg);
			free(newmsg);
			return 0;
		}
	}

	/* Okay, we've recieved a valid message. */
	if (newmsg->incomplete) {
		/* It's incomplete.  Remember it to finish later. */
		const char *msgdt = mcp_mesg_arg_getline(newmsg, MCP_DATATAG, 0);

		newmsg->datatag = string_dup(msgdt);
		mcp_mesg_arg_remove(newmsg, MCP_DATATAG);
		newmsg->next = mfr->messages;
		mfr->messages = newmsg;
	} else {
		/* It's complete.  Execute the callback function for this package. */
		mcp_frame_package_docallback(mfr, newmsg);
		mcp_mesg_clear(newmsg);
		free(newmsg);
	}
	return 1;
}
Ejemplo n.º 8
0
/*
 * Parses the PKI_MEM that contains the header looking for specific HTTP
 * headers, the requested path, and the HTTP version and code. Returns
 * PKI_OK in case of success, PKI_ERR otherwise.
 */
int __parse_http_header(PKI_HTTP *msg)
{
    // Let's parse the first line of the HTTP message
    char *eol = NULL;
    char *method = NULL;
    char *path = NULL;
    char *http_version = NULL;
    char *line = NULL;
    char *tmp_ptr = NULL;
    size_t line_size = 0;

    // Shortcut for msg->head
    PKI_MEM *m = NULL;

    // Checks the input
    if (msg == NULL || msg->head == NULL || msg->head->data == NULL || msg->head->size < 1)
    {
    	PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);
    	return PKI_ERR;
    }

    // For better understanding, we use a proxy variable to access the head
    m = msg->head;

    // Let's parse the path and the details from the first line in the header
    if (((eol = strchr((char *)m->data, '\n')) == NULL) &&
  		  (eol = strchr((char*)m->data, '\r')) == NULL)
    {
    	// ERROR: here we should have at least one line (since we already
    	// have the eoh detected, return the error by returning NULL
    	return PKI_ERR;
    }

    // Let's parse the path and version number
    line_size = (size_t) (eol - (char*)m->data);
    if ((line = PKI_Malloc(line_size + 1)) == NULL)
    {
  	  PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
  	  return PKI_ERR;
    }

    // Copy the first line (strtok_r alters the original string)
    memcpy(line, m->data, line_size);

    // Retrieves the first token - [i.e., GET/POST/HTTP ...]
    method = strtok_r(line, " ", &tmp_ptr);
    if (method == NULL)
    {
  	  PKI_log_err("Can not parse HTTP method");
  	  PKI_Free(line);

  	  return PKI_ERR;
    }

    if (strncmp_nocase(method, PKI_HTTP_METHOD_HTTP_TXT, 4) == 0)
    {
  	  // This is usually an HTTP response
  	  msg->method = PKI_HTTP_METHOD_HTTP;

  	  // Let's get the version and the code
  	  if (sscanf((const char *)msg->head->data,"HTTP/%f %d", &msg->version, &msg->code) < 1)
  	  {
  		  PKI_log_debug("ERROR Parsing HTTP Version and Code");
  		  PKI_Free(line);

  		  return PKI_ERR;
  	  }
    }
    else if (strncmp_nocase(method, PKI_HTTP_METHOD_GET_TXT, 3) == 0 ||
		  strncmp_nocase(method, PKI_HTTP_METHOD_POST_TXT, 4) == 0)
    {
  	  if (strncmp_nocase(method, PKI_HTTP_METHOD_GET_TXT, 3) == 0)
  		  msg->method = PKI_HTTP_METHOD_GET;
  	  else
  		  msg->method = PKI_HTTP_METHOD_POST;

  	  path = strtok_r(NULL, " ", &tmp_ptr);
  	  if (path == NULL)
  	  {
  		  // This is an error, we should get the path for a POST or a GET
  		  PKI_Free(line);

  		  return PKI_ERR;
  	  }

  	  msg->path = strdup(path);

  	  http_version = strtok_r(NULL, " ", &tmp_ptr);
  	  if (http_version == NULL)
  	  {
  		  // This is an error, we should be able to get the HTTP version from the third token
  		  PKI_Free(line);

  		  return PKI_ERR;
  	  }
  	  else if(sscanf(http_version,"HTTP/%f", &msg->version) < 1)
  	  {
  		  PKI_log_debug("ERROR Parsing HTTP Version");
  		  PKI_Free(line);
  		  return PKI_ERR;
  	  }
    }
    else
    {
    	PKI_log_err("Unsupported HTTP Method detected (%s)", method);
    	PKI_Free(line);

    	return PKI_ERR;
    }

    // We do not need the line anymore, let's free the memory
    if (line) PKI_Free(line);

    // Success
	return PKI_OK;
}
Ejemplo n.º 9
0
int PKI_HTTP_get_socket (const PKI_SOCKET * sock,
	                 const char       * data,
			 size_t             data_size,
		         const char       * content_type,
			 int                method,
			 int                timeout,
	                 size_t             max_size,
			 PKI_MEM_STACK   ** sk ) {

	size_t len = 0;

	const char *my_cont_type = "application/unknown";

	PKI_HTTP *http_rv	 = NULL;

	int rv   = -1;
	int ret  = PKI_OK;

	size_t max_len = 0;
	size_t auth_len = 0;

	char *tmp  = NULL;
	char *auth_tmp = NULL;
    
	char *head_get =
			"GET %s HTTP/1.1\r\n"
			"Host: %s\r\n"
			"User-Agent: LibPKI\r\n"
			"Connection: close\r\n"
			"%s";

	char *head_post = 
			"POST %s HTTP/1.1\r\n"
			"Host: %s\r\n"
			"User-Agent: LibPKI\r\n"
			"Connection: close\r\n"
			"Content-type: %s\r\n"
			"Content-Length: %d\r\n"
			"%s";

	char *head = NULL;

	if ( timeout < 0 ) timeout = 0;

	if ( !sock || !sock->url ) return PKI_ERR;

	// Process the authentication information if provided by the caller
	if (sock->url && sock->url->usr && sock->url->pwd)
	{
		// Rough estimate for the auth string
		max_len = strlen(sock->url->usr) + strlen(sock->url->pwd) + 100;

		// Special case for when a usr/pwd was specified in the URL
		auth_tmp = PKI_Malloc(len);
		auth_len = (size_t)snprintf(auth_tmp, len, "Authentication: user %s:%s\r\n\r\n", sock->url->usr, sock->url->pwd);
	}
	else
	{
		// If we do not have the auth info, we just add the end of header
		auth_len = 2;
		auth_tmp = "\r\n";
	}

	if (method == PKI_HTTP_METHOD_GET)
	{
		// Gets the right header
		head = head_get;

		// Estimate the header's final size
		max_len =
				strlen(head) +
				strlen(sock->url->path) +
				strlen(sock->url->addr) +
				101;

		// Allocates enough space for the header
		tmp = PKI_Malloc ( max_len + auth_len );

		// Prints the header into the tmp container
		len = (size_t) snprintf(tmp, max_len, head, sock->url->path, sock->url->addr, auth_tmp);
	}
	else if (method == PKI_HTTP_METHOD_POST)
	{
		// Gets the right head
		head = head_post;

		// Determines the right content type
		if ( content_type ) my_cont_type = content_type;
		else my_cont_type = "text/html";

		// Checks the max len for the allocated header
		max_len =
				strlen(head) +
				strlen(sock->url->path) +
				strlen(sock->url->addr) +
				strlen(my_cont_type) +
				101;

		// Allocates the memory for the header
		tmp = PKI_Malloc ( max_len + auth_len );

		// Prints the header into the tmp container
		len = (size_t) snprintf(tmp, max_len, head, sock->url->path, sock->url->addr, 
					my_cont_type, data_size, auth_tmp );
	}
	else
	{
		PKI_log_err ( "Method (%d) not supported!", method );
		return PKI_ERR;
	}

	// PKI_MEM *r = PKI_MEM_new_data(len, tmp);
	// URL_put_data("file://http_req.txt", r, NULL, NULL, 0, 0, NULL);
	// PKI_MEM_free(r);

	if ((rv = (int) PKI_SOCKET_write(sock, tmp, len)) < 0)
	{
		PKI_log_err("Can not write HTTP header to socket");
		PKI_Free(tmp);
		goto err;
	}

	// Free the tmp pointer that held the request header
	if (tmp) PKI_Free (tmp);

	// If we were using a POST method, we need to actually send the data
	if(data != NULL)
	{
		PKI_log_err("{DEBUG} Writing Data -> data_size = %d, data = %p", data_size, data);

		if ((PKI_SOCKET_write(sock, data, data_size)) < 0)
		{
			PKI_log_err ("Can not write POST to socket.");
			goto err;
		}
	}
	
	// Let's now wait for the response from the server
	if ((http_rv = PKI_HTTP_get_message(sock, timeout, max_size)) == NULL)
	{
		PKI_log_err ("HTTP retrieval error\n");
		goto err;
	}

	// We shall now check for the return code
	if (http_rv->code >= 400 )
	{
		goto err;
	}
	else if (http_rv->code >= 300)
	{
		/* Redirection - let's try that */
		if (http_rv->location == NULL)
		{
			PKI_log_debug ( "HTTP Redirection but no location provided!");
			goto err;
		}

    PKI_log_debug("HTTP Redirection Detected [URL: %s]", http_rv->location );

		if (strstr(http_rv->location, "://") != NULL)
		{
			URL *url_tmp = NULL;

			if( strncmp_nocase( http_rv->location, sock->url->url_s, 
					(int) strlen(http_rv->location)) == 0)
			{
				PKI_log_debug( "HTTP cyclic redirection!");
				goto err;
			}

			if ((url_tmp = URL_new ( http_rv->location )) == NULL)
			{
				PKI_log_debug("HTTP location is not a valid URI (%s)", http_rv->location );
				goto err;
			}

			if ( sock->url->ssl == 0 )
			{
				ret = PKI_HTTP_get_url ( url_tmp, data, 
					data_size, content_type, method, timeout, 
							max_size, sk, NULL );
			}
			else
			{
				PKI_SSL *ssl2 = PKI_SSL_dup ( sock->ssl );

				ret = PKI_HTTP_get_url ( url_tmp, data, 
					data_size, content_type, method, timeout, 
							max_size, sk, ssl2 );
			}

			if ( url_tmp ) URL_free ( url_tmp );
	
			goto end;

		}
		else
		{
			const char *prot_s = NULL;
			char new_url[2048];
			URL *my_new_url = NULL;
			PKI_SSL *ssl2 = PKI_SSL_dup ( sock->ssl );

			prot_s = URL_proto_to_string ( sock->url->proto );
			if( !prot_s ) goto err;

			snprintf(new_url, sizeof(new_url),"%s://%s%s", prot_s, sock->url->addr, http_rv->location );

			if( strncmp_nocase( new_url, sock->url->url_s, (int) strlen ( new_url )) == 0 )
			{
				PKI_log_debug( "HTTP cyclic redirection!");
				goto err;
			}

			my_new_url = URL_new ( new_url );

			ret = PKI_HTTP_get_url ( my_new_url, data, data_size, content_type, method,
						timeout, max_size, sk, ssl2 );

			if (ssl2) PKI_SSL_free ( ssl2 );
		}
	}
	else if (http_rv->code != 200)
	{
		PKI_log_debug( "Unknown HTTP Return code [Code: %d]", http_rv->code );
		goto err;
	}

	/*
	PKI_log_err("{DEBUG} method = %d, header->size = %d, body = %p, body_size = %d",
			  http_rv->method, http_rv->head->size, http_rv->body, http_rv->body->size);
	URL_put_data("file://http-resp-header.txt", http_rv->head, NULL, NULL, 0, 0, NULL);
	URL_put_data("file://http-resp-data.txt", http_rv->body, NULL, NULL, 0, 0, NULL);
	*/

	// If a Pointer was provided, we want the data back
	if (sk) {

		// Checks if the caller provided an already allocated data
		// structure. If not, we allocate it.
		if (*sk) PKI_STACK_MEM_free_all(*sk);

    // Allocates a new structure
		if ((*sk = PKI_STACK_MEM_new()) == NULL) {

      // If a memory error occurs report it and exit
			PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);

      // Nothing more to do
			goto err;
		}

		// Add the returned value to the stack
		if (PKI_STACK_MEM_push(*sk, http_rv->body) != PKI_OK) {
			PKI_log_err("Can not push the HTTP result body in the result stack");
			goto err;
		}

		// Remove ownership of the body PKI_MEM from the original
		// HTTP msg container
		http_rv->body = NULL;
	}

end:
	// Finally free the HTTP message memory
	if (http_rv) PKI_HTTP_free(http_rv);

	// Returns the result
	return ret;

err:
	// Error condition
	if (http_rv) PKI_HTTP_free ( http_rv );

	// Free the locally allocated memory
	if (*sk) PKI_STACK_MEM_free_all(*sk);
	*sk = NULL;

	return PKI_ERR;
}
Ejemplo n.º 10
0
PKI_MEM_STACK *URL_get_data_pkcs11_url ( URL *url, ssize_t size ) {

#ifdef HAVE_P11
	// PKCS11_CTX   *ctx   = NULL;
	PKCS11_SLOT  *slots = NULL;
	PKCS11_TOKEN *tk    = NULL;

	char *libfile = NULL;
	int num = 0;
	int i = 0;

	char * search_label = NULL;
	char * search_id = NULL;
	char * search_slot = NULL;
	char * search_slotid = NULL;

	PKI_MEM *tmp_mem = NULL;
	PKI_MEM_STACK *sk = NULL;

	if( !url ) return (NULL);

	/*
	if((libfile = pkcs11_parse_url_libpath ( url )) == NULL ) {
		return( NULL );
	}
	*/

	/*
	slot = pkcs11_parse_url_slot ( url );
	id = pkcs11_parse_url_id ( url );
	*/

	if( ctx == NULL ) {
		if((ctx = PKCS11_CTX_new ()) == NULL ) {
			return(NULL);
		}

		PKI_log_debug("Loading %s Library", url->addr );
		if(( i = PKCS11_CTX_load(ctx, url->addr)) != 0 ) {
			PKI_log_err("Can not load library %s [err::%d]", url->addr, i);
			// ERR_print_errors_fp( stderr );
		}
	}

	if( PKCS11_enumerate_slots( ctx, &slots, &num ) == -1 ) {
		PKI_log_err ("Can not enumerate slots");
		goto err;
        };

	if(( sk = PKI_STACK_MEM_new()) == NULL ) {
		goto err;
	}

	search_slot   = pkcs11_parse_url_getval( url, "slot" );
	search_slotid = pkcs11_parse_url_getval( url, "slotid" );
	search_label  = pkcs11_parse_url_getval( url, "label" );
	search_id     = pkcs11_parse_url_getval( url, "id" );
	
	if( search_slot )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::SLOT =>  %s\n", search_slot);
	if( search_slotid )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::SLOTID =>  %s\n", search_slotid);
	if( search_label )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::LABEL => %s\n", search_label);
	if( search_id )
		PKI_log_debug("DEBUG::PKCS11::SEARCH::ID =>    %s\n", search_id);

	for(i = 0; i < num; i++ ) {

		BIO *mem = NULL;
		BUF_MEM *mem_buf = NULL;

		PKCS11_CERT *certs = NULL;
		PKCS11_SLOT *p = NULL;
		PKCS11_CERT *x = NULL;

		PKCS11_KEY  *keyList = NULL;
		PKCS11_KEY  *key     = NULL;
		EVP_PKEY    *evp_pkey = NULL;

		int n = 0;
		int t = 0;
		int n_objs = 0;
		int p_ret = 0;
		
                p = &slots[i];

                if((!p) || ((tk = p->token) == NULL) ) {
			continue;
		}

		if( (search_slot) && ( strncmp_nocase( search_slot, 
				tk->label, strlen(search_slot) == 0) )) {
			continue;
		}

		if( (search_slotid) && ( atoi(search_slotid) != i )) {
			PKI_log_debug("PKCS11::SLOTID is %s (%d), curr is %d\n",
					search_slotid, atoi(search_slotid), i);
			continue;
		}

		if( strncmp_nocase( url->attrs, "cert", 4 ) == 0) {
			PKI_log_debug("PKCS11::CERT DATATYPE SELECTED!\n");
			if((mem = BIO_new(BIO_s_mem())) == NULL ) {
				goto err;
			}

			/* Get the list of certificates in the slot */
			p_ret = PKCS11_enumerate_certs( tk, &certs, &n_objs);

			for( n = 0; n < n_objs; n++ ) {

				/* Pointer to the current certificate */
				x = &certs[n];

				PKI_log_debug("PKCS11::CERT label=%s\n",
					x->label);
				PKI_log_debug("PKCS11::CERT id=");
				for( t = 0; t < x->id_len; t ++ ) {
					printf("%c", x->id[t] );
				} printf("\n");

				if( (search_label) &&
					(strncmp_nocase( search_label, x->label,
						strlen( search_label)) != 0 )){
					PKI_log_debug("PKCS11::LABEL does not"
						"match, SKIPPING!!!!\n");
					continue;
				}
 
				if( search_id ) {
					int stop = 0;

					for( t = 0; t < x->id_len; t ++ ) {
						if( search_id[t] != x->id[t] ) {
							stop = 1;
							break;
						}
					}

					if( stop == 1 ) { 
					printf("DEBUG::PKCS11::ID does not"
						"match, SKIPPING!!!!\n");
						continue;
					}
				}
 
				/* Write the cert in PEM format to memory */
				p_ret = PEM_write_bio_X509( mem, x->x509 );

				/* Get the pointer to the memory buffer */
				BIO_get_mem_ptr( mem, &mem_buf );

				/* Push a PKI_MEM buffer on the stack */
				tmp_mem = PKI_MEM_new_null();
				PKI_MEM_add ( tmp_mem, mem_buf->data, 
							mem_buf->length);
				PKI_STACK_push( sk, tmp_mem );
			}

			/* Free the temp memory buffer */
			if( mem ) BIO_free( mem );

		} else if (strncmp_nocase( url->attrs, "key", 3) == 0 ) {
			char *pin = NULL;

			PKI_log_debug("PKCS11::KEY DATATYPE SELECTED!\n");

			pin = pkcs11_parse_url_getval( url, "pin" );

			if ( (tk->loginRequired == 1) && (pin != NULL ) ) {
				p_ret = PKCS11_login ( p, 0, pin );
				PKI_log_debug("PKCS11::LOGIN Result %d\n",
					p_ret );
        		}

			if((mem = BIO_new(BIO_s_mem())) == NULL ) {
				goto err;
			}

		        p_ret = PKCS11_enumerate_keys ( tk, &keyList, &n_objs );

			for( n = 0; n < n_objs; n++ ) {
				key = &keyList[n];

				printf("DEBUG::PKCS11::KEY label=%s\n",
					key->label);
				printf("DEBUG::PKCS11::KEY id=");
				for( t = 0; t < key->id_len; t ++ ) {
					printf("%c", key->id[t] );
				} printf("\n");

				if( (search_label) &&
					(strncmp_nocase( search_label, x->label,
						strlen( search_label)) != 0 )){
					printf("DEBUG::PKCS11::LABEL does not"
						"match, SKIPPING!!!!\n");
					continue;
				}
 
				if( search_id ) {
					int stop = 0;

					for( t = 0; t < x->id_len; t ++ ) {
						if( search_id[t] != x->id[t] ) {
							stop = 1;
							break;
						}
					}

					if( stop == 1 ) { 
					printf("DEBUG::PKCS11::ID does not"
						"match, SKIPPING!!!!\n");
						continue;
					}
				}
 
				/* Get Private Key in OpenSSL format */
				evp_pkey = PKCS11_get_private_key( key );

				/* Write the cert in PEM format to memory */
				p_ret = PEM_write_bio_PUBKEY( mem, evp_pkey );

				/* Get the pointer to the memory buffer */
				BIO_get_mem_ptr( mem, &mem_buf );

				/* Push a PKI_MEM buffer on the stack */
				tmp_mem = PKI_MEM_new_null();
				PKI_MEM_add ( tmp_mem, mem_buf->data, 
							mem_buf->length);
				PKI_STACK_push( sk, tmp_mem );
			}

			if( mem ) BIO_free ( mem );

		} else {
			printf("DEBUG::PKCS11::OTHER DATATYPE SELECTED!\n");
		}
	}

err:
	if( slots ) PKCS11_release_all_slots( ctx, slots, num );

	/*
	if( ctx ) { 
		PKCS11_CTX_unload(ctx);
		PKCS11_CTX_free(ctx);
	}
	*/

	if( libfile ) PKI_Free (libfile);

	if( search_slot ) PKI_Free ( search_slot );
	if( search_slotid ) PKI_Free ( search_slotid );
	if( search_label ) PKI_Free ( search_label );
	if( search_id ) PKI_Free ( search_id );

	return ( sk );

#else
	return ( NULL );
#endif
}
Ejemplo n.º 11
0
int OCSPD_build_ca_list ( OCSPD_CONFIG *handler,
			PKI_CONFIG_STACK *ca_conf_sk) {

	int i = 0;
	PKI_STACK *ca_list = NULL;

	PKI_log_debug("Building CA List");

	if ( !ca_conf_sk ) {
		PKI_log( PKI_LOG_ERR, "No stack of ca configs!");
		return ( PKI_ERR );
	}

	if((ca_list = PKI_STACK_new((void (*))CA_LIST_ENTRY_free)) == NULL ) {
		PKI_log_err ( "Memory Error");
	return ( PKI_ERR );
	}

	for (i = 0; i < PKI_STACK_CONFIG_elements( ca_conf_sk ); i++)
	{
		char *tmp_s = NULL;
		URL *tmp_url = NULL;
		PKI_X509_CERT *tmp_cert = NULL;

		CA_LIST_ENTRY *ca = NULL;
		PKI_CONFIG *cnf = NULL;

		/* Get the current Configureation file */
		cnf = PKI_STACK_CONFIG_get_num( ca_conf_sk, i );
		if (!cnf) continue;

		/* Get the CA cert from the cfg file itself */
		if((tmp_s = PKI_CONFIG_get_value( cnf, "/caConfig/caCertValue" )) == NULL )
		{
			/* Get the CA parsed url */
			if((tmp_url = URL_new( PKI_CONFIG_get_value( cnf, "/caConfig/caCertUrl" ))) == NULL )
			{
				/* Error, can not parse url data */
				PKI_log( PKI_LOG_ERR, "Can not parse CA cert url (%s)", 
					PKI_CONFIG_get_value(cnf, "/caConfig/caCertUrl"));

				continue;
			}

			if((tmp_cert = PKI_X509_CERT_get_url(tmp_url, NULL, NULL ))== NULL)
			{
				PKI_log_err("Can not get CA cert from (%s)", tmp_url);
				URL_free (tmp_url);

				continue;
			}
		}
		else
		{
			PKI_X509_CERT_STACK *cc_sk = NULL;
			PKI_MEM *mm = NULL;

			if((mm = PKI_MEM_new_null()) == NULL )
			{
				PKI_Free(tmp_s);
				continue;
			}

			PKI_MEM_add ( mm, tmp_s, strlen(tmp_s));

			if((cc_sk=PKI_X509_CERT_STACK_get_mem(mm, NULL)) == NULL )
			{
				PKI_log_err ( "Can not parse cert from /caConfig/caCertValue");
				PKI_Free(tmp_s);

				continue;
			}

			if ((tmp_cert = PKI_STACK_X509_CERT_pop( cc_sk )) == NULL )
			{
				PKI_log_err ( "No elements on stack from /caConfig/caCertValue");

				PKI_STACK_X509_CERT_free_all(cc_sk);
				PKI_Free(tmp_s);

				continue;
			}

			PKI_STACK_X509_CERT_free ( cc_sk );
			PKI_Free(tmp_s);
		}

		/* OCSPD create the CA entry */
		if ((ca = CA_LIST_ENTRY_new()) == NULL )
		{
			PKI_log_err ( "CA List structure init error");

			/* remember to do THIS!!!! */
			if( tmp_url ) URL_free ( tmp_url );
			if( tmp_cert ) PKI_X509_CERT_free ( tmp_cert );

			continue;
		}

		ca->ca_cert = tmp_cert;
		tmp_cert = NULL;

		ca->ca_url = tmp_url;
		tmp_url = NULL;

		ca->ca_id = PKI_CONFIG_get_value( cnf, "/caConfig/name" );
		ca->cid = CA_ENTRY_CERTID_new ( ca->ca_cert, handler->digest );

		/* Get the CRL URL and the CRL itself */
		if((tmp_s = PKI_CONFIG_get_value(cnf, "/caConfig/crlUrl")) == NULL)
		{
			PKI_STACK *cdp_sk = NULL;

			/* Now let's get it from PRQP */

			/* Now from the Certificate */
			
			if((cdp_sk = PKI_X509_CERT_get_cdp (ca->ca_cert)) ==NULL)
			{
				// No source for the CRL Distribution Point
				PKI_log_err ( "ERROR::Can not find the CDP for %s, skipping CA", ca->ca_id );

				CA_LIST_ENTRY_free ( ca );
				continue;
			}

			while ((tmp_s = PKI_STACK_pop ( cdp_sk )) != NULL)
			{
				if ((ca->crl_url = URL_new ( tmp_s )) == NULL )
				{
					PKI_log_err( "URL %s not in the right format!");
					CA_LIST_ENTRY_free ( ca );
					continue;
				}
				else if( tmp_s ) PKI_Free ( tmp_s );

				break;
			}
		}
		else
		{
			PKI_log_debug("Got CRL Url -> %s", tmp_s );

			if((ca->crl_url = URL_new ( tmp_s )) == NULL )
			{
				PKI_log_err ("Error Parsing CRL URL [%s] for CA [%s]", ca->ca_id, tmp_s);

				CA_LIST_ENTRY_free ( ca );
				PKI_Free(tmp_s);

				continue;
			}

			PKI_Free(tmp_s);
		}

		if(OCSPD_load_crl ( ca, handler ) == PKI_ERR )
		{
			PKI_log_err ( "Can not get CRL for %s", ca->ca_id);
			CA_LIST_ENTRY_free ( ca );

			continue;
		}

		/* If the Server has a Token to be used with this CA, let's
                   load it */
		if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/serverToken" )) == NULL)
		{
			/* No token in config, let's see if a specific cert
			   is configured */
			ca->token = NULL;

			if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/serverCertUrl" )) == NULL )
			{
				/* No cert is configured, we will use the defaults */
				ca->server_cert = NULL;
			}
			else
			{
				/* The Server's cert URL is found, let's load the certificate */
				if ((tmp_cert = PKI_X509_CERT_get ( tmp_s, NULL, NULL )) == NULL )
				{
					PKI_log_err("Can not get server's cert from %s!", tmp_s );

					CA_LIST_ENTRY_free ( ca );
					PKI_Free(tmp_s);

					continue;
				}
				else
				{
					ca->server_cert = tmp_cert;
				}

				PKI_Free(tmp_s);
			}
		}
		else
		{
			/* A Token for this CA is found - we do not load
 			   it to avoid problems with Thread Initialization */
			ca->server_cert = NULL;
			ca->token_name = tmp_s;
			ca->token = PKI_TOKEN_new_null();

			if ((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/pkiConfigDir" )) != NULL) {
				ca->token_config_dir = strdup( tmp_s );
				PKI_Free(tmp_s);
			}
			else
			{
				ca->token_config_dir = strdup(handler->token_config_dir);
			}
		}

		if((tmp_s = PKI_CONFIG_get_value ( cnf, "/caConfig/caCompromised" )) == NULL) {
			ca->compromised = 0;
		}
		else
		{
			ca->compromised = atoi(tmp_s);
			PKI_Free(tmp_s);
		}

		/* Responder Id Type */
		if ((tmp_s = PKI_CONFIG_get_value(cnf, "/caConfig/responderIdType")) != NULL)
		{
			if (strncmp_nocase(tmp_s, "keyid", 5) == 0) 
			{
				ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_KEYID;
			}
			else if (strncmp_nocase(tmp_s, "name", 4) == 0)
			{
				ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_NAME;
			}
			else
			{
				PKI_log_err("Can not parse responderIdType: %s (allowed 'keyid' or 'name')", tmp_s);
				exit(1);
			}

			PKI_Free(tmp_s);
		}
		else
		{
			// Default Value
			ca->response_id_type = PKI_X509_OCSP_RESPID_TYPE_BY_NAME;
		}

		// Now let's add the CA_LIST_ENTRY to the list of configured CAs
		PKI_STACK_push ( ca_list, ca );

	}

	handler->ca_list = ca_list;

	return ( PKI_OK );
}
Ejemplo n.º 12
0
/* Functions */
OCSPD_CONFIG * OCSPD_load_config(char *configfile)
{
	OCSPD_CONFIG *h = NULL;
	PKI_CONFIG *cnf = NULL;
	PKI_CONFIG_STACK *ca_config_stack = NULL;

	char *tmp_s = NULL;
	char *tmp_s2 = NULL;

	int i;

	/* Check for the environment variable PRQP_CONF */
	if (configfile == NULL) configfile = getenv("OCSPD_CONF");

	/* If not, check for the default CONFIG_FILE */
	if (configfile == NULL) configfile = CONFIG_FILE;

	if( !configfile ) {
		/* No config file is available */
		PKI_log(PKI_LOG_ERR, "No config file provided!");
		return (NULL);
	}

	/* Load the config file */
	if(( cnf = PKI_CONFIG_load ( configfile )) == NULL ) {
		PKI_log( PKI_LOG_ERR, "Can not load config file [%s]!",
			configfile );
		return (NULL);
	}
	if(( h = (OCSPD_CONFIG *)PKI_Malloc(sizeof(OCSPD_CONFIG))) == NULL) {
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		goto err;
	}

	/* Set the group and user string to NULL */
	h->user = NULL;
	h->group = NULL;

	/* Set the PRQPD verbose status */
	h->verbose   = 0;
	h->debug     = 0;
	h->nthreads  = 5;
	h->http_proto = "1.0";
	h->max_timeout_secs = 5;

	h->crl_auto_reload = 3600;
	h->crl_reload_expired = 1;
	h->crl_check_validity = 600;

	/* Copy the config filename so that it could be re-loaded on SIGHUP */
	h->cnf_filename = strdup( configfile );

	/* Initialize the COND variables and MUTEXES */
	for( i = 0; i < sizeof ( h->mutexes ) / sizeof( PKI_MUTEX ); i++ )
	{
		PKI_MUTEX_init ( &h->mutexes[i] );
	}

	for( i = 0; i < sizeof ( h->condVars ) / sizeof( PKI_COND ); i++)
	{
		PKI_COND_init ( &h->condVars[i] );
	}

	PKI_RWLOCK_init ( &h->crl_lock );

	/* Token Initialization */
	if (( tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/general/pkiConfigDir")) == NULL)
	{
		PKI_log_err("Missing pkiConfigDir in configuration!");
		return NULL;
	}
	else 
	{
		if ((tmp_s2 = PKI_CONFIG_get_value( cnf, "/serverConfig/general/token" )) != NULL)
		{
			h->token_name = strdup( tmp_s2 );
			h->token_config_dir = strdup ( tmp_s );

			if ((h->token = PKI_TOKEN_new_null()) == NULL)
			{
				PKI_log( PKI_LOG_ERR, "Memory error for new token");
				exit(1);
			}

			PKI_Free(tmp_s2);
		}
		else
		{
			PKI_log_err("No General Token provided in configuration.");

			PKI_Free(tmp_s);
			return NULL;
		}

		PKI_Free(tmp_s);
	}

	/* Thread configuration */
	if((tmp_s = PKI_CONFIG_get_value(cnf, "/serverConfig/general/spawnThreads")) != NULL)
	{
		int t = 0;
		if((t = atoi( tmp_s )) > 0 ) h->nthreads = t;

		PKI_Free(tmp_s);
	}

	if((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/general/caConfigDir")) != NULL)
	{
		h->ca_config_dir = strdup(tmp_s);

		ca_config_stack = PKI_CONFIG_load_dir(h->ca_config_dir, NULL);
		if (ca_config_stack == NULL)
		{
			PKI_log( PKI_LOG_ERR, "Can't load caConfigDir (%s)", h->ca_config_dir);
			PKI_Free(tmp_s);

			goto err;
		}

		PKI_Free(tmp_s);
	}
	else
	{
		PKI_log( PKI_LOG_ERR, "/serverConfig/general/caConfigDir needed in conf!\n");
		goto err;
	}

	/* Pid File */
	if((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/general/pidFile")) != NULL )
	{
		h->pidfile = strdup(tmp_s);

		PKI_Free(tmp_s);
	}

	/* AutoReload timeout */
	if((tmp_s = PKI_CONFIG_get_value( cnf, 
		"/serverConfig/general/crlAutoReload")) != NULL)
	{
		h->crl_auto_reload = atoi(tmp_s);

		if( h->crl_auto_reload <= 0 )
		{
			h->crl_auto_reload = 0;
			PKI_log(PKI_LOG_INFO, "Auto Reload Disabled");
		}

		PKI_Free(tmp_s);
	}

	/* CRL validity check timeout */
	if((tmp_s = PKI_CONFIG_get_value( cnf, 
			"/serverConfig/general/crlCheckValidity")) != NULL )
	{
		h->crl_check_validity = atoi(tmp_s);
		if ( h->crl_check_validity <= 0 )
		{
			h->crl_check_validity = 0;
			PKI_log(PKI_LOG_INFO, "CRL check validity disabled");
		}

		PKI_Free(tmp_s);
	}

	/* AutoReload timeout */
	if ((tmp_s = PKI_CONFIG_get_value( cnf, 
				"/serverConfig/general/crlReloadExpired")) != NULL )
	{
		if (strncmp_nocase(tmp_s, "n", 1) == 0)
		{
			h->crl_reload_expired = 0;
			PKI_log(PKI_LOG_INFO, "Expired CRLs Reload Disabled");
		}

		PKI_Free(tmp_s);
	}

	/* Server Privileges */
	if ((tmp_s = PKI_CONFIG_get_value(cnf, "/serverConfig/security/user")) != NULL)
	{
		h->user = strdup(tmp_s);
		PKI_Free(tmp_s);
	}

	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/security/group" )) != NULL)
	{
		h->group = strdup(tmp_s);
		PKI_Free(tmp_s);
	}

	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/security/chrootDir" )) != NULL )
	{
		h->chroot_dir = strdup(tmp_s);
		PKI_Free(tmp_s);
	}

	/* Bind Address */
	if((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/network/bindAddress" )) == NULL)
	{
		// If not bindAddress, let's use the universal one
		tmp_s = strdup("http://0.0.0.0:2560");
	}

	if ((h->bindUrl = URL_new( tmp_s )) == NULL)
	{
		PKI_log( PKI_LOG_ERR, "Can't parse bindAddress (%s)", tmp_s );
		PKI_Free(tmp_s);

		goto err;
	}

	// We need to free the tmp_s
	PKI_Free(tmp_s);

	/* HTTP Version */
	if((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/network/httpProtocol")) != NULL)
	{
		h->http_proto = strdup(tmp_s);
		PKI_Free(tmp_s);
	}

	/* Timeout for incoming connections */
	if((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/network/timeOut")) != NULL )
	{
		long t = 0;

		if ((t = atol( tmp_s )) > 0) h->max_timeout_secs = (unsigned int) t;
		PKI_Free(tmp_s);
	}

	/* Maximum Request Size */
	if((tmp_s = PKI_CONFIG_get_value( cnf,
				"/serverConfig/response/maxReqSize" )) != NULL ) {
		int t = 0;

		if((t = atoi( tmp_s )) > 0 ) {
			h->max_req_size = t;
		}
		PKI_Free(tmp_s);
	}


	// Default
	h->digest = PKI_DIGEST_ALG_SHA1;

	/* Digest Algorithm to be used */
	if ((tmp_s = PKI_CONFIG_get_value(cnf, "/serverConfig/response/digestAlgorithm" )) != NULL)
	{
		h->digest = PKI_DIGEST_ALG_get_by_name( tmp_s );

		if (!h->digest) 
		{
			PKI_log_err("Can not parse response digest algorithm: %s", tmp_s);
			exit(1);
		}
		else PKI_log_debug("Selected response digest algorithm: %s", tmp_s);

		PKI_Free(tmp_s);
	}

	/* Signing Digest Algorithm to be used */
	if((tmp_s = PKI_CONFIG_get_value( cnf,
			"/serverConfig/response/signatureDigestAlgorithm" )) == NULL)
	{
		PKI_log_debug("No specific signature digest algorithm selected.");
		h->sigDigest = NULL;
	}
	else
	{
		h->sigDigest = PKI_DIGEST_ALG_get_by_name( tmp_s );

		if (!h->sigDigest) 
		{
			PKI_log_err("Can not parse signing digest algorithm: %s", tmp_s);
			exit(1);
		}
		else PKI_log_debug("Selected signature digest algorithm: %s", tmp_s);

		PKI_Free(tmp_s);
	}

	/* Now Parse the PRQP Response Section */
	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/response/validity/days" )) != NULL)
	{
		h->ndays = atoi(tmp_s);
		PKI_Free(tmp_s);
	}

	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/response/validity/mins" )) != NULL)
	{
		h->nmin = atoi(tmp_s);
		PKI_Free(tmp_s);
	}

	h->set_nextUpdate = h->ndays * 3600 + h->nmin * 60;

	/* Database Options */
	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/general/dbUrl")) != NULL)
	{
		if ((h->db_url = URL_new ( tmp_s )) == NULL)
		{
			PKI_log_err ( "Database Url not parsable (%s)", tmp_s );
			PKI_Free(tmp_s);
			goto err;
		}

		PKI_Free(tmp_s);
	}

	/* Database Persistant */
	if ((tmp_s = PKI_CONFIG_get_value( cnf, "/serverConfig/general/dbPersistant")) != NULL)
	{
		if (strncmp_nocase ( "n", tmp_s, 1 ) == 0 )
			h->db_persistant = 0;
		else 
			h->db_persistant = 1;

		PKI_Free(tmp_s);
	}

	/* Now we should load the CA configuration files and generate the
	   CERT_ID for the different CAs */
	if ((OCSPD_build_ca_list( h, ca_config_stack )) == PKI_ERR )
	{

		PKI_log(PKI_LOG_ERR, "Can not build CA list!");
		if (ca_config_stack) PKI_STACK_CONFIG_free ( ca_config_stack );
		goto err;
	}

	if (ca_config_stack) PKI_STACK_CONFIG_free ( ca_config_stack );

	return ( h );

err:
	if( ca_config_stack ) PKI_STACK_CONFIG_free ( ca_config_stack );
	if( cnf ) PKI_CONFIG_free ( cnf );
	if( h ) PKI_Free ( h );

	return( NULL );
}
Ejemplo n.º 13
0
PKI_X509_EXTENSION *PKI_X509_EXTENSION_value_new_profile ( 
		PKI_X509_PROFILE *profile, PKI_CONFIG *oids, 
			PKI_CONFIG_ELEMENT *extNode, PKI_TOKEN *tk ) {

	/* TODO: Implement the extended version of the extensions, this
	   should allow better extensions management. That is, the value
	   will be encoded as:

		extName=@section

		[ section ]
		extName=value
		otherVal=val
		otherVal=val
		...

	   The corresponding XML should be:

		<pki:extension name=".." critical=".." >
		   <pki:value name="" type=".." tag=".."> .. </pki:value>
		   <pki:value name="" type=".." tag=".."> .. </pki:value>
		</pki:extension>

	  */

	PKI_CONFIG_ELEMENT *valNode = NULL;
	PKI_X509_EXTENSION *ret = NULL;
	PKI_X509_EXTENSION_VALUE *ext = NULL;

	xmlChar *type_s = NULL;
	xmlChar *tag_s = NULL;
	xmlChar *oid_s = NULL;
	xmlChar *value_s = NULL;
	xmlChar *name_s = NULL;
	xmlChar *crit_s = NULL;

	PKI_OID *oid = NULL;


	X509V3_CTX v3_ctx;
	CONF *conf = NULL;

	char *envValString = NULL;
	char *valString = NULL;
	int crit = 0;

	if( !profile || !extNode ) {
		PKI_log_debug("ERROR, no profile or extNode provided in "
				"PKI_X509_EXTENSION_value_new_profile()");
		return (NULL);
	}

	if((crit_s = xmlGetProp( extNode, BAD_CAST "critical" )) != NULL ) {
		if( strncmp_nocase( (char *) crit_s, "n", 1 ) == 0) {
			crit = 0;
		} else {
			crit = 1;
		}
	}

	if((name_s = xmlGetProp( extNode, BAD_CAST "name" )) == NULL ) {
		PKI_log_debug("ERROR, no name property in node %s", 
							extNode->name);
		if( crit_s ) xmlFree ( crit_s );
		return (NULL);
	}

	if ((oid = PKI_OID_get((char *) name_s)) == NULL)
	{
		if ((oid = PKI_CONFIG_OID_search(oids, (char *)name_s)) == NULL)
		{
			PKI_ERROR(PKI_ERR_OBJECT_CREATE, NULL);
			return NULL;
		}
	}
	else
	{
		PKI_OID_free ( oid );
	}

	/*
	int nid = NID_undef;
	if((nid = OBJ_sn2nid( (char *) name_s )) == NID_undef ) {
		PKI_OID *oid = NULL;

		oid = PKI_CONFIG_OID_search ( oids, (char *) name_s );
		if( !oid ) {
			PKI_log_debug( "ERROR, can not create object (%s)!",
				name_s );
			return( NULL );
		}
	}
	*/

	if ((valString = (char *) PKI_Malloc(BUFF_MAX_SIZE)) == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		if( name_s ) xmlFree ( name_s );
		if( crit_s ) xmlFree (crit_s);
		return( NULL );
	}

	memset( valString, 0, BUFF_MAX_SIZE );

	if( crit == 1 ) snprintf( valString, BUFF_MAX_SIZE -1, "%s", "critical" );

	for (valNode = extNode->children; valNode; valNode = valNode->next)
	{
		if ((valNode->type == XML_ELEMENT_NODE) &&
				((strncmp_nocase((char *)(valNode->name),"value",5)) == 0))
		{
			char tmp[BUFF_MAX_SIZE];

			type_s = xmlGetProp( valNode, BAD_CAST "type" );
			tag_s = xmlGetProp( valNode, BAD_CAST "tag" );
			oid_s = xmlGetProp( valNode, BAD_CAST "oid" );

			value_s = xmlNodeListGetString( profile, 
						valNode->xmlChildrenNode, 0);

			if( oid_s ) {
				/* Let's be sure the OID is created */
				if((oid = PKI_CONFIG_OID_search(oids, 
						(char *) value_s)) == NULL ) {
					PKI_log_debug ("WARNING, no oid "
						"created for %s!", oid_s );
				} else {
					PKI_OID_free ( oid );
				}
			}

			memset((unsigned char * )tmp, 0, BUFF_MAX_SIZE );

			if( tag_s ) {
				snprintf( tmp, BUFF_MAX_SIZE - 1, "%s;", 
					_ext_txt( tag_s ) );
			}

			if( type_s == NULL ) {
				if( !oid_s ) {
					strncat( tmp, (char *) value_s, 
							BUFF_MAX_SIZE - strlen( tmp ));
				} else {
					if( value_s && (strlen((char *) value_s) > 0) ) {
						strncat( tmp, (char *) oid_s, 
						 	BUFF_MAX_SIZE - strlen( tmp ) );
						strncat( tmp, ":", 
							BUFF_MAX_SIZE - strlen ( tmp ));
						strncat( tmp, (char *) value_s,
							BUFF_MAX_SIZE - strlen (tmp ));
					} else {
						strncat( tmp, "OID:", 
							BUFF_MAX_SIZE - strlen(tmp));
						strncat( tmp, (char *) oid_s, 
							BUFF_MAX_SIZE - strlen( tmp ));
					}
				}
			} else {
				strncat( tmp, (char *) _ext_txt(type_s), 
						BUFF_MAX_SIZE - strlen( tmp ));
				if( value_s && (strlen((char*)value_s) > 0) ) {
					if(strcmp_nocase( (char*) type_s, "ia5org")) {
					    strncat( tmp, ":", 
						BUFF_MAX_SIZE - strlen( tmp ));
					} else {
					    strncat( tmp, ",", 
						BUFF_MAX_SIZE - strlen( tmp ));
					}
					strncat( tmp, (char *) value_s, 
						BUFF_MAX_SIZE - strlen( tmp ));
				}
			}
				
			if( strlen( valString ) > 0 ) {
				strncat( valString, ",", BUFF_MAX_SIZE - 1);
			}

			strncat( valString, (char *) tmp, BUFF_MAX_SIZE - 1 );

			if( type_s ) xmlFree ( type_s );
			if( oid_s ) xmlFree ( oid_s );
			if( tag_s ) xmlFree ( tag_s );
			if( value_s ) xmlFree ( value_s );
        	}
	}
	//PKI_log_debug("INFO, Encoding %s=%s", name_s, valString);

	v3_ctx.db = NULL;
	v3_ctx.db_meth = NULL;
	v3_ctx.crl = NULL;
	v3_ctx.flags = 0;

	if ( tk ) {
		v3_ctx.issuer_cert  =  (X509 *)
			PKI_X509_get_value ( tk->cacert );
		v3_ctx.subject_cert =  (X509 *)
			PKI_X509_get_value ( tk->cert );
		v3_ctx.subject_req  =  (X509_REQ *)
			PKI_X509_get_value ( tk->req );
	} else {
		v3_ctx.issuer_cert = NULL;
		v3_ctx.subject_cert = NULL;
		v3_ctx.subject_req = NULL;
	}

	/* Sets the ctx.db and ctx.method */
	conf = NCONF_new( NULL );
	X509V3_set_nconf(&v3_ctx, conf);

	if((envValString = get_env_string( valString )) != NULL ) {
		PKI_log_debug("EXT STRING => %s=%s", name_s, envValString);
		ext = X509V3_EXT_conf(NULL, &v3_ctx, (char *) name_s, 
						(char *) envValString);
		PKI_Free ( envValString );
	} else {
		ext = X509V3_EXT_conf(NULL, &v3_ctx, (char *) name_s, 
						(char *) valString);
	}

	if( !ext ) {
		PKI_log_debug("EXT::ERR::%s",
			ERR_error_string(ERR_get_error(), NULL ));
		return NULL;
	}

	if(( ret = PKI_X509_EXTENSION_new()) == NULL ) {
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		X509_EXTENSION_free ( ext );
		return NULL;
	}

	ret->value = ext;
	ret->oid = ext->object;

	if( name_s ) xmlFree ( name_s );
	if( crit_s ) xmlFree (crit_s );

	if( valString ) PKI_Free ( valString );
	if( conf ) NCONF_free ( conf );

	return ( ret );
}