File: libmoonshot-msrpc.c

package info (click to toggle)
moonshot-ui 1.1.0+libsecret~2
  • links: PTS
  • area: main
  • in suites: bullseye, sid
  • size: 4,460 kB
  • sloc: ansic: 39,118; sh: 4,682; makefile: 201; sed: 27; xml: 10
file content (457 lines) | stat: -rw-r--r-- 15,677 bytes parent folder | download | duplicates (5)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/* libmoonshot - Moonshot client library
 * Copyright (c) 2011, JANET(UK)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of JANET(UK) nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Author: Sam Thursfield <samthursfield@codethink.co.uk>
 */

#include <windows.h>
//#include <rpc.h>
#include <msrpc-mingw.h>

#include "libmoonshot.h"
#include "libmoonshot-common.h"
#include "moonshot-msrpc.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#define MOONSHOT_ENDPOINT_NAME "/org/janet/Moonshot"
#define MOONSHOT_INSTALL_PATH_KEY "Software\\Moonshot"

void *__RPC_USER MIDL_user_allocate (size_t size) {
    return malloc (size);
}

void __RPC_USER MIDL_user_free (void *data) {
    if (data == NULL)
        return;

    free (data);
}

void moonshot_free (void *data)
{
    free (data);
}

static MoonshotError *moonshot_error_new_from_status (MoonshotErrorCode code,
                                                      DWORD             status)
{
    MoonshotError *error = malloc (sizeof (MoonshotError));
    error->code = code;
    error->message = malloc (256);

    FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, status, 0, (LPSTR)error->message, 255, NULL);
    return error;
}

static MoonshotError *moonshot_error_new_with_status (MoonshotErrorCode code,
                                                      DWORD             status,
                                                      const char        *format, ...)
{
    MoonshotError *error = malloc (sizeof (MoonshotError));
    char *buffer;
    va_list args;
    int length;

    va_start (args, format);

    error->code = code;

    buffer = malloc (strlen (format) + 256 + 3);
    strcpy (buffer, format);
    strcat (buffer, ": ");

    FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
                   NULL,
                   status,
                   0,
                   (LPSTR)buffer + strlen (format) + 3,
                   255,
                   NULL);

    length = _vscprintf (buffer, args);
    error->message = malloc (length + 1);
    _vsnprintf (error->message, length, buffer, args);
    free (buffer);

    va_end (args);

    return error;
}

static void launch_server (MoonshotError **error) {
    HKEY key = NULL;
    STARTUPINFO startup_info = { 0 };
    PROCESS_INFORMATION process_info = { 0 };
    LONG status;
    BOOL success;
    DWORD value_type;
    DWORD length;
    char exe_path[1024];

    status = RegOpenKeyEx (HKEY_LOCAL_MACHINE,
                           MOONSHOT_INSTALL_PATH_KEY,
                           0,
                           KEY_READ,
                           &key);

    if (status == ERROR_FILE_NOT_FOUND) {
        *error = moonshot_error_new
                   (MOONSHOT_ERROR_INSTALLATION_ERROR,
                    "Moonshot is not installed correctly on this system. "
                    "(Registry key HKLM\\%s was not found).",
                    MOONSHOT_INSTALL_PATH_KEY);
        return;
    } else if (status != 0) {
        *error = moonshot_error_new_with_status
                   (MOONSHOT_ERROR_OS_ERROR,
                    status,
                    "Unable to read registry key HKLM\\%s",
                    MOONSHOT_INSTALL_PATH_KEY);
        return;
    }

    length = 1023;
    status = RegQueryValueEx (key, NULL, NULL, &value_type, (LPBYTE )exe_path, &length);

    if (value_type != REG_SZ) {
        *error = moonshot_error_new_with_status
                   (MOONSHOT_ERROR_INSTALLATION_ERROR,
                    status,
                    "Value of registry key HKLM\\%s is invalid. Please set it "
                    "to point to the location of moonshot.exe",
                    MOONSHOT_INSTALL_PATH_KEY);
        return;
    }


    if (status != 0) {
        *error = moonshot_error_new_with_status
                   (MOONSHOT_ERROR_OS_ERROR,
                    status,
                    "Unable to read value of registry key HKLM\\%s",
                    MOONSHOT_INSTALL_PATH_KEY);
        return;
    }

    startup_info.cb = sizeof (startup_info);
    success = CreateProcess (exe_path,
                             NULL,
                             NULL,
                             NULL,
                             TRUE,
                             DETACHED_PROCESS,
                             NULL,
                             NULL,
                             &startup_info, &process_info);

    if (! success) {
        *error = moonshot_error_new_with_status
                   (MOONSHOT_ERROR_UNABLE_TO_START_SERVICE,
                    GetLastError (),
                    "Unable to spawn the moonshot server at '%s'",
                    exe_path);
        return;
    }
}

static void bind_rpc (MoonshotError **error)
{
    DWORD status;
    int   i;

    status = rpc_client_bind (&moonshot_binding_handle,
                              MOONSHOT_ENDPOINT_NAME,
                              RPC_PER_USER);

    if (status != RPC_S_OK) {
        *error = moonshot_error_new_from_status (MOONSHOT_ERROR_IPC_ERROR,
                                                 status);
        return;
    }

    status = RpcMgmtIsServerListening (moonshot_binding_handle);

    if (status == RPC_S_NOT_LISTENING) {
        launch_server (error);

        if (*error != NULL)
            return;

        /* Allow 1 minute for the server to launch before we time out */
        for (i=0; i<600; i++) {
            Sleep (100); /* ms */

            status = RpcMgmtIsServerListening (moonshot_binding_handle);

            if (status == RPC_S_OK)
                return;

            if (status != RPC_S_NOT_LISTENING)
                break;
        }
    }

    if (status != RPC_S_OK)
        *error = moonshot_error_new_from_status (MOONSHOT_ERROR_IPC_ERROR,
                                                 status);
}

static void init_rpc (MoonshotError **error)
{
    static volatile LONG binding_init_flag = 2;

    /* Hack to avoid requiring a moonshot_init() function. Windows does not
     * provide any synchronisation primitives that can be statically init'ed,
     * but we can use its atomic variable access functions to achieve the same.
     * See: http://msdn.microsoft.com/en-us/library/ms684122%28v=vs.85%29.aspx
     */

    if (binding_init_flag == 0)
        return;

    if (InterlockedCompareExchange (&binding_init_flag, 1, 2) == 2) {
        bind_rpc (error);

        /* We'll handle all exceptions locally to avoid interfering with any
         * other RPC/other exception handling that goes on in the process,
         * and so we can store the problem in a MooshotError instead of
         * aborting.
         */
        rpc_set_global_exception_handler_enable (FALSE);

        if (InterlockedCompareExchange (&binding_init_flag, 0, 1) != 1) {
            /* This should never happen */
            fprintf (stderr, "moonshot: Internal synchronisation error");
        }
    } else {
        while (binding_init_flag != 0)
            Sleep (100); /* ms */
    }
}


int moonshot_get_identity (const char     *nai,
                           const char     *password,
                           const char     *service,
                           char          **nai_out,
                           char          **password_out,
                           char          **server_certificate_hash_out,
                           char          **ca_certificate_out,
                           char          **subject_name_constraint_out,
                           char          **subject_alt_name_constraint_out,
                           MoonshotError **error)
{
    int success = FALSE;
    RpcAsyncCall call;

    init_rpc (error);

    if (*error != NULL)
        return FALSE;

    rpc_async_call_init (&call);

    if (nai == NULL) nai = "";
    if (password == NULL) password = "";
    if (service == NULL) service = "";

    *nai_out = NULL;
    *password_out = NULL;
    *server_certificate_hash_out = NULL;
    *ca_certificate_out = NULL;
    *subject_name_constraint_out = NULL;
    *subject_alt_name_constraint_out = NULL;

    RPC_TRY_EXCEPT {
        moonshot_get_identity_rpc (&call,
                                   nai,
                                   password,
                                   service,
                                   nai_out,
                                   password_out,
                                   server_certificate_hash_out,
                                   ca_certificate_out,
                                   subject_name_constraint_out,
                                   subject_alt_name_constraint_out);

        success = rpc_async_call_complete_int (&call);
    }
    RPC_EXCEPT {
        *error = moonshot_error_new_from_status (MOONSHOT_ERROR_IPC_ERROR,
                                                 RPC_GET_EXCEPTION_CODE ());
    }
    RPC_END_EXCEPT

    if (*error != NULL)
        return FALSE;

    if (success == FALSE) {
        *error = moonshot_error_new (MOONSHOT_ERROR_NO_IDENTITY_SELECTED,
                                     "No identity was returned by the Moonshot "
                                     "user interface.");
        return FALSE;
    }

    return TRUE;
}


int moonshot_get_default_identity (char          **nai_out,
                                   char          **password_out,
                                   char          **server_certificate_hash_out,
                                   char          **ca_certificate_out,
                                   char          **subject_name_constraint_out,
                                   char          **subject_alt_name_constraint_out,
                                   MoonshotError **error)
{
    int success = FALSE;
    RpcAsyncCall call;

    init_rpc (error);

    if (*error != NULL)
        return FALSE;

    rpc_async_call_init (&call);

    *nai_out = NULL;
    *password_out = NULL;
    *server_certificate_hash_out = NULL;
    *ca_certificate_out = NULL;
    *subject_name_constraint_out = NULL;
    *subject_alt_name_constraint_out = NULL;

    RPC_TRY_EXCEPT {
        moonshot_get_default_identity_rpc (&call,
                                           nai_out,
                                           password_out,
                                           server_certificate_hash_out,
                                           ca_certificate_out,
                                           subject_name_constraint_out,
                                           subject_alt_name_constraint_out);

        success = rpc_async_call_complete_int (&call);
    }
    RPC_EXCEPT {
        *error = moonshot_error_new_from_status (MOONSHOT_ERROR_IPC_ERROR,
                                                 RPC_GET_EXCEPTION_CODE ());
    }
    RPC_END_EXCEPT

    if (*error != NULL)
        return FALSE;

    if (success == FALSE) {
        *error = moonshot_error_new (MOONSHOT_ERROR_NO_IDENTITY_SELECTED,
                                     "No identity was returned by the Moonshot "
                                     "user interface.");
        return FALSE;
    }

    return TRUE;
};

int moonshot_install_id_card (const char     *display_name,
                              const char     *user_name,
                              const char     *password,
                              const char     *realm,
                              char           *rules_patterns[],
                              int             rules_patterns_length,
                              char           *rules_always_confirm[],
                              int             rules_always_confirm_length,
                              char           *services[],
                              int             services_length,
                              const char     *ca_cert,
                              const char     *subject,
                              const char     *subject_alt,
                              const char     *server_cert,
                              int             force_flat_file_store,
                              MoonshotError **error)
{
    int success = FALSE;

    init_rpc (error);
    if (*error != NULL)
        return FALSE;

    if (user_name == NULL) user_name = "";
    if (password == NULL) password = "";
    if (realm == NULL) realm = "";
    if (ca_cert == NULL) ca_cert = "";
    if (subject == NULL) subject = "";
    if (subject_alt == NULL) subject_alt = "";
    if (server_cert == NULL) server_cert = "";

    RPC_TRY_EXCEPT {
        success = moonshot_install_id_card_rpc (display_name,
                                                user_name,
                                                password,
                                                realm,
                                                rules_patterns,
                                                rules_patterns_length,
                                                rules_always_confirm,
                                                rules_always_confirm_length,
                                                services,
                                                services_length,
                                                ca_cert,
                                                subject,
                                                subject_alt,
                                                server_cert,
                                                force_flat_file_store);
    }
    RPC_EXCEPT {
        *error = moonshot_error_new_from_status (MOONSHOT_ERROR_IPC_ERROR,
                                                 RPC_GET_EXCEPTION_CODE ());
    }
    RPC_END_EXCEPT
    return success;
}

BOOL WINAPI DllMain (HINSTANCE  hinst,
                     DWORD      reason,
                     void      *reserved)
{
    if (reason == DLL_PROCESS_DETACH) {
        /* Process exiting/DLL being unloaded. This is a good
         * opportunity to free the RPC binding.
         *
         * FIXME: we can't use the msrpc-mingw routine for this in case
         * it was already unloaded. I'd love to work out how to link
         * that library statically into libmoonshot-0.dll.
         */
        RpcBindingFree (&moonshot_binding_handle);
    }

    return TRUE;
}