bool editor_palette<Item>::scroll_up()
{
	int decrement = item_width_;
	if (items_start_ + num_visible_items() == num_items() && num_items() % item_width_ != 0) {
		decrement = num_items() % item_width_;
	}
	if(items_start_ >= decrement) {
		items_start_ -= decrement;
		draw();
		return true;
	}
	return false;
}
bool editor_palette<Item>::scroll_down()
{
	bool end_reached = (!(items_start_ + nitems_ + item_width_ <= num_items()));
	bool scrolled = false;

	// move downwards
	if(!end_reached) {
		items_start_ += item_width_;
		scrolled = true;
	}
	else if (items_start_ + nitems_ + (num_items() % item_width_) <= num_items()) {
		items_start_ += num_items() % item_width_;
		scrolled = true;
	}
	set_dirty(scrolled);
	draw();
	return scrolled;
}
int CertificateRevocationListToBeSignedConstraint(
    struct CertificateRevocationListToBeSigned *ctbsp)
{
    long version = 0;
    int num = num_items(&ctbsp->extensions.self);
    struct CRLEntry *crlentryp;
    for (crlentryp =
         (struct CRLEntry *)member_casn(&ctbsp->revokedCertificates.self, 0);
         crlentryp; crlentryp = (struct CRLEntry *)next_of(&crlentryp->self))
    {
        if (vsize_casn(&crlentryp->extensions.self) > 0)
            num++;
    }
    read_casn_num(&ctbsp->version.self, &version);
    if (version > 1 || (!version && num > 0))
        return 0;
    return 1;
}
示例#4
0
const char *signCMS(
    struct CMS *cms,
    const char *keyfilename,
    bool bad)
{
    bool hashContext_initialized = false;
    CRYPT_CONTEXT hashContext;
    bool sigKeyContext_initialized = false;
    CRYPT_CONTEXT sigKeyContext;
    CRYPT_KEYSET cryptKeyset;
    int signatureLength;
    int tbs_lth;
    char *msg = (char *)0;
    uchar *tbsp;
    uchar *signature = NULL;
    uchar hash[40];
    struct casn *sidp;
    struct Attribute *attrp;
    struct AttrTableDefined *attrtdp;
    struct SignerInfo *sigInfop;

    // signer info
    // firat clear out any old stuff in signerInfos that may have been put
    // there by old code
    while (num_items(&cms->content.signedData.signerInfos.self) > 0)
        eject_casn(&cms->content.signedData.signerInfos.self, 0);
    sigInfop =
        (struct SignerInfo *)
        inject_casn(&(cms->content.signedData.signerInfos.self), 0);

    // write the signature version (3) to the signer info
    write_casn_num(&sigInfop->version.self, 3);

    // find the SID
    if ((sidp = findSID(cms)) == NULL)
        return "finding SID";

    // copy the CMS's SID over to the signature's SID
    copy_casn(&sigInfop->sid.subjectKeyIdentifier, sidp);

    // use sha256 as the algorithm
    write_objid(&sigInfop->digestAlgorithm.algorithm, id_sha256);

    // no parameters to sha256
    write_casn(&sigInfop->digestAlgorithm.parameters.sha256, (uchar *) "", 0);

    // first attribute: content type
    attrp = (struct Attribute *)inject_casn(&sigInfop->signedAttrs.self, 0);
    write_objid(&attrp->attrType, id_contentTypeAttr);
    attrtdp =
        (struct AttrTableDefined *)inject_casn(&attrp->attrValues.self, 0);
    copy_casn(&attrtdp->contentType,
              &cms->content.signedData.encapContentInfo.eContentType);

    // second attribute: message digest
    attrp = (struct Attribute *)inject_casn(&sigInfop->signedAttrs.self, 1);
    write_objid(&attrp->attrType, id_messageDigestAttr);

    // create the hash for the content

    // first pull out the content
    if ((tbs_lth =
         readvsize_casn(&cms->content.signedData.encapContentInfo.eContent.
                        self, &tbsp)) < 0)
        return "getting content";

    // set up the context, initialize crypt
    memset(hash, 0, 40);
    if (cryptInit_wrapper() != CRYPT_OK)
        return "initializing cryptlib";

    // the following calls function f, and if f doesn't return 0 sets
    // msg to m, then breaks out of the loop. Used immediately below.
#define CALL(f,m) if (f != 0) { msg = m; break; }

    // use a "do { ... } while (0)" loop to bracket this code, so we can
    // bail out on failure. (Note that this construct isn't really a
    // loop; it's a way to use break as a more clean version of goto.)
    do
    {
        // first sign the body of the message

        // create the context
        CALL(cryptCreateContext(&hashContext, CRYPT_UNUSED, CRYPT_ALGO_SHA2),
             "creating context");
        hashContext_initialized = true;

        // generate the hash
        CALL(cryptEncrypt(hashContext, tbsp, tbs_lth), "hashing");
        CALL(cryptEncrypt(hashContext, tbsp, 0), "hashing");

        // get the hash value. then we're done, so destroy it
        CALL(cryptGetAttributeString
             (hashContext, CRYPT_CTXINFO_HASHVALUE, hash, &signatureLength),
             "getting first hash");
        CALL(cryptDestroyContext(hashContext),
             "destroying intermediate context");

        // insert the hash as the first attribute
        attrtdp =
            (struct AttrTableDefined *)inject_casn(&attrp->attrValues.self, 0);
        write_casn(&attrtdp->messageDigest, hash, signatureLength);

        // create signing time attribute; mark the signing time as now
        if (getenv("RPKI_NO_SIGNING_TIME") == NULL)
        {
            attrp =
                (struct Attribute *)inject_casn(&sigInfop->signedAttrs.self, 2);
            write_objid(&attrp->attrType, id_signingTimeAttr);
            attrtdp =
                (struct AttrTableDefined *)inject_casn(&attrp->attrValues.self, 0);
            write_casn_time(&attrtdp->signingTime.utcTime, time((time_t *) 0));
        }

        // we are all done with the content
        free(tbsp);

        // now sign the attributes

        // get the size of signed attributes and allocate space for them
        if ((tbs_lth = size_casn(&sigInfop->signedAttrs.self)) < 0)
        {
            msg = "sizing SignerInfo";
            break;
        }
        tbsp = (uchar *) calloc(1, tbs_lth);
        encode_casn(&sigInfop->signedAttrs.self, tbsp);
        *tbsp = ASN_SET;

        // create a new, fresh hash context for hashing the attrs, and hash
        // them
        CALL(cryptCreateContext(&hashContext, CRYPT_UNUSED, CRYPT_ALGO_SHA2),
             "creating hash context");
        CALL(cryptEncrypt(hashContext, tbsp, tbs_lth), "hashing attrs");
        CALL(cryptEncrypt(hashContext, tbsp, 0), "hashing attrs");

        // get the hash value
        CALL(cryptGetAttributeString
             (hashContext, CRYPT_CTXINFO_HASHVALUE, hash, &signatureLength),
             "getting attr hash");

        // get the key and sign it
        CALL(cryptKeysetOpen
             (&cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, keyfilename,
              CRYPT_KEYOPT_READONLY), "opening key set");
        CALL(cryptCreateContext(&sigKeyContext, CRYPT_UNUSED, CRYPT_ALGO_RSA),
             "creating RSA context");
        sigKeyContext_initialized = true;
        CALL(cryptGetPrivateKey
             (cryptKeyset, &sigKeyContext, CRYPT_KEYID_NAME, "label",
              "password"), "getting key");
        CALL(cryptCreateSignature
             (NULL, 0, &signatureLength, sigKeyContext, hashContext),
             "signing");

        // check the signature to make sure it's right
        signature = (uchar *) calloc(1, signatureLength + 20);

        // second parameter is signatureMaxLength, so we allow a little more
        CALL(cryptCreateSignature
             (signature, signatureLength + 20, &signatureLength, sigKeyContext,
              hashContext), "signing");

        // verify that the signature is right
        CALL(cryptCheckSignature
             (signature, signatureLength, sigKeyContext, hashContext),
             "verifying");

        // end of protected block
    } while (0);

    // done with cryptlib, shut it down
    if (hashContext_initialized)
    {
        cryptDestroyContext(hashContext);
        hashContext_initialized = false;
    }
    if (sigKeyContext_initialized)
    {
        cryptDestroyContext(sigKeyContext);
        sigKeyContext_initialized = false;
    }

    // did we have any trouble above? if so, bail
    if (msg != 0)
    {
        return msg;
    }

    // ok, write the signature back to the object
    struct SignerInfo sigInfo;
    SignerInfo(&sigInfo, (ushort) 0);
    decode_casn(&sigInfo.self, signature);

    // were we supposed to make a bad signature? if so, make it bad
    if (bad)
    {
        uchar *sig;
        int siz = readvsize_casn(&sigInfo.signature, &sig);
        sig[0]++;
        write_casn(&sigInfo.signature, sig, siz);
        free(sig);
    }

    // copy the signature into the object
    copy_casn(&sigInfop->signature, &sigInfo.signature);
    delete_casn(&sigInfo.self);

    // all done with it now
    free(signature);

    // Mark it as encrypted with rsa, no params.
    // See http://www.ietf.org/mail-archive/web/sidr/current/msg04813.html for
    // why we use id_rsadsi_rsaEncryption instead of id_sha_256WithRSAEncryption
    // here.
    write_objid(&sigInfop->signatureAlgorithm.algorithm,
                id_rsadsi_rsaEncryption);
    write_casn(&sigInfop->signatureAlgorithm.parameters.self, (uchar *) "", 0);

    // no errors, we return NULL
    return NULL;
}
示例#5
0
文件: put_sia.c 项目: dseomn/rpstir
int main(
    int argc,
    char *argv[])
{

    int delete_existing = 0;    /* delete existing SIA access descriptions */
    const char *file = NULL;    /* certificate file */
    struct Certificate cert;    /* ASN.1 certificate object */
    struct Extension *extp;     /* ASN.1 X.509 extension pointer */
    struct SubjectInfoAccess *siap;     /* ASN.1 SIA pointer */

    int c = 0;                  /* getopt option character */
    int i;                      /* loop counter */
    int ret;                    /* return value */

    /*
     * Parse command line arguments.
     */
    opterr = 0;
    while ((c = getopt(argc, argv, "dr:m:s:h")) != -1)
    {
        switch (c)
        {
        case 'd':
            delete_existing = 1;
            break;
        case 'r':              /* id-ad-caRepository */
            if (add_sia_request('r', optarg) != 0)
            {
                fprintf(stderr, "Error: failed to add URI request -r %s\n",
                        optarg);
                return -1;
            }
            break;
        case 'm':              /* id-ad-rpkiManifest */
            if (add_sia_request('m', optarg) != 0)
            {
                fprintf(stderr, "Error: failed to add URI request -m %s\n",
                        optarg);
                return -1;
            }
            break;
        case 's':              /* id-ad-signedObject */
            if (add_sia_request('s', optarg) != 0)
            {
                fprintf(stderr, "Error: failed to add URI request -s %s\n",
                        optarg);
                return -1;
            }
            break;
        case 'h':
            usage(argc, argv);
            return -1;
        case '?':
            if (isprint(optopt))
                fprintf(stderr, "Unknown option `-%c'.\n", optopt);
            else
                fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
            usage(argc, argv);
            return -1;
        default:
            usage(argc, argv);
            return -1;
        }
    }
    if (optind >= argc)
    {                           /* no arguments remain? */
        usage(argc, argv);
        return -1;
    }
    file = argv[optind];

    /*
     * Parse certificate.
     */
    Certificate(&cert, (unsigned short)0);      /* constructor */
    ret = get_casn_file(&cert.self, (char *)file, 0);
    if (ret < 0)
    {
        fprintf(stderr, "Could not open file: %s\n", file);
        return -2;
    }

    /*
     * Find or create SIA extension.
     */
    extp = find_extension(&cert.toBeSigned.extensions,
                          id_pe_subjectInfoAccess, false);
    if (!extp)
    {
        extp =
            make_extension(&cert.toBeSigned.extensions,
                          id_pe_subjectInfoAccess);
        if (!extp)
        {
            fprintf(stderr, "Could not create SIA extension.\n");
            return -3;
        }
    }
    siap = &extp->extnValue.subjectInfoAccess;

    /*
     * Optionally delete existing AccessDescriptions.
     */
    if (delete_existing)
    {
        clear_casn(&siap->self);        /* This messes up the "DEFINED BY"
                                         * flag, so we need to set it again in
                                         * the next line.  */
        if (write_objid(&extp->extnID, id_pe_subjectInfoAccess) < 0)
        {
            fprintf(stderr, "Error clearing existing URIs.\n");
            return -1;
        }
    }

    /*
     * For each AccessDescription request, insert it.
     */
    for (i = 0; i < num_sia_requests; i++)
    {
        int current_size;
        struct AccessDescription *adp;  /* ASN.1 AccessDescription pointer */

        /*
         * Append new entry.
         */
        current_size = num_items(&siap->self);
        adp =
            (struct AccessDescription *)inject_casn(&siap->self, current_size);
        if (!adp)
        {
            fprintf(stderr, "Error: failed to append access description.\n");
            return -1;
        }

        if (write_objid(&adp->accessMethod,
                        (char *)sia_requests[i].accessMethod) < 0)
        {
            fprintf(stderr, "Error: failed to set access method.\n");
            return -1;
        }

        if (write_casn(&adp->accessLocation.url,
                       (unsigned char *)sia_requests[i].accessLocation,
                       strlen(sia_requests[i].accessLocation)) < 0)
        {
            fprintf(stderr, "Error: failed to set access location.\n");
            return -1;
        }
    }

    /*
     * Check for non-empty SIA (RFC 5280)
     */
    if (num_items(&siap->self) == 0)
    {
        fprintf(stderr,
                "SIA must have at least one AccessDescription, per RFC5280.\n");
        return -1;
    }

    /*
     * Write to file.
     */
    if (put_casn_file(&cert.self, (char *)file, 0) < 0)
    {
        fprintf(stderr, "Error: failed to write %s\n", file);
        return -4;
    }

    /*
     * Clean up.
     */
    delete_casn(&cert.self);
    return 0;
}
示例#6
0
/*
 * ipv4 address are a comma separated list of either prefix or range
 * specifications for ipv4 addresses
 */
int write_cert_addrs(
    void *cert,
    void *val,
    int type)
{
    struct CertificateToBeSigned *tbsp =
        &((struct Certificate *)cert)->toBeSigned;
    struct Extension *extp;
    struct Extensions *extsp = &tbsp->extensions;
    struct IPAddressFamilyA *famp;
    char *ptr,
       *next,
       *buf;
    int ptr_len;
    char token = ',';
    char family[2];
    int num = 0;

    family[0] = 0;
    if (type == IPv4)
        family[1] = 1;
    else
        family[1] = 2;

    extp = find_extension(extsp, id_pe_ipAddrBlock, false);
    if (!extp)
    {
        extp = make_extension(extsp, id_pe_ipAddrBlock);
        write_casn_num(&extp->critical, 1);
    }

    if (type == IPv6)
        famp =
            (struct IPAddressFamilyA *)inject_casn(&extp->extnValue.
                                                   ipAddressBlock.self,
                                                   num_items(&extp->extnValue.
                                                             ipAddressBlock.
                                                             self));
    else
        famp =
            (struct IPAddressFamilyA *)inject_casn(&extp->extnValue.
                                                   ipAddressBlock.self, 0);

    write_casn(&famp->addressFamily, (unsigned char *)family, 2);

    // if it is inherit - set that and done
    if (strncmp(val, "inherit", strlen("inherit")) == 0)
    {
        struct IPAddressChoiceA *addrChoice = &famp->ipAddressChoice;
        write_casn(&addrChoice->inherit, (uchar *) "", 0);
        return SUCCESS;
    }

    // go through all addresses listed and add them to the block
    ptr = val;
    while (ptr != NULL)
    {
        next = strchr(ptr, token);
        while (isspace((int)(unsigned char)*ptr))
            ptr++;              // strip leading spaces
        if (next == NULL)
            ptr_len = strlen(ptr);
        else
        {
            ptr_len = (char *)next - (char *)ptr;
            next++;
        }
        if ((buf = strndup(ptr, ptr_len)) == NULL)
            return -1;

        if (write_family(famp, buf, num++) < 0)
            return -1;
        ptr = next;
    }

    return SUCCESS;
}
bool editor_palette<Item>::can_scroll_down()
{
	return (items_start_ + nitems_ + item_width_ <= num_items());
}
void editor_palette<Item>::draw_contents()
{
	toolkit_.set_mouseover_overlay(gui_);

	std::shared_ptr<gui::button> palette_menu_button = gui_.find_menu_button("menu-editor-terrain");
	if (palette_menu_button) {

		t_string& name = groups_[active_group_index()].name;
		std::string& icon = groups_[active_group_index()].icon;

		palette_menu_button->set_tooltip_string(name);
		palette_menu_button->set_overlay(icon);
	}

	unsigned int y = palette_y_;
	unsigned int x = palette_x_;
	int starting = items_start_;
	int ending = std::min<int>(starting + nitems_, num_items());

	std::shared_ptr<gui::button> upscroll_button = gui_.find_action_button("upscroll-button-editor");
	if (upscroll_button)
		upscroll_button->enable(starting != 0);
	std::shared_ptr<gui::button> downscroll_button = gui_.find_action_button("downscroll-button-editor");
	if (downscroll_button)
		downscroll_button->enable(ending != num_items());


	int counter = starting;
	for (int i = 0, size = num_visible_items(); i < size ; ++i) {
		//TODO check if the conditions still hold for the counter variable
		//for (unsigned int counter = starting; counter < ending; counter++)

		gui::tristate_button& tile = buttons_[i];

		tile.hide(true);

		if (i >= ending) continue;

		const std::string item_id = active_group()[counter];
		//typedef std::map<std::string, Item> item_map_wurscht;
		typename item_map::iterator item = item_map_.find(item_id);

		surface item_image(nullptr);
		std::stringstream tooltip_text;
		draw_item((*item).second, item_image, tooltip_text);

		bool is_core = non_core_items_.find(get_id((*item).second)) == non_core_items_.end();
		if (!is_core) {
			tooltip_text << " "
					<< font::span_color(font::BAD_COLOR)
			<< _("(non-core)") << "\n"
			<< _("Will not work in game without extra care.")
			<< "</span>";
		}

		const int counter_from_zero = counter - starting;
		SDL_Rect dstrect;
		dstrect.x = x + (counter_from_zero % item_width_) * item_space_;
		dstrect.y = y;
		dstrect.w = item_size_ + 2;
		dstrect.h = item_size_ + 2;

		tile.set_location(dstrect);
		tile.set_tooltip_string(tooltip_text.str());
		tile.set_item_image(item_image);
		tile.set_item_id(item_id);

//		if (get_id((*item).second) == selected_bg_item_
//				&& get_id((*item).second) == selected_fg_item_) {
//			tile.set_pressed(gui::tristate_button::BOTH);
//		} else if (get_id((*item).second) == selected_bg_item_) {
//			tile.set_pressed(gui::tristate_button::RIGHT);
//		} else if (get_id((*item).second) == selected_fg_item_) {
//			tile.set_pressed(gui::tristate_button::LEFT);
//		} else {
//			tile.set_pressed(gui::tristate_button::NONE);
//		}

		if (is_selected_bg_item(get_id(item->second))
				&& is_selected_fg_item(get_id(item->second))) {
			tile.set_pressed(gui::tristate_button::BOTH);
		} else if (is_selected_bg_item(get_id(item->second))) {
			tile.set_pressed(gui::tristate_button::RIGHT);
		} else if (is_selected_fg_item(get_id(item->second))) {
			tile.set_pressed(gui::tristate_button::LEFT);
		} else {
			tile.set_pressed(gui::tristate_button::NONE);
		}

		tile.set_dirty(true);
		tile.hide(false);
		tile.draw();

		// Adjust location
		if (counter_from_zero % item_width_ == item_width_ - 1)
			y += item_space_;
		++counter;
	}
}