-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathazure.c
92 lines (71 loc) · 2.45 KB
/
azure.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <string.h>
#include <time.h>
#include <stddef.h>
#include "azure.h"
#include "misc.h"
#include "trace.h"
#include "ntv.h"
#include "http.h"
#include "http_client.h"
#include <openssl/hmac.h>
char *
azure_sas_token(const char *resource, const char *sakey,
int valid_duration, const char *keyname)
{
scoped_char *canonical_resource =
url_escape_alloc(resource, URL_ESCAPE_PARAM);
time_t ttl = time(NULL) + valid_duration;
scoped_char *to_sign = fmt("%s\n%ld", canonical_resource, (long)ttl);
uint8_t key[256];
int keylen = base64_decode(key, sakey, sizeof(key));
uint8_t hmac[32];
HMAC(EVP_sha256(), key, keylen, (const uint8_t *)to_sign,
strlen(to_sign), hmac, NULL);
scoped_char *b64_hmac = base64_encode_a(hmac, sizeof(hmac),
BASE64_STANDARD);
scoped_char *sig = url_escape_alloc(b64_hmac, URL_ESCAPE_PARAM);
return fmt("SharedAccessSignature sr=%s&sig=%s&se=%ld%s%s",
canonical_resource, sig, (long)ttl,
keyname ? "&skn=" : "",
keyname ?: "");
}
ntv_t *
azure_vm_get_machine_identity(void)
{
char errbuf[512];
const char *url = "http://169.254.169.254/metadata/instance?api-version=2018-02-01";
scoped_http_result(hcr);
if(http_client_request(&hcr, url,
HCR_TIMEOUT(2),
HCR_FLAGS(HCR_DECODE_BODY_AS_JSON),
HCR_ERRBUF(errbuf, sizeof(errbuf)),
HCR_HEADER("Metadata", "true"),
NULL)) {
trace(LOG_ERR, "Failed to get azure instance metadata from %s -- %s",
url, errbuf);
return NULL;
}
ntv_t *result = hcr.hcr_json_result;
hcr.hcr_json_result = NULL;
return result;
}
ntv_t *
azure_vm_get_machine_token(const char *aud)
{
char errbuf[512];
scoped_char *url = fmt("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=%s", aud);
scoped_http_result(hcr);
if(http_client_request(&hcr, url,
HCR_TIMEOUT(2),
HCR_FLAGS(HCR_DECODE_BODY_AS_JSON),
HCR_ERRBUF(errbuf, sizeof(errbuf)),
HCR_HEADER("Metadata", "true"),
NULL)) {
trace(LOG_ERR, "Failed to get azure instance token for %s from %s -- %s",
aud, url, errbuf);
return NULL;
}
ntv_t *result = hcr.hcr_json_result;
hcr.hcr_json_result = NULL;
return result;
}