示例#1
0
/**
 * Count the number of characters in a word.
 * The first character is already valid for a keyword
 *
 * @param pc   The structure to update, str is an input.
 * @return     Whether a word was parsed (always true)
 */
bool parse_word(tok_ctx& ctx, chunk_t& pc, bool skipcheck)
{
   int             ch;
   static unc_text intr_txt("@interface");

   /* The first character is already valid */
   pc.str.clear();
   pc.str.append(ctx.get());

   while (ctx.more() && CharTable::IsKw2(ctx.peek()))
   {
      ch = ctx.get();
      pc.str.append(ch);

      /* HACK: Non-ASCII character are only allowed in identifiers */
      if (ch > 0x7f)
      {
         skipcheck = true;
      }
   }
   pc.type = CT_WORD;

   if (skipcheck)
   {
      return(true);
   }

   /* Detect pre-processor functions now */
   if ((cpd.in_preproc == CT_PP_DEFINE) &&
       (cpd.preproc_ncnl_count == 1))
   {
      if (ctx.peek() == '(')
      {
         pc.type = CT_MACRO_FUNC;
      }
      else
      {
         pc.type = CT_MACRO;
      }
   }
   else
   {
      /* '@interface' is reserved, not an interface itself */
      if ((cpd.lang_flags & LANG_JAVA) && pc.str.startswith("@") &&
          !pc.str.equals(intr_txt))
      {
         pc.type = CT_ANNOTATION;
      }
      else
      {
         /* Turn it into a keyword now */
         pc.type = find_keyword_type(pc.text(), pc.str.size());
      }
   }

   return(true);
} // parse_word
示例#2
0
/**
 * Count the number of characters in the number.
 * The next bit of text starts with a number (0-9 or '.'), so it is a number.
 * Count the number of characters in the number.
 *
 * This should cover all number formats for all languages.
 * Note that this is not a strict parser. It will happily parse numbers in
 * an invalid format.
 *
 * For example, only D allows underscores in the numbers, but they are
 * allowed in all formats.
 *
 * @param pc   The structure to update, str is an input.
 * @return     Whether a number was parsed
 */
static bool parse_number(tok_ctx &ctx, chunk_t &pc)
{
   int  tmp;
   bool is_float;
   bool did_hex = false;

   /* A number must start with a digit or a dot, followed by a digit */
   if (!is_dec(ctx.peek()) &&
       ((ctx.peek() != '.') || !is_dec(ctx.peek(1))))
   {
      return(false);
   }

   is_float = (ctx.peek() == '.');
   if (is_float && (ctx.peek(1) == '.'))
   {
      return(false);
   }

   /* Check for Hex, Octal, or Binary
    * Note that only D and Pawn support binary, but who cares?
    */
   if (ctx.peek() == '0')
   {
      pc.str.append(ctx.get());  /* store the '0' */
      int     ch;
      chunk_t pc_temp;
      size_t  pc_length;

      pc_temp.str.append('0');
      // MS constant might have an "h" at the end. Look for it
      ctx.save();
      while (ctx.more() && CharTable::IsKw2(ctx.peek()))
      {
         ch = ctx.get();
         pc_temp.str.append(ch);
      }
      pc_length = pc_temp.len();
      ch        = pc_temp.str[pc_length - 1];
      ctx.restore();
      LOG_FMT(LGUY, "%s(%d): pc_temp:%s\n", __func__, __LINE__, pc_temp.text());
      if (ch == 'h')
      {
         // we have an MS hexadecimal number with "h" at the end
         LOG_FMT(LGUY, "%s(%d): MS hexadecimal number\n", __func__, __LINE__);
         did_hex = true;
         do
         {
            pc.str.append(ctx.get()); /* store the rest */
         } while (is_hex_(ctx.peek()));
         pc.str.append(ctx.get());    /* store the h */
         LOG_FMT(LGUY, "%s(%d): pc:%s\n", __func__, __LINE__, pc.text());
      }
      else
      {
         switch (unc_toupper(ctx.peek()))
         {
         case 'X':               /* hex */
            did_hex = true;
            do
            {
               pc.str.append(ctx.get());  /* store the 'x' and then the rest */
            } while (is_hex_(ctx.peek()));
            break;

         case 'B':               /* binary */
            do
            {
               pc.str.append(ctx.get());  /* store the 'b' and then the rest */
            } while (is_bin_(ctx.peek()));
            break;

         case '0':                /* octal or decimal */
         case '1':
         case '2':
         case '3':
         case '4':
         case '5':
         case '6':
         case '7':
         case '8':
         case '9':
            do
            {
               pc.str.append(ctx.get());
            } while (is_oct_(ctx.peek()));
            break;

         default:
            /* either just 0 or 0.1 or 0UL, etc */
            break;
         }
      }
   }
   else
   {
      /* Regular int or float */
      while (is_dec_(ctx.peek()))
      {
         pc.str.append(ctx.get());
      }
   }

   /* Check if we stopped on a decimal point & make sure it isn't '..' */
   if ((ctx.peek() == '.') && (ctx.peek(1) != '.'))
   {
      pc.str.append(ctx.get());
      is_float = true;
      if (did_hex)
      {
         while (is_hex_(ctx.peek()))
         {
            pc.str.append(ctx.get());
         }
      }
      else
      {
         while (is_dec_(ctx.peek()))
         {
            pc.str.append(ctx.get());
         }
      }
   }

   /* Check exponent
    * Valid exponents per language (not that it matters):
    * C/C++/D/Java: eEpP
    * C#/Pawn:      eE
    */
   tmp = unc_toupper(ctx.peek());
   if ((tmp == 'E') || (tmp == 'P'))
   {
      is_float = true;
      pc.str.append(ctx.get());
      if ((ctx.peek() == '+') || (ctx.peek() == '-'))
      {
         pc.str.append(ctx.get());
      }
      while (is_dec_(ctx.peek()))
      {
         pc.str.append(ctx.get());
      }
   }

   /* Check the suffixes
    * Valid suffixes per language (not that it matters):
    *        Integer       Float
    * C/C++: uUlL64        lLfF
    * C#:    uUlL          fFdDMm
    * D:     uUL           ifFL
    * Java:  lL            fFdD
    * Pawn:  (none)        (none)
    *
    * Note that i, f, d, and m only appear in floats.
    */
   while (1)
   {
      tmp = unc_toupper(ctx.peek());
      if ((tmp == 'I') || (tmp == 'F') || (tmp == 'D') || (tmp == 'M'))
      {
         is_float = true;
      }
      else if ((tmp != 'L') && (tmp != 'U'))
      {
         break;
      }
      pc.str.append(ctx.get());
   }

   /* skip the Microsoft-specific '64' suffix */
   if ((ctx.peek() == '6') && (ctx.peek(1) == '4'))
   {
      pc.str.append(ctx.get());
      pc.str.append(ctx.get());
   }

   pc.type = is_float ? CT_NUMBER_FP : CT_NUMBER;

   /* If there is anything left, then we are probably dealing with garbage or
    * some sick macro junk. Eat it.
    */
   parse_suffix(ctx, pc);

   return(true);
} // parse_number
示例#3
0
/**
 * @brief main of scepclient
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
    /* external values */
    extern char * optarg;
    extern int optind;

    /* type of input and output files */
    typedef enum {
        PKCS1      =  0x01,
        PKCS10     =  0x02,
        PKCS7      =  0x04,
        CERT_SELF  =  0x08,
        CERT       =  0x10,
        CACERT_ENC =  0x20,
        CACERT_SIG =  0x40,
    } scep_filetype_t;

    /* filetype to read from, defaults to "generate a key" */
    scep_filetype_t filetype_in = 0;

    /* filetype to write to, no default here */
    scep_filetype_t filetype_out = 0;

    /* input files */
    char *file_in_pkcs1      = DEFAULT_FILENAME_PKCS1;
    char *file_in_pkcs10     = DEFAULT_FILENAME_PKCS10;
    char *file_in_cert_self  = DEFAULT_FILENAME_CERT_SELF;
    char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
    char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;

    /* output files */
    char *file_out_pkcs1     = DEFAULT_FILENAME_PKCS1;
    char *file_out_pkcs10    = DEFAULT_FILENAME_PKCS10;
    char *file_out_pkcs7     = DEFAULT_FILENAME_PKCS7;
    char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
    char *file_out_cert      = DEFAULT_FILENAME_CERT;
    char *file_out_ca_cert   = DEFAULT_FILENAME_CACERT_ENC;

    /* by default user certificate is requested */
    bool request_ca_certificate = FALSE;

    /* by default existing files are not overwritten */
    bool force = FALSE;

    /* length of RSA key in bits */
    u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;

    /* validity of self-signed certificate */
    time_t validity  = DEFAULT_CERT_VALIDITY;
    time_t notBefore = 0;
    time_t notAfter  = 0;

    /* distinguished name for requested certificate, ASCII format */
    char *distinguishedName = NULL;

    /* challenge password */
    char challenge_password_buffer[MAX_PASSWORD_LENGTH];

    /* symmetric encryption algorithm used by pkcs7, default is DES */
    encryption_algorithm_t pkcs7_symmetric_cipher = ENCR_DES;
    size_t pkcs7_key_size = 0;

    /* digest algorithm used by pkcs7, default is MD5 */
    hash_algorithm_t pkcs7_digest_alg = HASH_MD5;

    /* signature algorithm used by pkcs10, default is MD5 */
    hash_algorithm_t pkcs10_signature_alg = HASH_MD5;

    /* URL of the SCEP-Server */
    char *scep_url = NULL;

    /* Name of CA to fetch CA certs for */
    char *ca_name = "CAIdentifier";

    /* http request method, default is GET */
    bool http_get_request = TRUE;

    /* poll interval time in manual mode in seconds */
    u_int poll_interval = DEFAULT_POLL_INTERVAL;

    /* maximum poll time */
    u_int max_poll_time = 0;

    err_t ugh = NULL;

    /* initialize library */
    if (!library_init(NULL))
    {
        library_deinit();
        exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
    }
    if (lib->integrity &&
            !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
    {
        fprintf(stderr, "integrity check of scepclient failed\n");
        library_deinit();
        exit(SS_RC_DAEMON_INTEGRITY);
    }

    /* initialize global variables */
    pkcs1             = chunk_empty;
    pkcs7             = chunk_empty;
    serialNumber      = chunk_empty;
    transID           = chunk_empty;
    fingerprint       = chunk_empty;
    encoding          = chunk_empty;
    pkcs10_encoding   = chunk_empty;
    issuerAndSubject  = chunk_empty;
    challengePassword = chunk_empty;
    getCertInitial    = chunk_empty;
    scep_response     = chunk_empty;
    subjectAltNames   = linked_list_create();
    options           = options_create();

    for (;;)
    {
        static const struct option long_opts[] = {
            /* name, has_arg, flag, val */
            { "help", no_argument, NULL, 'h' },
            { "version", no_argument, NULL, 'v' },
            { "optionsfrom", required_argument, NULL, '+' },
            { "quiet", no_argument, NULL, 'q' },
            { "debug", required_argument, NULL, 'l' },
            { "in", required_argument, NULL, 'i' },
            { "out", required_argument, NULL, 'o' },
            { "force", no_argument, NULL, 'f' },
            { "httptimeout", required_argument, NULL, 'T' },
            { "keylength", required_argument, NULL, 'k' },
            { "dn", required_argument, NULL, 'd' },
            { "days", required_argument, NULL, 'D' },
            { "startdate", required_argument, NULL, 'S' },
            { "enddate", required_argument, NULL, 'E' },
            { "subjectAltName", required_argument, NULL, 's' },
            { "password", required_argument, NULL, 'p' },
            { "algorithm", required_argument, NULL, 'a' },
            { "url", required_argument, NULL, 'u' },
            { "caname", required_argument, NULL, 'c'},
            { "method", required_argument, NULL, 'm' },
            { "interval", required_argument, NULL, 't' },
            { "maxpolltime", required_argument, NULL, 'x' },
            { 0,0,0,0 }
        };

        /* parse next option */
        int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:c:m:t:x:APRCMS", long_opts, NULL);

        switch (c)
        {
        case EOF:       /* end of flags */
            break;

        case 'h':       /* --help */
            usage(NULL);

        case 'v':       /* --version */
            version();

        case 'q':       /* --quiet */
            log_to_stderr = FALSE;
            continue;

        case 'l':		/* --debug <level> */
            default_loglevel = atoi(optarg);
            continue;

        case 'i':       /* --in <type> [= <filename>] */
        {
            char *filename = strstr(optarg, "=");

            if (filename)
            {
                /* replace '=' by '\0' */
                *filename = '\0';
                /* set pointer to start of filename */
                filename++;
            }
            if (strcaseeq("pkcs1", optarg))
            {
                filetype_in |= PKCS1;
                if (filename)
                    file_in_pkcs1 = filename;
            }
            else if (strcaseeq("pkcs10", optarg))
            {
                filetype_in |= PKCS10;
                if (filename)
                    file_in_pkcs10 = filename;
            }
            else if (strcaseeq("cacert-enc", optarg))
            {
                filetype_in |= CACERT_ENC;
                if (filename)
                    file_in_cacert_enc = filename;
            }
            else if (strcaseeq("cacert-sig", optarg))
            {
                filetype_in |= CACERT_SIG;
                if (filename)
                    file_in_cacert_sig = filename;
            }
            else if (strcaseeq("cert-self", optarg))
            {
                filetype_in |= CERT_SELF;
                if (filename)
                    file_in_cert_self = filename;
            }
            else
            {
                usage("invalid --in file type");
            }
            continue;
        }

        case 'o':       /* --out <type> [= <filename>] */
        {
            char *filename = strstr(optarg, "=");

            if (filename)
            {
                /* replace '=' by '\0' */
                *filename = '\0';
                /* set pointer to start of filename */
                filename++;
            }
            if (strcaseeq("pkcs1", optarg))
            {
                filetype_out |= PKCS1;
                if (filename)
                    file_out_pkcs1 = filename;
            }
            else if (strcaseeq("pkcs10", optarg))
            {
                filetype_out |= PKCS10;
                if (filename)
                    file_out_pkcs10 = filename;
            }
            else if (strcaseeq("pkcs7", optarg))
            {
                filetype_out |= PKCS7;
                if (filename)
                    file_out_pkcs7 = filename;
            }
            else if (strcaseeq("cert-self", optarg))
            {
                filetype_out |= CERT_SELF;
                if (filename)
                    file_out_cert_self = filename;
            }
            else if (strcaseeq("cert", optarg))
            {
                filetype_out |= CERT;
                if (filename)
                    file_out_cert = filename;
            }
            else if (strcaseeq("cacert", optarg))
            {
                request_ca_certificate = TRUE;
                if (filename)
                    file_out_ca_cert = filename;
            }
            else
            {
                usage("invalid --out file type");
            }
            continue;
        }

        case 'f':       /* --force */
            force = TRUE;
            continue;

        case 'T':       /* --httptimeout */
            http_timeout = atoi(optarg);
            if (http_timeout <= 0)
            {
                usage("invalid httptimeout specified");
            }
            continue;

        case '+':       /* --optionsfrom <filename> */
            if (!options->from(options, optarg, &argc, &argv, optind))
            {
                exit_scepclient("optionsfrom failed");
            }
            continue;

        case 'k':        /* --keylength <length> */
        {
            div_t q;

            rsa_keylength = atoi(optarg);
            if (rsa_keylength == 0)
                usage("invalid keylength");

            /* check if key length is a multiple of 8 bits */
            q = div(rsa_keylength, 2*BITS_PER_BYTE);
            if (q.rem != 0)
            {
                exit_scepclient("keylength is not a multiple of %d bits!"
                                , 2*BITS_PER_BYTE);
            }
            continue;
        }

        case 'D':       /* --days */
            if (optarg == NULL || !isdigit(optarg[0]))
            {
                usage("missing number of days");
            }
            else
            {
                char *endptr;
                long days = strtol(optarg, &endptr, 0);

                if (*endptr != '\0' || endptr == optarg
                        || days <= 0)
                    usage("<days> must be a positive number");
                validity = 24*3600*days;
            }
            continue;

        case 'S':       /* --startdate */
            if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
            {
                usage("date format must be YYMMDDHHMMSSZ");
            }
            else
            {
                chunk_t date = { optarg, 13 };
                notBefore = asn1_to_time(&date, ASN1_UTCTIME);
            }
            continue;

        case 'E':       /* --enddate */
            if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
            {
                usage("date format must be YYMMDDHHMMSSZ");
            }
            else
            {
                chunk_t date = { optarg, 13 };
                notAfter = asn1_to_time(&date, ASN1_UTCTIME);
            }
            continue;

        case 'd':       /* --dn */
            if (distinguishedName)
            {
                usage("only one distinguished name allowed");
            }
            distinguishedName = optarg;
            continue;

        case 's':       /* --subjectAltName */
        {
            char *value = strstr(optarg, "=");

            if (value)
            {
                /* replace '=' by '\0' */
                *value = '\0';
                /* set pointer to start of value */
                value++;
            }

            if (strcaseeq("email", optarg) ||
                    strcaseeq("dns", optarg) ||
                    strcaseeq("ip", optarg))
            {
                subjectAltNames->insert_last(subjectAltNames,
                                             identification_create_from_string(value));
                continue;
            }
            else
            {
                usage("invalid --subjectAltName type");
                continue;
            }
        }

        case 'p':       /* --password */
            if (challengePassword.len > 0)
            {
                usage("only one challenge password allowed");
            }
            if (strcaseeq("%prompt", optarg))
            {
                printf("Challenge password: "******"challenge password could not be read");
                }
            }
            else
            {
                challengePassword.ptr = optarg;
                challengePassword.len = strlen(optarg);
            }
            continue;

        case 'u':       /* -- url */
            if (scep_url)
            {
                usage("only one URL argument allowed");
            }
            scep_url = optarg;
            continue;

        case 'c':       /* -- caname */
            ca_name = optarg;
            continue;

        case 'm':       /* --method */
            if (strcaseeq("get", optarg))
            {
                http_get_request = TRUE;
            }
            else if (strcaseeq("post", optarg))
            {
                http_get_request = FALSE;
            }
            else
            {
                usage("invalid http request method specified");
            }
            continue;

        case 't':       /* --interval */
            poll_interval = atoi(optarg);
            if (poll_interval <= 0)
            {
                usage("invalid interval specified");
            }
            continue;

        case 'x':       /* --maxpolltime */
            max_poll_time = atoi(optarg);
            continue;

        case 'a':       /*--algorithm [<type>=]algo */
        {
            const proposal_token_t *token;
            char *type = optarg;
            char *algo = strstr(optarg, "=");

            if (algo)
            {
                *algo = '\0';
                algo++;
            }
            else
            {
                type = "enc";
                algo = optarg;
            }

            if (strcaseeq("enc", type))
            {
                token = lib->proposal->get_token(lib->proposal, algo);
                if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
                {
                    usage("invalid algorithm specified");
                }
                pkcs7_symmetric_cipher = token->algorithm;
                pkcs7_key_size = token->keysize;
                if (encryption_algorithm_to_oid(token->algorithm,
                                                token->keysize) == OID_UNKNOWN)
                {
                    usage("unsupported encryption algorithm specified");
                }
            }
            else if (strcaseeq("dgst", type) ||
                     strcaseeq("sig", type))
            {
                hash_algorithm_t hash;

                token = lib->proposal->get_token(lib->proposal, algo);
                if (token == NULL || token->type != INTEGRITY_ALGORITHM)
                {
                    usage("invalid algorithm specified");
                }
                hash = hasher_algorithm_from_integrity(token->algorithm,
                                                       NULL);
                if (hash == OID_UNKNOWN)
                {
                    usage("invalid algorithm specified");
                }
                if (strcaseeq("dgst", type))
                {
                    pkcs7_digest_alg = hash;
                }
                else
                {
                    pkcs10_signature_alg = hash;
                }
            }
            else
            {
                usage("invalid --algorithm type");
            }
            continue;
        }
        default:
            usage("unknown option");
        }
        /* break from loop */
        break;
    }

    init_log("scepclient");

    /* load plugins, further infrastructure may need it */
    if (!lib->plugins->load(lib->plugins, NULL,
                            lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
    {
        exit_scepclient("plugin loading failed");
    }
    DBG1(DBG_APP, "  loaded plugins: %s",
         lib->plugins->loaded_plugins(lib->plugins));

    if ((filetype_out == 0) && (!request_ca_certificate))
    {
        usage("--out filetype required");
    }
    if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
    {
        usage("in CA certificate request, no other --in or --out option allowed");
    }

    /* check if url is given, if cert output defined */
    if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
    {
        usage("URL of SCEP server required");
    }

    /* check for sanity of --in/--out */
    if (!filetype_in && (filetype_in > filetype_out))
    {
        usage("cannot generate --out of given --in!");
    }

    /* get CA cert */
    if (request_ca_certificate)
    {
        char ca_path[PATH_MAX];
        container_t *container;
        pkcs7_t *pkcs7;

        if (!scep_http_request(scep_url, chunk_create(ca_name, strlen(ca_name)),
                               SCEP_GET_CA_CERT, http_get_request,
                               http_timeout, &scep_response))
        {
            exit_scepclient("did not receive a valid scep response");
        }

        join_paths(ca_path, sizeof(ca_path), CA_CERT_PATH, file_out_ca_cert);

        pkcs7 = lib->creds->create(lib->creds, CRED_CONTAINER, CONTAINER_PKCS7,
                                   BUILD_BLOB_ASN1_DER, scep_response, BUILD_END);

        if (!pkcs7)
        {   /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */

            DBG1(DBG_APP, "unable to parse PKCS#7, assuming plain CA cert");
            if (!chunk_write(scep_response, ca_path, "ca cert",  0022, force))
            {
                exit_scepclient("could not write ca cert file '%s'", ca_path);
            }
        }
        else
        {
            enumerator_t *enumerator;
            certificate_t *cert;
            int ra_certs = 0, ca_certs = 0;
            int ra_index = 1, ca_index = 1;

            enumerator = pkcs7->create_cert_enumerator(pkcs7);
            while (enumerator->enumerate(enumerator, &cert))
            {
                x509_t *x509 = (x509_t*)cert;
                if (x509->get_flags(x509) & X509_CA)
                {
                    ca_certs++;
                }
                else
                {
                    ra_certs++;
                }
            }
            enumerator->destroy(enumerator);

            enumerator = pkcs7->create_cert_enumerator(pkcs7);
            while (enumerator->enumerate(enumerator, &cert))
            {
                x509_t *x509 = (x509_t*)cert;
                bool ca_cert = x509->get_flags(x509) & X509_CA;
                char cert_path[PATH_MAX], *path = ca_path;

                if (ca_cert && ca_certs > 1)
                {
                    add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                    "-%.1d", ca_index++);
                    path = cert_path;
                }
                else if (!ca_cert)
                {   /* use CA name as base for RA certs */
                    if (ra_certs > 1)
                    {
                        add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                        "-ra-%.1d", ra_index++);
                    }
                    else
                    {
                        add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                        "-ra");
                    }
                    path = cert_path;
                }

                if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
                        !chunk_write(encoding, path,
                                     ca_cert ? "ca cert" : "ra cert", 0022, force))
                {
                    exit_scepclient("could not write cert file '%s'", path);
                }
                chunk_free(&encoding);
            }
            enumerator->destroy(enumerator);
            container = &pkcs7->container;
            container->destroy(container);
        }
        exit_scepclient(NULL); /* no further output required */
    }

    creds = mem_cred_create();
    lib->credmgr->add_set(lib->credmgr, &creds->set);

    /*
     * input of PKCS#1 file
     */
    if (filetype_in & PKCS1)    /* load an RSA key pair from file */
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_in_pkcs1);

        private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
                                         BUILD_FROM_FILE, path, BUILD_END);
    }
    else                                /* generate an RSA key pair */
    {
        private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
                                         BUILD_KEY_SIZE, rsa_keylength,
                                         BUILD_END);
    }
    if (private_key == NULL)
    {
        exit_scepclient("no RSA private key available");
    }
    creds->add_key(creds, private_key->get_ref(private_key));
    public_key = private_key->get_public_key(private_key);

    /* check for minimum key length */
    if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
    {
        exit_scepclient("length of RSA key has to be at least %d bits",
                        RSA_MIN_OCTETS * BITS_PER_BYTE);
    }

    /*
     * input of PKCS#10 file
     */
    if (filetype_in & PKCS10)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_in_pkcs10);

        pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
                                        CERT_PKCS10_REQUEST, BUILD_FROM_FILE,
                                        path, BUILD_END);
        if (!pkcs10_req)
        {
            exit_scepclient("could not read certificate request '%s'", path);
        }
        subject = pkcs10_req->get_subject(pkcs10_req);
        subject = subject->clone(subject);
    }
    else
    {
        if (distinguishedName == NULL)
        {
            char buf[BUF_LEN];
            int n = sprintf(buf, DEFAULT_DN);

            /* set the common name to the hostname */
            if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
            {
                exit_scepclient("no hostname defined, use "
                                "--dn <distinguished name> option");
            }
            distinguishedName = buf;
        }

        DBG2(DBG_APP, "dn: '%s'", distinguishedName);
        subject = identification_create_from_string(distinguishedName);
        if (subject->get_type(subject) != ID_DER_ASN1_DN)
        {
            exit_scepclient("parsing of distinguished name failed");
        }

        DBG2(DBG_APP, "building pkcs10 object:");
        pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
                                        CERT_PKCS10_REQUEST,
                                        BUILD_SIGNING_KEY, private_key,
                                        BUILD_SUBJECT, subject,
                                        BUILD_SUBJECT_ALTNAMES, subjectAltNames,
                                        BUILD_CHALLENGE_PWD, challengePassword,
                                        BUILD_DIGEST_ALG, pkcs10_signature_alg,
                                        BUILD_END);
        if (!pkcs10_req)
        {
            exit_scepclient("generating pkcs10 request failed");
        }
    }
    pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
    fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
    DBG1(DBG_APP, "  fingerprint:    %s", fingerprint.ptr);

    /*
     * output of PKCS#10 file
     */
    if (filetype_out & PKCS10)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs10);

        if (!chunk_write(pkcs10_encoding, path, "pkcs10",  0022, force))
        {
            exit_scepclient("could not write pkcs10 file '%s'", path);
        }
        filetype_out &= ~PKCS10;   /* delete PKCS10 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * output of PKCS#1 file
     */
    if (filetype_out & PKCS1)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_out_pkcs1);

        DBG2(DBG_APP, "building pkcs1 object:");
        if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
                !chunk_write(pkcs1, path, "pkcs1", 0066, force))
        {
            exit_scepclient("could not write pkcs1 file '%s'", path);
        }
        filetype_out &= ~PKCS1;   /* delete PKCS1 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    scep_generate_transaction_id(public_key, &transID, &serialNumber);
    DBG1(DBG_APP, "  transaction ID: %.*s", (int)transID.len, transID.ptr);

    /*
     * read or generate self-signed X.509 certificate
     */
    if (filetype_in & CERT_SELF)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), HOST_CERT_PATH, file_in_cert_self);

        x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_signer)
        {
            exit_scepclient("could not read certificate file '%s'", path);
        }
    }
    else
    {
        notBefore = notBefore ? notBefore : time(NULL);
        notAfter  = notAfter  ? notAfter  : (notBefore + validity);
        x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_SIGNING_KEY, private_key,
                                         BUILD_PUBLIC_KEY, public_key,
                                         BUILD_SUBJECT, subject,
                                         BUILD_NOT_BEFORE_TIME, notBefore,
                                         BUILD_NOT_AFTER_TIME, notAfter,
                                         BUILD_SERIAL, serialNumber,
                                         BUILD_SUBJECT_ALTNAMES, subjectAltNames,
                                         BUILD_END);
        if (!x509_signer)
        {
            exit_scepclient("generating certificate failed");
        }
    }
    creds->add_cert(creds, TRUE, x509_signer->get_ref(x509_signer));

    /*
     * output of self-signed X.509 certificate file
     */
    if (filetype_out & CERT_SELF)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert_self);

        if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
        {
            exit_scepclient("encoding certificate failed");
        }
        if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
        {
            exit_scepclient("could not write self-signed cert file '%s'", path);
        }
        chunk_free(&encoding);
        filetype_out &= ~CERT_SELF;   /* delete CERT_SELF flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * load ca encryption certificate
     */
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_enc);

        x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_ca_enc)
        {
            exit_scepclient("could not load encryption cacert file '%s'", path);
        }
    }

    /*
     * input of PKCS#7 file
     */
    if (filetype_in & PKCS7)
    {
        /* user wants to load a pkcs7 encrypted request
         * operation is not yet supported!
         * would require additional parsing of transaction-id

           pkcs7 = pkcs7_read_from_file(file_in_pkcs7);

         */
    }
    else
    {
        DBG2(DBG_APP, "building pkcs7 request");
        pkcs7 = scep_build_request(pkcs10_encoding,
                                   transID, SCEP_PKCSReq_MSG, x509_ca_enc,
                                   pkcs7_symmetric_cipher, pkcs7_key_size,
                                   x509_signer, pkcs7_digest_alg, private_key);
        if (!pkcs7.ptr)
        {
            exit_scepclient("failed to build pkcs7 request");
        }
    }

    /*
     * output pkcs7 encrypted and signed certificate request
     */
    if (filetype_out & PKCS7)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs7);

        if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
        {
            exit_scepclient("could not write pkcs7 file '%s'", path);
        }
        filetype_out &= ~PKCS7;   /* delete PKCS7 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * output certificate fetch from SCEP server
     */
    if (filetype_out & CERT)
    {
        bool stored = FALSE;
        certificate_t *cert;
        enumerator_t  *enumerator;
        char path[PATH_MAX];
        time_t poll_start = 0;
        pkcs7_t *p7;
        container_t *container = NULL;
        chunk_t chunk;
        scep_attributes_t attrs = empty_scep_attributes;

        join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_sig);

        x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_ca_sig)
        {
            exit_scepclient("could not load signature cacert file '%s'", path);
        }

        creds->add_cert(creds, TRUE, x509_ca_sig->get_ref(x509_ca_sig));

        if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
                               http_get_request, http_timeout, &scep_response))
        {
            exit_scepclient("did not receive a valid scep response");
        }
        ugh = scep_parse_response(scep_response, transID, &container, &attrs);
        if (ugh != NULL)
        {
            exit_scepclient(ugh);
        }

        /* in case of manual mode, we are going into a polling loop */
        if (attrs.pkiStatus == SCEP_PENDING)
        {
            identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);

            DBG1(DBG_APP, "  scep request pending, polling every %d seconds",
                 poll_interval);
            poll_start = time_monotonic(NULL);
            issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
                                         issuer->get_encoding(issuer),
                                         subject);
        }
        while (attrs.pkiStatus == SCEP_PENDING)
        {
            if (max_poll_time > 0 &&
                    (time_monotonic(NULL) - poll_start >= max_poll_time))
            {
                exit_scepclient("maximum poll time reached: %d seconds"
                                , max_poll_time);
            }
            DBG2(DBG_APP, "going to sleep for %d seconds", poll_interval);
            sleep(poll_interval);
            free(scep_response.ptr);
            container->destroy(container);

            DBG2(DBG_APP, "fingerprint:    %.*s",
                 (int)fingerprint.len, fingerprint.ptr);
            DBG2(DBG_APP, "transaction ID: %.*s",
                 (int)transID.len, transID.ptr);

            chunk_free(&getCertInitial);
            getCertInitial = scep_build_request(issuerAndSubject,
                                                transID, SCEP_GetCertInitial_MSG, x509_ca_enc,
                                                pkcs7_symmetric_cipher, pkcs7_key_size,
                                                x509_signer, pkcs7_digest_alg, private_key);
            if (!getCertInitial.ptr)
            {
                exit_scepclient("failed to build scep request");
            }
            if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
                                   http_get_request, http_timeout, &scep_response))
            {
                exit_scepclient("did not receive a valid scep response");
            }
            ugh = scep_parse_response(scep_response, transID, &container, &attrs);
            if (ugh != NULL)
            {
                exit_scepclient(ugh);
            }
        }

        if (attrs.pkiStatus != SCEP_SUCCESS)
        {
            container->destroy(container);
            exit_scepclient("reply status is not 'SUCCESS'");
        }

        if (!container->get_data(container, &chunk))
        {
            container->destroy(container);
            exit_scepclient("extracting signed-data failed");
        }
        container->destroy(container);

        /* decrypt enveloped-data container */
        container = lib->creds->create(lib->creds,
                                       CRED_CONTAINER, CONTAINER_PKCS7,
                                       BUILD_BLOB_ASN1_DER, chunk,
                                       BUILD_END);
        free(chunk.ptr);
        if (!container)
        {
            exit_scepclient("could not decrypt envelopedData");
        }

        if (!container->get_data(container, &chunk))
        {
            container->destroy(container);
            exit_scepclient("extracting encrypted-data failed");
        }
        container->destroy(container);

        /* parse signed-data container */
        container = lib->creds->create(lib->creds,
                                       CRED_CONTAINER, CONTAINER_PKCS7,
                                       BUILD_BLOB_ASN1_DER, chunk,
                                       BUILD_END);
        free(chunk.ptr);
        if (!container)
        {
            exit_scepclient("could not parse singed-data");
        }
        /* no need to verify the signed-data container, the signature does NOT
         * cover the contained certificates */

        /* store the end entity certificate */
        join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert);

        p7 = (pkcs7_t*)container;
        enumerator = p7->create_cert_enumerator(p7);
        while (enumerator->enumerate(enumerator, &cert))
        {
            x509_t *x509 = (x509_t*)cert;

            if (!(x509->get_flags(x509) & X509_CA))
            {
                if (stored)
                {
                    exit_scepclient("multiple certs received, only first stored");
                }
                if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
                        !chunk_write(encoding, path, "requested cert", 0022, force))
                {
                    exit_scepclient("could not write cert file '%s'", path);
                }
                chunk_free(&encoding);
                stored = TRUE;
            }
        }
        enumerator->destroy(enumerator);
        container->destroy(container);
        chunk_free(&attrs.transID);
        chunk_free(&attrs.senderNonce);
        chunk_free(&attrs.recipientNonce);

        filetype_out &= ~CERT;   /* delete CERT flag */
    }

    exit_scepclient(NULL);
    return -1; /* should never be reached */
}