contrib / credential / wincred / git-credential-wincred.con commit Merge branch 'ob/imap-send-ssl-verify' into maint (2a5964a)
   1/*
   2 * A git credential helper that interface with Windows' Credential Manager
   3 *
   4 */
   5#include <windows.h>
   6#include <stdio.h>
   7#include <io.h>
   8#include <fcntl.h>
   9
  10/* common helpers */
  11
  12#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
  13
  14static void die(const char *err, ...)
  15{
  16        char msg[4096];
  17        va_list params;
  18        va_start(params, err);
  19        vsnprintf(msg, sizeof(msg), err, params);
  20        fprintf(stderr, "%s\n", msg);
  21        va_end(params);
  22        exit(1);
  23}
  24
  25static void *xmalloc(size_t size)
  26{
  27        void *ret = malloc(size);
  28        if (!ret && !size)
  29                ret = malloc(1);
  30        if (!ret)
  31                 die("Out of memory");
  32        return ret;
  33}
  34
  35/* MinGW doesn't have wincred.h, so we need to define stuff */
  36
  37typedef struct _CREDENTIAL_ATTRIBUTEW {
  38        LPWSTR Keyword;
  39        DWORD  Flags;
  40        DWORD  ValueSize;
  41        LPBYTE Value;
  42} CREDENTIAL_ATTRIBUTEW, *PCREDENTIAL_ATTRIBUTEW;
  43
  44typedef struct _CREDENTIALW {
  45        DWORD                  Flags;
  46        DWORD                  Type;
  47        LPWSTR                 TargetName;
  48        LPWSTR                 Comment;
  49        FILETIME               LastWritten;
  50        DWORD                  CredentialBlobSize;
  51        LPBYTE                 CredentialBlob;
  52        DWORD                  Persist;
  53        DWORD                  AttributeCount;
  54        PCREDENTIAL_ATTRIBUTEW Attributes;
  55        LPWSTR                 TargetAlias;
  56        LPWSTR                 UserName;
  57} CREDENTIALW, *PCREDENTIALW;
  58
  59#define CRED_TYPE_GENERIC 1
  60#define CRED_PERSIST_LOCAL_MACHINE 2
  61#define CRED_MAX_ATTRIBUTES 64
  62
  63typedef BOOL (WINAPI *CredWriteWT)(PCREDENTIALW, DWORD);
  64typedef BOOL (WINAPI *CredEnumerateWT)(LPCWSTR, DWORD, DWORD *,
  65    PCREDENTIALW **);
  66typedef VOID (WINAPI *CredFreeT)(PVOID);
  67typedef BOOL (WINAPI *CredDeleteWT)(LPCWSTR, DWORD, DWORD);
  68
  69static HMODULE advapi;
  70static CredWriteWT CredWriteW;
  71static CredEnumerateWT CredEnumerateW;
  72static CredFreeT CredFree;
  73static CredDeleteWT CredDeleteW;
  74
  75static void load_cred_funcs(void)
  76{
  77        /* load DLLs */
  78        advapi = LoadLibrary("advapi32.dll");
  79        if (!advapi)
  80                die("failed to load advapi32.dll");
  81
  82        /* get function pointers */
  83        CredWriteW = (CredWriteWT)GetProcAddress(advapi, "CredWriteW");
  84        CredEnumerateW = (CredEnumerateWT)GetProcAddress(advapi,
  85            "CredEnumerateW");
  86        CredFree = (CredFreeT)GetProcAddress(advapi, "CredFree");
  87        CredDeleteW = (CredDeleteWT)GetProcAddress(advapi, "CredDeleteW");
  88        if (!CredWriteW || !CredEnumerateW || !CredFree || !CredDeleteW)
  89                die("failed to load functions");
  90}
  91
  92static WCHAR *wusername, *password, *protocol, *host, *path, target[1024];
  93
  94static void write_item(const char *what, LPCWSTR wbuf, int wlen)
  95{
  96        char *buf;
  97        int len = WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NULL, 0, NULL,
  98            FALSE);
  99        buf = xmalloc(len);
 100
 101        if (!WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, buf, len, NULL, FALSE))
 102                die("WideCharToMultiByte failed!");
 103
 104        printf("%s=", what);
 105        fwrite(buf, 1, len, stdout);
 106        putchar('\n');
 107        free(buf);
 108}
 109
 110/*
 111 * Match an (optional) expected string and a delimiter in the target string,
 112 * consuming the matched text by updating the target pointer.
 113 */
 114static int match_part(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
 115{
 116        LPCWSTR delim_pos, start = *ptarget;
 117        int len;
 118
 119        /* find start of delimiter (or end-of-string if delim is empty) */
 120        if (*delim)
 121                delim_pos = wcsstr(start, delim);
 122        else
 123                delim_pos = start + wcslen(start);
 124
 125        /*
 126         * match text up to delimiter, or end of string (e.g. the '/' after
 127         * host is optional if not followed by a path)
 128         */
 129        if (delim_pos)
 130                len = delim_pos - start;
 131        else
 132                len = wcslen(start);
 133
 134        /* update ptarget if we either found a delimiter or need a match */
 135        if (delim_pos || want)
 136                *ptarget = delim_pos ? delim_pos + wcslen(delim) : start + len;
 137
 138        return !want || (!wcsncmp(want, start, len) && !want[len]);
 139}
 140
 141static int match_cred(const CREDENTIALW *cred)
 142{
 143        LPCWSTR target = cred->TargetName;
 144        if (wusername && wcscmp(wusername, cred->UserName))
 145                return 0;
 146
 147        return match_part(&target, L"git", L":") &&
 148                match_part(&target, protocol, L"://") &&
 149                match_part(&target, wusername, L"@") &&
 150                match_part(&target, host, L"/") &&
 151                match_part(&target, path, L"");
 152}
 153
 154static void get_credential(void)
 155{
 156        CREDENTIALW **creds;
 157        DWORD num_creds;
 158        int i;
 159
 160        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 161                return;
 162
 163        /* search for the first credential that matches username */
 164        for (i = 0; i < num_creds; ++i)
 165                if (match_cred(creds[i])) {
 166                        write_item("username", creds[i]->UserName,
 167                                wcslen(creds[i]->UserName));
 168                        write_item("password",
 169                                (LPCWSTR)creds[i]->CredentialBlob,
 170                                creds[i]->CredentialBlobSize / sizeof(WCHAR));
 171                        break;
 172                }
 173
 174        CredFree(creds);
 175}
 176
 177static void store_credential(void)
 178{
 179        CREDENTIALW cred;
 180
 181        if (!wusername || !password)
 182                return;
 183
 184        cred.Flags = 0;
 185        cred.Type = CRED_TYPE_GENERIC;
 186        cred.TargetName = target;
 187        cred.Comment = L"saved by git-credential-wincred";
 188        cred.CredentialBlobSize = (wcslen(password)) * sizeof(WCHAR);
 189        cred.CredentialBlob = (LPVOID)password;
 190        cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
 191        cred.AttributeCount = 0;
 192        cred.Attributes = NULL;
 193        cred.TargetAlias = NULL;
 194        cred.UserName = wusername;
 195
 196        if (!CredWriteW(&cred, 0))
 197                die("CredWrite failed");
 198}
 199
 200static void erase_credential(void)
 201{
 202        CREDENTIALW **creds;
 203        DWORD num_creds;
 204        int i;
 205
 206        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 207                return;
 208
 209        for (i = 0; i < num_creds; ++i) {
 210                if (match_cred(creds[i]))
 211                        CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0);
 212        }
 213
 214        CredFree(creds);
 215}
 216
 217static WCHAR *utf8_to_utf16_dup(const char *str)
 218{
 219        int wlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
 220        WCHAR *wstr = xmalloc(sizeof(WCHAR) * wlen);
 221        MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, wlen);
 222        return wstr;
 223}
 224
 225static void read_credential(void)
 226{
 227        char buf[1024];
 228
 229        while (fgets(buf, sizeof(buf), stdin)) {
 230                char *v;
 231                int len = strlen(buf);
 232                /* strip trailing CR / LF */
 233                while (len && strchr("\r\n", buf[len - 1]))
 234                        buf[--len] = 0;
 235
 236                if (!*buf)
 237                        break;
 238
 239                v = strchr(buf, '=');
 240                if (!v)
 241                        die("bad input: %s", buf);
 242                *v++ = '\0';
 243
 244                if (!strcmp(buf, "protocol"))
 245                        protocol = utf8_to_utf16_dup(v);
 246                else if (!strcmp(buf, "host"))
 247                        host = utf8_to_utf16_dup(v);
 248                else if (!strcmp(buf, "path"))
 249                        path = utf8_to_utf16_dup(v);
 250                else if (!strcmp(buf, "username")) {
 251                        wusername = utf8_to_utf16_dup(v);
 252                } else if (!strcmp(buf, "password"))
 253                        password = utf8_to_utf16_dup(v);
 254                else
 255                        die("unrecognized input");
 256        }
 257}
 258
 259int main(int argc, char *argv[])
 260{
 261        const char *usage =
 262            "Usage: git credential-wincred <get|store|erase>\n";
 263
 264        if (!argv[1])
 265                die(usage);
 266
 267        /* git use binary pipes to avoid CRLF-issues */
 268        _setmode(_fileno(stdin), _O_BINARY);
 269        _setmode(_fileno(stdout), _O_BINARY);
 270
 271        read_credential();
 272
 273        load_cred_funcs();
 274
 275        if (!protocol || !(host || path))
 276                return 0;
 277
 278        /* prepare 'target', the unique key for the credential */
 279        wcscpy(target, L"git:");
 280        wcsncat(target, protocol, ARRAY_SIZE(target));
 281        wcsncat(target, L"://", ARRAY_SIZE(target));
 282        if (wusername) {
 283                wcsncat(target, wusername, ARRAY_SIZE(target));
 284                wcsncat(target, L"@", ARRAY_SIZE(target));
 285        }
 286        if (host)
 287                wcsncat(target, host, ARRAY_SIZE(target));
 288        if (path) {
 289                wcsncat(target, L"/", ARRAY_SIZE(target));
 290                wcsncat(target, path, ARRAY_SIZE(target));
 291        }
 292
 293        if (!strcmp(argv[1], "get"))
 294                get_credential();
 295        else if (!strcmp(argv[1], "store"))
 296                store_credential();
 297        else if (!strcmp(argv[1], "erase"))
 298                erase_credential();
 299        /* otherwise, ignore unknown action */
 300        return 0;
 301}