static char *print_binary(cJSON *item, int depth){ char* b64; char* out, *prt, *prt2, *prt3; int size=base64_encode_alloc( item->valuedata, item->valuesize, &b64 ); int lines = size / 50 + 1; int len = lines * ( depth * 2 + 6 + 51 ) + 11; out = cJSON_malloc( len ); prt = out; *prt = 0; strcpy( prt, "!!binary |\n" ); prt += 11; prt3 = b64 + size; prt2 = b64; while( prt2 < prt3 ){ int i; for( i = 0; i < depth * 2 + 2; i ++ ){ *prt++ = ' '; }; int resto = prt3 - prt2 > 50 ? 50 : prt3 - prt2; memcpy( prt, prt2, resto ); prt2 += 50; prt += resto; *prt ++ = '\n'; } *prt++ = 0; free( b64 ); return out; }
static bool cmdSecretGetValue(vshControl *ctl, const vshCmd *cmd) { virSecretPtr secret; char *base64; unsigned char *value; size_t value_size; bool ret = false; secret = vshCommandOptSecret(ctl, cmd, NULL); if (secret == NULL) return false; value = virSecretGetValue(secret, &value_size, 0); if (value == NULL) goto cleanup; base64_encode_alloc((char *)value, value_size, &base64); memset(value, 0, value_size); VIR_FREE(value); if (base64 == NULL) { vshError(ctl, "%s", _("Failed to allocate memory")); goto cleanup; } vshPrint(ctl, "%s", base64); memset(base64, 0, strlen(base64)); VIR_FREE(base64); ret = true; cleanup: virSecretFree(secret); return ret; }
static char *print_binary(cJSON *item) { char* b64; int size=base64_encode_alloc( item->valuedata, item->valuesize, &b64 ); char* out = print_string_ptr( b64 ); free( b64 ); return out; }
data_buffer mini_base64_encode(char *data, size_t len) { data_buffer retval; retval.data = NULL; retval.len = base64_encode_alloc(data, len, &(retval.data)); return retval; }
char * amxml_format_tag( char *tag, char *value) { char *b64value; char *c; int need_raw; char *result; char *quoted_value; char *q; quoted_value = malloc(strlen(value)+1); q = quoted_value; need_raw = 0; for(c=value; *c != '\0'; c++) { // Check include negative value, with the 8th bit set. if (*c <= ' ' || (unsigned char)*c > 127 || *c == '<' || *c == '>' || *c == '"' || *c == '&' || *c == '\\' || *c == '\'' || *c == '\t' || *c == '\f' || *c == '\r' || *c == '\n') { need_raw = 1; *q++ = '_'; } else { *q++ = *c; } } *q = '\0'; if (need_raw) { base64_encode_alloc(value, strlen(value), &b64value); result = vstralloc("<", tag, " encoding=\"raw\" raw=\"", b64value, "\">", quoted_value, "</", tag, ">", NULL); amfree(b64value); } else { result = vstralloc("<", tag, ">", value, "</", tag, ">", NULL); } amfree(quoted_value); return result; }
/** * virStringEncodeBase64: * @buf: buffer of bytes to encode * @buflen: number of bytes to encode * * Encodes @buf to base 64 and returns the resulting string. The caller is * responsible for freeing the result. */ char * virStringEncodeBase64(const uint8_t *buf, size_t buflen) { char *ret; base64_encode_alloc((const char *) buf, buflen, &ret); if (!ret) { virReportOOMError(); return NULL; } return ret; }
static int raw_pubkey_to_base64(const gnutls_datum_t* raw, gnutls_datum_t * b64) { int ret; char* out; ret = base64_encode_alloc((void*)raw->data, raw->size, &out); if (ret == 0) return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR); b64->data = (void*)out; b64->size = ret; return 0; }
int main(int argc, char** argv) { if (argc < 2) { usage(argv[0]); return -1; } int ch = 0; char *out = NULL; int len = -1; while ((ch = getopt(argc, argv, "e:d:h")) != -1) { switch (ch) { case 'e': { len = base64_encode_alloc(optarg, strlen(optarg), &out); printf("source:%s , encoded:%s , encode_len:%d\n", optarg, out, len); out = NULL; len = -1; } break; case 'd': { base64_decode_alloc(optarg, strlen(optarg), &out, &len); printf("source:%s , encoded:%s , decode_len:%d\n", optarg, out, len); out = NULL; len = -1; } break; case 'h': { usage(argv[0]); } break; case '?': { usage(argv[0]); } break; } } return 0; }
char *make_password(const char *crypted) { char *base64pass; unsigned char *packed; unsigned int len; char *passbuf; packed = pack(crypted, &len); base64_encode_alloc((char *)packed, len, &base64pass); passbuf = malloc(strlen(base64pass) + 1 + 5); strcpy(passbuf, "{MD5}"); strcat(passbuf, base64pass); //log_module(MAIN_LOG, LOG_DEBUG, "Encoded password is: '%s'", passbuf); free(base64pass); return passbuf; }
static void serialize_memsegment(MemSegment * msg, xmlNodePtr memories_n) { xmlNodePtr memory_n = xmlNewChild(memories_n, NULL, BAD_CAST "memory", NULL); create_hex_node(msg->get_start(), "base", memory_n); char * base64_code; size_t outlen = base64_encode_alloc ((const char*)msg->data_ptr(), msg->get_length(), &base64_code); if (base64_code == NULL) { fprintf(stderr, "err encoding memory to base64\n"); return; } xmlNewChild(memory_n, NULL, BAD_CAST "data", BAD_CAST base64_code); free(base64_code); }
size_t base64url_encode_alloc (const uint8_t *data, size_t len, char **out) { size_t i; assert(NULL != data); assert(NULL != out); size_t s = base64_encode_alloc (data, len, out); char *burl = *out; for (i = 0; i < s; i++) { if ('+' == *(burl+i)) *(burl+i) = '-'; else if ('/' == *(burl+i)) *(burl+i) = '_'; else if ('=' == *(burl+i)) *(burl+i) = 0; } return strnlen (burl, s); }
int main (void) { const char *in = "abcdefghijklmnop"; const char *b64in = "YWJjZGVmZw=="; char out[255]; size_t len; bool ok; char *p; memset (out, 0x42, sizeof (out)); base64_encode (in, 0, out, 0); ASSERT (out[0] == '\x42'); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 1); ASSERT (memcmp (out, "YQ==", 1) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 2); ASSERT (memcmp (out, "YQ==", 2) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 3); ASSERT (memcmp (out, "YQ==", 3) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 4); ASSERT (memcmp (out, "YQ==", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 1, out, 8); ASSERT (memcmp (out, "YQ==", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 2, out, 4); ASSERT (memcmp (out, "YWI=", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 3, out, 4); ASSERT (memcmp (out, "YWJj", 4) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 4, out, 5); ASSERT (memcmp (out, "YWJjZA==", 5) == 0); memset (out, 0x42, sizeof (out)); base64_encode (in, 4, out, 100); ASSERT (memcmp (out, "YWJjZA==", 6) == 0); /* Decode. */ memset (out, 0x42, sizeof (out)); len = 0; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 0); memset (out, 0x42, sizeof (out)); len = 1; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 1); ASSERT (memcmp (out, "abcdefg", 1) == 0); memset (out, 0x42, sizeof (out)); len = 2; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 2); ASSERT (memcmp (out, "abcdefg", 2) == 0); memset (out, 0x42, sizeof (out)); len = 3; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (out, "abcdefg", 3) == 0); memset (out, 0x42, sizeof (out)); len = 4; ok = base64_decode (b64in, 4, out, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (out, "abcdefg", 3) == 0); memset (out, 0x42, sizeof (out)); len = 100; ok = base64_decode (b64in, strlen (b64in), out, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", 7) == 0); /* Allocating encode */ len = base64_encode_alloc (in, strlen (in), &p); ASSERT (len == 24); ASSERT (strcmp (p, "YWJjZGVmZ2hpamtsbW5vcA==") == 0); free (p); len = base64_encode_alloc (in, SIZE_MAX - 5, &p); ASSERT (len == 0); /* Decode context function */ { struct base64_decode_context ctx; base64_decode_ctx_init (&ctx); len = sizeof (out); ok = base64_decode_ctx (&ctx, b64in, strlen (b64in), out, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", len) == 0); } /* Allocating decode context function */ ok = base64_decode_alloc_ctx (NULL, b64in, strlen (b64in), &p, &len); ASSERT (ok); ASSERT (len == 7); ASSERT (memcmp (out, "abcdefg", len) == 0); free (p); { struct base64_decode_context ctx; const char *newlineb64 = "YWJjZG\nVmZ2hp\namtsbW5vcA=="; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, newlineb64, strlen (newlineb64), &p, &len); ASSERT (ok); ASSERT (len == strlen (in)); ASSERT (memcmp (p, in, len) == 0); free (p); } { struct base64_decode_context ctx; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, "YW\nJjZGVmZ2hp", 13, &p, &len); ASSERT (ok); ASSERT (len == 9); ASSERT (memcmp (p, "abcdefghi", len) == 0); free (p); base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, "YW\n", 3, &p, &len); ASSERT (ok); ASSERT (len == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "JjZGVmZ2", 8, &p, &len); ASSERT (ok); ASSERT (len == 6); ASSERT (memcmp (p, "abcdef", len) == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "hp", 2, &p, &len); ASSERT (ok); ASSERT (len == 3); ASSERT (memcmp (p, "ghi", len) == 0); free (p); ok = base64_decode_alloc_ctx (&ctx, "", 0, &p, &len); ASSERT (ok); free (p); } { struct base64_decode_context ctx; const char *newlineb64 = "\n\n\n\n\n"; base64_decode_ctx_init (&ctx); ok = base64_decode_alloc_ctx (&ctx, newlineb64, strlen (newlineb64), &p, &len); ASSERT (ok); ASSERT (len == 0); free (p); } ok = base64_decode_alloc_ctx (NULL, " ! ", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "abc\ndef", 7, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa", 2, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aax", 3, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=X", 4, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aa=X", 4, &p, &len); ASSERT (!ok); ok = base64_decode_alloc_ctx (NULL, "aax=X", 5, &p, &len); ASSERT (!ok); return 0; }
static int virStorageBackendRBDOpenRADOSConn(virStorageBackendRBDStatePtr *ptr, virConnectPtr conn, virStoragePoolObjPtr pool) { int ret = -1; unsigned char *secret_value = NULL; size_t secret_value_size; char *rados_key = NULL; virBuffer mon_host = VIR_BUFFER_INITIALIZER; virSecretPtr secret = NULL; char secretUuid[VIR_UUID_STRING_BUFLEN]; int i; char *mon_buff = NULL; VIR_DEBUG("Found Cephx username: %s", pool->def->source.auth.cephx.username); if (pool->def->source.auth.cephx.username != NULL) { VIR_DEBUG("Using cephx authorization"); if (rados_create(&ptr->cluster, pool->def->source.auth.cephx.username) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("failed to initialize RADOS")); goto cleanup; } if (pool->def->source.auth.cephx.secret.uuidUsable) { virUUIDFormat(pool->def->source.auth.cephx.secret.uuid, secretUuid); VIR_DEBUG("Looking up secret by UUID: %s", secretUuid); secret = virSecretLookupByUUIDString(conn, secretUuid); } else if (pool->def->source.auth.cephx.secret.usage != NULL) { VIR_DEBUG("Looking up secret by usage: %s", pool->def->source.auth.cephx.secret.usage); secret = virSecretLookupByUsage(conn, VIR_SECRET_USAGE_TYPE_CEPH, pool->def->source.auth.cephx.secret.usage); } if (secret == NULL) { virReportError(VIR_ERR_NO_SECRET, "%s", _("failed to find the secret")); goto cleanup; } secret_value = virSecretGetValue(secret, &secret_value_size, 0); base64_encode_alloc((char *)secret_value, secret_value_size, &rados_key); memset(secret_value, 0, secret_value_size); if (rados_key == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("failed to decode the RADOS key")); goto cleanup; } VIR_DEBUG("Found cephx key: %s", rados_key); if (rados_conf_set(ptr->cluster, "key", rados_key) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "rados_key"); goto cleanup; } memset(rados_key, 0, strlen(rados_key)); if (rados_conf_set(ptr->cluster, "auth_supported", "cephx") < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "auth_supported"); goto cleanup; } } else { VIR_DEBUG("Not using cephx authorization"); if (rados_create(&ptr->cluster, NULL) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("failed to create the RADOS cluster")); goto cleanup; } if (rados_conf_set(ptr->cluster, "auth_supported", "none") < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "auth_supported"); goto cleanup; } } VIR_DEBUG("Found %zu RADOS cluster monitors in the pool configuration", pool->def->source.nhost); for (i = 0; i < pool->def->source.nhost; i++) { if (pool->def->source.hosts[i].name != NULL && !pool->def->source.hosts[i].port) { virBufferAsprintf(&mon_host, "%s:6789,", pool->def->source.hosts[i].name); } else if (pool->def->source.hosts[i].name != NULL && pool->def->source.hosts[i].port) { virBufferAsprintf(&mon_host, "%s:%d,", pool->def->source.hosts[i].name, pool->def->source.hosts[i].port); } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("received malformed monitor, check the XML definition")); } } if (virBufferError(&mon_host)) { virReportOOMError(); goto cleanup; } mon_buff = virBufferContentAndReset(&mon_host); VIR_DEBUG("RADOS mon_host has been set to: %s", mon_buff); if (rados_conf_set(ptr->cluster, "mon_host", mon_buff) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "mon_host"); goto cleanup; } ptr->starttime = time(0); if (rados_connect(ptr->cluster) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to connect to the RADOS monitor on: %s"), mon_buff); goto cleanup; } ret = 0; cleanup: VIR_FREE(secret_value); VIR_FREE(rados_key); virSecretFree(secret); virBufferFreeAndReset(&mon_host); VIR_FREE(mon_buff); return ret; }
static int json_luks1_digest(const struct luks_phdr *hdr_v1, struct json_object **digest_object) { char keyslot_str[2], *base64_str; int ks; size_t base64_len; struct json_object *digest_obj, *array, *field; digest_obj = json_object_new_object(); if (!digest_obj) return -ENOMEM; /* type field */ field = json_object_new_string("pbkdf2"); if (!field) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "type", field); /* keyslots array */ array = json_object_new_array(); if (!array) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "keyslots", json_object_get(array)); for (ks = 0; ks < LUKS_NUMKEYS; ks++) { if (hdr_v1->keyblock[ks].active != LUKS_KEY_ENABLED) continue; (void) snprintf(keyslot_str, sizeof(keyslot_str), "%d", ks); field = json_object_new_string(keyslot_str); if (!field || json_object_array_add(array, field) < 0) { json_object_put(field); json_object_put(array); json_object_put(digest_obj); return -ENOMEM; } } json_object_put(array); /* segments array */ array = json_object_new_array(); if (!array) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "segments", json_object_get(array)); field = json_object_new_string("0"); if (!field || json_object_array_add(array, field) < 0) { json_object_put(field); json_object_put(array); json_object_put(digest_obj); return -ENOMEM; } json_object_put(array); /* hash field */ field = json_object_new_string(hdr_v1->hashSpec); if (!field) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "hash", field); /* salt field */ base64_len = base64_encode_alloc(hdr_v1->mkDigestSalt, LUKS_SALTSIZE, &base64_str); if (!base64_str) { json_object_put(digest_obj); if (!base64_len) return -EINVAL; return -ENOMEM; } field = json_object_new_string_len(base64_str, base64_len); free(base64_str); if (!field) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "salt", field); /* digest field */ base64_len = base64_encode_alloc(hdr_v1->mkDigest, LUKS_DIGESTSIZE, &base64_str); if (!base64_str) { json_object_put(digest_obj); if (!base64_len) return -EINVAL; return -ENOMEM; } field = json_object_new_string_len(base64_str, base64_len); free(base64_str); if (!field) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "digest", field); /* iterations field */ field = json_object_new_int64(hdr_v1->mkDigestIterations); if (!field) { json_object_put(digest_obj); return -ENOMEM; } json_object_object_add(digest_obj, "iterations", field); *digest_object = digest_obj; return 0; }
static int json_luks1_keyslot(const struct luks_phdr *hdr_v1, int keyslot, struct json_object **keyslot_object) { char *base64_str, cipher[LUKS_CIPHERNAME_L+LUKS_CIPHERMODE_L]; size_t base64_len; struct json_object *keyslot_obj, *field, *jobj_kdf, *jobj_af, *jobj_area; uint64_t offset, area_size, offs_a, offs_b, length; keyslot_obj = json_object_new_object(); json_object_object_add(keyslot_obj, "type", json_object_new_string("luks2")); json_object_object_add(keyslot_obj, "key_size", json_object_new_int64(hdr_v1->keyBytes)); /* KDF */ jobj_kdf = json_object_new_object(); json_object_object_add(jobj_kdf, "type", json_object_new_string(CRYPT_KDF_PBKDF2)); json_object_object_add(jobj_kdf, "hash", json_object_new_string(hdr_v1->hashSpec)); json_object_object_add(jobj_kdf, "iterations", json_object_new_int64(hdr_v1->keyblock[keyslot].passwordIterations)); /* salt field */ base64_len = base64_encode_alloc(hdr_v1->keyblock[keyslot].passwordSalt, LUKS_SALTSIZE, &base64_str); if (!base64_str) { json_object_put(keyslot_obj); json_object_put(jobj_kdf); if (!base64_len) return -EINVAL; return -ENOMEM; } field = json_object_new_string_len(base64_str, base64_len); free(base64_str); json_object_object_add(jobj_kdf, "salt", field); json_object_object_add(keyslot_obj, "kdf", jobj_kdf); /* AF */ jobj_af = json_object_new_object(); json_object_object_add(jobj_af, "type", json_object_new_string("luks1")); json_object_object_add(jobj_af, "hash", json_object_new_string(hdr_v1->hashSpec)); /* stripes field ignored, fixed to LUKS_STRIPES (4000) */ json_object_object_add(jobj_af, "stripes", json_object_new_int(4000)); json_object_object_add(keyslot_obj, "af", jobj_af); /* Area */ jobj_area = json_object_new_object(); json_object_object_add(jobj_area, "type", json_object_new_string("raw")); /* encryption algorithm field */ if (*hdr_v1->cipherMode != '\0') { (void) snprintf(cipher, sizeof(cipher), "%s-%s", hdr_v1->cipherName, hdr_v1->cipherMode); json_object_object_add(jobj_area, "encryption", json_object_new_string(cipher)); } else json_object_object_add(jobj_area, "encryption", json_object_new_string(hdr_v1->cipherName)); /* area */ if (LUKS_keyslot_area(hdr_v1, 0, &offs_a, &length) || LUKS_keyslot_area(hdr_v1, 1, &offs_b, &length) || LUKS_keyslot_area(hdr_v1, keyslot, &offset, &length)) { json_object_put(keyslot_obj); json_object_put(jobj_area); return -EINVAL; } area_size = offs_b - offs_a; json_object_object_add(jobj_area, "key_size", json_object_new_int(hdr_v1->keyBytes)); json_object_object_add(jobj_area, "offset", json_object_new_uint64(offset)); json_object_object_add(jobj_area, "size", json_object_new_uint64(area_size)); json_object_object_add(keyslot_obj, "area", jobj_area); *keyslot_object = keyslot_obj; return 0; }
static int virStorageBackendRBDOpenRADOSConn(virStorageBackendRBDStatePtr ptr, virConnectPtr conn, virStoragePoolObjPtr pool) { int ret = -1; int r = 0; unsigned char *secret_value = NULL; size_t secret_value_size; char *rados_key = NULL; virBuffer mon_host = VIR_BUFFER_INITIALIZER; virSecretPtr secret = NULL; char secretUuid[VIR_UUID_STRING_BUFLEN]; size_t i; char *mon_buff = NULL; const char *client_mount_timeout = "30"; const char *mon_op_timeout = "30"; const char *osd_op_timeout = "30"; VIR_DEBUG("Found Cephx username: %s", pool->def->source.auth.cephx.username); if (pool->def->source.auth.cephx.username != NULL) { VIR_DEBUG("Using cephx authorization"); r = rados_create(&ptr->cluster, pool->def->source.auth.cephx.username); if (r < 0) { virReportSystemError(-r, "%s", _("failed to initialize RADOS")); goto cleanup; } if (!conn) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("'ceph' authentication not supported " "for autostarted pools")); return -1; } if (pool->def->source.auth.cephx.secret.uuidUsable) { virUUIDFormat(pool->def->source.auth.cephx.secret.uuid, secretUuid); VIR_DEBUG("Looking up secret by UUID: %s", secretUuid); secret = virSecretLookupByUUIDString(conn, secretUuid); } else if (pool->def->source.auth.cephx.secret.usage != NULL) { VIR_DEBUG("Looking up secret by usage: %s", pool->def->source.auth.cephx.secret.usage); secret = virSecretLookupByUsage(conn, VIR_SECRET_USAGE_TYPE_CEPH, pool->def->source.auth.cephx.secret.usage); } if (secret == NULL) { if (pool->def->source.auth.cephx.secret.uuidUsable) { virReportError(VIR_ERR_NO_SECRET, _("no secret matches uuid '%s'"), secretUuid); } else { virReportError(VIR_ERR_NO_SECRET, _("no secret matches usage value '%s'"), pool->def->source.auth.cephx.secret.usage); } goto cleanup; } secret_value = conn->secretDriver->secretGetValue(secret, &secret_value_size, 0, VIR_SECRET_GET_VALUE_INTERNAL_CALL); if (!secret_value) { if (pool->def->source.auth.cephx.secret.uuidUsable) { virReportError(VIR_ERR_INTERNAL_ERROR, _("could not get the value of the secret " "for username '%s' using uuid '%s'"), pool->def->source.auth.cephx.username, secretUuid); } else { virReportError(VIR_ERR_INTERNAL_ERROR, _("could not get the value of the secret " "for username '%s' using usage value '%s'"), pool->def->source.auth.cephx.username, pool->def->source.auth.cephx.secret.usage); } goto cleanup; } base64_encode_alloc((char *)secret_value, secret_value_size, &rados_key); memset(secret_value, 0, secret_value_size); if (rados_key == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("failed to decode the RADOS key")); goto cleanup; } VIR_DEBUG("Found cephx key: %s", rados_key); if (rados_conf_set(ptr->cluster, "key", rados_key) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "rados_key"); goto cleanup; } memset(rados_key, 0, strlen(rados_key)); if (rados_conf_set(ptr->cluster, "auth_supported", "cephx") < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "auth_supported"); goto cleanup; } } else { VIR_DEBUG("Not using cephx authorization"); if (rados_create(&ptr->cluster, NULL) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("failed to create the RADOS cluster")); goto cleanup; } if (rados_conf_set(ptr->cluster, "auth_supported", "none") < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "auth_supported"); goto cleanup; } } VIR_DEBUG("Found %zu RADOS cluster monitors in the pool configuration", pool->def->source.nhost); for (i = 0; i < pool->def->source.nhost; i++) { if (pool->def->source.hosts[i].name != NULL && !pool->def->source.hosts[i].port) { virBufferAsprintf(&mon_host, "%s:6789,", pool->def->source.hosts[i].name); } else if (pool->def->source.hosts[i].name != NULL && pool->def->source.hosts[i].port) { virBufferAsprintf(&mon_host, "%s:%d,", pool->def->source.hosts[i].name, pool->def->source.hosts[i].port); } else { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("received malformed monitor, check the XML definition")); } } if (virBufferError(&mon_host)) { virReportOOMError(); goto cleanup; } mon_buff = virBufferContentAndReset(&mon_host); VIR_DEBUG("RADOS mon_host has been set to: %s", mon_buff); if (rados_conf_set(ptr->cluster, "mon_host", mon_buff) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to set RADOS option: %s"), "mon_host"); goto cleanup; } /* * Set timeout options for librados. * In case the Ceph cluster is down libvirt won't block forever. * Operations in librados will return -ETIMEDOUT when the timeout is reached. */ VIR_DEBUG("Setting RADOS option client_mount_timeout to %s", client_mount_timeout); rados_conf_set(ptr->cluster, "client_mount_timeout", client_mount_timeout); VIR_DEBUG("Setting RADOS option rados_mon_op_timeout to %s", mon_op_timeout); rados_conf_set(ptr->cluster, "rados_mon_op_timeout", mon_op_timeout); VIR_DEBUG("Setting RADOS option rados_osd_op_timeout to %s", osd_op_timeout); rados_conf_set(ptr->cluster, "rados_osd_op_timeout", osd_op_timeout); ptr->starttime = time(0); r = rados_connect(ptr->cluster); if (r < 0) { virReportSystemError(-r, _("failed to connect to the RADOS monitor on: %s"), mon_buff); goto cleanup; } ret = 0; cleanup: VIR_FREE(secret_value); VIR_FREE(rados_key); if (secret != NULL) virSecretFree(secret); virBufferFreeAndReset(&mon_host); VIR_FREE(mon_buff); return ret; }
bool FragmentationEncoderService::addAttributes(DataObjectRef originalDataObject, DataObjectRef fragmentDataObject, string sequenceNumberListCsv) { //copy attributes. though eventually will use rich metadata? const Attributes* originalAttributes = originalDataObject->getAttributes(); for (Attributes::const_iterator it = originalAttributes->begin(); it != originalAttributes->end(); it++) { const Attribute attr = (*it).second; bool addAttribute = fragmentDataObject->addAttribute(attr); if (!addAttribute) { HAGGLE_ERR("unable to add attribute\n"); return false; } } //add sequence number attribute // char sequenceBuffer[33]; // memset(sequenceBuffer, 0, sizeof(sequenceBuffer)); // sprintf(sequenceBuffer, "%d", sequenceNumber); // HAGGLE_DBG("stringSequenceNumber=%s\n", sequenceBuffer); // bool addedSequenceNUmber = fragmentDataObject->addAttribute( // HAGGLE_ATTR_FRAGMENTATION_SEQUENCE_NUMBER, sequenceBuffer, 0); // if (!addedSequenceNUmber) { // HAGGLE_ERR("unable to add addedSequenceNUmber attribute\n"); // return false; // } HAGGLE_DBG2("stringSequenceNumber=%s\n", sequenceNumberListCsv.c_str()); bool addedSequenceNumber = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_SEQUENCE_NUMBER, sequenceNumberListCsv, 0); if (!addedSequenceNumber) { HAGGLE_ERR("Unable to add sequence number attribute\n"); return false; } //add attribute to indicate data object is fragmentation block bool addedIsFragmentationCodedAttribute = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_NAME, "TRUE", 0); if (!addedIsFragmentationCodedAttribute) { HAGGLE_ERR("Unable to add fragmentation attribute\n"); return false; } //add original data len attribute char lenBuffer[33]; memset(lenBuffer, 0, sizeof(lenBuffer)); int len = fragmentationDataObjectUtility->getFileLength(originalDataObject); if(len == 0) { HAGGLE_ERR("Orignal data len is zero - file already deleted\n"); return false; } sprintf(lenBuffer, "%d", len); bool addedDataLenAttribute = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_ORIG_LEN, lenBuffer, 0); if (!addedDataLenAttribute) { HAGGLE_ERR("Unable to add original data len attribute\n"); return false; } //add dataobject id const char* originalId = originalDataObject->getIdStr(); string originalStringId = originalId; bool addedIdAttribute = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_DATAOBJECT_ID, originalStringId, 0); if (!addedIdAttribute) { HAGGLE_ERR("Unable to add original data object id attribute\n"); return false; } //add dataobject name string originalName = fragmentationDataObjectUtility->getFileName(originalDataObject); HAGGLE_DBG2("Add original name %s as attribute\n", originalName.c_str()); bool addedNameAttribute = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_ORIG_NAME, originalName, 0); if (!addedNameAttribute) { HAGGLE_ERR("Unable to add original name attribute\n"); return false; } //add create time string originalCreateTime = originalDataObject->getCreateTime().getAsString(); HAGGLE_DBG2("Add original create time %s as attribute\n", originalCreateTime.c_str()); bool addedCreatedTimeAttribute = fragmentDataObject->addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_CREATION_TIME, originalCreateTime, 0); if (!addedCreatedTimeAttribute) { HAGGLE_ERR("Unable to add original create time attribute\n"); return false; } //set create time of fragment to same create time as parent so fragment data object ids can match up Timeval createTime(originalCreateTime); fragmentDataObject->setCreateTime(createTime); if(originalDataObject->getSignature()) { // MOS //add signee string parentSignee = originalDataObject->getSignee(); HAGGLE_DBG2("Add original signee %s as attribute\n",parentSignee.c_str()); bool addedSigneeAttribute = fragmentDataObject-> addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_ORIG_SIGNEE,parentSignee,0); if(!addedSigneeAttribute) { HAGGLE_ERR("Unable to add original signee attribute\n"); return false; } //add signature char *base64_signature = NULL; if (base64_encode_alloc((char *)originalDataObject->getSignature(), originalDataObject->getSignatureLength(), &base64_signature) <= 0) { HAGGLE_ERR("Unable to generate base64 encoded signature\n"); return false; } string parentSignature = base64_signature; HAGGLE_DBG2("Add original signature %s as attribute\n",parentSignature.c_str()); bool addedSignatureAttribute = fragmentDataObject-> addAttribute(HAGGLE_ATTR_FRAGMENTATION_PARENT_ORIG_SIGNATURE,parentSignature,0); if(!addedSignatureAttribute) { HAGGLE_ERR("Unable to add original signature attribute\n"); return false; } if(base64_signature) { free(base64_signature); base64_signature = NULL; } } return true; }
/** * Esta función se encargará de producir, lo que para el SAT[1], es un sello * digital. Este sello digital consiste en el firmado digital del hash de un * string, que para los casos de un CFDi se trataría de la cadena original * * El usuario es responsable de liberar la memoria del resultado (con free()) * [1]: http://www.sat.gob.mx */ unsigned char * sello_alloc(const char *keyfile, const char *digest, const unsigned char *cadena, const int verbose) { int read = 0; int len = 0; unsigned char *buffer = NULL; const unsigned char *tmp; unsigned char signbuffer[1024]; unsigned int signlen = 0; char *data = NULL; FILE *file = NULL; BIO* err = NULL; EVP_MD_CTX mdctx; EVP_PKEY *privateKey = NULL; file = fopen(keyfile, "rb"); if ( file == NULL ) { /* An error ocurred */ if ( verbose ) { fprintf(stderr, "No fue posible leer correctamente el archivo %s.\n", keyfile); } return NULL; } len = fseek(file, 0, SEEK_END); if ( len ) { /* An error did occur */ if ( verbose ) { fprintf(stderr, "No fue posible obtener el final del archivo %s.\n", keyfile); } fclose(file); return NULL; } len = ftell(file); rewind(file); buffer = (unsigned char *)calloc(len + 1, sizeof(unsigned char)); read = fread(buffer, sizeof(unsigned char), len, file); fclose(file); if ( read != len ) { if ( verbose ) { fprintf(stderr, "An error has ocurred. The number of items read was %d, but it should be %d instead.\n", read, len); free(buffer); } return NULL; } /* Set the BIO method for the error messages */ if ( err == NULL ) { if ( (err = BIO_new(BIO_s_file())) ) { BIO_set_fp(err, stderr, BIO_NOCLOSE|BIO_FP_TEXT); } } /* Now convert the bytes to a EVP_PKEY structure */ tmp = buffer; privateKey = d2i_AutoPrivateKey(NULL, &tmp, len); if ( privateKey == NULL ) { if ( verbose ) { BIO_printf(err, "Error at reading the private key on %s.\n", keyfile); ERR_print_errors(err); } free(buffer); return NULL; } free(buffer); /* Add all digest algorithms to the table */ OpenSSL_add_all_digests(); /* Initialize the digest context */ EVP_MD_CTX_init(&mdctx); if ( EVP_DigestInit_ex(&mdctx, EVP_get_digestbyname(digest), 0 ) == 0 ) { if ( verbose ) { BIO_printf(err, "Error at initializing the digest context to use '%s' as digest algorithm.\n", digest); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } /* Sign up the data in the current context */ if ( EVP_SignInit_ex(&mdctx, EVP_get_digestbyname(digest), 0) == 0 ) { if ( verbose ) { BIO_printf(err, "Error at setting up the signing context to use digest '%s'.\n", digest); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } if ( EVP_SignUpdate(&mdctx, cadena, strlen((char *)cadena)) == 0 ) { if ( verbose ) { BIO_printf(err, "Error hashing the data into the signing context.\n"); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } signlen = sizeof(signbuffer); memset(signbuffer, 0, 1024); if ( EVP_SignFinal(&mdctx, signbuffer, (unsigned int* )&signlen, privateKey) == 0 ) { if ( verbose ) { BIO_printf(err, "Error signing the data in the context with the private key.\n"); ERR_print_errors(err); } EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); return NULL; } EVP_MD_CTX_cleanup(&mdctx); EVP_PKEY_free(privateKey); EVP_cleanup(); BIO_free(err); /* Now prepare the data to be base64 encoded */ base64_encode_alloc((const char *)signbuffer, signlen, &data); return (unsigned char *)data; }
int main (int argc, char **argv) { short supports_tls=FALSE; int n = 0; double elapsed_time; long microsec; int result = STATE_UNKNOWN; char *cmd_str = NULL; char *helocmd = NULL; char *error_msg = ""; struct timeval tv; /* Catch pipe errors in read/write - sometimes occurs when writing QUIT */ (void) signal (SIGPIPE, SIG_IGN); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* If localhostname not set on command line, use gethostname to set */ if(! localhostname){ localhostname = malloc (HOST_MAX_BYTES); if(!localhostname){ printf(_("malloc() failed!\n")); return STATE_CRITICAL; } if(gethostname(localhostname, HOST_MAX_BYTES)){ printf(_("gethostname() failed!\n")); return STATE_CRITICAL; } } if(use_ehlo) xasprintf (&helocmd, "%s%s%s", SMTP_EHLO, localhostname, "\r\n"); else xasprintf (&helocmd, "%s%s%s", SMTP_HELO, localhostname, "\r\n"); if (verbose) printf("HELOCMD: %s", helocmd); /* initialize the MAIL command with optional FROM command */ xasprintf (&cmd_str, "%sFROM:<%s>%s", mail_command, from_arg, "\r\n"); if (verbose && send_mail_from) printf ("FROM CMD: %s", cmd_str); /* initialize alarm signal handling */ (void) signal (SIGALRM, socket_timeout_alarm_handler); /* set socket timeout */ (void) alarm (socket_timeout); /* start timer */ gettimeofday (&tv, NULL); /* try to connect to the host at the given port number */ result = my_tcp_connect (server_address, server_port, &sd); if (result == STATE_OK) { /* we connected */ /* watch for the SMTP connection string and */ /* return a WARNING status if we couldn't read any data */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else { if (verbose) printf ("%s", buffer); /* strip the buffer of carriage returns */ strip (buffer); /* make sure we find the response we are looking for */ if (!strstr (buffer, server_expect)) { if (server_port == SMTP_PORT) printf (_("Invalid SMTP response received from host: %s\n"), buffer); else printf (_("Invalid SMTP response received from host on port %d: %s\n"), server_port, buffer); return STATE_WARNING; } } /* send the HELO/EHLO command */ send(sd, helocmd, strlen(helocmd), 0); /* allow for response to helo command to reach us */ if (recvlines(buffer, MAX_INPUT_BUFFER) <= 0) { printf (_("recv() failed\n")); return STATE_WARNING; } else if(use_ehlo){ if(strstr(buffer, "250 STARTTLS") != NULL || strstr(buffer, "250-STARTTLS") != NULL){ supports_tls=TRUE; } } if(use_ssl && ! supports_tls){ printf(_("WARNING - TLS not supported by server\n")); smtp_quit(); return STATE_WARNING; } #ifdef HAVE_SSL if(use_ssl) { /* send the STARTTLS command */ send(sd, SMTP_STARTTLS, strlen(SMTP_STARTTLS), 0); recvlines(buffer, MAX_INPUT_BUFFER); /* wait for it */ if (!strstr (buffer, server_expect)) { printf (_("Server does not support STARTTLS\n")); smtp_quit(); return STATE_UNKNOWN; } result = np_net_ssl_init(sd); if(result != STATE_OK) { printf (_("CRITICAL - Cannot create SSL context.\n")); np_net_ssl_cleanup(); close(sd); return STATE_CRITICAL; } else { ssl_established = 1; } /* * Resend the EHLO command. * * RFC 3207 (4.2) says: ``The client MUST discard any knowledge * obtained from the server, such as the list of SMTP service * extensions, which was not obtained from the TLS negotiation * itself. The client SHOULD send an EHLO command as the first * command after a successful TLS negotiation.'' For this * reason, some MTAs will not allow an AUTH LOGIN command before * we resent EHLO via TLS. */ if (my_send(helocmd, strlen(helocmd)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot send EHLO command via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) printf(_("sent %s"), helocmd); if ((n = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { printf("%s\n", _("SMTP UNKNOWN - Cannot read EHLO response via TLS.")); my_close(); return STATE_UNKNOWN; } if (verbose) { printf("%s", buffer); } # ifdef USE_OPENSSL if ( check_cert ) { result = np_net_ssl_check_cert(days_till_exp_warn, days_till_exp_crit); my_close(); return result; } # endif /* USE_OPENSSL */ } #endif if (send_mail_from) { my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); } while (n < ncommands) { xasprintf (&cmd_str, "%s%s", commands[n], "\r\n"); my_send(cmd_str, strlen(cmd_str)); if (recvlines(buffer, MAX_INPUT_BUFFER) >= 1 && verbose) printf("%s", buffer); strip (buffer); if (n < nresponses) { cflags |= REG_EXTENDED | REG_NOSUB | REG_NEWLINE; errcode = regcomp (&preg, responses[n], cflags); if (errcode != 0) { regerror (errcode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Could Not Compile Regular Expression")); return ERROR; } excode = regexec (&preg, buffer, 10, pmatch, eflags); if (excode == 0) { result = STATE_OK; } else if (excode == REG_NOMATCH) { result = STATE_WARNING; printf (_("SMTP %s - Invalid response '%s' to command '%s'\n"), state_text (result), buffer, commands[n]); } else { regerror (excode, &preg, errbuf, MAX_INPUT_BUFFER); printf (_("Execute Error: %s\n"), errbuf); result = STATE_UNKNOWN; } } n++; } if (authtype != NULL) { if (strcmp (authtype, "LOGIN") == 0) { char *abuf; int ret; do { if (authuser == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authuser specified, ")); break; } if (authpass == NULL) { result = STATE_CRITICAL; xasprintf(&error_msg, _("no authpass specified, ")); break; } /* send AUTH LOGIN */ my_send(SMTP_AUTH_LOGIN, strlen(SMTP_AUTH_LOGIN)); if (verbose) printf (_("sent %s\n"), "AUTH LOGIN"); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { xasprintf(&error_msg, _("recv() failed after AUTH LOGIN, ")); result = STATE_WARNING; break; } if (verbose) printf (_("received %s\n"), buffer); if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after AUTH LOGIN, ")); break; } /* encode authuser with base64 */ base64_encode_alloc (authuser, strlen(authuser), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) printf (_("sent %s\n"), abuf); if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authuser, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "334", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authuser, ")); break; } /* encode authpass with base64 */ base64_encode_alloc (authpass, strlen(authpass), &abuf); xasprintf(&abuf, "%s\r\n", abuf); my_send(abuf, strlen(abuf)); if (verbose) { printf (_("sent %s\n"), abuf); } if ((ret = recvlines(buffer, MAX_INPUT_BUFFER)) <= 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("recv() failed after sending authpass, ")); break; } if (verbose) { printf (_("received %s\n"), buffer); } if (strncmp (buffer, "235", 3) != 0) { result = STATE_CRITICAL; xasprintf(&error_msg, _("invalid response received after authpass, ")); break; } break; } while (0); } else { result = STATE_CRITICAL; xasprintf(&error_msg, _("only authtype LOGIN is supported, ")); } } /* tell the server we're done */ smtp_quit(); /* finally close the connection */ close (sd); } /* reset the alarm */ alarm (0); microsec = deltime (tv); elapsed_time = (double)microsec / 1.0e6; if (result == STATE_OK) { if (check_critical_time && elapsed_time > critical_time) result = STATE_CRITICAL; else if (check_warning_time && elapsed_time > warning_time) result = STATE_WARNING; } printf (_("SMTP %s - %s%.3f sec. response time%s%s|%s\n"), state_text (result), error_msg, elapsed_time, verbose?", ":"", verbose?buffer:"", fperfdata ("time", elapsed_time, "s", (int)check_warning_time, warning_time, (int)check_critical_time, critical_time, TRUE, 0, FALSE, 0)); return result; }
int main(int argc, char *argv[]) { plan(52); int32_t ret; uint8_t in[BUF_LEN], ref[BUF_LEN], out[BUF_LEN], out2[BUF_LEN], *out3; uint32_t in_len, ref_len; // 0. test invalid input ret = base64_encode(NULL, 0, out, BUF_LEN); ok(ret == KNOT_EINVAL, "base64_encode: NULL input buffer"); ret = base64_encode(in, BUF_LEN, NULL, 0); ok(ret == KNOT_EINVAL, "base64_encode: NULL output buffer"); ret = base64_encode(in, MAX_BIN_DATA_LEN + 1, out, BUF_LEN); ok(ret == KNOT_ERANGE, "base64_encode: input buffer too large"); ret = base64_encode(in, BUF_LEN, out, BUF_LEN); ok(ret == KNOT_ERANGE, "base64_encode: output buffer too small"); ret = base64_encode_alloc(NULL, 0, &out3); ok(ret == KNOT_EINVAL, "base64_encode_alloc: NULL input buffer"); ret = base64_encode_alloc(in, MAX_BIN_DATA_LEN + 1, &out3); ok(ret == KNOT_ERANGE, "base64_encode_alloc: input buffer too large"); ret = base64_encode_alloc(in, BUF_LEN, NULL); ok(ret == KNOT_EINVAL, "base64_encode_alloc: NULL output buffer"); ret = base64_decode(NULL, 0, out, BUF_LEN); ok(ret == KNOT_EINVAL, "base64_decode: NULL input buffer"); ret = base64_decode(in, BUF_LEN, NULL, 0); ok(ret == KNOT_EINVAL, "base64_decode: NULL output buffer"); ret = base64_decode(in, UINT32_MAX, out, BUF_LEN); ok(ret == KNOT_ERANGE, "base64_decode: input buffer too large"); ret = base64_decode(in, BUF_LEN, out, 0); ok(ret == KNOT_ERANGE, "base64_decode: output buffer too small"); ret = base64_decode_alloc(NULL, 0, &out3); ok(ret == KNOT_EINVAL, "base64_decode_alloc: NULL input buffer"); ret = base64_decode_alloc(in, UINT32_MAX, &out3); ok(ret == KNOT_ERANGE, "base64_decode_aloc: input buffer too large"); ret = base64_decode_alloc(in, BUF_LEN, NULL); ok(ret == KNOT_EINVAL, "base64_decode_alloc: NULL output buffer"); // 1. test vector -> ENC -> DEC strlcpy((char *)in, "", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "1. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "1. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "1. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "1. test vector - DEC output content"); } // 2. test vector -> ENC -> DEC strlcpy((char *)in, "f", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zg==", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "2. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "2. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "2. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "2. test vector - DEC output content"); } // 3. test vector -> ENC -> DEC strlcpy((char *)in, "fo", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zm8=", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "3. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "3. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "3. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "3. test vector - DEC output content"); } // 4. test vector -> ENC -> DEC strlcpy((char *)in, "foo", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zm9v", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "4. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "4. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "4. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "4. test vector - DEC output content"); } // 5. test vector -> ENC -> DEC strlcpy((char *)in, "foob", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zm9vYg==", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "5. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "5. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "5. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "5. test vector - DEC output content"); } // 6. test vector -> ENC -> DEC strlcpy((char *)in, "fooba", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zm9vYmE=", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "6. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "6. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "6. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "6. test vector - DEC output content"); } // 7. test vector -> ENC -> DEC strlcpy((char *)in, "foobar", BUF_LEN); in_len = strlen((char *)in); strlcpy((char *)ref, "Zm9vYmFy", BUF_LEN); ref_len = strlen((char *)ref); ret = base64_encode(in, in_len, out, BUF_LEN); ok(ret == ref_len, "7. test vector - ENC output length"); if (ret < 0) { skip("Encode err"); } else { ok(memcmp(out, ref, ret) == 0, "7. test vector - ENC output content"); } ret = base64_decode(out, ret, out2, BUF_LEN); ok(ret == in_len, "7. test vector - DEC output length"); if (ret < 0) { skip("Decode err"); } else { ok(memcmp(out2, in, ret) == 0, "7. test vector - DEC output content"); } // Bad paddings ret = base64_decode((uint8_t *)"A===", 4, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Bad padding length 3"); ret = base64_decode((uint8_t *)"====", 4, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Bad padding length 4"); ret = base64_decode((uint8_t *)"AA=A", 4, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Bad padding character on position 2"); ret = base64_decode((uint8_t *)"Zg==Zg==", 8, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Two quartets with padding"); // Bad data length ret = base64_decode((uint8_t *)"A", 1, out, BUF_LEN); ok(ret == KNOT_BASE64_ESIZE, "Bad data length 1"); ret = base64_decode((uint8_t *)"AA", 2, out, BUF_LEN); ok(ret == KNOT_BASE64_ESIZE, "Bad data length 2"); ret = base64_decode((uint8_t *)"AAA", 3, out, BUF_LEN); ok(ret == KNOT_BASE64_ESIZE, "Bad data length 3"); ret = base64_decode((uint8_t *)"AAAAA", 5, out, BUF_LEN); ok(ret == KNOT_BASE64_ESIZE, "Bad data length 5"); // Bad data character ret = base64_decode((uint8_t *)"AAA$", 4, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Bad data character dollar"); ret = base64_decode((uint8_t *)"AAA ", 4, out, BUF_LEN); ok(ret == KNOT_BASE64_ECHAR, "Bad data character space"); return 0; }