コード例 #1
0
void security_check(void)
{
	unsigned int secure_context_base;
	int ret;

	/* Set Secure Context Base Address*/
	secure_context_base = CONFIG_SYS_SDRAM_BASE + PART_SIZE_BL1 - 1024;

	/* Verify Kernel */
	ret = check_signature((SB20_CONTEXT *)secure_context_base,
			(unsigned char *)CONFIG_SECURE_KERNEL_BASE, CONFIG_SECURE_KERNEL_SIZE - 256,
			(unsigned char *)(CONFIG_SECURE_KERNEL_BASE +
			CONFIG_SECURE_KERNEL_SIZE - 256), 256);
	if (ret) {
		printf("Kernel Integrity check fail\nSystem Halt....");
		while (1);
	}
	printf("Kernel Integirty check success.\n");

#ifdef CONFIG_SECURE_ROOTFS
	/* Verify rootfs */
	ret = check_signature((SB20_CONTEXT *)secure_context_base,
			(unsigned char *)CONFIG_SECURE_ROOTFS_BASE, CONFIG_SECURE_ROOTFS_SIZE - 256,
			(unsigned char *)(CONFIG_SECURE_ROOTFS_BASE +
			CONFIG_SECURE_ROOTFS_SIZE - 256), 256);
	if (ret) {
		printf("rootfs Integrity check fail\nSystem Halt....");
		while (1);
	}
	printf("rootfs Integirty check success.\n");
#endif
}
コード例 #2
0
ファイル: security_check.c プロジェクト: exynos4-sdk/uboot
void security_check(void)
{
	unsigned char hash_code[20];
	unsigned int bl1_size = PART_SIZE_FWBL1;
	unsigned int secure_context_base;

	if(bl1_size == (15 * 1024)) {
		secure_context_base = 0x40003800;
	} else
		secure_context_base = 0x40001c00;

	ace_hash_sha1_digest(hash_code, (unsigned char *)CONFIG_SECURE_KERNEL_BASE, CONFIG_SECURE_KERNEL_SIZE-256);

	if(check_signature( (SB20_CONTEXT *)secure_context_base,
			hash_code, 20,
			(unsigned char*)(CONFIG_SECURE_KERNEL_BASE+CONFIG_SECURE_KERNEL_SIZE-256),
			256 ) != 0) {
		printf("Kernel Integrity check fail\nSystem Halt....");
		while(1);
	}
	printf("Kernel Integirty check success.\n");

#ifdef CONFIG_SECURE_ROOTFS
	ace_hash_sha1_digest(hash_code, (unsigned char *)CONFIG_SECURE_ROOTFS_BASE, CONFIG_SECURE_ROOTFS_SIZE-256);

	if(check_signature( (SB20_CONTEXT *)secure_context_base,
			hash_code, 20,
			(unsigned char*)(CONFIG_SECURE_ROOTFS_BASE+CONFIG_SECURE_ROOTFS_SIZE-256),
			256 ) != 0) {
		printf("rootfs Integrity check fail\nSystem Halt....");
		while(1);
	}
	printf("rootfs Integirty check success.\n");
#endif
}
コード例 #3
0
static gboolean
handle_mime_object (MuMsg *msg, GMimeObject *mobj, GMimeObject *parent,
		    MuMsgOptions opts, unsigned *index, gboolean decrypted,
		    MuMsgPartForeachFunc func, gpointer user_data)
{
	if (GMIME_IS_PART (mobj))
		return handle_part
			(msg, GMIME_PART(mobj), parent,
			 opts, index, decrypted, func, user_data);
	else if (GMIME_IS_MESSAGE_PART (mobj))
		return handle_message_part
			(msg, GMIME_MESSAGE_PART(mobj),
			 parent, opts, index, decrypted, func, user_data);
	else if ((opts & MU_MSG_OPTION_VERIFY) &&
	         GMIME_IS_MULTIPART_SIGNED (mobj)) {
		check_signature
			(msg, GMIME_MULTIPART_SIGNED (mobj), opts);
		return handle_multipart
			(msg, GMIME_MULTIPART (mobj), mobj, opts,
			 index, decrypted, func, user_data);
	} else if ((opts & MU_MSG_OPTION_DECRYPT) &&
	           GMIME_IS_MULTIPART_ENCRYPTED (mobj))
		return handle_encrypted_part
			(msg, GMIME_MULTIPART_ENCRYPTED (mobj),
			 opts, index, func, user_data);
	else if (GMIME_IS_MULTIPART (mobj))
		return handle_multipart
			(msg, GMIME_MULTIPART (mobj), parent, opts,
			 index, decrypted, func, user_data);
	return TRUE;
}
コード例 #4
0
/*
* Check the signature on an object
*/
bool X509_Object::check_signature(const Public_Key* pub_key) const
   {
   if(!pub_key)
      throw Exception("No key provided for " + m_PEM_label_pref + " signature check");
   std::unique_ptr<const Public_Key> key(pub_key);
   return check_signature(*key);
}
コード例 #5
0
ファイル: tag.c プロジェクト: PEPE-coin/git
static int run_gpg_verify(const char *buf, unsigned long size, unsigned flags)
{
	struct signature_check sigc;
	size_t payload_size;
	int ret;

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

	payload_size = parse_signature(buf, size);

	if (size == payload_size) {
		if (flags & GPG_VERIFY_VERBOSE)
			write_in_full(1, buf, payload_size);
		return error("no signature found");
	}

	ret = check_signature(buf, payload_size, buf + payload_size,
				size - payload_size, &sigc);

	if (!(flags & GPG_VERIFY_OMIT_STATUS))
		print_signature_buffer(&sigc, flags);

	signature_check_clear(&sigc);
	return ret;
}
コード例 #6
0
ファイル: cbtable.c プロジェクト: Der-Jan/grub-zfs
grub_err_t
grub_linuxbios_table_iterate (int (*hook) (grub_linuxbios_table_item_t,
					   void *),
			      void *hook_data)
{
  grub_linuxbios_table_header_t table_header;
  grub_linuxbios_table_item_t table_item;

  /* Assuming table_header is aligned to its size (8 bytes).  */

  for (table_header = (grub_linuxbios_table_header_t) 0x500;
       table_header < (grub_linuxbios_table_header_t) 0x1000; table_header++)
    if (check_signature (table_header))
      goto signature_found;

  for (table_header = (grub_linuxbios_table_header_t) 0xf0000;
       table_header < (grub_linuxbios_table_header_t) 0x100000; table_header++)
    if (check_signature (table_header))
      goto signature_found;

  grub_fatal ("Could not find coreboot table\n");

signature_found:

  table_item =
    (grub_linuxbios_table_item_t) ((char *) table_header +
				   table_header->header_size);
  for (; table_item < (grub_linuxbios_table_item_t) ((char *) table_header
						     + table_header->header_size
						     + table_header->table_size);
       table_item = (grub_linuxbios_table_item_t) ((char *) table_item + table_item->size))
    {
      if (table_item->tag == GRUB_LINUXBIOS_MEMBER_LINK
         && check_signature ((grub_linuxbios_table_header_t) (grub_addr_t)
                             *(grub_uint64_t *) (table_item + 1)))
       {
         table_header = (grub_linuxbios_table_header_t) (grub_addr_t)
           *(grub_uint64_t *) (table_item + 1);
         goto signature_found;   
       }
      if (hook (table_item, hook_data))
       return 1;
    }

  return 0;
}
コード例 #7
0
ファイル: check_signature.c プロジェクト: dseomn/rpstir
int main(
    int argc,
    char **argv)
{
    OPEN_LOG("check_signature", LOG_USER);
    if (argc != 3)
        FATAL(MSG_USAGE);
    struct Certificate locert,
        hicert;
    struct CertificateRevocationList crl;
    Certificate(&locert, (ushort) 0);
    Certificate(&hicert, (ushort) 0);
    CertificateRevocationList(&crl, (ushort) 0);
    struct Blob blob;
    Blob(&blob, (ushort) 0);
    struct casn *tbsp,
       *sigp;
    struct AlgorithmIdentifier *algp;
    char *sfx = strchr(argv[1], (int)'.');
    int ansr;
    if (!strcmp(sfx, ".cer"))
    {
        tbsp = &locert.toBeSigned.self;
        algp = &locert.algorithm;
        sigp = &locert.signature;
        ansr = get_casn_file(&locert.self, argv[1], 0);
    }
    else if (!strcmp(sfx, ".crl"))
    {
        tbsp = &crl.toBeSigned.self;
        algp = &crl.algorithm;
        sigp = &crl.signature;
        ansr = get_casn_file(&crl.self, argv[1], 0);
    }
    else if (!strcmp(sfx, ".blb"))
    {
        tbsp = &blob.toBeSigned;
        algp = &blob.algorithm;
        sigp = &blob.signature;
        ansr = get_casn_file(&blob.self, argv[1], 0);
    }
    else
        FATAL(MSG_TYPE, argv[1]);
    if (ansr < 0)
        FATAL(MSG_GET, argv[1]);
    if (get_casn_file(&hicert.self, argv[2], 0) < 0)
        FATAL(MSG_GET, argv[2]);
    if (diff_objid(&algp->algorithm, id_sha_256WithRSAEncryption))
    {
        char oidbuf[80];
        read_objid(&algp->algorithm, oidbuf);
        FATAL(MSG_ALG, oidbuf);
    }
    if (!check_signature(tbsp, &hicert, sigp))
        fprintf(stderr, "Signature failed\n");
    fprintf(stderr, "Signature succeeded\n");
    return 0;
}
コード例 #8
0
SerialFlashFile SerialFlashChip::open(const char *filename)
{
	uint32_t maxfiles, straddr;
	uint16_t hash, hashtable[8];
	uint32_t i, n, index=0;
	uint32_t buf[3];
	SerialFlashFile file;

	maxfiles = check_signature();
	 //Serial.printf("sig: %08X\n", maxfiles);
	if (!maxfiles) return file;
	maxfiles &= 0xFFFF;
	hash = filename_hash(filename);
	 //Serial.printf("hash %04X for \"%s\"\n", hash, filename);
	while (index < maxfiles) {
		n = 8;
		if (n > maxfiles - index) n = maxfiles - index;
		SerialFlash.read(8 + index * 2, hashtable, n * 2);
		 //Serial.printf(" read %u: ", 8 + index * 2);
		 //pbuf(hashtable, n * 2);
		for (i=0; i < n; i++) {
			if (hashtable[i] == hash) {
				 //Serial.printf("  hash match at index %u\n", index+i);
				buf[2] = 0;
				SerialFlash.read(8 + maxfiles * 2 + (index+i) * 10, buf, 10);

				 //Serial.printf("  maxf=%d, index=%d, i=%d\n", maxfiles, index, i);
				 //Serial.printf("  read %u: ", 8 + maxfiles * 2 + (index+i) * 10);
				 //pbuf(buf, 10);
				straddr = 8 + maxfiles * 12 + buf[2] * 4;
				 //Serial.printf("  straddr = %u\n", straddr);
				if (filename_compare(filename, straddr)) {
					 //Serial.printf("  match!\n");
					 //Serial.printf("  addr = %u\n", buf[0]);
					 //Serial.printf("  len =  %u\n", buf[1]);
					file.address = buf[0];
					file.length = buf[1];
					file.offset = 0;
					file.dirindex = index + i;
					return file;
				}
			} else if (hashtable[i] == 0xFFFF) {
				return file;
			}
		}
		index += n;
	}
	return file;
}
コード例 #9
0
bool SerialFlashChip::readdir(char *filename, uint32_t strsize, uint32_t &filesize)
{
	uint32_t maxfiles, index, straddr;
	uint32_t i, n;
	uint32_t buf[2];
	uint16_t hash;
	char str[16], *p=filename;

	filename[0] = 0;
	maxfiles = check_signature();
	if (!maxfiles) return false;
	maxfiles &= 0xFFFF; 
	index = dirindex;
	while (1) {
		if (index >= maxfiles) return false;
		 //Serial.printf("readdir, index = %u\n", index);
		SerialFlash.read(8 + index * 2, &hash, 2);
		if (hash != 0) break;
		index++;  // skip deleted entries
	}
	dirindex = index + 1;
	buf[1] = 0;
	SerialFlash.read(8 + 4 + maxfiles * 2 + index * 10, buf, 6);
	if (buf[0] == 0xFFFFFFFF) return false;
	filesize = buf[0];
	straddr = 8 + maxfiles * 12 + buf[1] * 4;
	 //Serial.printf("  length = %u\n", buf[0]);
	 //Serial.printf("  straddr = %u\n", straddr);

	while (strsize) {
		n = strsize;
		if (n > sizeof(str)) n = sizeof(str);
		SerialFlash.read(straddr, str, n);
		for (i=0; i < n; i++) {
			*p++ = str[i];
			if (str[i] == 0) {
				 //Serial.printf("  name = %s\n", filename);
				return true;
			}
		}
		strsize -= n;
		straddr += n;
	}
	*(p - 1) = 0;
	 //Serial.printf("  name(overflow) = %s\n", filename);
	return true;
}
コード例 #10
0
ファイル: fsam7400.c プロジェクト: ArthySundaram/firstrepo
static inline int fsam_map_memory(void)
{
   const unsigned long max_offset = BIOS_CODE_MAPSIZE - BIOS_SIGN_SIZE - PTR_POSITION;
   unsigned long offset;
   unsigned int addr;
   mem_code = ioremap(BIOS_CODE_ADDR, BIOS_CODE_MAPSIZE);
   if (!mem_code)
      goto fail;
   DEBUG_OUT3("physical memory %x-%x mapped to virtual address %p\n",
              BIOS_CODE_ADDR, BIOS_CODE_ADDR+BIOS_CODE_MAPSIZE, mem_code);
   for ( offset = 0; offset < max_offset; offset += ALLIGNED_STEP )
      if (check_signature((void*)TOUL(mem_code) + offset, bios_sign, BIOS_SIGN_SIZE))
         break;
   if (offset >= max_offset)
     goto fail;
   DEBUG_OUT1("bios signature found at offset %lx\n", offset);
   addr = readl((void*)TOUL(mem_code) + offset + PTR_POSITION);
   if (addr < BIOS_CODE_ADDR) {
      DEBUG_OUT0("bios routine out of memory range, "
                 "doing some new memory mapping...\n");
      iounmap(mem_code);
      mem_code = NULL;
      addr &= BIOS_CODE_ALT_MASK;
      mem_code = ioremap(addr, BIOS_CODE_ALT_MAPSIZE);
      if (!mem_code)
         goto fail;
      DEBUG_OUT3("physical memory %x-%x mapped to virtual address %p\n",
                 addr, addr+BIOS_CODE_ALT_MAPSIZE, mem_code);
      addr &= 0x3FFF;
   } else
     addr &= 0xFFFF;

   bios_code = addr + TOUL(mem_code);
   DEBUG_OUT1("supposed address of bios routine is %lx\n", bios_code);
   return 1;
 fail:
   fsam_unmap_memory();
   return 0;
}
コード例 #11
0
ファイル: eicon_isa.c プロジェクト: chinnyannieb/empeg-hijack
int
eicon_isa_bootload(eicon_isa_card *card, eicon_isa_codebuf *cb) {
	int	tmp;
	int               timeout;
	eicon_isa_codebuf cbuf;
	unsigned char     *code;
	eicon_isa_boot    *boot;

	if (copy_from_user(&cbuf, cb, sizeof(eicon_isa_codebuf)))
		return -EFAULT;

	/* Allocate code-buffer and copy code from userspace */
	if (cbuf.bootstrap_len > 1024) {
		printk(KERN_WARNING "eicon_isa_boot: Invalid startup-code size %ld\n",
		       cbuf.bootstrap_len);
		return -EINVAL;
	}
	if (!(code = kmalloc(cbuf.bootstrap_len, GFP_KERNEL))) {
		printk(KERN_WARNING "eicon_isa_boot: Couldn't allocate code buffer\n");
		return -ENOMEM;
	}
	if (copy_from_user(code, &cb->code, cbuf.bootstrap_len)) {
		kfree(code);
		return -EFAULT;
	}

	if (card->type == EICON_CTYPE_ISAPRI)
		card->ramsize  = RAMSIZE_P;
	else
		card->ramsize  = RAMSIZE;

	/* Register shmem */
	if (check_shmem((unsigned long)card->shmem, card->ramsize)) {
		printk(KERN_WARNING "eicon_isa_boot: memory at 0x%lx already in use.\n",
			(unsigned long)card->shmem);
		kfree(code);
		return -EBUSY;
	}
	request_shmem((unsigned long)card->shmem, card->ramsize, "Eicon ISA ISDN");
#ifdef EICON_MCA_DEBUG
	printk(KERN_INFO "eicon_isa_boot: card->ramsize = %d.\n", card->ramsize);
#endif
	card->mvalid = 1;

	switch(card->type) {
		case EICON_CTYPE_S:
		case EICON_CTYPE_SX:
		case EICON_CTYPE_SCOM:
		case EICON_CTYPE_QUADRO:
		case EICON_CTYPE_ISABRI:
			card->intack   = (__u8 *)card->shmem + INTACK;
			card->startcpu = (__u8 *)card->shmem + STARTCPU;
			card->stopcpu  = (__u8 *)card->shmem + STOPCPU;
			break;
		case EICON_CTYPE_S2M:
		case EICON_CTYPE_ISAPRI:
			card->intack   = (__u8 *)card->shmem + INTACK_P;
			card->startcpu = (__u8 *)card->shmem + STARTCPU_P;
			card->stopcpu  = (__u8 *)card->shmem + STOPCPU_P;
			break;
		default:
			printk(KERN_WARNING "eicon_isa_boot: Invalid card type %d\n", card->type);
			eicon_isa_release_shmem(card);
			kfree(code);
			return -EINVAL;
	}

	/* clear any pending irq's */
	readb(card->intack);
#ifdef CONFIG_MCA
	if (MCA_bus) {
		if (card->type == EICON_CTYPE_SCOM) {
			outb_p(0,card->io+1);
		}
		else {
			printk(KERN_WARNING "eicon_isa_boot: Card type not supported yet.\n");
			eicon_isa_release_shmem(card);
			return -EINVAL;
		};

#ifdef EICON_MCA_DEBUG
	printk(KERN_INFO "eicon_isa_boot: card->io      = %x.\n", card->io);
	printk(KERN_INFO "eicon_isa_boot: card->irq     = %d.\n", (int)card->irq);
#endif
	}
#else
	/* set reset-line active */
	writeb(0, card->stopcpu); 
#endif  /* CONFIG_MCA */
	/* clear irq-requests */
	writeb(0, card->intack);
	readb(card->intack);

	/* Copy code into card */
	memcpy_toio(&card->shmem->c, code, cbuf.bootstrap_len);

	/* Check for properly loaded code */
	if (!check_signature((unsigned long)&card->shmem->c, code, 1020)) {
		printk(KERN_WARNING "eicon_isa_boot: Could not load startup-code\n");
		eicon_isa_release_shmem(card);
		kfree(code);
		return -EIO;
	}
	/* if 16k-ramsize, duplicate the reset-jump-code */
	if (card->ramsize == RAMSIZE_P)
		memcpy_toio((__u8 *)card->shmem + 0x3ff0, &code[0x3f0], 12);

	kfree(code);
	boot = &card->shmem->boot;

	/* Delay 0.2 sec. */
	SLEEP(20);

	/* Start CPU */
	writeb(cbuf.boot_opt, &boot->ctrl);
#ifdef CONFIG_MCA
	if (MCA_bus) {
		outb_p(0, card->io);
	}
#else 
	writeb(0, card->startcpu); 
#endif /* CONFIG_MCA */

	/* Delay 0.2 sec. */
	SLEEP(20);

	timeout = jiffies + (HZ * 22);
	while (timeout > jiffies) {
		if (readb(&boot->ctrl) == 0)
			break;
		SLEEP(10);
	}
	if (readb(&boot->ctrl) != 0) {
		printk(KERN_WARNING "eicon_isa_boot: CPU test failed.\n");
#ifdef EICON_MCA_DEBUG
		printk(KERN_INFO "eicon_isa_boot: &boot->ctrl = %d.\n",
			readb(&boot->ctrl));
#endif
		eicon_isa_release_shmem(card);
		return -EIO;
	}

	/* Check for memory-test errors */
	if (readw(&boot->ebit)) {
		printk(KERN_WARNING "eicon_isa_boot: memory test failed (bit 0x%04x at 0x%08x)\n",
		       readw(&boot->ebit), readl(&boot->eloc));
		eicon_isa_release_shmem(card);
		return -EIO;
	}

        /* Check card type and memory size */
        tmp = readb(&boot->card);
	if ((tmp < 0) || (tmp > 4)) {
		printk(KERN_WARNING "eicon_isa_boot: Type detect failed\n");
		eicon_isa_release_shmem(card);
		return -EIO;
	}
	card->type = tmp;
	((eicon_card *)card->card)->type = tmp;

        tmp = readb(&boot->msize);
        if (tmp != 8 && tmp != 16 && tmp != 24 &&
            tmp != 32 && tmp != 48 && tmp != 60) {
                printk(KERN_WARNING "eicon_isa_boot: invalid memsize\n");
		eicon_isa_release_shmem(card);
                return -EIO;
        }
	printk(KERN_INFO "%s: startup-code loaded\n", eicon_ctype_name[card->type]); 
	if ((card->type == EICON_CTYPE_QUADRO) && (card->master)) {
		tmp = eicon_addcard(card->type, card->physmem, card->irq, 
					((eicon_card *)card->card)->regname);
		printk(KERN_INFO "Eicon: %d adapters added\n", tmp);
	}
	return 0;
}
コード例 #12
0
ファイル: x509chain.c プロジェクト: greendev5/Openswan
/* establish trust into a candidate authcert by going up the trust chain.
 * validity and revocation status are not checked.
 */
bool
trust_authcert_candidate(const x509cert_t *cert, const x509cert_t *alt_chain)
{
    int pathlen;

    lock_authcert_list("trust_authcert_candidate");

    for (pathlen = 0; pathlen < MAX_CA_PATH_LEN; pathlen++)
    {
       const x509cert_t *authcert = NULL;

       DBG(DBG_CONTROL,
           char buf[ASN1_BUF_LEN];
           dntoa(buf, ASN1_BUF_LEN, cert->subject);
           DBG_log("subject: '%s'",buf);
           dntoa(buf, ASN1_BUF_LEN, cert->issuer);
           DBG_log("issuer:  '%s'",buf);
           if (cert->authKeyID.ptr != NULL)
           {
               datatot(cert->authKeyID.ptr, cert->authKeyID.len, ':'
                   , buf, ASN1_BUF_LEN);
               DBG_log("authkey:  %s", buf);
           }
	   );

       /* search in alternative chain first */
       authcert = get_alt_cacert(cert->issuer, cert->authKeySerialNumber
           , cert->authKeyID, alt_chain);

       if (authcert != NULL)
       {
           DBG(DBG_CONTROL,
               DBG_log("issuer cacert found in alternative chain")
           )
       }
       else
       {
           /* search in trusted chain */
           authcert = get_authcert(cert->issuer, cert->authKeySerialNumber
               , cert->authKeyID, AUTH_CA);

           if (authcert != NULL)
           {
               DBG(DBG_CONTROL,
                   DBG_log("issuer cacert found")
               )
           }
           else
           {
               plog("issuer cacert not found");
               unlock_authcert_list("trust_authcert_candidate");
               return FALSE;
           }
       }

       if (!check_signature(cert->tbsCertificate, cert->signature,
                            cert->algorithm, authcert))
       {
           plog("invalid certificate signature");
           unlock_authcert_list("trust_authcert_candidate");
           return FALSE;
       }
       DBG(DBG_CONTROL,
           DBG_log("valid certificate signature")
       )

       /* check if cert is a self-signed root ca */
       if (pathlen > 0 && same_dn(cert->issuer, cert->subject))
       {
           DBG(DBG_CONTROL,
               DBG_log("reached self-signed root ca")
           )
           unlock_authcert_list("trust_authcert_candidate");
           return TRUE;
       }

       /* go up one step in the trust chain */
       cert = authcert;
    }
コード例 #13
0
ファイル: pubkey.cpp プロジェクト: jurajsomorovsky/botan
bool PK_Verifier::verify_message(const byte msg[], size_t msg_length,
                                 const byte sig[], size_t sig_length)
   {
   update(msg, msg_length);
   return check_signature(sig, sig_length);
   }
コード例 #14
0
ファイル: x509.c プロジェクト: OPSF/uClinux
/*
 * Insert X.509 CRL into chained list
 */
bool
insert_crl(chunk_t blob, chunk_t crl_uri)
{
    x509crl_t *crl = alloc_thing(x509crl_t, "x509crl");

    *crl = empty_x509crl;

    if (parse_x509crl(blob, 0, crl))
    {
	x509cert_t *issuer_cert;
	x509crl_t *oldcrl;
	bool valid_sig;
	generalName_t *gn;

	/* add distribution point */
	gn = alloc_thing(generalName_t, "generalName");
	gn->kind = GN_URI;
	gn->name = crl_uri;
	gn->next = crl->distributionPoints;
	crl->distributionPoints = gn;

	lock_authcert_list("insert_crl");
	/* get the issuer cacert */
	issuer_cert = get_authcert(crl->issuer, crl->authKeySerialNumber,
	    crl->authKeyID, AUTH_CA);

	if (issuer_cert == NULL)
	{
	    char distpoint[PATH_MAX];

	    distpoint[0] = '\0';
	    strncat(distpoint, (char *)crl->distributionPoints->name.ptr,
		    (crl->distributionPoints->name.len < PATH_MAX ?
		     crl->distributionPoints->name.len : PATH_MAX));
	    
	    openswan_log("crl issuer cacert not found for (%s)",
			 distpoint);;

	    free_crl(crl);
	    unlock_authcert_list("insert_crl");
	    return FALSE;
	}
	DBG(DBG_X509,
	    DBG_log("crl issuer cacert found")
	)

	/* check the issuer's signature of the crl */
	valid_sig = check_signature(crl->tbsCertList, crl->signature
			, crl->algorithm, issuer_cert);
	unlock_authcert_list("insert_crl");

	if (!valid_sig)
	{
	    free_crl(crl);
	    return FALSE;
	}
	DBG(DBG_X509,
	    DBG_log("valid crl signature")
	)

	lock_crl_list("insert_crl");
	oldcrl = get_x509crl(crl->issuer, crl->authKeySerialNumber
	    , crl->authKeyID);

	if (oldcrl != NULL)
	{
	    if (crl->thisUpdate > oldcrl->thisUpdate)
	    {
#ifdef HAVE_THREADS
		/* keep any known CRL distribution points */
		add_distribution_points(oldcrl->distributionPoints
		    , &crl->distributionPoints);
#endif

		/* now delete the old CRL */
		free_first_crl();
		DBG(DBG_X509,
		    DBG_log("thisUpdate is newer - existing crl deleted")
		)
	    }
	    else
	    {
コード例 #15
0
ファイル: ocsp.cpp プロジェクト: AlexNk/botan
Response::Response(const Certificate_Store& trusted_roots,
                   const std::vector<byte>& response_bits)
   {
   BER_Decoder response_outer = BER_Decoder(response_bits).start_cons(SEQUENCE);

   size_t resp_status = 0;

   response_outer.decode(resp_status, ENUMERATED, UNIVERSAL);

   if(resp_status != 0)
      throw std::runtime_error("OCSP response status " + std::to_string(resp_status));

   if(response_outer.more_items())
      {
      BER_Decoder response_bytes =
         response_outer.start_cons(ASN1_Tag(0), CONTEXT_SPECIFIC).start_cons(SEQUENCE);

      response_bytes.decode_and_check(OID("1.3.6.1.5.5.7.48.1.1"),
                                      "Unknown response type in OCSP response");

      BER_Decoder basicresponse =
         BER_Decoder(response_bytes.get_next_octet_string()).start_cons(SEQUENCE);

      std::vector<byte> tbs_bits;
      AlgorithmIdentifier sig_algo;
      std::vector<byte> signature;
      std::vector<X509_Certificate> certs;

      basicresponse.start_cons(SEQUENCE)
           .raw_bytes(tbs_bits)
         .end_cons()
         .decode(sig_algo)
         .decode(signature, BIT_STRING);
      decode_optional_list(basicresponse, ASN1_Tag(0), certs);

      size_t responsedata_version = 0;
      X509_DN name;
      std::vector<byte> key_hash;
      X509_Time produced_at;
      Extensions extensions;

      BER_Decoder(tbs_bits)
         .decode_optional(responsedata_version, ASN1_Tag(0),
                          ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))

         .decode_optional(name, ASN1_Tag(1),
                          ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))

         .decode_optional_string(key_hash, OCTET_STRING, 2,
                                 ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))

         .decode(produced_at)

         .decode_list(m_responses)

         .decode_optional(extensions, ASN1_Tag(1),
                          ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC));

      if(certs.empty())
         {
         if(auto cert = trusted_roots.find_cert(name, std::vector<byte>()))
            certs.push_back(*cert);
         else
            throw std::runtime_error("Could not find certificate that signed OCSP response");
         }

      check_signature(tbs_bits, sig_algo, signature, trusted_roots, certs);
      }

   response_outer.end_cons();
   }
コード例 #16
0
ファイル: mbr.c プロジェクト: htchiang/zeke
int mbr_register(int fd, int * part_count)
{
    file_t * file;
    vnode_t * parent_vnode;
    struct dev_info * parent;
    uint8_t * block_0 = NULL;
    int parts = 0;
    int retval = 0;

#ifdef configMBR_DEBUG
    KERROR(KERROR_DEBUG, "%s(fd: %d, part_count: %p)\n", __func__,
           fd, part_count);
#endif

    file = fs_fildes_ref(curproc->files, fd, 1);

    parent_vnode = file->vnode;
    parent = (struct dev_info *)parent_vnode->vn_specinfo;
    if (!(S_ISBLK(parent_vnode->vn_mode) || S_ISCHR(parent_vnode->vn_mode))) {
        KERROR(KERROR_ERR, "MBR: not a device\n");

        retval = -ENODEV;
        goto fail;
    }

    /* Check the validity of the parent device. */
    if (!parent) {
        KERROR(KERROR_ERR, "MBR: invalid parent device\n");

        retval = -ENODEV;
        goto fail;
    }

    block_0 = kmalloc(MBR_SIZE);
    if (!block_0) {
        retval = -ENOMEM;
        goto fail;
    }

#ifdef configMBR_DEBUG
    KERROR(KERROR_DEBUG,
           "MBR: reading block 0 from device %s\n",
           parent->dev_name);
#endif

    retval = read_block_0(block_0, file);
    if (retval)
        goto fail;
    retval = check_signature(block_0);
    if (retval)
        goto fail;

#ifdef configMBR_DEBUG
    KERROR(KERROR_DEBUG,
             "MBR: found valid MBR on device %s\n", parent->dev_name);
#endif

    /*
     * If parent block size is not MBR_SIZE, we have to coerce start_block
     * and blocks to fit.
     */
    if (parent->block_size < MBR_SIZE) {
        /* We do not support parent device block sizes < 512 */
        KERROR(KERROR_ERR,
                 "MBR: block size of %s is too small (%i)\n",
                 parent->dev_name, parent->block_size);

        retval = -ENOTSUP;
        goto fail;
    }

    uint32_t block_size_adjust = parent->block_size / MBR_SIZE;
    if (parent->block_size % MBR_SIZE) {
        /*
         * We do not support parent device block sizes that are not
         * multiples of 512.
         */
        KERROR(KERROR_ERR,
               "MBR: block size of %s is not a multiple of 512 (%i)\n",
               parent->dev_name, parent->block_size);

        retval = -ENOTSUP;
        goto fail;
    }

#ifdef configMBR_DEBUG
    if (block_size_adjust > 1) {
        KERROR(KERROR_DEBUG, "MBR: block_size_adjust: %i\n",
                 block_size_adjust);
    }
#endif

    int major_num = DEV_MAJOR(parent->dev_id) + 1;
    for (size_t i = 0; i < 4; i++) {
        size_t p_offset = 0x1be + (i * 0x10);
        struct mbr_dev * d;

        if (block_0[p_offset + 4] == 0x00) {
            /* Invalid partition */
            continue;
        }

        d = kzalloc(sizeof(struct mbr_dev));
        if (!d) {
            KERROR(KERROR_ERR, "MBR: Out of memory");

            retval = -ENOMEM;
            break;
        }

        d->dev.dev_id = DEV_MMTODEV(major_num, mbr_dev_count);
        d->dev.drv_name = driver_name;
        ksprintf(d->dev.dev_name, sizeof(d->dev.dev_name), "%sp%u",
                 parent->dev_name, i);
        d->dev.read = mbr_read;
        d->dev.write = (parent->write) ? mbr_write : NULL;
        d->dev.block_size = parent->block_size;
        d->dev.flags = parent->flags;
        d->part_no = i;
        d->part_id = block_0[p_offset + 4];
        d->start_block = read_word(block_0, p_offset + 8);
        d->blocks = read_word(block_0, p_offset + 12);
        d->parent = parent;

        /* Adjust start_block and blocks to the parent block size */
        if (d->start_block % block_size_adjust) {
            KERROR(KERROR_ERR,
                   "MBR: partition number %i on %s does not start on a block "
                   "boundary (%i).\n",
                   d->part_no, parent->dev_name, d->start_block);

            retval = -EFAULT;
            goto fail;
        }
        d->start_block /= block_size_adjust;

        if (d->blocks % block_size_adjust) {
            KERROR(KERROR_ERR,
                   "MBR: partition number %i on %s does not have a length "
                   "that is an exact multiple of the block length (%i).\n",
                   d->part_no, parent->dev_name, d->start_block);

            retval = -EFAULT;
            goto fail;
        }
        d->blocks /= block_size_adjust;
        d->dev.num_blocks = d->blocks;

#ifdef configMBR_DEBUG
        KERROR(KERROR_DEBUG,
               "MBR: partition number %i (%s) of type %x, "
               "start sector %u, sector count %u, p_offset %03x\n",
               d->part_no, d->dev.dev_name, d->part_id,
               d->start_block, d->blocks, p_offset);
#endif

        make_dev(&d->dev, 0, 0, 0666, NULL);
        mbr_dev_count++;
        parts++;

        /* Register the fs */
        //register_fs__((struct dev_info *)d, d->part_id);
        /* TODO Register the fs dev with devfs */
    }

    KERROR(KERROR_INFO, "MBR: found total of %i partition(s)\n",
           parts);

fail:
    kfree(block_0);
    fs_fildes_ref(curproc->files, fd, -1);

    if (retval != 0) {
        KERROR(KERROR_ERR, "MBR registration failed on device: \"%s\"\n",
               parent->dev_name);
    }

    return retval;
}
コード例 #17
0
ファイル: decrypt.cpp プロジェクト: Caio99BR/DualBootPatcher
static bool signature_ok()
{
    return check_signature(CRYPTFSTOOL_REC_PATH, CRYPTFSTOOL_REC_PATH ".sig")
            && check_signature(CRYPTFSTOOL_PATH, CRYPTFSTOOL_PATH ".sig");
}
コード例 #18
0
ファイル: signature.hpp プロジェクト: ef-tsuruo/pluginsdk
			void check_invariant () const {
				SXASSERT(bool(this));
				check_signature();
			}
コード例 #19
0
bool SerialFlashChip::create(const char *filename, uint32_t length, uint32_t align)
{
	uint32_t maxfiles, stringsize;
	uint32_t index, buf[3];
	uint32_t address, straddr, len;
	SerialFlashFile file;

	// check if the file already exists
	if (exists(filename)) return false;

	// first, get the filesystem parameters
	maxfiles = check_signature();
	if (!maxfiles) return false;
	stringsize = (maxfiles & 0xFFFF0000) >> 14;
	maxfiles &= 0xFFFF;

	// find the first unused slot for this file
	index = find_first_unallocated_file_index(maxfiles);
	if (index >= maxfiles) return false;
	 //Serial.printf("index = %u\n", index);
	// compute where to store the filename and actual data
	straddr = 8 + maxfiles * 12;
	if (index == 0) {
		address = straddr + stringsize;
	} else {
		buf[2] = 0;
		SerialFlash.read(8 + maxfiles * 2 + (index-1) * 10, buf, 10);
		address = buf[0] + buf[1];
		straddr += buf[2] * 4;
		straddr += string_length(straddr);
		straddr = (straddr + 3) & 0x0003FFFC;
	}
	 //Serial.printf("straddr = %u\n", straddr);
	 //Serial.printf("address = %u\n", address);
	 //Serial.printf("length = %u\n", length);
	if (align > 0) {
		// for files aligned to sectors, adjust addr & len
		address += align - 1;
		address /= align;
		address *= align;
		 //Serial.printf("align address = %u\n", address);
		length += align - 1;
		length /= align;
		length *= align;
		 //Serial.printf("align length = %u\n", length);
	} else {
		// always align every file to a page boundary
		// for predictable write latency and to guarantee
		// write suspend for reading another file can't
		// conflict on the same page (2 files never share
		// a write page).
		address = (address + 255) & 0xFFFFFF00;
	}
	 //Serial.printf("address = %u\n", address);
	// last check, if enough space exists...
	len = strlen(filename);
	// TODO: check for enough string space for filename

    // 5 bytes, to allow for extra 2 bytes in Spansion device IDs
	uint8_t id[5];
	SerialFlash.readID(id);
	if (address + length > SerialFlash.capacity(id)) return false;

	SerialFlash.write(straddr, filename, len+1);
	buf[0] = address;
	buf[1] = length;
	buf[2] = (straddr - (8 + maxfiles * 12)) / 4;
	SerialFlash.write(8 + maxfiles * 2 + index * 10, buf, 10);
	 //Serial.printf("  write %u: ", 8 + maxfiles * 2 + index * 10);
	 //pbuf(buf, 10);
	while (!SerialFlash.ready()) ;  // TODO: timeout
	 
	buf[0] = filename_hash(filename);
	 //Serial.printf("hash = %04X\n", buf[0]);
	SerialFlash.write(8 + index * 2, buf, 2);
	while (!SerialFlash.ready()) ;  // TODO: timeout
	return true;
}
コード例 #20
0
ファイル: x509.c プロジェクト: mkj/libreswan
/*
 * Insert X.509 CRL into chained list
 */
bool insert_crl(chunk_t blob, chunk_t crl_uri)
{
	x509crl_t *crl = alloc_thing(x509crl_t, "x509crl");

	*crl = empty_x509crl;

	if (parse_x509crl(blob, 0, crl)) {
		x509cert_t *issuer_cert;
		x509crl_t *oldcrl;
		bool valid_sig;
		generalName_t *gn;

		/* add distribution point */
		gn = alloc_thing(generalName_t, "generalName");
		gn->kind = GN_URI;
		gn->name = crl_uri;
		gn->next = crl->distributionPoints;
		crl->distributionPoints = gn;

		lock_authcert_list("insert_crl");
		/* get the issuer cacert */
		issuer_cert = get_authcert(crl->issuer,
					   crl->authKeySerialNumber,
					   crl->authKeyID, AUTH_CA);

		if (issuer_cert == NULL) {
			chunk_t *n = &crl->distributionPoints->name;

			loglog(RC_LOG_SERIOUS,
			       "CRL rejected: crl issuer cacert not found for %.*s",
			       (int)n->len, (char *)n->ptr);

			free_crl(crl);
			unlock_authcert_list("insert_crl");
			return FALSE;
		}
		DBG(DBG_X509,
		    DBG_log("crl issuer cacert found"));

		/* check the issuer's signature of the crl */
		valid_sig = check_signature(crl->tbsCertList, crl->signature,
					    crl->algorithm, issuer_cert);
		unlock_authcert_list("insert_crl");

		if (!valid_sig) {
			free_crl(crl);
			return FALSE;
		}
		DBG(DBG_X509,
		    DBG_log("valid crl signature"));

		lock_crl_list("insert_crl");
		oldcrl = get_x509crl(crl->issuer, crl->authKeySerialNumber,
				     crl->authKeyID);

		if (oldcrl != NULL) {
			if (realbefore(oldcrl->thisUpdate, crl->thisUpdate)) {
				/* old CRL is older than new CRL: replace */
#if defined(LIBCURL) || defined(LDAP_VER)
				/* keep any known CRL distribution points */
				add_distribution_points(
					oldcrl->distributionPoints,
					&crl->distributionPoints);
#endif

				/* now delete the old CRL */
				free_first_crl();
				DBG(DBG_X509,
				    DBG_log("thisUpdate is newer - existing crl deleted"));
			} else {
				/* old CRL is not older than new CRL: keep old one */
				unlock_crl_list("insert_crls");
				DBG(DBG_X509,
				    DBG_log("thisUpdate is not newer - existing crl not replaced"));
				free_crl(crl);
				/*
				 * is the fetched crl valid?
				 * now + 2 * crl_check_interval < oldcrl->nextUpdate
				 */
				return realbefore(realtimesum(realnow(), deltatimescale(2, 1, crl_check_interval)), oldcrl->nextUpdate);
			}
		}

		/* insert new CRL */
		crl->next = x509crls;
		x509crls = crl;

		unlock_crl_list("insert_crl");

		/*
		 * is the new crl valid?
		 * now + 2 * crl_check_interval < crl->nextUpdate
		 */
		return realbefore(realtimesum(realnow(), deltatimescale(2, 1, crl_check_interval)), crl->nextUpdate);
	} else {
		loglog(RC_LOG_SERIOUS, "  error in X.509 crl %s",
		       (char *)crl_uri.ptr);
		free_crl(crl);
		return FALSE;
	}
}
コード例 #21
0
ファイル: ocsp.c プロジェクト: FMayzek/gnupg
/* Check whether the certificate either given by fingerprint CERT_FPR
   or directly through the CERT object is valid by running an OCSP
   transaction.  With FORCE_DEFAULT_RESPONDER set only the configured
   default responder is used. */
gpg_error_t
ocsp_isvalid (ctrl_t ctrl, ksba_cert_t cert, const char *cert_fpr,
              int force_default_responder)
{
  gpg_error_t err;
  ksba_ocsp_t ocsp = NULL;
  ksba_cert_t issuer_cert = NULL;
  ksba_sexp_t sigval = NULL;
  gcry_sexp_t s_sig = NULL;
  ksba_isotime_t current_time;
  ksba_isotime_t this_update, next_update, revocation_time, produced_at;
  ksba_isotime_t tmp_time;
  ksba_status_t status;
  ksba_crl_reason_t reason;
  char *url_buffer = NULL;
  const char *url;
  gcry_md_hd_t md = NULL;
  int i, idx;
  char *oid;
  ksba_name_t name;
  fingerprint_list_t default_signer = NULL;

  /* Get the certificate.  */
  if (cert)
    {
      ksba_cert_ref (cert);

      err = find_issuing_cert (ctrl, cert, &issuer_cert);
      if (err)
        {
          log_error (_("issuer certificate not found: %s\n"),
                     gpg_strerror (err));
          goto leave;
        }
    }
  else
    {
      cert = get_cert_local (ctrl, cert_fpr);
      if (!cert)
        {
          log_error (_("caller did not return the target certificate\n"));
          err = gpg_error (GPG_ERR_GENERAL);
          goto leave;
        }
      issuer_cert = get_issuing_cert_local (ctrl, NULL);
      if (!issuer_cert)
        {
          log_error (_("caller did not return the issuing certificate\n"));
          err = gpg_error (GPG_ERR_GENERAL);
          goto leave;
        }
    }

  /* Create an OCSP instance.  */
  err = ksba_ocsp_new (&ocsp);
  if (err)
    {
      log_error (_("failed to allocate OCSP context: %s\n"),
                 gpg_strerror (err));
      goto leave;
    }



  /* Figure out the OCSP responder to use.
     1. Try to get the reponder from the certificate.
        We do only take http and https style URIs into account.
     2. If this fails use the default responder, if any.
   */
  url = NULL;
  for (idx=0; !url && !opt.ignore_ocsp_service_url && !force_default_responder
         && !(err=ksba_cert_get_authority_info_access (cert, idx,
                                                       &oid, &name)); idx++)
    {
      if ( !strcmp (oid, oidstr_ocsp) )
        {
          for (i=0; !url && ksba_name_enum (name, i); i++)
            {
              char *p = ksba_name_get_uri (name, i);
              if (p && (!ascii_strncasecmp (p, "http:", 5)
                        || !ascii_strncasecmp (p, "https:", 6)))
                url = url_buffer = p;
              else
                xfree (p);
            }
        }
      ksba_name_release (name);
      ksba_free (oid);
    }
  if (err && gpg_err_code (err) != GPG_ERR_EOF)
    {
      log_error (_("can't get authorityInfoAccess: %s\n"), gpg_strerror (err));
      goto leave;
    }
  if (!url)
    {
      if (!opt.ocsp_responder || !*opt.ocsp_responder)
        {
          log_info (_("no default OCSP responder defined\n"));
          err = gpg_error (GPG_ERR_CONFIGURATION);
          goto leave;
        }
      if (!opt.ocsp_signer)
        {
          log_info (_("no default OCSP signer defined\n"));
          err = gpg_error (GPG_ERR_CONFIGURATION);
          goto leave;
        }
      url = opt.ocsp_responder;
      default_signer = opt.ocsp_signer;
      if (opt.verbose)
        log_info (_("using default OCSP responder '%s'\n"), url);
    }
  else
    {
      if (opt.verbose)
        log_info (_("using OCSP responder '%s'\n"), url);
    }

  /* Ask the OCSP responder. */
  err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
  if (err)
    {
      log_error (_("failed to establish a hashing context for OCSP: %s\n"),
                 gpg_strerror (err));
      goto leave;
    }
  err = do_ocsp_request (ctrl, ocsp, md, url, cert, issuer_cert);
  if (err)
    goto leave;

  /* We got a useful answer, check that the answer has a valid signature. */
  sigval = ksba_ocsp_get_sig_val (ocsp, produced_at);
  if (!sigval || !*produced_at)
    {
      err = gpg_error (GPG_ERR_INV_OBJ);
      goto leave;
    }
  if ( (err = canon_sexp_to_gcry (sigval, &s_sig)) )
    goto leave;
  xfree (sigval);
  sigval = NULL;
  err = check_signature (ctrl, ocsp, s_sig, md, default_signer);
  if (err)
    goto leave;

  /* We only support one certificate per request.  Check that the
     answer matches the right certificate. */
  err = ksba_ocsp_get_status (ocsp, cert,
                              &status, this_update, next_update,
                              revocation_time, &reason);
  if (err)
    {
      log_error (_("error getting OCSP status for target certificate: %s\n"),
                 gpg_strerror (err));
      goto leave;
    }

  /* In case the certificate has been revoked, we better invalidate
     our cached validation status. */
  if (status == KSBA_STATUS_REVOKED)
    {
      time_t validated_at = 0; /* That is: No cached validation available. */
      err = ksba_cert_set_user_data (cert, "validated_at",
                                     &validated_at, sizeof (validated_at));
      if (err)
        {
          log_error ("set_user_data(validated_at) failed: %s\n",
                     gpg_strerror (err));
          err = 0; /* The certificate is anyway revoked, and that is a
                      more important message than the failure of our
                      cache. */
        }
    }


  if (opt.verbose)
    {
      log_info (_("certificate status is: %s  (this=%s  next=%s)\n"),
                status == KSBA_STATUS_GOOD? _("good"):
                status == KSBA_STATUS_REVOKED? _("revoked"):
                status == KSBA_STATUS_UNKNOWN? _("unknown"):
                status == KSBA_STATUS_NONE? _("none"): "?",
                this_update, next_update);
      if (status == KSBA_STATUS_REVOKED)
        log_info (_("certificate has been revoked at: %s due to: %s\n"),
                  revocation_time,
                  reason == KSBA_CRLREASON_UNSPECIFIED?   "unspecified":
                  reason == KSBA_CRLREASON_KEY_COMPROMISE? "key compromise":
                  reason == KSBA_CRLREASON_CA_COMPROMISE?   "CA compromise":
                  reason == KSBA_CRLREASON_AFFILIATION_CHANGED?
                                                      "affiliation changed":
                  reason == KSBA_CRLREASON_SUPERSEDED?   "superseeded":
                  reason == KSBA_CRLREASON_CESSATION_OF_OPERATION?
                                                  "cessation of operation":
                  reason == KSBA_CRLREASON_CERTIFICATE_HOLD?
                                                  "certificate on hold":
                  reason == KSBA_CRLREASON_REMOVE_FROM_CRL?
                                                  "removed from CRL":
                  reason == KSBA_CRLREASON_PRIVILEGE_WITHDRAWN?
                                                  "privilege withdrawn":
                  reason == KSBA_CRLREASON_AA_COMPROMISE? "AA compromise":
                  reason == KSBA_CRLREASON_OTHER?   "other":"?");

    }


  if (status == KSBA_STATUS_REVOKED)
    err = gpg_error (GPG_ERR_CERT_REVOKED);
  else if (status == KSBA_STATUS_UNKNOWN)
    err = gpg_error (GPG_ERR_NO_DATA);
  else if (status != KSBA_STATUS_GOOD)
    err = gpg_error (GPG_ERR_GENERAL);

  /* Allow for some clock skew. */
  gnupg_get_isotime (current_time);
  add_seconds_to_isotime (current_time, opt.ocsp_max_clock_skew);

  if (strcmp (this_update, current_time) > 0 )
    {
      log_error (_("OCSP responder returned a status in the future\n"));
      log_info ("used now: %s  this_update: %s\n", current_time, this_update);
      if (!err)
        err = gpg_error (GPG_ERR_TIME_CONFLICT);
    }

  /* Check that THIS_UPDATE is not too far back in the past. */
  gnupg_copy_time (tmp_time, this_update);
  add_seconds_to_isotime (tmp_time,
                          opt.ocsp_max_period+opt.ocsp_max_clock_skew);
  if (!*tmp_time || strcmp (tmp_time, current_time) < 0 )
    {
      log_error (_("OCSP responder returned a non-current status\n"));
      log_info ("used now: %s  this_update: %s\n",
                current_time, this_update);
      if (!err)
        err = gpg_error (GPG_ERR_TIME_CONFLICT);
    }

  /* Check that we are not beyound NEXT_UPDATE  (plus some extra time). */
  if (*next_update)
    {
      gnupg_copy_time (tmp_time, next_update);
      add_seconds_to_isotime (tmp_time,
                              opt.ocsp_current_period+opt.ocsp_max_clock_skew);
      if (!*tmp_time && strcmp (tmp_time, current_time) < 0 )
        {
          log_error (_("OCSP responder returned an too old status\n"));
          log_info ("used now: %s  next_update: %s\n",
                    current_time, next_update);
          if (!err)
            err = gpg_error (GPG_ERR_TIME_CONFLICT);
        }
    }


 leave:
  gcry_md_close (md);
  gcry_sexp_release (s_sig);
  xfree (sigval);
  ksba_cert_release (issuer_cert);
  ksba_cert_release (cert);
  ksba_ocsp_release (ocsp);
  xfree (url_buffer);
  return err;
}
コード例 #22
0
ファイル: x509.c プロジェクト: mkj/libreswan
/*
 * verify if a cert hasn't been revoked by a crl
 */
static bool verify_by_crl(/*const*/ x509cert_t *cert, bool strict,
				    realtime_t *until)
{
	x509crl_t *crl;
	char ibuf[ASN1_BUF_LEN], cbuf[ASN1_BUF_LEN];

	lock_crl_list("verify_by_crl");
	crl = get_x509crl(cert->issuer, cert->authKeySerialNumber,
			  cert->authKeyID);

	dntoa(ibuf, ASN1_BUF_LEN, cert->issuer);

	if (crl == NULL) {
		unlock_crl_list("verify_by_crl");
		libreswan_log("no crl from issuer \"%s\" found (strict=%s)",
			      ibuf,
			      strict ? "yes" : "no");

#if defined(LIBCURL) || defined(LDAP_VER)
		if (cert->crlDistributionPoints != NULL) {
			add_crl_fetch_request(cert->issuer,
					      cert->crlDistributionPoints);
			wake_fetch_thread("verify_by_crl");
		}
#endif
		if (strict)
			return FALSE;
	} else {
		x509cert_t *issuer_cert;
		bool valid;

		DBG(DBG_X509,
		    DBG_log("issuer crl \"%s\" found", ibuf));

#if defined(LIBCURL) || defined(LDAP_VER)
		add_distribution_points(cert->crlDistributionPoints,
					&crl->distributionPoints);
#endif

		lock_authcert_list("verify_by_crl");

		issuer_cert = get_authcert(crl->issuer,
					   crl->authKeySerialNumber,
					   crl->authKeyID, AUTH_CA);
		dntoa(cbuf, ASN1_BUF_LEN, crl->issuer);
		valid = check_signature(crl->tbsCertList, crl->signature,
					crl->algorithm, issuer_cert);

		unlock_authcert_list("verify_by_crl");

		if (valid) {
			bool revoked_crl, expired_crl;

			DBG(DBG_X509,
			    DBG_log("valid crl signature on \"%s\"", cbuf));

			/* with strict crl policy the public key must have the same
			 * lifetime as the crl
			 */
			if (strict && realbefore(crl->nextUpdate, *until))
				*until = crl->nextUpdate;

			/* has the certificate been revoked? */
			revoked_crl = x509_check_revocation(crl,
							    cert->serialNumber);

			/* is the crl still valid? */
			expired_crl = realbefore(crl->nextUpdate, realnow());

			unlock_crl_list("verify_by_crl");

			if (expired_crl) {
				char tbuf[REALTIMETOA_BUF];

				libreswan_log(
					"crl update for \"%s\" is overdue since %s",
					cbuf,
					realtimetoa(crl->nextUpdate, TRUE,
						tbuf, sizeof(tbuf)));

#if defined(LIBCURL) || defined(LDAP_VER)
				/* try to fetch a crl update */
				if (cert->crlDistributionPoints != NULL) {
					add_crl_fetch_request(cert->issuer,
							      cert->crlDistributionPoints);
					wake_fetch_thread("verify_by_crl");
				}
#endif
			} else {
				DBG(DBG_X509,
				    DBG_log("crl is \"%s\" valid", cbuf));
			}

			if (revoked_crl || (strict && expired_crl)) {
				/* remove any cached public keys */
				remove_x509_public_key(cert);
				return FALSE;
			}
		} else {
			unlock_crl_list("verify_by_crl");
			libreswan_log("invalid crl signature on \"%s\"", cbuf);
			if (strict)
				return FALSE;
		}
	}
	return TRUE;
}
コード例 #23
0
   void transaction_evaluation_state::evaluate_withdraw( const withdraw_operation& op )
   { try {
      obalance_record arec = _current_state->get_balance_record( op.balance_id );
      if( !arec ) fail( BTS_UNDEFINED_ADDRESS, fc::variant(op) );

      switch( (withdraw_condition_types)arec->condition.condition )
      {
         case withdraw_signature_type:  
         {
            add_required_signature( arec->condition.as<withdraw_with_signature>().owner );
            break;
         }

         case withdraw_multi_sig_type:
         {
            auto multi_sig = arec->condition.as<withdraw_with_multi_sig>();
            uint32_t valid_signatures = 0;
            for( auto sig : multi_sig.owners )
               valid_signatures += check_signature( sig );
            if( valid_signatures < multi_sig.required )
               fail( BTS_MISSING_SIGNATURE, fc::variant(op) );
            break;
         }

         case withdraw_password_type:
         {
            auto pass = arec->condition.as<withdraw_with_password>();
            uint32_t count = 0;
            count += check_signature( pass.payor );
            count += check_signature( pass.payee );
            if( count < 2 && op.claim_input_data.size() ) 
               count += pass.password_hash == fc::ripemd160::hash( op.claim_input_data.data(), op.claim_input_data.size() );
            if( count != 2 )
               fail( BTS_MISSING_SIGNATURE, fc::variant(op) );
            break;
         }

         case withdraw_option_type:
         {
            auto option = arec->condition.as<withdraw_option>();

            if( _current_state->now() > option.date )
            {
               add_required_signature( option.optionor );
            }
            else // the option hasn't expired
            {
               add_required_signature( option.optionee );

               auto pay_amount = asset( op.amount, arec->condition.asset_id ) * option.strike_price;
               add_required_deposit( option.optionee, pay_amount ); 
            }
            break;
         }
         default:
            fail( BTS_INVALID_WITHDRAW_CONDITION, fc::variant(op) );
      }
      // update delegate vote on withdrawn account..

      arec->balance -= op.amount;
      arec->last_update = _current_state->now();
      add_balance( asset(op.amount, arec->condition.asset_id) );

      if( arec->condition.asset_id == 0 ) 
         sub_vote( arec->condition.delegate_id, op.amount );

      wlog( "store after withdraw ${r}", ("r",*arec) );
      _current_state->store_balance_record( *arec );
   } FC_RETHROW_EXCEPTIONS( warn, "", ("op",op) ) }