Example #1
1
ByteArray PublicKey::getDerEncoded()
		throw (EncodeException)
{
	BIO *buffer;
	int ndata, wrote;
	ByteArray ret;
	unsigned char *data;
	buffer = BIO_new(BIO_s_mem());
	if (buffer == NULL)
	{
		throw EncodeException(EncodeException::BUFFER_CREATING, "PublicKey::getDerEncoded");
	}
	wrote = i2d_PUBKEY_bio(buffer, this->key);
	if (!wrote)
	{
		BIO_free(buffer);
		throw EncodeException(EncodeException::DER_ENCODE, "PublicKey::getDerEncoded");
	}
	ndata = BIO_get_mem_data(buffer, &data);
	if (ndata <= 0)
	{
		BIO_free(buffer);
		throw EncodeException(EncodeException::BUFFER_READING, "PublicKey::getDerEncoded");
	}
	ret = ByteArray(data, ndata);
	BIO_free(buffer);
	return ret;
}
bool X509Certificate_OpenSSL::checkIssuer(ref <const X509Certificate> cert_) const
{
	ref <const X509Certificate_OpenSSL> cert =
		cert_.dynamicCast <const X509Certificate_OpenSSL>();

	// Get issuer for this cert
	BIO *out;
	unsigned char *issuer;

	out = BIO_new(BIO_s_mem());
	X509_NAME_print_ex(out, X509_get_issuer_name(m_data->cert), 0, XN_FLAG_RFC2253);
	int n = BIO_get_mem_data(out, &issuer);
	vmime::string thisIssuerName((char*)issuer, n);
	BIO_free(out);

	// Get subject of issuer
	unsigned char *subject;
	out = BIO_new(BIO_s_mem());
	X509_NAME_print_ex(out, X509_get_subject_name(cert->m_data->cert), 0, XN_FLAG_RFC2253);
	n = BIO_get_mem_data(out, &subject);
	vmime::string subjOfIssuer((char*)subject, n);
	BIO_free(out);

	return subjOfIssuer == thisIssuerName;
}
Example #3
0
		bool GenerateRSAKeyPair(int numBits, std::string& privKey, std::string& pubKey)
		{
			// TODO: add some error checking
			RSA* rsa = RSA_new();
			BIGNUM* bn = BN_new();
			BN_GENCB cb;
			BIO* bio_err = NULL;
			BN_GENCB_set(&cb, genrsa_cb, bio_err);
			BN_set_word(bn, RSA_F4);
			RSA_generate_key_ex(rsa, numBits, bn, &cb);

			BIO* privKeyBuff = BIO_new(BIO_s_mem());
			BIO* pubKeyBuff = BIO_new(BIO_s_mem());
			PEM_write_bio_RSAPrivateKey(privKeyBuff, rsa, 0, 0, 0, 0, 0);
			PEM_write_bio_RSA_PUBKEY(pubKeyBuff, rsa); // RSA_PUBKEY includes some data that RSAPublicKey doesn't have

			char* privKeyData;
			char* pubKeyData;
			auto privKeySize = BIO_get_mem_data(privKeyBuff, &privKeyData);
			auto pubKeySize = BIO_get_mem_data(pubKeyBuff, &pubKeyData);

			privKey = std::string(privKeyData, privKeySize);
			pubKey = std::string(pubKeyData, pubKeySize);
			
			BIO_free_all(privKeyBuff);
			BIO_free_all(pubKeyBuff);
			BN_free(bn);
			RSA_free(rsa);
			return true;
		}
Example #4
0
HTTPScode
https_recv(struct https_request *req, int *code, const char **body, int *len,
        int msecs)
{
        int n, err;
        
        if (BIO_reset(req->body) != 1) {
                ctx->errstr = _SSL_strerror();
                return (HTTPS_ERR_LIB);
        }
        /* Read loop sentinel set by parser in __on_message_done() */
        while (!req->done) {
                while ((n = BIO_read(req->cbio, ctx->parse_buf,
                            sizeof(ctx->parse_buf))) <= 0) {
                        if ((n = _BIO_wait(req->cbio, msecs)) != 1) {
                                ctx->errstr = n ? _SSL_strerror() :
                                    "Connection closed";
                                return (HTTPS_ERR_SERVER);
                        }
                }
                if ((err = http_parser_execute(req->parser,
                            &ctx->parse_settings, ctx->parse_buf, n)) != n) {
                        ctx->errstr = http_errno_description(err);
                        return (HTTPS_ERR_SERVER);
                }
        }
        *len = BIO_get_mem_data(req->body, (char **)body);
        *code = req->parser->status_code;
        
        return (HTTPS_OK);
}
Example #5
0
/* Requires no locking */
int	af_update_seg_frombio(AFFILE *af,const char *segname,unsigned long arg,BIO *bio)
{
    /* Get the buffer to write out */
    u_char *buf=0;
    size_t buflen = BIO_get_mem_data(bio,&buf);
    return af_update_seg(af,segname,0,buf,buflen);
}
Example #6
0
static PyObject *
z_py_zorp_crl_getattr(PyObject *o, char *name)
{
  ZorpCRL *self = (ZorpCRL *) o;
  PyObject *res = NULL;
  BIO *bio;
  guint len;
  gchar *mem;
  gchar buf[512];

  if (strcmp(name, "blob") == 0)
    {
      bio = BIO_new(BIO_s_mem());

      PEM_write_bio_X509_CRL(bio, self->crl);
      len = BIO_get_mem_data(bio, &mem);
      res = PyString_FromStringAndSize(mem, len);

      BIO_free(bio);
    }
  else if (strcmp(name, "issuer") == 0)
    {
      X509_NAME_oneline(X509_CRL_get_issuer(self->crl), buf, sizeof(buf));
      res = PyString_FromString(buf);
    }
  else
    {
      PyErr_SetString(PyExc_AttributeError, "Attribute not found");
    }
  return res;
}
Example #7
0
BOOL rsautil_rsa_to_privkeyblob(RSA *rsa, PBYTE *blob, DWORD *cbBlob)
{
	BOOL status = FALSE;
	BIO *out;
	EVP_PKEY *pk;
	int ret;
	char *ptr;

	if(pk = EVP_PKEY_new())
	{
		if(out = BIO_new(BIO_s_mem()))
		{
			EVP_PKEY_set1_RSA(pk, rsa);

			ret = i2b_PrivateKey_bio(out, pk);
			if(ret > 0)
			{
				*cbBlob = BIO_get_mem_data(out, &ptr);
				if(*blob = (PBYTE) LocalAlloc(LPTR, *cbBlob))
				{
					status = TRUE;
					RtlCopyMemory(*blob, ptr, *cbBlob);
				}
			}
			else /**/;
			BIO_free(out);
		}
		EVP_PKEY_free(pk);
	}
	return status;
}
void PEM_From_P12(PA_PluginParameters params)
{
	sLONG_PTR *pResult = (sLONG_PTR *)params->fResult;
	PackagePtr pParams = (PackagePtr)params->fParameters;
	
	C_BLOB Param1;
	C_BLOB Param2;
	C_TEXT Param3;
	C_TEXT returnValue;
	
	Param1.fromParamAtIndex(pParams, 1);
	Param3.fromParamAtIndex(pParams, 3);	
	
	BIO *bio = BIO_new_mem_buf((void *)Param1.getBytesPtr(), Param1.getBytesLength());

	if(bio){
		
		PKCS12 *p12 = d2i_PKCS12_bio(bio, NULL);
		
		if(p12){
			
			EVP_PKEY *key = NULL;
			X509 *cert = NULL;
			STACK_OF(X509) *ca = NULL;
            
			CUTF8String pass;
			Param3.copyUTF8String(&pass);
			
			if(PKCS12_parse(p12, (const char *)pass.c_str(), &key, &cert, &ca)){
				
				BIO *pem = BIO_new(BIO_s_mem());
				
				if(pem){
					
					PEM_write_bio_PrivateKey(pem, key, NULL, NULL, NULL, NULL, (void *)pass.c_str());
					
					char *buf = NULL;
					
					int len = BIO_get_mem_data(pem, &buf);
					
					if(len){
						Param2.setBytes((const uint8_t *)buf, len);
						Param2.toParamAtIndex(pParams, 2);
						CUTF8String pemStr = CUTF8String((const uint8_t *)buf, len);
						returnValue.setUTF8String(&pemStr);
					}
					
					BIO_free(pem);
					
				}
			}
		}
		
		BIO_free(bio);
		
	}	
	
	Param2.toParamAtIndex(pParams, 2);
	returnValue.setReturn(pResult);
}
Example #9
0
u2fs_rc dump_X509_cert(const u2fs_X509_t * cert, char **output)
{
  //input: openssl X509 certificate
  //output: PEM-formatted char buffer

  if (cert == NULL || output == NULL)
    return U2FS_MEMORY_ERROR;

  *output = NULL;

  BIO *bio = BIO_new(BIO_s_mem());
  if (bio == NULL)
    return U2FS_MEMORY_ERROR;

  if(!PEM_write_bio_X509(bio, (X509 *)cert)) {
    BIO_free(bio);
    return U2FS_CRYPTO_ERROR;
  }

  char *PEM_data;
  int length = BIO_get_mem_data(bio, &PEM_data);
  *output = malloc(length);
  if (*output == NULL) {
    BIO_free(bio);
    return U2FS_MEMORY_ERROR;
  }

  memcpy(*output, PEM_data, length);
  BIO_free(bio);

  return U2FS_OK;
}
Example #10
0
/*
 * Converts OpenSSL ASN1_STRING structure into text
 *
 * Converts ASN1_STRING into text, converting all the characters into
 * current database encoding if possible.  Any invalid characters are
 * replaced by question marks.
 *
 * Parameter: str - OpenSSL ASN1_STRING structure.  Memory management
 * of this structure is responsibility of caller.
 *
 * Returns Datum, which can be directly returned from a C language SQL
 * function.
 */
static Datum
ASN1_STRING_to_text(ASN1_STRING *str)
{
	BIO		   *membuf;
	size_t		size;
	char		nullterm;
	char	   *sp;
	char	   *dp;
	text	   *result;

	membuf = BIO_new(BIO_s_mem());
	if (membuf == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("could not create OpenSSL BIO structure")));
	(void) BIO_set_close(membuf, BIO_CLOSE);
	ASN1_STRING_print_ex(membuf, str,
						 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
						  | ASN1_STRFLGS_UTF8_CONVERT));
	/* ensure null termination of the BIO's content */
	nullterm = '\0';
	BIO_write(membuf, &nullterm, 1);
	size = BIO_get_mem_data(membuf, &sp);
	dp = pg_any_to_server(sp, size - 1, PG_UTF8);
	result = cstring_to_text(dp);
	if (dp != sp)
		pfree(dp);
	if (BIO_free(membuf) != 1)
		elog(ERROR, "could not free OpenSSL BIO structure");

	PG_RETURN_TEXT_P(result);
}
Example #11
0
static int fetch_data_from_bio(SSL *s, char **out)
{
    int i;
    BIO *bio = SSL_get_wbio(s);
    if (!bio) {
      fprintf(stderr, "Couldn't get write BIO for SSL object!\n");
      fflush(stderr);
      return -1;
    }
    char *crypted_data;
    long crypted_data_len = BIO_get_mem_data(bio, &crypted_data);
    *out = malloc(crypted_data_len);
    if (!*out) {
        return -1;
    }

    memcpy(*out, crypted_data, crypted_data_len);

    if (BIO_reset(bio) <= 0) {
      fprintf(stderr, "fetch_data_from_bio: BIO_reset returned <= 0\n");
      fflush(stderr);
      return -1;
    }
    i = crypted_data_len;

    return i; 
}
Example #12
0
// Verify the signed block, the first 32 bytes of the data must be the certificate hash to work.
int __fastcall util_verify(char* signature, int signlen, struct util_cert* cert, char** data)
{
	unsigned int size, r;
	BIO *out = NULL;
	PKCS7 *message = NULL;
	char* data2 = NULL;
	char hash[UTIL_HASHSIZE];
	STACK_OF(X509) *st = NULL;

	cert->x509 = NULL;
	cert->pkey = NULL;
	*data = NULL;
	message = d2i_PKCS7(NULL, (const unsigned char**)&signature, signlen);
	if (message == NULL) goto error;
	out = BIO_new(BIO_s_mem());

	// Lets rebuild the original message and check the size
	size = i2d_PKCS7(message, NULL);
	if (size < (unsigned int)signlen) goto error;

	// Check the PKCS7 signature, but not the certificate chain.
	r = PKCS7_verify(message, NULL, NULL, NULL, out, PKCS7_NOVERIFY);
	if (r == 0) goto error;

	// If data block contains less than 32 bytes, fail.
	size = BIO_get_mem_data(out, &data2);
	if (size <= UTIL_HASHSIZE) goto error;

	// Copy the data block
	*data = (char*)malloc(size + 1);
	if (*data == NULL) goto error;
	memcpy(*data, data2, size);
	(*data)[size] = 0;

	// Get the certificate signer
	st = PKCS7_get0_signers(message, NULL, PKCS7_NOVERIFY);
	cert->x509 = X509_dup(sk_X509_value(st, 0));
	sk_X509_free(st);

	// Get a full certificate hash of the signer
	r = UTIL_HASHSIZE;
	X509_digest(cert->x509, EVP_sha256(), (unsigned char*)hash, &r);

	// Check certificate hash with first 32 bytes of data.
	if (memcmp(hash, *data, UTIL_HASHSIZE) != 0) goto error;

	// Approved, cleanup and return.
	BIO_free(out);
	PKCS7_free(message);

	return size;

error:
	if (out != NULL) BIO_free(out);
	if (message != NULL) PKCS7_free(message);
	if (*data != NULL) free(*data);
	if (cert->x509 != NULL) { X509_free(cert->x509); cert->x509 = NULL; }

	return 0;
}
/*
 * Converts OpenSSL ASN1_STRING structure into text
 *
 * Converts ASN1_STRING into text, converting all the characters into
 * current database encoding if possible.  Any invalid characters are
 * replaced by question marks.
 *
 * Parameter: str - OpenSSL ASN1_STRING structure.	Memory managment
 * of this structure is responsibility of caller.
 *
 * Returns Datum, which can be directly returned from a C language SQL
 * function.
 */
Datum
ASN1_STRING_to_text(ASN1_STRING *str)
{
	BIO		   *membuf = NULL;
	size_t		size,
				outlen;
	char	   *sp;
	char	   *dp;
	text	   *result;

	membuf = BIO_new(BIO_s_mem());
	(void) BIO_set_close(membuf, BIO_CLOSE);
	ASN1_STRING_print_ex(membuf, str,
						 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
						  | ASN1_STRFLGS_UTF8_CONVERT));

	outlen = 0;
	BIO_write(membuf, &outlen, 1);
	size = BIO_get_mem_data(membuf, &sp);
	dp = (char *) pg_do_encoding_conversion((unsigned char *) sp,
											size - 1,
											PG_UTF8,
											GetDatabaseEncoding());
	outlen = strlen(dp);
	result = palloc(VARHDRSZ + outlen);
	memcpy(VARDATA(result), dp, outlen);
	if (dp != sp)
		pfree(dp);

	BIO_free(membuf);
	VARATT_SIZEP(result) = outlen + VARHDRSZ;
	PG_RETURN_TEXT_P(result);
}
Example #14
0
static int verify_certificate_chain(X509_STORE_CTX * x509_ctx, void * ignored) {
    qeo_platform_custom_certificate_validator custom_cert_validator_cb = qeo_platform_get_custom_certificate_validator();
    qeo_der_certificate certificate_chain[10];
    BIO* bios[10];
    int rc = 0;

    /** We need access to unchecked chain of certificates
     * No obvious API is found to get a hold of it. The API's available to get certificates
     * expect to do the verification first and only then you can get the chain.
     * As we want to do the validation ourselves, we just pull them out the struct to get
     * the untrusted chain.
     */
    STACK_OF(X509) *sk = x509_ctx->untrusted;

    if (sk) {
        //Lets check the stack.
        qeo_util_retcode_t retcode = QEO_UTIL_EFAIL;
        int certs = sk_X509_num(sk);
        int i;

        if (certs > 10) { //to many certificates;
            //there is also a limit of 10 in openssl for the maximum certificate chain length. We should not hit this; Still better safe then sorry.
            return 0;
        }
        memset(bios, 0, sizeof(BIO*) * 10);
        for (i = 0; i < certs ; i++) {
            int result;
            X509* cert = sk_X509_value(sk, i);
            //create a memory BIO
            BIO *mem = BIO_new(BIO_s_mem());
            if (NULL == mem) {
                goto out; //failed to create BIO
            }
            bios[i] = mem;
            //write to bio int i2d_X509_bio(BIO *bp, X509 *x);
            result = i2d_X509_bio(mem, cert);

            if (result < 0) {
                qeo_log_e("Failed to write certificate data to mem bio %d\n", result);
                goto out;
            }
            // add to array
            certificate_chain[i].size = BIO_get_mem_data(mem, &certificate_chain[i].cert_data);
        }
        //call the callback
        retcode = custom_cert_validator_cb(certificate_chain, certs);
        if (retcode == QEO_UTIL_OK) {
            rc = 1;
        } else {
            qeo_log_e("Custom certificate verification callback returned %d - Treating this as a verification error\n", retcode);
        }
out:
        //free memory
        for (i = 0; i < certs ; i++) {
            if (bios[i])
               BIO_vfree(bios[i]); //we take the void version; not much we can do if the free fails
        }
    }
    return rc;
}
Example #15
0
string
toBase64(const uint8_t* array, size_t arrayLength, bool addNewlines)
{
    BIO *base64 = BIO_new(BIO_f_base64());
    if (!base64)
        throw runtime_error("toBase64: BIO_new failed");

    if (!addNewlines)
        BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);

    BIO *outputBuffer = BIO_new(BIO_s_mem());
    if (!outputBuffer) {
        BIO_free(base64);
        throw runtime_error("toBase64: BIO_new failed");
    }
    outputBuffer = BIO_push(base64, outputBuffer);

    if (BIO_write(base64, array, arrayLength) <= 0) {
        BIO_free_all(outputBuffer);
        throw runtime_error("toBase64: BIO_write failed");
    }

    BIO_flush(base64);
    char *bufferPointer;
    size_t bufferSize = BIO_get_mem_data(outputBuffer, &bufferPointer);

    string result(bufferPointer, bufferSize);
    BIO_free_all(outputBuffer);
    return result;
}
Example #16
0
/** Base64-encode data
 * @param[in] data The data to be encoded
 * @param[in] len The length of the data
 * @return A pointer to the base64-encoded data. The data is stored in a dynamically-allocated buffer.
 */
char *cl_base64_encode(void *data, size_t len)
{
    BIO *bio, *b64;
    char *buf, *p;
    size_t elen;

    b64 = BIO_new(BIO_f_base64());
    if (!(b64))
        return NULL;
    bio = BIO_new(BIO_s_mem());
    if (!(bio)) {
        BIO_free(b64);
        return NULL;
    }

    bio = BIO_push(b64, bio);
    BIO_write(bio, data, len);

    BIO_flush(bio);
    elen = (size_t)BIO_get_mem_data(bio, &buf);

    /* Ensure we're dealing with a NULL-terminated string */
    p = (char *)malloc(elen+1);
    if (NULL == p) {
        BIO_free(b64);
        return NULL;
    }
    memcpy((void *)p, (void *)buf, elen);
    p[elen] = 0x00;
    buf = p;

    BIO_free_all(bio);

    return buf;
}
Example #17
0
static void clone_mem_bio(BIO *bio, void **buf, size_t *buflen)
{
  char *internal_buf;
  size_t len;

  *buf=NULL;

  len = BIO_get_mem_data(bio, &internal_buf);
  if (!internal_buf) {
    return;
  }

  if(buflen) {
    *buflen=len;
  }

  *buf = malloc(len+1); /* always allocate an extra space for a null
                           character, but leave it to caller to
                           actually set it if needed */
  if(!*buf) {
    return;
  }

  memcpy(*buf, internal_buf, len);
  return;
}
Example #18
0
char *EstEID_base64Encode(const char *input, int length) {
	BIO *memBio;
	BIO *b64Bio;
	char *b;
	int len;
	char *result;

	LOG_LOCATION;

	memBio = BIO_new(BIO_s_mem());
	b64Bio = BIO_new(BIO_f_base64());
	b64Bio = BIO_push(b64Bio, memBio);

	BIO_write(b64Bio, input, length);
	(void)BIO_flush(b64Bio);


	len = BIO_get_mem_data(memBio, &b);
	result = (char *)malloc(len + 1);
	strncpy(result, b, len);
	result[len] = 0;
	BIO_free_all(b64Bio);
	while (result[--len] == '\n') result[len] = 0;
	return result;
}
static std::string
privateKeyToPEMString (EVP_PKEY *pkey_)
{
  BIO *temp_memory_bio = BIO_new (BIO_s_mem() );

  if (!temp_memory_bio) {
    GST_ERROR ("Failed to allocate temporary memory bio");
    return "";
  }

  if (!PEM_write_bio_PrivateKey (
        temp_memory_bio, pkey_, nullptr, nullptr, 0, nullptr, nullptr) ) {
    GST_ERROR ("Failed to write private key");
    BIO_free (temp_memory_bio);
    return "";
  }

  BIO_write (temp_memory_bio, "\0", 1);
  char *buffer;
  BIO_get_mem_data (temp_memory_bio, &buffer);
  std::string priv_key_str = buffer;
  BIO_free (temp_memory_bio);

  return priv_key_str;
}
static int base64Encode(char* output, const unsigned char* data, size_t length)
{
    BIO* base64 = BIO_new(BIO_f_base64());
    if (base64 == NULL) {
        return -1;
    }
    BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
    BIO* memory = BIO_new(BIO_s_mem());
    if (memory == NULL) {
        BIO_free_all(base64);
        return -1;
    }
    BIO* bio = BIO_push(base64, memory);
    BIO_write(bio, data, length);
    if (BIO_flush(bio) == -1) {
        return -1;
    }
    const char* p;
    size_t n = BIO_get_mem_data(memory, &p);
    int i;
    for (i = 0; i < n; ++i) {
        if (*(p+i) == '+') {
            *(output+i) = '-';
        } else if (*(p+i) == '/') {
            *(output+i) = '_';
        } else if (*(p+i) == '=') {
            break;
        } else {
            *(output+i) = *(p+i);
        }
    }

    BIO_free_all(bio);
    return n;
}
Example #21
0
/*
 * Converts OpenSSL ASN1_STRING structure into text
 *
 * Converts ASN1_STRING into text, converting all the characters into
 * current database encoding if possible.  Any invalid characters are
 * replaced by question marks.
 *
 * Parameter: str - OpenSSL ASN1_STRING structure.	Memory managment
 * of this structure is responsibility of caller.
 *
 * Returns Datum, which can be directly returned from a C language SQL
 * function.
 */
datum_t
ASN1_STRING_to_text(ASN1_STRING *str)
{
	BIO		   *membuf;
	size_t		size;
	char		nullterm;
	char	   *sp;
	char	   *dp;
	text	   *result;

	membuf = BIO_new(BIO_s_mem());
	(void) BIO_set_close(membuf, BIO_CLOSE);
	ASN1_STRING_print_ex(membuf, str,
						 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
						  | ASN1_STRFLGS_UTF8_CONVERT));
	/* ensure null termination of the BIO's content */
	nullterm = '\0';
	BIO_write(membuf, &nullterm, 1);
	size = BIO_get_mem_data(membuf, &sp);
	dp = (char *) pg_do_encoding_conversion((unsigned char *) sp,
											size - 1,
											PG_UTF8,
											get_db_encoding());
	result = cstring_to_text(dp);
	if (dp != sp)
		pfree(dp);
	BIO_free(membuf);

	RET_TEXT_P(result);
}
Example #22
0
// success of certificates extraction
bool pemData(X509_STORE_CTX* ctx, ListHashSet<String>& certificates)
{
    bool ok = true;
    STACK_OF(X509)* certs = X509_STORE_CTX_get1_chain(ctx);
    for (int i = 0; i < sk_X509_num(certs); i++) {
        X509* uCert = sk_X509_value(certs, i);
        BIO* bio = BIO_new(BIO_s_mem());
        int res = PEM_write_bio_X509(bio, uCert);
        if (!res) {
            ok = false;
            BIO_free(bio);
            break;
        }

        unsigned char* certificateData;
        long length = BIO_get_mem_data(bio, &certificateData);
        if (length < 0) {
            ok = false;
            BIO_free(bio);
            break;
        }

        certificateData[length] = '\0';
        String certificate = certificateData;
        certificates.add(certificate);
        BIO_free(bio);
    }
        sk_X509_pop_free(certs, X509_free);
        return ok;
}
static time_t
ngx_ssl_stapling_time(ASN1_GENERALIZEDTIME *asn1time)
{
    u_char  *value;
    size_t   len;
    time_t   time;
    BIO     *bio;

    /*
     * OpenSSL doesn't provide a way to convert ASN1_GENERALIZEDTIME
     * into time_t.  To do this, we use ASN1_GENERALIZEDTIME_print(),
     * which uses the "MMM DD HH:MM:SS YYYY [GMT]" format (e.g.,
     * "Feb  3 00:55:52 2015 GMT"), and parse the result.
     */

    bio = BIO_new(BIO_s_mem());
    if (bio == NULL) {
        return NGX_ERROR;
    }

    /* fake weekday prepended to match C asctime() format */

    BIO_write(bio, "Tue ", sizeof("Tue ") - 1);
    ASN1_GENERALIZEDTIME_print(bio, asn1time);
    len = BIO_get_mem_data(bio, &value);

    time = ngx_parse_http_time(value, len);

    BIO_free(bio);

    return time;
}
Example #24
0
File: buf.c Project: ep69/clevis
json_t *
clevis_buf_encode(const clevis_buf_t *buf)
{
  json_t *out = NULL;
  BIO *mem = NULL;
  BIO *b64 = NULL;
  char *c = NULL;
  int r = 0;

  mem = BIO_new(BIO_s_mem());
  if (!mem)
    goto egress;

  b64 = BIO_new(BIO_f_base64());
  if (!b64)
    goto egress;

  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
  if (!BIO_push(b64, mem))
    goto egress;

  r = BIO_write(b64, buf->buf, buf->len);
  if (r != (int) buf->len)
    goto egress;

  BIO_flush(b64);

  r = BIO_get_mem_data(mem, &c);
  out = json_stringn(c, r);

egress:
  BIO_free(b64);
  BIO_free(mem);
  return out;
}
Example #25
0
int ssl3_digest_cached_records(SSL *s, int keep)
{
    const EVP_MD *md;
    long hdatalen;
    void *hdata;

    if (s->s3->handshake_dgst == NULL) {
        hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
        if (hdatalen <= 0) {
            SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, SSL_R_BAD_HANDSHAKE_LENGTH);
            return 0;
        }

        s->s3->handshake_dgst = EVP_MD_CTX_new();
        if (s->s3->handshake_dgst == NULL) {
            SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_MALLOC_FAILURE);
            return 0;
        }

        md = ssl_handshake_md(s);
        if (   md == NULL
            || !EVP_DigestInit_ex(s->s3->handshake_dgst, md, NULL)
            || !EVP_DigestUpdate(s->s3->handshake_dgst, hdata, hdatalen))
        {
            SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_INTERNAL_ERROR);
            return 0;
        }
    }
    if (keep == 0) {
        BIO_free(s->s3->handshake_buffer);
        s->s3->handshake_buffer = NULL;
    }

    return 1;
}
Example #26
0
char *PICA_id_to_base64(const unsigned char *id, char *buf)
{
	BIO *biomem, *b64;
	static char localbuf[PICA_ID_SIZE * 2];

	char *sourcebuf, *outputbuf = buf;
	long b64len;

	b64 = BIO_new(BIO_f_base64());
	biomem = BIO_new(BIO_s_mem());
	biomem = BIO_push(b64, biomem);
	BIO_write(biomem, id, PICA_ID_SIZE);
	BIO_flush(biomem);

	b64len = BIO_get_mem_data(biomem, &sourcebuf);

	if (outputbuf == NULL)
		outputbuf = localbuf;

	memcpy(outputbuf, sourcebuf, b64len);

	*strchr(outputbuf, '\n') = '\0';
	outputbuf[b64len] = '\0';

	BIO_free_all(biomem);

	return outputbuf;
}
Example #27
0
gchar*
s3_base64_encode(const GByteArray *to_enc) {
    BIO *bio_b64 = NULL, *bio_buff = NULL;
    long bio_b64_len;
    char *bio_b64_data = NULL, *ret = NULL;
    if (!to_enc) return NULL;

    /* Initialize base64 encoding filter */
    bio_b64 = BIO_new(BIO_f_base64());
    g_assert(bio_b64);
    BIO_set_flags(bio_b64, BIO_FLAGS_BASE64_NO_NL);

    /* Initialize memory buffer for the base64 encoding */
    bio_buff = BIO_new(BIO_s_mem());
    g_assert(bio_buff);
    bio_buff = BIO_push(bio_b64, bio_buff);

    /* Write the MD5 hash into the buffer to encode it in base64 */
    BIO_write(bio_buff, to_enc->data, to_enc->len);
    /* BIO_flush is a macro and GCC 4.1.2 complains without this cast*/
    (void) BIO_flush(bio_buff);

    /* Pull out the base64 encoding of the MD5 hash */
    bio_b64_len = BIO_get_mem_data(bio_buff, &bio_b64_data);
    g_assert(bio_b64_data);
    ret = g_strndup(bio_b64_data, bio_b64_len);

    /* If bio_b64 is freed separately, freeing bio_buff will
     * invalidly free memory and potentially segfault.
     */
    BIO_free_all(bio_buff);
    return ret;
}
Example #28
0
/*
 * Converts OpenSSL ASN1_STRING structure into text
 *
 * Converts ASN1_STRING into text, converting all the characters into
 * current database encoding if possible.  Any invalid characters are
 * replaced by question marks.
 *
 * Parameter: str - OpenSSL ASN1_STRING structure.	Memory management
 * of this structure is responsibility of caller.
 *
 * Returns Datum, which can be directly returned from a C language SQL
 * function.
 */
static Datum
ASN1_STRING_to_text(ASN1_STRING *str)
{
	BIO		   *membuf;
	size_t		size;
	char		nullterm;
	char	   *sp;
	char	   *dp;
	text	   *result;

	membuf = BIO_new(BIO_s_mem());
	(void) BIO_set_close(membuf, BIO_CLOSE);
	ASN1_STRING_print_ex(membuf, str,
						 ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
						  | ASN1_STRFLGS_UTF8_CONVERT));
	/* ensure null termination of the BIO's content */
	nullterm = '\0';
	BIO_write(membuf, &nullterm, 1);
	size = BIO_get_mem_data(membuf, &sp);
	dp = pg_any_to_server(sp, size - 1, PG_UTF8);
	result = cstring_to_text(dp);
	if (dp != sp)
		pfree(dp);
	BIO_free(membuf);

	PG_RETURN_TEXT_P(result);
}
Example #29
0
static const char *shmcache_get_crypto_errors(void) {
  unsigned int count = 0;
  unsigned long e = ERR_get_error();
  BIO *bio = NULL;
  char *data = NULL;
  long datalen;
  const char *str = "(unknown)";

  /* Use ERR_print_errors() and a memory BIO to build up a string with
   * all of the error messages from the error queue.
   */

  if (e)
    bio = BIO_new(BIO_s_mem());

  while (e) {
    pr_signals_handle();
    BIO_printf(bio, "\n  (%u) %s", ++count, ERR_error_string(e, NULL));
    e = ERR_get_error();
  }

  datalen = BIO_get_mem_data(bio, &data);
  if (data) {
    data[datalen] = '\0';
    str = pstrdup(permanent_pool, data);
  }

  if (bio)
    BIO_free(bio);

  return str;
}
Example #30
0
std::string PublicKey::getPemEncoded()
		throw (EncodeException)
{
	BIO *buffer;
	int ndata, wrote;
	std::string ret;
	ByteArray *retTemp;
	unsigned char *data;
	buffer = BIO_new(BIO_s_mem());
	if (buffer == NULL)
	{
		throw EncodeException(EncodeException::BUFFER_CREATING, "PublicKey::getPemEncoded");
	}
	wrote = PEM_write_bio_PUBKEY(buffer, this->key);
	if (!wrote)
	{
		BIO_free(buffer);
		throw EncodeException(EncodeException::PEM_ENCODE, "PublicKey::getPemEncoded");
	}
	ndata = BIO_get_mem_data(buffer, &data);
	if (ndata <= 0)
	{
		BIO_free(buffer);
		throw EncodeException(EncodeException::BUFFER_READING, "PublicKey::getPemEncoded");
	}
	retTemp = new ByteArray(data, ndata);
	ret = retTemp->toString();
	delete retTemp;
	BIO_free(buffer);
	return ret;
}