Пример #1
0
/**
 * The main program.
 */
int main( int argc, char *argv[] )
{
  int fd_ascii, fd_bin;
  struct stat stat_buf_ascii, stat_buf_bin;

  FILE *fp_ascii = fopen("record1.txt", "r");
  FILE *fp_bin = fopen("record1.bin", "w+");

  write_binary_file(fp_ascii, fp_bin);

  rewind(fp_bin); // reset point to the beginning of the file.
  show_reocrds(fp_bin);

  fclose(fp_ascii);
  fclose(fp_bin);

  fd_ascii = open("record1.txt", O_RDONLY);
  fd_bin = open("record1.bin", O_RDONLY);

  fstat(fd_ascii, &stat_buf_ascii);
  fstat(fd_bin, &stat_buf_bin);

  printf("Size of ascii file:  %lld bytes\n", stat_buf_ascii.st_size);
  printf("Size of binary file: %lld bytes\n", stat_buf_bin.st_size);
  
  return 0;
}
Пример #2
0
void Insert::execute(char* filename) {
    if (J2B(filename)) {
        write_binary_file();
        update_catalog();
        cout << "Insert file done!" << endl;
    } else {
        cout << "Insert file failed!" << endl;
    }
}
Пример #3
0
/*
 * Takes as input the name of the file to write the cert to on the
 * local file system (full path name expected).
 * The cert_data argument should contain the PKCS7 base64 encoded
 * certificate, with the cert_len argument specifying the length
 * of the cert.  This routine will either write the cert to the
 * local file system "as is", or it will convert the cert to
 * PEM format and write it as a PEM file.
 */
static void save_cert (char *file_name, unsigned char *cert_data, int cert_len)
{
    int pem_len;
    unsigned char *pem;
    char full_file_name[MAX_FILENAME_LEN];

    if (pem_out) {
	pem_len = est_convert_p7b64_to_pem(cert_data, cert_len, &pem);
	if (pem_len > 0) {
	    snprintf(full_file_name, MAX_FILENAME_LEN, "%s.%s", file_name, "pem");
	    write_binary_file(full_file_name, pem, pem_len);
	    free(pem);
	}
    } else {
	snprintf(full_file_name, MAX_FILENAME_LEN, "%s.%s", file_name, "pkcs7");
        write_binary_file(full_file_name, cert_data, cert_len);
    }
}
Пример #4
0
static int regular_csr_attempt (EST_CTX *ectx)
{
    int rv;
    unsigned char *attr_data = NULL;
    int attr_len;
    char file_name[MAX_FILENAME_LEN];

    /*
     * Just get the CSR attributes
     */
    rv = est_client_get_csrattrs(ectx, &attr_data, &attr_len);
    if (rv != EST_ERR_NONE) {
        printf("\nWarning: CSR attributes were not available");
    } else {
        snprintf(file_name, MAX_FILENAME_LEN, "%s/csr.base64", out_dir);
        write_binary_file(file_name, attr_data, attr_len);
    }
    return (rv);
}
int main(int argc, char *argv[])
{
	struct saved_data data;
	const char *path;
	char stack_path[PATH_MAX + 1];
	int rc;

	if (argc != 2) {
		fprintf(stderr, "usage: %s input_file\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	memset(&data, 0, sizeof(data));

	path = argv[1];

	rc = process_file(&data, path);
	if (rc < 0)
		return rc;

	rc = sort_specs(&data);
	if (rc)
		return rc;

	rc = snprintf(stack_path, sizeof(stack_path), "%s.bin", path);
	if (rc < 0 || rc >= sizeof(stack_path))
		return rc;
	rc = write_binary_file(&data, stack_path);
	if (rc < 0)
		return rc;

	rc = free_specs(&data);
	if (rc < 0)
		return rc;

	return 0;
}
Пример #6
0
/*
 * This test case uses an existing expired cert and
 * attempts to re-enroll it.  The expired certs contains
 * several X509 extensions. We verify the new issued
 * cert preserves these extensions using grep.  Note, 
 * preserving these extensions requires the OpenSSL CA
 * to enable the "copy_extensions" knob in the OpenSSL
 * config file.  This is why this test suite uses a
 * unique copy of estExampleCA.cnf.
 */
static void us898_test2 (void) 
{
    EST_CTX *ectx;
    EVP_PKEY *key;
    unsigned char *key_raw;
    int key_len;
    unsigned char *cert_raw;
    int cert_len;
    int rv;
    int pkcs7_len = 0;
    unsigned char *new_cert = NULL;
    X509 *cert = NULL;
    BIO *in;
    char cmd[200];
    unsigned char *attr_data = NULL;
    int attr_len;

    LOG_FUNC_NM;

    /*
     * Create a client context 
     */
    ectx = est_client_init(cacerts, cacerts_len, 
                           EST_CERT_FORMAT_PEM,
                           client_manual_cert_verify);
    CU_ASSERT(ectx != NULL);

    /*
     * Set the authentication mode to use a user id/password
     */
    rv = est_client_set_auth(ectx, US898_UID, US898_PWD, NULL, NULL);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Set the EST server address/port
     */
    est_client_set_server(ectx, US898_SERVER_IP, US898_SERVER_PORT);

    /*
     * Read in the private key
     */
    key_len = read_binary_file("US898/key-expired.pem", &key_raw);
    CU_ASSERT(key_len > 0);
    key = est_load_key(key_raw, key_len, EST_FORMAT_PEM);
    CU_ASSERT(key != NULL);
    free(key_raw);

    /*
     * Read in the old cert
     */
    cert_len = read_binary_file("US898/cert-expired.pem", &cert_raw);
    CU_ASSERT(cert_len > 0);
    in = BIO_new_mem_buf(cert_raw, cert_len);
    CU_ASSERT(in != NULL);
    if (!in) return;
    cert = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
    CU_ASSERT(cert != NULL);
    if (!cert) return; 
    BIO_free_all(in);
    free(cert_raw);

    /*
     * Get the latest CSR attributes
     */
    rv = est_client_get_csrattrs(ectx, &attr_data, &attr_len);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Enroll an expired cert that contains x509 extensions.
     */
    rv = est_client_reenroll(ectx, cert, &pkcs7_len, key);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Retrieve the cert that was given to us by the EST server
     */
    if (rv == EST_ERR_NONE) {
	new_cert = malloc(pkcs7_len);
	CU_ASSERT(new_cert != NULL);
	rv = est_client_copy_enrolled_cert(ectx, new_cert);
	CU_ASSERT(rv == EST_ERR_NONE);
    }

    /*
     * Save the cert to a local file
     */
    rv = write_binary_file(US898_TC2_CERT_B64, new_cert, pkcs7_len);
    CU_ASSERT(rv == 1);

    /*
     * Base 64 decode the cert response
     */
    sprintf(cmd, "openssl base64 -d -in %s -out %s", US898_TC2_CERT_B64, US898_TC2_CERT_PK7);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Convert the pkcs7 cert to a PEM cert
     */
    sprintf(cmd, "openssl pkcs7 -in %s -inform DER -print_certs -out %s", US898_TC2_CERT_PK7, US898_TC2_CERT_PEM);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Convert PEM cert to a textual representation of the cert
     */
    sprintf(cmd, "openssl x509 -text -in %s > %s", US898_TC2_CERT_PEM, US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Verify the jimbob DNS extension was preserved
     */
    sprintf(cmd, "grep jimbob %s", US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Verify the bobcat DNS extension was preserved
     */
    sprintf(cmd, "grep bobcat %s", US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Verify the IP address extension was preserved
     */
    sprintf(cmd, "grep 172 %s", US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Verify the Repudiation key usage extension was preserved
     */
    sprintf(cmd, "grep Repudiation %s", US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Verify the public key was preserved
     */
    sprintf(cmd, "grep '00:e3:ca:38:65:fb:9c:46:a6:22:b1:be:17:bc:50' %s", US898_TC2_CERT_TXT);
    rv = system(cmd);
    CU_ASSERT(rv == 0);

    /*
     * Clean up
     */
    if (new_cert) free(new_cert);
    est_destroy(ectx);
}
Пример #7
0
int main(int argc, char *argv[])
{
	const char *path = NULL;
	const char *out_file = NULL;
	char stack_path[PATH_MAX + 1];
	char *tmp = NULL;
	int fd, rc, opt;
	FILE *policy_fp = NULL;
	struct stat buf;
	struct selabel_handle *rec = NULL;
	struct saved_data *data = NULL;

	if (argc < 2)
		usage(argv[0]);

	while ((opt = getopt(argc, argv, "o:p:")) > 0) {
		switch (opt) {
		case 'o':
			out_file = optarg;
			break;
		case 'p':
			policy_file = optarg;
			break;
		default:
			usage(argv[0]);
		}
	}

	if (optind >= argc)
		usage(argv[0]);

	path = argv[optind];
	if (stat(path, &buf) < 0) {
		fprintf(stderr, "Can not stat: %s: %m\n", path);
		exit(EXIT_FAILURE);
	}

	/* Open binary policy if supplied. */
	if (policy_file) {
		policy_fp = fopen(policy_file, "r");

		if (!policy_fp) {
			fprintf(stderr, "Failed to open policy: %s\n",
							    policy_file);
			exit(EXIT_FAILURE);
		}

		if (sepol_set_policydb_from_file(policy_fp) < 0) {
			fprintf(stderr, "Failed to load policy: %s\n",
							    policy_file);
			fclose(policy_fp);
			exit(EXIT_FAILURE);
		}
	}

	/* Generate dummy handle for process_line() function */
	rec = (struct selabel_handle *)calloc(1, sizeof(*rec));
	if (!rec) {
		fprintf(stderr, "Failed to calloc handle\n");
		if (policy_fp)
			fclose(policy_fp);
		exit(EXIT_FAILURE);
	}
	rec->backend = SELABEL_CTX_FILE;

	/* Need to set validation on to get the bin file generated by the
	 * process_line function, however as the bin file being generated
	 * may not be related to the currently loaded policy (that it
	 * would be validated against), then set callback to ignore any
	 * validation - unless the -p option is used in which case if an
	 * error is detected, the process will be aborted. */
	rec->validating = 1;
	selinux_set_callback(SELINUX_CB_VALIDATE,
			    (union selinux_callback)&validate_context);

	data = (struct saved_data *)calloc(1, sizeof(*data));
	if (!data) {
		fprintf(stderr, "Failed to calloc saved_data\n");
		free(rec);
		if (policy_fp)
			fclose(policy_fp);
		exit(EXIT_FAILURE);
	}

	rec->data = data;

	rc = process_file(rec, path);
	if (rc < 0)
		goto err;

	rc = sort_specs(data);
	if (rc)
		goto err;

	if (out_file)
		rc = snprintf(stack_path, sizeof(stack_path), "%s", out_file);
	else
		rc = snprintf(stack_path, sizeof(stack_path), "%s.bin", path);

	if (rc < 0 || rc >= (int)sizeof(stack_path))
		goto err;

	tmp = malloc(strlen(stack_path) + 7);
	if (!tmp)
		goto err;

	rc = sprintf(tmp, "%sXXXXXX", stack_path);
	if (rc < 0)
		goto err;

	fd  = mkstemp(tmp);
	if (fd < 0)
		goto err;

	rc = fchmod(fd, buf.st_mode);
	if (rc < 0) {
		perror("fchmod failed to set permission on compiled regexs");
		goto err_unlink;
	}

	rc = write_binary_file(data, fd);
	if (rc < 0)
		goto err_unlink;

	rc = rename(tmp, stack_path);
	if (rc < 0)
		goto err_unlink;

	rc = 0;
out:
	if (policy_fp)
		fclose(policy_fp);

	free_specs(data);
	free(rec);
	free(data);
	free(tmp);
	return rc;

err_unlink:
	unlink(tmp);
err:
	rc = -1;
	goto out;
}
Пример #8
0
/*
 * Callback function used by EST stack to process a PKCS10
 * enrollment request with the CA.  The parameters are:
 *
 *   pkcs10  Contains the CSR that should be sent to
 *              the CA to be signed.
 *   pkcs10_len Length of the CSR char array
 *   pcks7   Should contain the signed PKCS7 certificate
 *              from the CA server.  You'll need allocate
 *              space and copy the cert into this char array.
 *   pkcs7_len  Length of the pkcs7 char array, you will set this.
 *   user_id    If HTTP authentication was used to identify the
 *              EST client, this will contain the user ID supplied
 *              by the client.
 *   peer_cert  If the EST client presented a certificate to identify
 *              itself during the TLS handshake, this parameter will
 *              contain that certificate.
 *   path_seg   If the incoming request contains a path segment it
 *              is extracted from the URI and passed here.  Typically
 *              used to mux between multiple CAs or to identify a
 *              specific profile to use by the CA.
 *   app_data   an optional pointer to information that is to be
 *              used by the application layer.
 *
 */
int process_pkcs10_enrollment (unsigned char * pkcs10, int p10_len,
                               unsigned char **pkcs7, int *pkcs7_len,
                               char *user_id, X509 *peer_cert, char *path_seg,
                               void *app_data)
{
    BIO *result = NULL;
    char *buf;
#ifndef WIN32
    int rc;
#endif
    char sn[64];
    char file_name[MAX_FILENAME_LEN];

    if (verbose) {
        /*
         * Informational only
         */
        if (user_id) {
            /*
             * Should be safe to log the user ID here since HTTP auth
             * has succeeded at this point.
             */
            printf("\n%s - User ID is %s\n", __FUNCTION__, user_id);
        }
        if (peer_cert) {
            memset(sn, 0, 64);
            extract_sub_name(peer_cert, sn, 64);
            printf("\n%s - Peer cert CN is %s\n", __FUNCTION__, sn);
        }
        if (app_data) {
            printf("ex_data value is %x\n", *((unsigned int *) app_data));
        }
        if (path_seg) {
            printf("\nPath segment was included in enrollment URI. "
                "Path Segment = %s\n", path_seg);
        }
    }

    /*
     * If we're simulating manual certificate enrollment,
     * the CA will not automatically sign the cert request.
     * We'll attempt to lookup in our local table if this
     * cert has already been sent to us, if not, add it
     * to the table and send the 'retry' message back to the
     * client.  But if this cert request has been seen in the
     * past, then we'll continue with the enrollment.
     * To summarize, we're simulating manual enrollment by
     * forcing the client to request twice, and we'll automatically
     * enroll on the second request.
     */
    if (manual_enroll) {
        if (lookup_pkcs10_request(pkcs10, p10_len)) {
            /*
             * We've seen this cert request in the past.
             * Remove it from the lookup table and allow
             * the enrollment to continue.
             * Fall-thru to enrollment logic below
             */
        } else {
            /*
             * Couldn't find this request, it's the first time
             * we've seen it.  Therefore, send the retry
             * response.
             */
            return (EST_ERR_CA_ENROLL_RETRY);
        }

    }

#ifndef WIN32
    rc = pthread_mutex_lock(&m);
    if (rc) {
        printf("\nmutex lock failed rc=%d", rc);
        exit(1);
    }
#else
    EnterCriticalSection(&enrollment_critical_section);
#endif 

    if (write_csr) {
        /*
         * Dump out pkcs10 to a file, this will contain a list of the OIDs in the CSR.
         */
        snprintf(file_name, MAX_FILENAME_LEN, "/tmp/csr.p10");
        write_binary_file(file_name, pkcs10, p10_len);
    }

    result = ossl_simple_enroll(pkcs10, p10_len);
#ifndef WIN32
    rc = pthread_mutex_unlock(&m);
    if (rc) {
        printf("\nmutex unlock failed rc=%d", rc);
        exit(1);
    }
#else
    LeaveCriticalSection(&enrollment_critical_section);
#endif

    /*
     * The result is a BIO containing the pkcs7 signed certificate
     * Need to convert it to char and copy the results so we can
     * free the BIO.
     */
    *pkcs7_len = BIO_get_mem_data(result, (char**) &buf);
    if (*pkcs7_len > 0 && *pkcs7_len < MAX_CERT_LEN) {
        *pkcs7 = malloc(*pkcs7_len);
        memcpy(*pkcs7, buf, *pkcs7_len);
    }

    BIO_free_all(result);
    return EST_ERR_NONE;
}
Пример #9
0
void Insert::update_buffer() {

    if (size == 0) return;

    sort_ids_values();

    // store attrbutes_num
    if (buffer_size == DATAPAGESIZE) {
        write_binary_file();
    }

    if (buffer_size + INTBYTESIZE <= DATAPAGESIZE) {
        memcpy(buffer + buffer_size, (char*)&size, INTBYTESIZE);
        buffer_size += INTBYTESIZE;
    } else {
        char size_tem[4];
        memcpy(size_tem, (char*)&size, INTBYTESIZE);

        int interval = DATAPAGESIZE - buffer_size;
        memcpy(buffer + buffer_size, size_tem, interval);
        buffer_size += interval;
        write_binary_file();
        memcpy(buffer + buffer_size, size_tem + interval, INTBYTESIZE - interval);
        buffer_size += (INTBYTESIZE - interval);
    }

    // store aids
    for (int i = 0; i < size; i++) {
        if (buffer_size == DATAPAGESIZE) {
            write_binary_file();
        }

        if (buffer_size + INTBYTESIZE <= DATAPAGESIZE) {
            memcpy(buffer + buffer_size, (char*)&ids[i], INTBYTESIZE);
            buffer_size += INTBYTESIZE;
        } else {
            unsigned int id = ids[i];
            char id_tem[4];
            memcpy(id_tem, (char*)&ids[i], INTBYTESIZE);

            int interval = DATAPAGESIZE - buffer_size;
            memcpy(buffer + buffer_size, id_tem, interval);
            buffer_size += interval;
            write_binary_file();
            memcpy(buffer + buffer_size, id_tem + interval, INTBYTESIZE - interval);
            buffer_size += INTBYTESIZE - interval;
        }
    }

    // store offset
    unsigned int len = 0;

    for (int i = 0; i <= size; i++) {

        if (i == 0) len = 0;
        else if (id_type[ids[i - 1]] == "int") {
            len += 4;
        }
        else if (id_type[ids[i - 1]] == "bool") {
            len += 1;
        } else {
            len += values[i - 1].size();
        }

        // cout << "len = " << len << endl;

        if (buffer_size == DATAPAGESIZE) {
            write_binary_file();
        }

        if (buffer_size + INTBYTESIZE <= DATAPAGESIZE) {
            memcpy(buffer + buffer_size, (char*)&len, INTBYTESIZE);
            buffer_size += INTBYTESIZE;

        } else {
            char len_tem[4];
            memcpy(len_tem, (char*)&len, INTBYTESIZE);

            int interval = DATAPAGESIZE - buffer_size;
            memcpy(buffer + buffer_size, len_tem, interval);
            buffer_size += interval;

            write_binary_file();

            memcpy(buffer + buffer_size, len_tem + interval, INTBYTESIZE - interval);
            buffer_size += INTBYTESIZE - interval;
        }
    }

    // store data
    for (int i = 0; i < size; i++) {
        if (id_type[ids[i]] == "arr" || id_type[ids[i]] == "text" || id_type[ids[i]] == "json_obj" || id_type[ids[i]] == "bool") {
            if (buffer_size == DATAPAGESIZE) {
                write_binary_file();
            }

            if (buffer_size + values[i].size() <= DATAPAGESIZE) {
                memcpy(buffer + buffer_size, (char*)values[i].c_str(), values[i].size());
                buffer_size += values[i].size();
            } else {
                int interval = DATAPAGESIZE - buffer_size;
                char* str_tem = (char*)values[i].c_str();

                memcpy(buffer + buffer_size, (char*)&str_tem, interval);
                buffer_size += interval;
                write_binary_file();
                memcpy(buffer + buffer_size, (char*)(&str_tem + interval), values[i].size() - interval);
                buffer_size += values[i].size() - interval;
            }
        } else {
            unsigned int int_tem = 0;
            char* str_tem = (char*)values[i].c_str();

            istrstream istr(str_tem);
            istr >> int_tem;

            if (buffer_size == DATAPAGESIZE) {
                write_binary_file();
            }

            if (buffer_size + INTBYTESIZE <= DATAPAGESIZE) {
                memcpy(buffer + buffer_size, (char*)&int_tem, INTBYTESIZE);
                buffer_size += INTBYTESIZE;
            } else {
                char data_tem[4];
                memcpy(data_tem, (char*)&int_tem, INTBYTESIZE);

                int interval = DATAPAGESIZE - buffer_size;
                memcpy(buffer + buffer_size, (char*)&data_tem, interval);
                buffer_size += interval;

                write_binary_file();

                memcpy(buffer + buffer_size, (char*)(&data_tem + interval),INTBYTESIZE - interval);
                buffer_size += INTBYTESIZE - interval;
            }
        }
    }

    size = 0;
}
Пример #10
0
int main (int argc, char **argv)
{
    signed char c;
    int set_fips_return = 0;
    char file_name[MAX_FILENAME_LEN];
    BIO *keyin;
    BIO *certin;
    static struct option long_options[] = {
        { "trustanchor",  1, 0,    0 },
        { "srp",          0, 0,    0 },
        { "srp-user",     1, 0,    0 },
        { "srp-password", 1, 0,    0 },
        { "auth-token",   1, 0,    0 },
        { "common-name",  1, 0,    0 },
        { "pem-output",   0, 0,    0 },
        { NULL,           0, NULL, 0 }
    };
    int option_index = 0;
    int trustanchor = 1; /* default to require a trust anchor */
    char *trustanchor_file = NULL;

    est_http_uid[0] = 0x0;
    est_http_pwd[0] = 0x0;

    /*
     * Set the default common name to put into the Subject field
     */
    strncpy(subj_cn, "127.0.0.1", MAX_CN);

    memset(csr_file, 0, 1);
    memset(priv_key_file, 0, 1);
    memset(client_key_file, 0, 1);
    memset(client_cert_file, 0, 1);
    memset(out_dir, 0, 1);

    while ((c = getopt_long(argc, argv, "?zfvagerx:y:k:s:p:o:c:w:u:h:", long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
#if 0
            printf("option %s", long_options[option_index].name);
            if (optarg) {
                printf(" with arg %s", optarg);
            }
            printf("\n");
#endif
            if (!strncmp(long_options[option_index].name, "trustanchor", strlen("trustanchor"))) {
                if (!strncmp(optarg, "no", strlen("no"))) {
                    trustanchor = 0;
                } else {
                    trustanchor_file = optarg;
                }
            }
            if (!strncmp(long_options[option_index].name, "srp", strlen("srp"))) {
                srp = 1;
            }
            if (!strncmp(long_options[option_index].name, "srp-user", strlen("srp-user"))) {
                strncpy(est_srp_uid, optarg, MAX_UID_LEN);
            }
            if (!strncmp(long_options[option_index].name, "srp-password", strlen("srp-password"))) {
                strncpy(est_srp_pwd, optarg, MAX_PWD_LEN);
            }
	    if (!strncmp(long_options[option_index].name,"auth-token", strlen("auth-token"))) {
		strncpy(est_auth_token, optarg, MAX_AUTH_TOKEN_LEN);
                token_auth_mode = 1;
	    }
            if (!strncmp(long_options[option_index].name, "common-name", strlen("common-name"))) {
                strncpy(subj_cn, optarg, MAX_CN);
            }
            if (!strncmp(long_options[option_index].name, "pem-output", strlen("pem-output"))) {
                pem_out = 1;
            }
            break;
        case 'v':
            verbose = 1;
            break;
        case 'z':
            force_pop = 1;
            break;
        case 'a':
            getcsr = 1;
            break;
        case 'g':
            getcert = 1;
            break;
        case 'e':
            enroll = 1;
            break;
        case 'r':
            reenroll = 1;
            break;
        case 'u':
            strncpy(est_http_uid, optarg, MAX_UID_LEN);
            break;
        case 'h':
            strncpy(est_http_pwd, optarg, MAX_PWD_LEN);
            break;
        case 's':
            strncpy(est_server, optarg, MAX_SERVER_LEN);
            break;
        case 'x':
            strncpy(priv_key_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'y':
            strncpy(csr_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'k':
            strncpy(client_key_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'c':
            strncpy(client_cert_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'o':
            strncpy(out_dir, optarg, MAX_FILENAME_LEN);
            break;
        case 'p':
            est_port = atoi(optarg);
            break;
        case 'f':
            /* Turn FIPS on if requested and exit if failure */
            set_fips_return = FIPS_mode_set(1);
            if (!set_fips_return) {
                printf("\nERROR setting FIPS MODE ON ...\n");
                ERR_load_crypto_strings();
                ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
                exit(1);
            } else {
                printf("\nRunning EST Sample Client with FIPS MODE = ON\n");
            };
            break;
        case 'w':
            read_timeout = atoi(optarg);
            if (read_timeout > EST_SSL_READ_TIMEOUT_MAX) {
                printf("\nMaxium number of seconds to wait is %d, ", EST_SSL_READ_TIMEOUT_MAX);
                printf("please use a lower value with the -w option\n");
                exit(1);
            }
            break;
        default:
            show_usage_and_exit();
            break;
        }
    }
    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc) {
            printf("%s ", argv[optind++]);
        }
        printf("\n");
    }
    argc -= optind;
    argv += optind;

    if (est_http_uid[0] && !est_http_pwd[0]) {
        printf("Error: The password for HTTP authentication must be specified when the HTTP user name is set.\n");
        exit(1);
    }

    if (csr_file[0] && getcsr) {
        printf("\nError: The -a option (CSR attributes) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (csr_file[0] && priv_key_file[0]) {
        printf("\nError: The -x option (private key for CSR) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (csr_file[0] && force_pop) {
        printf("\nError: The -z option (PoP) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (reenroll & csr_file[0]) {
        printf("\nError: The -y option (predefined CSRs) does not make sense for re-enrollment\n");
        exit(1);
    }

    if (verbose) {
        print_version();
        printf("\nUsing EST server %s:%d", est_server, est_port);
        if (csr_file        [0]) {
            printf("\nUsing CSR file %s", csr_file);
        }
        if (priv_key_file   [0]) {
            printf("\nUsing identity private key file %s", priv_key_file);
        }
        if (client_cert_file[0]) {
            printf("\nUsing identity client cert file %s", client_cert_file);
        }
        if (client_key_file [0]) {
            printf("\nUsing identity private key file %s", client_key_file);
        }
    }

    if (enroll && reenroll) {
        printf("\nThe enroll and reenroll operations can not be used together\n");
        exit(1);
    }

    if (!out_dir[0]) {
        printf("\nOutput directory must be specified with -o option\n");
        exit(1);
    }

    if (trustanchor) {
        if (!trustanchor_file) {
            /*
             * Get the trust anchor filename from the environment var
             */
            if (!getenv("EST_OPENSSL_CACERT")) {
                printf("\nCACERT file not set, set EST_OPENSSL_CACERT to resolve");
                exit(1);
            }
            trustanchor_file = getenv("EST_OPENSSL_CACERT");
        }

        /*
         * Read in the CA certificates
         */
        cacerts_len = read_binary_file(trustanchor_file, &cacerts);
        if (cacerts_len <= 0) {
            printf("\nCACERT file could not be read\n");
            exit(1);
        }
    }

    /*
     * Read in the current client certificate
     */
    if (client_cert_file[0]) {
        certin = BIO_new(BIO_s_file_internal());
        if (BIO_read_filename(certin, client_cert_file) <= 0) {
            printf("\nUnable to read client certificate file %s\n", client_cert_file);
            exit(1);
        }
        /*
         * This reads the file, which is expected to be PEM encoded.  If you're using
         * DER encoded certs, you would invoke d2i_X509_bio() instead.
         */
        client_cert = PEM_read_bio_X509(certin, NULL, NULL, NULL);
        if (client_cert == NULL) {
            printf("\nError while reading PEM encoded client certificate file %s\n", client_cert_file);
            exit(1);
        }
        BIO_free(certin);
    }

    /*
     * Read in the client's private key
     */
    if (client_key_file[0]) {
        keyin = BIO_new(BIO_s_file_internal());
        if (BIO_read_filename(keyin, client_key_file) <= 0) {
            printf("\nUnable to read client private key file %s\n", client_key_file);
            exit(1);
        }
        /*
         * This reads in the private key file, which is expected to be a PEM
         * encoded private key.  If using DER encoding, you would invoke
         * d2i_PrivateKey_bio() instead.
         */
        client_priv_key = PEM_read_bio_PrivateKey(keyin, NULL, NULL, NULL);
        if (client_priv_key == NULL) {
            printf("\nError while reading PEM encoded private key file %s\n", client_key_file);
            ERR_print_errors_fp(stderr);
            exit(1);
        }
        BIO_free(keyin);
    }

    est_apps_startup();

#if DEBUG_OSSL_LEAKS
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif

    if (verbose) {
        est_init_logger(EST_LOG_LVL_INFO, &test_logger_stdout);
        est_enable_backtrace(1);
    } else {
        est_init_logger(EST_LOG_LVL_ERR, &test_logger_stdout);
    }

    if (!priv_key_file[0] && enroll && !csr_file[0]) {
	printf("\nA private key is required for enrolling.  Creating a new RSA key pair since you didn't provide a key using the -x option.");
        /*
         * Create a private key that will be used for the
         * enroll operation.
         */
        new_pkey = generate_private_key(&new_pkey_len);
        snprintf(file_name, MAX_FILENAME_LEN, "%s/newkey.pem", out_dir);
        write_binary_file(file_name, new_pkey, new_pkey_len);
        free(new_pkey);

        /*
         * prepare to read it back in to an EVP_PKEY struct
         */
        strncpy(priv_key_file, file_name, MAX_FILENAME_LEN);

    }

    if (enroll && !csr_file[0]) {
	/* Read in the private key file */
	priv_key = read_private_key(priv_key_file);
    }


    do_operation();

    if (priv_key) {
        EVP_PKEY_free(priv_key);
    }
    if (client_priv_key) {
        EVP_PKEY_free(client_priv_key);
    }
    if (client_cert) {
        X509_free(client_cert);
    }

    free(cacerts);
    if (c_cert_len) {
        free(c_cert);
    }
    if (c_key_len) {
        free(c_key);
    }

    est_apps_shutdown();

#if DEBUG_OSSL_LEAKS
    BIO *bio_err;
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
    CRYPTO_mem_leaks(bio_err);
    BIO_free(bio_err);
#endif

    printf("\n");
    return 0;
}
Пример #11
0
static void do_operation ()
{
    EST_CTX *ectx;
    unsigned char *pkcs7;
    int pkcs7_len = 0;
    int rv;
    char file_name[MAX_FILENAME_LEN];
    unsigned char *new_client_cert;
    int retry_delay = 0;
    time_t retry_time = 0;
    char *operation;

    ectx = est_client_init(cacerts, cacerts_len,
                           EST_CERT_FORMAT_PEM,
                           client_manual_cert_verify);
    if (!ectx) {
        printf("\nUnable to initialize EST context.  Aborting!!!\n");
        exit(1);
    }

    rv = est_client_set_read_timeout(ectx, read_timeout);
    if (rv != EST_ERR_NONE) {
        printf("\nUnable to configure read timeout from server.  Aborting!!!\n");
        printf("EST error code %d (%s)\n", rv, EST_ERR_NUM_TO_STR(rv));
        exit(1);
    }

    rv = est_client_set_auth(ectx, est_http_uid, est_http_pwd, client_cert, client_priv_key);
    if (rv != EST_ERR_NONE) {
        printf("\nUnable to configure client authentication.  Aborting!!!\n");
        printf("EST error code %d (%s)\n", rv, EST_ERR_NUM_TO_STR(rv));
        exit(1);
    }


    if (srp) {
        rv = est_client_enable_srp(ectx, 1024, est_srp_uid, est_srp_pwd);
        if (rv != EST_ERR_NONE) {
            printf("\nUnable to enable SRP.  Aborting!!!\n");
            exit(1);
        }
    }

    if (token_auth_mode) {
        rv = est_client_set_auth_cred_cb(ectx, auth_credentials_token_cb);
        if (rv != EST_ERR_NONE) {
	    printf("\nUnable to register token auth callback.  Aborting!!!\n");
	    exit(1);
        }        
    }            

    est_client_set_server(ectx, est_server, est_port);

    if (getcert) {
        operation = "Get CA Cert";

        rv = est_client_get_cacerts(ectx, &pkcs7_len);
        if (rv == EST_ERR_NONE) {
            if (verbose) {
                printf("\nGet CA Cert success\n");
            }

            /*
             * allocate a buffer to retrieve the CA certs
             * and get them copied in
             */
            pkcs7 = malloc(pkcs7_len);
            rv = est_client_copy_cacerts(ectx, pkcs7);

            /*
             * Dump the retrieved cert to stdout
             */
            if (verbose) {
                dumpbin(pkcs7, pkcs7_len);
            }

            /*
             * Generate the output file name, which contains the thread ID
             * and iteration number.
             */
            snprintf(file_name, MAX_FILENAME_LEN, "%s/cacert.pkcs7", out_dir);
            write_binary_file(file_name, pkcs7, pkcs7_len);

            free(pkcs7);

        }
    }

    if (enroll && getcsr) {
        operation = "Regular enrollment with server-defined attributes";

        rv = regular_enroll_attempt(ectx);

        if (rv == EST_ERR_CA_ENROLL_RETRY) {

            /*
             * go get the retry period
             */
            rv = est_client_copy_retry_after(ectx, &retry_delay, &retry_time);
            if (verbose) {
                printf("\nretry after period copy rv = %d "
                       "Retry-After delay seconds = %d "
                       "Retry-After delay time = %s\n",
                       rv, retry_delay, ctime(&retry_time) );
            }
            if (rv == EST_ERR_NONE) {
                retry_enroll_delay(retry_delay, retry_time);
            }
            /*
             * now that we're back, try to enroll again
             */
            rv = regular_enroll_attempt(ectx);

        }

    } else if (enroll && !getcsr) {
        operation = "Simple enrollment without server-defined attributes";

        rv = simple_enroll_attempt(ectx);

        if (rv == EST_ERR_CA_ENROLL_RETRY) {

            /*
             * go get the retry period
             */
            rv = est_client_copy_retry_after(ectx, &retry_delay, &retry_time);
            if (verbose) {
                printf("\nretry after period copy rv = %d "
                       "Retry-After delay seconds = %d "
                       "Retry-After delay time = %s\n",
                       rv, retry_delay, ctime(&retry_time) );
            }
            if (rv == EST_ERR_NONE) {
                retry_enroll_delay(retry_delay, retry_time);
            }

            /*
             * now that we're back, try to enroll again
             */
            rv = simple_enroll_attempt(ectx);
        }

    } else if (!enroll && getcsr) {
        operation = "Get CSR attribues";

        rv = regular_csr_attempt(ectx);

    }

    /* Split reenroll from enroll to allow both messages to be sent */
    if (reenroll) {
        operation = "Re-enrollment";

        rv = est_client_reenroll(ectx, client_cert, &pkcs7_len, client_priv_key);
        if (verbose) {
            printf("\nreenroll rv = %d (%s) with pkcs7 length = %d\n",
                   rv, EST_ERR_NUM_TO_STR(rv), pkcs7_len);
        }
        if (rv == EST_ERR_NONE) {
            /*
             * client library has obtained the new client certificate.
             * now retrieve it from the library
             */
            new_client_cert = malloc(pkcs7_len);
            if (new_client_cert == NULL) {
                if (verbose) {
                    printf("\nmalloc of destination buffer for reenroll cert failed\n");
                }
            }

            rv = est_client_copy_enrolled_cert(ectx, new_client_cert);
            if (verbose) {
                printf("\nreenroll copy rv = %d\n", rv);
            }
            if (rv == EST_ERR_NONE) {
                /*
                 * Enrollment copy worked, dump the pkcs7 cert to stdout
                 */
                if (verbose) {
                    dumpbin(new_client_cert, pkcs7_len);
                }
            }

            /*
             * Generate the output file name, which contains the thread ID
             * and iteration number.
             */
            snprintf(file_name, MAX_FILENAME_LEN, "%s/newcert", out_dir);
            save_cert(file_name, new_client_cert, pkcs7_len);
            free(new_client_cert);
        }
    }

    if (rv != EST_ERR_NONE) {
        /*
         * something went wrong.
         */
        printf("\n%s failed with code %d (%s)\n",
               operation, rv, EST_ERR_NUM_TO_STR(rv));
    }

    est_destroy(ectx);

    ERR_clear_error();
    ERR_remove_thread_state(NULL);
}
Пример #12
0
int main (int argc, char **argv) 
{
    EST_ERROR rv;
    char c;
    char *key_data;
    EVP_PKEY *key;
    char *trustanchor_file;
    EST_CTX *ectx;
    int p7_len;
    int ca_certs_len;
    unsigned char *new_client_cert;
    unsigned char *new_certs;
    static struct option long_options[] = {
        {"srp", 0, 0, 0},
        {"srp-user", 1, 0, 0},
        {"srp-password", 1, 0, 0},
        {"auth-token", 1, 0, 0},
        {NULL, 0, NULL, 0}
    };
    int option_index = 0;

    est_http_uid[0] = 0x0;
    est_http_pwd[0] = 0x0;

    while ((c = getopt_long(argc, argv, "s:p:u:h:", long_options, &option_index)) != -1) {
        switch (c) {
            case 0:
		if (!strncmp(long_options[option_index].name,"srp", strlen("srp"))) {
		    srp = 1;
		}
		if (!strncmp(long_options[option_index].name,"srp-user", strlen("srp-user"))) {
		    strncpy(est_srp_uid, optarg, MAX_UID_LEN);
		}
		if (!strncmp(long_options[option_index].name,"srp-password", strlen("srp-password"))) {
		    strncpy(est_srp_pwd, optarg, MAX_PWD_LEN);
		}
		if (!strncmp(long_options[option_index].name,"auth-token", strlen("auth-token"))) {
		    strncpy(est_auth_token, optarg, MAX_AUTH_TOKEN_LEN);
                    token_auth_mode = 1;
		}
                break;
            case 'u':
		strncpy(est_http_uid, optarg, MAX_UID_LEN);
                break;
            case 'h':
		strncpy(est_http_pwd, optarg, MAX_PWD_LEN);
                break;
            case 's':
		strncpy(est_server, optarg, MAX_SERVER_LEN);
                break;
            case 'p':
		est_port = atoi(optarg);
                break;
            default:
                show_usage_and_exit();
                break;
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }    
    argc -= optind;
    argv += optind;

    if (est_http_uid[0] && !est_http_pwd[0]) {
	printf ("Error: The password for HTTP authentication must be specified when the HTTP user name is set.\n");
	exit(1);
    }

    /*
     * Initialize the library, including OpenSSL
     */
    est_apps_startup();
        
    print_version();
    printf("\nUsing EST server %s:%d", est_server, est_port);

    /*
     * Read in the trusted certificates, which are used by
     * libEST to verify the identity of the EST server.
     */
    trustanchor_file = getenv("EST_OPENSSL_CACERT");
    cacerts_len = read_binary_file(trustanchor_file, &cacerts);
    if (cacerts_len <= 0) {
        printf("\nTrusted certs file could not be read.  Did you set EST_OPENSSL_CACERT?\n");
        exit(1);
    }
    
    /*
     * This is not required, but we'll enable full debugs
     */
#ifndef WIN32
    /* Initialize the EST logging */
    est_init_logger(EST_LOG_LVL_INFO, NULL);
#else
    InitializeCriticalSection (&logger_critical_section);
    est_init_logger(EST_LOG_LVL_INFO, &windows_logger_stderr);
#endif 

    /*
     * Create a public/private key pair that will be used for 
     * the enrollment.  We'll write this out to a local
     * file called new_key.pem.
     */
    key_data = generate_private_RSA_key(2048, NULL/* no password_cb */);

    write_binary_file("./new_key.pem", (unsigned char *)key_data, strlen(key_data));

    /*
     * Use the load_clear macro to load in an unencrypted key
     */
    key = load_clear_private_key_PEM(key_data);

    if(!key) {
        printf("\nUnable to load newly created key from PEM file\n");
        exit(1);
    }
    memset(key_data, 0, strlen(key_data));
    free(key_data);
    key_data = NULL;

    ectx = setup_est_context();
    if (!ectx) {
	printf("\nUnable to create EST client context\n");
	exit(1);
    }
    
    /*
     * Attempt to provision a new cert
     */
    rv = est_client_provision_cert(ectx, "localhost", &p7_len, &ca_certs_len, key);
    if (rv != EST_ERR_NONE) {
	printf("\nProvisioning failed with error %s\n", EST_ERR_NUM_TO_STR(rv));
	exit(1);
    } 
    EVP_PKEY_free(key);

    /*
     * Retrieve a copy of the cert
     */
    new_client_cert = malloc(p7_len);
    if (new_client_cert == NULL){
	printf("\nFailed to allocate memory for the newly provisioned cert\n");
	exit(1);
    }                    
    rv = est_client_copy_enrolled_cert(ectx, new_client_cert);
    if (rv != EST_ERR_NONE) {
        printf("\nFailed to copy new cert with code %d (%s)\n", 
            rv, EST_ERR_NUM_TO_STR(rv));
	exit(1);
    }

    /*
     * Save the cert to local storage
     */
    write_binary_file(cert_file_name, new_client_cert, p7_len);
    free(new_client_cert);

    /*
     * Retrieve a copy of the new trust anchor
     */
    new_certs = malloc(ca_certs_len);
    rv = est_client_copy_cacerts(ectx, new_certs);
    if (rv != EST_ERR_NONE) {
        printf("\nFailed to copy new CA certs with code %d (%s)\n", 
            rv, EST_ERR_NUM_TO_STR(rv));
	exit(1);
    }

    /*
     * Your appliations should save the CA certs to local storage in case
     * they're needed for future use.
     */
    write_binary_file(ca_file_name, new_certs, ca_certs_len); 
    free(new_certs);

    printf("\n\nSuccess!!!\n");
   
    free(cacerts);
    est_destroy(ectx);

    est_apps_shutdown();

    printf("\n");
    return 0;
}
Пример #13
0
int main(int argc, char *argv[])
{
	struct saved_data data;
	const char *path;
	char stack_path[PATH_MAX + 1];
	int rc;
	char *tmp= NULL;
	int fd;
	struct stat buf;

	if (argc != 2) {
		fprintf(stderr, "usage: %s input_file\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	memset(&data, 0, sizeof(data));

	path = argv[1];

	if (stat(path, &buf) < 0) {
		fprintf(stderr, "Can not stat: %s: %m\n", path);
		exit(EXIT_FAILURE);
	}

	rc = process_file(&data, path);
	if (rc < 0)
		return rc;

	rc = sort_specs(&data);
	if (rc)
		return rc;

	rc = snprintf(stack_path, sizeof(stack_path), "%s.bin", path);
	if (rc < 0 || rc >= (int)sizeof(stack_path))
		return rc;

	if (asprintf(&tmp, "%sXXXXXX", stack_path) < 0)
		return -1;

	fd  = mkstemp(tmp);
	if (fd < 0)
		goto err;

	rc = fchmod(fd, buf.st_mode);
	if (rc < 0) {
		perror("fchmod failed to set permission on compiled regexs");
		goto err;
	}

	rc = write_binary_file(&data, fd);

	if (rc < 0)
		goto err;

	rename(tmp, stack_path);
	rc = free_specs(&data);
	if (rc < 0)
		goto err;

	rc = 0;
out:
	free(tmp);
	return rc;
err:
	rc = -1;
	goto out;
}