Coverage Report

Created: 2026-10-15 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541/plugins/ua_accesscontrol_default.c
Line
Count
Source
1
/* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
2
 * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
3
 *
4
 *    Copyright 2016-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
5
 *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
6
 *    Copyright 2019 (c) HMS Industrial Networks AB (Author: Jonas Green)
7
 *    Copyright 2026 (c) o6 Automation GmbH (Author: Julius Pfrommer)
8
 */
9
10
#include <open62541/plugin/accesscontrol_default.h>
11
12
#ifdef UA_ENABLE_RBAC
13
/* Internal RBAC API; not declared in public plugin headers. */
14
UA_StatusCode
15
UA_Server_getEffectivePermissions(UA_Server *server,
16
                                  const UA_NodeId *sessionId,
17
                                  const UA_NodeId *nodeId,
18
                                  UA_PermissionType *effectivePermissions);
19
#endif
20
21
/* Example access control management. Anonymous and username / password login.
22
 * The access rights are maximally permissive.
23
 *
24
 * FOR PRODUCTION USE, THIS EXAMPLE PLUGIN SHOULD BE REPLACED WITH LESS
25
 * PERMISSIVE ACCESS CONTROL.
26
 *
27
 * For TransferSubscriptions, we check whether the transfer happens between
28
 * Sessions for the same user. */
29
30
typedef struct {
31
    UA_Boolean allowAnonymous;
32
    size_t usernamePasswordLoginSize;
33
    UA_UsernamePasswordLogin *usernamePasswordLogin;
34
    UA_UsernamePasswordLoginCallback loginCallback;
35
    void *loginContext;
36
    UA_CertificateGroup verifyX509;
37
} AccessControlContext;
38
39
#define ANONYMOUS_POLICY "open62541-anonymous-policy"
40
#define CERTIFICATE_POLICY "open62541-certificate-policy"
41
#define USERNAME_POLICY "open62541-username-policy"
42
43
/************************/
44
/* Access Control Logic */
45
/************************/
46
47
static UA_StatusCode
48
activateSession_default(UA_Server *server, UA_AccessControl *ac,
49
                        const UA_EndpointDescription *endpointDescription,
50
                        const UA_ByteString *secureChannelRemoteCertificate,
51
                        const UA_NodeId *sessionId,
52
                        const UA_ExtensionObject *userIdentityToken,
53
0
                        void **sessionContext) {
54
0
    AccessControlContext *context = (AccessControlContext*)ac->context;
55
56
    /* The empty token is interpreted as anonymous */
57
0
    UA_AnonymousIdentityToken anonToken;
58
0
    UA_ExtensionObject tmpIdentity;
59
0
    if(userIdentityToken->encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
60
0
        UA_AnonymousIdentityToken_init(&anonToken);
61
0
        UA_ExtensionObject_init(&tmpIdentity);
62
0
        UA_ExtensionObject_setValueNoDelete(&tmpIdentity,
63
0
                                            &anonToken,
64
0
                                            &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN]);
65
0
        userIdentityToken = &tmpIdentity;
66
0
    }
67
68
    /* Could the token be decoded? */
69
0
    if(userIdentityToken->encoding != UA_EXTENSIONOBJECT_DECODED &&
70
0
       userIdentityToken->encoding != UA_EXTENSIONOBJECT_DECODED_NODELETE)
71
0
        return UA_STATUSCODE_BADIDENTITYTOKENINVALID;
72
73
0
    const UA_DataType *tokenType = userIdentityToken->content.decoded.type;
74
0
    if(tokenType == &UA_TYPES[UA_TYPES_ANONYMOUSIDENTITYTOKEN]) {
75
        /* Anonymous login */
76
0
        if(!context->allowAnonymous)
77
0
            return UA_STATUSCODE_BADIDENTITYTOKENINVALID;
78
0
        if(context->loginCallback) {
79
0
            UA_StatusCode res =
80
0
                context->loginCallback(&UA_STRING_NULL, &UA_BYTESTRING_NULL,
81
0
                                       context->usernamePasswordLoginSize,
82
0
                                       context->usernamePasswordLogin,
83
0
                                       sessionContext, context->loginContext);
84
0
            if(res != UA_STATUSCODE_GOOD)
85
0
                return UA_STATUSCODE_BADUSERACCESSDENIED;
86
0
        }
87
0
    } else if(tokenType == &UA_TYPES[UA_TYPES_USERNAMEIDENTITYTOKEN]) {
88
        /* Username and password */
89
0
        const UA_UserNameIdentityToken *userToken = (UA_UserNameIdentityToken*)
90
0
            userIdentityToken->content.decoded.data;
91
92
        /* Empty username and password */
93
0
        if(userToken->userName.length == 0 && userToken->password.length == 0)
94
0
            return UA_STATUSCODE_BADIDENTITYTOKENINVALID;
95
96
        /* Try to match username/pw */
97
0
        if(context->loginCallback) {
98
            /* Configured callback */
99
0
            UA_StatusCode res =
100
0
                context->loginCallback(&userToken->userName, &userToken->password,
101
0
                                       context->usernamePasswordLoginSize,
102
0
                                       context->usernamePasswordLogin,
103
0
                                       sessionContext, context->loginContext);
104
0
            if(res != UA_STATUSCODE_GOOD)
105
0
                return UA_STATUSCODE_BADUSERACCESSDENIED;
106
0
        } else {
107
            /* Compare against the configured list  */
108
0
            UA_Boolean match = false;
109
0
            for(size_t i = 0; i < context->usernamePasswordLoginSize; i++) {
110
0
                UA_UsernamePasswordLogin *upl = &context->usernamePasswordLogin[i];
111
0
                if(!UA_String_equal(&userToken->userName, &upl->username))
112
0
                   continue;
113
0
                if(userToken->password.length != upl->password.length)
114
0
                    continue;
115
0
                if(!UA_constantTimeEqual(userToken->password.data,
116
0
                                         upl->password.data,
117
0
                                         upl->password.length))
118
0
                    continue;
119
0
                match = true;
120
0
                break;
121
0
            }
122
0
            if(!match)
123
0
                return UA_STATUSCODE_BADUSERACCESSDENIED;
124
0
        }
125
0
    } else if(tokenType == &UA_TYPES[UA_TYPES_X509IDENTITYTOKEN]) {
126
        /* x509 certificate was already validated against the sessionPKI in the
127
         * server */
128
0
    } else {
129
        /* Unsupported token type */
130
0
        return UA_STATUSCODE_BADIDENTITYTOKENINVALID;
131
0
    }
132
133
    /* Store the endpoint's SecurityPolicyUri as a custom session attribute.
134
     * This is needed later in allowTransferSubscription_default to determine
135
     * whether the session was established over a secure channel. */
136
0
    if(endpointDescription) {
137
0
        UA_Variant spUri;
138
0
        UA_Variant_setScalar(&spUri, (void*)(uintptr_t)&endpointDescription->securityPolicyUri,
139
0
                             &UA_TYPES[UA_TYPES_STRING]);
140
0
        UA_Server_setSessionAttribute(server, sessionId,
141
0
                                      UA_QUALIFIEDNAME(0, "channelSecurityPolicyUri"),
142
0
                                      &spUri);
143
0
    }
144
145
0
    return UA_STATUSCODE_GOOD;
146
0
}
147
148
static void
149
closeSession_default(UA_Server *server, UA_AccessControl *ac,
150
0
                     const UA_NodeId *sessionId, void *sessionContext) {
151
0
}
152
153
/* Map RBAC PermissionType bits to the node's UserWriteMask.
154
 *
155
 * OPC UA Part 3, Table 8 defines three separate permission bits that
156
 * control attribute writing:
157
 *   - WriteAttribute  -> all WriteMask bits EXCEPT RolePermissions
158
 *                        and Historizing (the "catch-all" permission)
159
 *   - WriteRolePermissions -> UA_WRITEMASK_ROLEPERMISSIONS (bit 23)
160
 *   - WriteHistorizing     -> UA_WRITEMASK_HISTORIZING    (bit 9)
161
 *
162
 * 0xFFFFFFFF effectivePerms means "no RBAC restrictions configured" for
163
 * the node, so we return all-bits-set (fully permissive). */
164
static UA_UInt32
165
getUserRightsMask_default(UA_Server *server, UA_AccessControl *ac,
166
                          const UA_NodeId *sessionId, void *sessionContext,
167
0
                          const UA_NodeId *nodeId, void *nodeContext) {
168
#ifdef UA_ENABLE_RBAC
169
    UA_PermissionType effectivePerms = 0;
170
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
171
                                                          nodeId, &effectivePerms);
172
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
173
        return 0xFFFFFFFF;
174
    UA_UInt32 userWriteMask = 0;
175
    if(effectivePerms & UA_PERMISSIONTYPE_WRITEATTRIBUTE) {
176
        /* Grant all attribute-write bits, then carve out the two that
177
         * have their own dedicated permission bits. */
178
        userWriteMask = 0xFFFFFFFF;
179
        userWriteMask &= ~UA_WRITEMASK_ROLEPERMISSIONS;
180
        userWriteMask &= ~UA_WRITEMASK_HISTORIZING;
181
    }
182
    if(effectivePerms & UA_PERMISSIONTYPE_WRITEROLEPERMISSIONS)
183
        userWriteMask |= UA_WRITEMASK_ROLEPERMISSIONS;
184
    if(effectivePerms & UA_PERMISSIONTYPE_WRITEHISTORIZING)
185
        userWriteMask |= UA_WRITEMASK_HISTORIZING;
186
    return userWriteMask;
187
#else
188
0
    return 0xFFFFFFFF;
189
0
#endif
190
0
}
191
192
/* Map RBAC PermissionType bits to the Variable node's UserAccessLevel.
193
 *
194
 * OPC UA Part 3, Table 8 maps:
195
 *   - Read          -> ACCESSLEVELMASK_READ         (bit 0)
196
 *   - Write         -> ACCESSLEVELMASK_WRITE        (bit 1)
197
 *   - ReadHistory   -> ACCESSLEVELMASK_HISTORYREAD  (bit 2)
198
 *   - InsertHistory |
199
 *     ModifyHistory |
200
 *     DeleteHistory -> ACCESSLEVELMASK_HISTORYWRITE (bit 3)
201
 *
202
 * StatusWrite (bit 5) and TimestampWrite (bit 6) are not mapped from
203
 * RBAC permissions — they remain restricted unless the node has no
204
 * RBAC configuration (0xFFFFFFFF). */
205
static UA_Byte
206
getUserAccessLevel_default(UA_Server *server, UA_AccessControl *ac,
207
                           const UA_NodeId *sessionId, void *sessionContext,
208
0
                           const UA_NodeId *nodeId, void *nodeContext) {
209
#ifdef UA_ENABLE_RBAC
210
    UA_PermissionType effectivePerms = 0;
211
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
212
                                                          nodeId, &effectivePerms);
213
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
214
        return 0xFF;
215
    UA_Byte userAccessLevel = 0;
216
    if(effectivePerms & UA_PERMISSIONTYPE_READ)
217
        userAccessLevel |= UA_ACCESSLEVELMASK_READ;
218
    if(effectivePerms & UA_PERMISSIONTYPE_WRITE)
219
        userAccessLevel |= UA_ACCESSLEVELMASK_WRITE;
220
    if(effectivePerms & UA_PERMISSIONTYPE_READHISTORY)
221
        userAccessLevel |= UA_ACCESSLEVELMASK_HISTORYREAD;
222
    if(effectivePerms & (UA_PERMISSIONTYPE_INSERTHISTORY |
223
                         UA_PERMISSIONTYPE_MODIFYHISTORY |
224
                         UA_PERMISSIONTYPE_DELETEHISTORY))
225
        userAccessLevel |= UA_ACCESSLEVELMASK_HISTORYWRITE;
226
    return userAccessLevel;
227
#else
228
0
    return 0xFF;
229
0
#endif
230
0
}
231
232
/* OPC UA Part 3, Table 8: Call permission -> UserExecutable attribute. */
233
static UA_Boolean
234
getUserExecutable_default(UA_Server *server, UA_AccessControl *ac,
235
                          const UA_NodeId *sessionId, void *sessionContext,
236
0
                          const UA_NodeId *methodId, void *methodContext) {
237
#ifdef UA_ENABLE_RBAC
238
    UA_PermissionType effectivePerms = 0;
239
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
240
                                                          methodId, &effectivePerms);
241
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
242
        return true;
243
    return (effectivePerms & UA_PERMISSIONTYPE_CALL) != 0;
244
#else
245
0
    return true;
246
0
#endif
247
0
}
248
249
/* Call permission is checked on both the object and the method node.
250
 * Both must grant CALL for the method invocation to be allowed. */
251
static UA_Boolean
252
getUserExecutableOnObject_default(UA_Server *server, UA_AccessControl *ac,
253
                                  const UA_NodeId *sessionId, void *sessionContext,
254
                                  const UA_NodeId *methodId, void *methodContext,
255
0
                                  const UA_NodeId *objectId, void *objectContext) {
256
#ifdef UA_ENABLE_RBAC
257
    UA_PermissionType objectPerms = 0;
258
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
259
                                                          objectId, &objectPerms);
260
    if(res != UA_STATUSCODE_GOOD)
261
        return true;
262
    if(objectPerms != 0xFFFFFFFF && !(objectPerms & UA_PERMISSIONTYPE_CALL))
263
        return false;
264
    UA_PermissionType methodPerms = 0;
265
    res = UA_Server_getEffectivePermissions(server, sessionId,
266
                                            methodId, &methodPerms);
267
    if(res != UA_STATUSCODE_GOOD)
268
        return true;
269
    if(methodPerms != 0xFFFFFFFF && !(methodPerms & UA_PERMISSIONTYPE_CALL))
270
        return false;
271
    return true;
272
#else
273
0
    return true;
274
0
#endif
275
0
}
276
277
/* AddNode permission is checked on the parent node. */
278
static UA_Boolean
279
allowAddNode_default(UA_Server *server, UA_AccessControl *ac,
280
                     const UA_NodeId *sessionId, void *sessionContext,
281
0
                     const UA_AddNodesItem *item) {
282
#ifdef UA_ENABLE_RBAC
283
    UA_PermissionType effectivePerms = 0;
284
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
285
                                                          &item->parentNodeId.nodeId,
286
                                                          &effectivePerms);
287
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
288
        return true;
289
    return (effectivePerms & UA_PERMISSIONTYPE_ADDNODE) != 0;
290
#else
291
0
    return true;
292
0
#endif
293
0
}
294
295
/* AddReference permission is checked on the source node. */
296
static UA_Boolean
297
allowAddReference_default(UA_Server *server, UA_AccessControl *ac,
298
                          const UA_NodeId *sessionId, void *sessionContext,
299
0
                          const UA_AddReferencesItem *item) {
300
#ifdef UA_ENABLE_RBAC
301
    UA_PermissionType effectivePerms = 0;
302
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
303
                                                          &item->sourceNodeId,
304
                                                          &effectivePerms);
305
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
306
        return true;
307
    return (effectivePerms & UA_PERMISSIONTYPE_ADDREFERENCE) != 0;
308
#else
309
0
    return true;
310
0
#endif
311
0
}
312
313
/* DeleteNode permission is checked on the node itself. */
314
static UA_Boolean
315
allowDeleteNode_default(UA_Server *server, UA_AccessControl *ac,
316
                        const UA_NodeId *sessionId, void *sessionContext,
317
0
                        const UA_DeleteNodesItem *item) {
318
#ifdef UA_ENABLE_RBAC
319
    UA_PermissionType effectivePerms = 0;
320
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
321
                                                          &item->nodeId,
322
                                                          &effectivePerms);
323
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
324
        return true;
325
    return (effectivePerms & UA_PERMISSIONTYPE_DELETENODE) != 0;
326
#else
327
0
    return true;
328
0
#endif
329
0
}
330
331
/* RemoveReference permission is checked on the source node. */
332
static UA_Boolean
333
allowDeleteReference_default(UA_Server *server, UA_AccessControl *ac,
334
                             const UA_NodeId *sessionId, void *sessionContext,
335
0
                             const UA_DeleteReferencesItem *item) {
336
#ifdef UA_ENABLE_RBAC
337
    UA_PermissionType effectivePerms = 0;
338
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
339
                                                          &item->sourceNodeId,
340
                                                          &effectivePerms);
341
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
342
        return true;
343
    return (effectivePerms & UA_PERMISSIONTYPE_REMOVEREFERENCE) != 0;
344
#else
345
0
    return true;
346
0
#endif
347
0
}
348
349
/* OPC UA Part 3, Table 8: Browse permission. */
350
static UA_Boolean
351
allowBrowseNode_default(UA_Server *server, UA_AccessControl *ac,
352
                        const UA_NodeId *sessionId, void *sessionContext,
353
0
                        const UA_NodeId *nodeId, void *nodeContext) {
354
#ifdef UA_ENABLE_RBAC
355
    UA_PermissionType effectivePerms = 0;
356
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
357
                                                          nodeId, &effectivePerms);
358
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
359
        return true;
360
    return (effectivePerms & UA_PERMISSIONTYPE_BROWSE) != 0;
361
#else
362
0
    return true;
363
0
#endif
364
0
}
365
366
#ifdef UA_ENABLE_SUBSCRIPTIONS
367
static UA_Boolean
368
allowCreateSubscription_default(UA_Server *server, UA_AccessControl *ac,
369
0
                                const UA_NodeId *sessionId, void *sessionContext) {
370
0
    return true;
371
0
}
372
373
static UA_Boolean
374
allowTransferSubscription_default(UA_Server *server, UA_AccessControl *ac,
375
                                  const UA_NodeId *oldSessionId, void *oldSessionContext,
376
0
                                  const UA_NodeId *newSessionId, void *newSessionContext) {
377
    /* A detached Subscription (no old Session). The server only calls this
378
     * after it has verified that the new Session has the identity of the
379
     * Session the Subscription was detached from. */
380
0
    if(!oldSessionId)
381
0
        return true;
382
383
    /* Get clientUserId for both sessions */
384
0
    UA_Variant session1UserId;
385
0
    UA_Variant_init(&session1UserId);
386
0
    UA_Server_getSessionAttribute(server, oldSessionId,
387
0
                                  UA_QUALIFIEDNAME(0, "clientUserId"),
388
0
                                  &session1UserId);
389
0
    UA_Variant session2UserId;
390
0
    UA_Variant_init(&session2UserId);
391
0
    UA_Server_getSessionAttribute(server, newSessionId,
392
0
                                  UA_QUALIFIEDNAME(0, "clientUserId"),
393
0
                                  &session2UserId);
394
395
    /* clientUserId is always a String type */
396
0
    UA_Boolean result = false;
397
0
    if(session1UserId.type == &UA_TYPES[UA_TYPES_STRING] &&
398
0
       session2UserId.type == &UA_TYPES[UA_TYPES_STRING]) {
399
0
        UA_String *userId1 = (UA_String*)session1UserId.data;
400
0
        UA_String *userId2 = (UA_String*)session2UserId.data;
401
        
402
0
        if(userId1->length == 0 && userId2->length == 0) {
403
            /* Both users are anonymous.
404
             * For anonymous users, the OPC UA specification requires
405
             * checking the ApplicationUri from the clientDescription
406
             * to verify that the same application is transferring the
407
             * subscription (e.g. after a network interruption or client
408
             * crash with reconnect on a different SecureChannel).
409
             *
410
             * Additionally, on unsecure connections (SecurityPolicy#None)
411
             * the ApplicationUri is not verified against a certificate,
412
             * so the transfer must be rejected. */
413
414
            /* First check: Both sessions must use a secure channel
415
             * (not SecurityPolicy#None). The securityPolicyUri was
416
             * stored as a session attribute during ActivateSession. */
417
0
            UA_Variant session1SpUri;
418
0
            UA_Variant_init(&session1SpUri);
419
0
            UA_Server_getSessionAttribute(server, oldSessionId,
420
0
                                          UA_QUALIFIEDNAME(0, "channelSecurityPolicyUri"),
421
0
                                          &session1SpUri);
422
0
            UA_Variant session2SpUri;
423
0
            UA_Variant_init(&session2SpUri);
424
0
            UA_Server_getSessionAttribute(server, newSessionId,
425
0
                                          UA_QUALIFIEDNAME(0, "channelSecurityPolicyUri"),
426
0
                                          &session2SpUri);
427
428
0
            UA_Boolean bothSecure = false;
429
0
            if(session1SpUri.type == &UA_TYPES[UA_TYPES_STRING] &&
430
0
               session2SpUri.type == &UA_TYPES[UA_TYPES_STRING]) {
431
0
                UA_String *spUri1 = (UA_String*)session1SpUri.data;
432
0
                UA_String *spUri2 = (UA_String*)session2SpUri.data;
433
                /* Reject if either session uses SecurityPolicy#None */
434
0
                if(!UA_String_equal(spUri1, &UA_SECURITY_POLICY_NONE_URI) &&
435
0
                   !UA_String_equal(spUri2, &UA_SECURITY_POLICY_NONE_URI)) {
436
0
                    bothSecure = true;
437
0
                }
438
0
            }
439
440
0
            UA_Variant_clear(&session1SpUri);
441
0
            UA_Variant_clear(&session2SpUri);
442
443
            /* Second check: If both channels are secure, compare the
444
             * ApplicationUri from the clientDescription. On secure
445
             * connections the ApplicationUri is validated against
446
             * the client certificate during CreateSession. */
447
0
            if(bothSecure) {
448
0
                UA_Variant session1Desc;
449
0
                UA_Variant_init(&session1Desc);
450
0
                UA_Server_getSessionAttribute(server, oldSessionId,
451
0
                                              UA_QUALIFIEDNAME(0, "clientDescription"),
452
0
                                              &session1Desc);
453
0
                UA_Variant session2Desc;
454
0
                UA_Variant_init(&session2Desc);
455
0
                UA_Server_getSessionAttribute(server, newSessionId,
456
0
                                              UA_QUALIFIEDNAME(0, "clientDescription"),
457
0
                                              &session2Desc);
458
459
0
                if(session1Desc.type == &UA_TYPES[UA_TYPES_APPLICATIONDESCRIPTION] &&
460
0
                   session2Desc.type == &UA_TYPES[UA_TYPES_APPLICATIONDESCRIPTION]) {
461
0
                    UA_ApplicationDescription *desc1 =
462
0
                        (UA_ApplicationDescription*)session1Desc.data;
463
0
                    UA_ApplicationDescription *desc2 =
464
0
                        (UA_ApplicationDescription*)session2Desc.data;
465
0
                    if(desc1->applicationUri.length > 0 &&
466
0
                       desc2->applicationUri.length > 0 &&
467
0
                       UA_String_equal(&desc1->applicationUri,
468
0
                                       &desc2->applicationUri)) {
469
0
                        result = true;
470
0
                    }
471
0
                }
472
473
0
                UA_Variant_clear(&session1Desc);
474
0
                UA_Variant_clear(&session2Desc);
475
0
            }
476
0
        } else if(UA_String_equal(userId1, userId2)) {
477
            /* Same authenticated user - allow transfer */
478
0
            result = true;
479
0
        }
480
0
    }
481
    
482
0
    UA_Variant_clear(&session1UserId);
483
0
    UA_Variant_clear(&session2UserId);
484
    
485
0
    return result;
486
0
}
487
#endif
488
489
#ifdef UA_ENABLE_HISTORIZING
490
/* OPC UA Part 3, Table 8: InsertHistory / ModifyHistory permissions.
491
 * INSERT -> InsertHistory, REPLACE/UPDATE -> ModifyHistory. */
492
static UA_Boolean
493
allowHistoryUpdateUpdateData_default(UA_Server *server, UA_AccessControl *ac,
494
                                     const UA_NodeId *sessionId, void *sessionContext,
495
                                     const UA_NodeId *nodeId,
496
                                     UA_PerformUpdateType performInsertReplace,
497
0
                                     const UA_DataValue *value) {
498
#ifdef UA_ENABLE_RBAC
499
    UA_PermissionType effectivePerms = 0;
500
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
501
                                                          nodeId, &effectivePerms);
502
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
503
        return true;
504
    if(performInsertReplace == UA_PERFORMUPDATETYPE_INSERT)
505
        return (effectivePerms & UA_PERMISSIONTYPE_INSERTHISTORY) != 0;
506
    else if(performInsertReplace == UA_PERFORMUPDATETYPE_REPLACE ||
507
            performInsertReplace == UA_PERFORMUPDATETYPE_UPDATE)
508
        return (effectivePerms & UA_PERMISSIONTYPE_MODIFYHISTORY) != 0;
509
    return true;
510
#else
511
0
    return true;
512
0
#endif
513
0
}
514
515
/* OPC UA Part 3, Table 8: DeleteHistory permission. */
516
static UA_Boolean
517
allowHistoryUpdateDeleteRawModified_default(UA_Server *server, UA_AccessControl *ac,
518
                                            const UA_NodeId *sessionId, void *sessionContext,
519
                                            const UA_NodeId *nodeId,
520
                                            UA_DateTime startTimestamp,
521
                                            UA_DateTime endTimestamp,
522
0
                                            bool isDeleteModified) {
523
#ifdef UA_ENABLE_RBAC
524
    UA_PermissionType effectivePerms = 0;
525
    UA_StatusCode res = UA_Server_getEffectivePermissions(server, sessionId,
526
                                                          nodeId, &effectivePerms);
527
    if(res != UA_STATUSCODE_GOOD || effectivePerms == 0xFFFFFFFF)
528
        return true;
529
    return (effectivePerms & UA_PERMISSIONTYPE_DELETEHISTORY) != 0;
530
#else
531
0
    return true;
532
0
#endif
533
0
}
534
#endif
535
536
/***************************************/
537
/* Create Delete Access Control Plugin */
538
/***************************************/
539
540
0
static void clear_default(UA_AccessControl *ac) {
541
0
    UA_Array_delete((void*)(uintptr_t)ac->userTokenPolicies,
542
0
                    ac->userTokenPoliciesSize,
543
0
                    &UA_TYPES[UA_TYPES_USERTOKENPOLICY]);
544
0
    ac->userTokenPolicies = NULL;
545
0
    ac->userTokenPoliciesSize = 0;
546
547
0
    AccessControlContext *context = (AccessControlContext*)ac->context;
548
549
0
    if (context) {
550
0
        for(size_t i = 0; i < context->usernamePasswordLoginSize; i++) {
551
0
            UA_String_clear(&context->usernamePasswordLogin[i].username);
552
0
            UA_ByteString_clear(&context->usernamePasswordLogin[i].password);
553
0
        }
554
0
        if(context->usernamePasswordLoginSize > 0)
555
0
            UA_free(context->usernamePasswordLogin);
556
557
0
        UA_free(ac->context);
558
0
        ac->context = NULL;
559
0
    }
560
0
}
561
562
UA_StatusCode
563
UA_AccessControl_default(UA_ServerConfig *config,
564
                         UA_Boolean allowAnonymous,
565
                         const UA_String *userTokenPolicyUri,
566
                         size_t usernamePasswordLoginSize,
567
0
                         const UA_UsernamePasswordLogin *usernamePasswordLogin) {
568
0
    UA_LOG_WARNING(config->logging, UA_LOGCATEGORY_SERVER,
569
0
                   "AccessControl: Unconfigured AccessControl. Users have all permissions.");
570
0
    UA_AccessControl *ac = &config->accessControl;
571
572
0
    if(ac->clear)
573
0
        ac->clear(ac);
574
575
0
    ac->clear = clear_default;
576
0
    ac->activateSession = activateSession_default;
577
0
    ac->closeSession = closeSession_default;
578
0
    ac->getUserRightsMask = getUserRightsMask_default;
579
0
    ac->getUserAccessLevel = getUserAccessLevel_default;
580
0
    ac->getUserExecutable = getUserExecutable_default;
581
0
    ac->getUserExecutableOnObject = getUserExecutableOnObject_default;
582
0
    ac->allowAddNode = allowAddNode_default;
583
0
    ac->allowAddReference = allowAddReference_default;
584
0
    ac->allowBrowseNode = allowBrowseNode_default;
585
586
0
#ifdef UA_ENABLE_SUBSCRIPTIONS
587
0
    ac->allowCreateSubscription = allowCreateSubscription_default;
588
0
    ac->allowTransferSubscription = allowTransferSubscription_default;
589
0
#endif
590
591
0
#ifdef UA_ENABLE_HISTORIZING
592
0
    ac->allowHistoryUpdateUpdateData = allowHistoryUpdateUpdateData_default;
593
0
    ac->allowHistoryUpdateDeleteRawModified = allowHistoryUpdateDeleteRawModified_default;
594
0
#endif
595
596
0
    ac->allowDeleteNode = allowDeleteNode_default;
597
0
    ac->allowDeleteReference = allowDeleteReference_default;
598
599
0
    AccessControlContext *context = (AccessControlContext*)
600
0
            UA_malloc(sizeof(AccessControlContext));
601
0
    if(!context)
602
0
        return UA_STATUSCODE_BADOUTOFMEMORY;
603
0
    memset(context, 0, sizeof(AccessControlContext));
604
0
    ac->context = context;
605
606
    /* Allow anonymous? */
607
0
    context->allowAnonymous = allowAnonymous;
608
0
    if(allowAnonymous) {
609
0
        UA_LOG_INFO(config->logging, UA_LOGCATEGORY_SERVER,
610
0
                    "AccessControl: Anonymous login is enabled");
611
0
    }
612
613
    /* Copy username/password to the access control plugin */
614
0
    if(usernamePasswordLoginSize > 0) {
615
0
        context->usernamePasswordLogin = (UA_UsernamePasswordLogin*)
616
0
            UA_malloc(usernamePasswordLoginSize * sizeof(UA_UsernamePasswordLogin));
617
0
        if(!context->usernamePasswordLogin)
618
0
            return UA_STATUSCODE_BADOUTOFMEMORY;
619
0
        context->usernamePasswordLoginSize = usernamePasswordLoginSize;
620
0
        for(size_t i = 0; i < usernamePasswordLoginSize; i++) {
621
0
            UA_String_copy(&usernamePasswordLogin[i].username,
622
0
                           &context->usernamePasswordLogin[i].username);
623
0
            UA_ByteString_copy(&usernamePasswordLogin[i].password,
624
0
                           &context->usernamePasswordLogin[i].password);
625
0
        }
626
0
    }
627
628
0
    size_t numOfPolcies = 1;
629
0
    if(!userTokenPolicyUri) {
630
0
        if(config->securityPoliciesSize > 0)
631
0
            numOfPolcies = config->securityPoliciesSize;
632
0
        else {
633
0
            UA_LOG_WARNING(config->logging, UA_LOGCATEGORY_SERVER,
634
0
                           "No security policies defined for the secure channel.");
635
0
            return UA_STATUSCODE_BADINTERNALERROR;
636
0
        }
637
0
    }
638
639
    /* Set the allowed policies */
640
0
    size_t policies = 0;
641
0
    if(allowAnonymous)
642
0
        policies++;
643
0
    if(usernamePasswordLoginSize > 0)
644
0
        policies++;
645
0
    if(config->sessionPKI.verifyCertificate)
646
0
        policies++;
647
0
    ac->userTokenPoliciesSize = 0;
648
0
    ac->userTokenPolicies = (UA_UserTokenPolicy *)
649
0
        UA_Array_new(policies * numOfPolcies, &UA_TYPES[UA_TYPES_USERTOKENPOLICY]);
650
0
    if(!ac->userTokenPolicies)
651
0
        return UA_STATUSCODE_BADOUTOFMEMORY;
652
0
    ac->userTokenPoliciesSize = policies * numOfPolcies;
653
654
0
    if(policies == 0) {
655
0
        UA_LOG_WARNING(config->logging, UA_LOGCATEGORY_SERVER,
656
0
                       "No allowed policies set.");
657
0
        return UA_STATUSCODE_GOOD;
658
0
    }
659
660
0
    const UA_String *utpUri = NULL;
661
0
    policies = 0;
662
0
    for(size_t i = 0; i < numOfPolcies; i++) {
663
0
        if(userTokenPolicyUri) {
664
0
            utpUri = userTokenPolicyUri;
665
0
        } else {
666
0
            utpUri = &config->securityPolicies[i].policyUri;
667
0
        }
668
0
        if(allowAnonymous) {
669
0
            ac->userTokenPolicies[policies].tokenType = UA_USERTOKENTYPE_ANONYMOUS;
670
0
            ac->userTokenPolicies[policies].policyId = UA_STRING_ALLOC(ANONYMOUS_POLICY);
671
0
            UA_String_copy(utpUri,
672
0
                               &ac->userTokenPolicies[policies].securityPolicyUri);
673
0
            policies++;
674
0
        }
675
676
0
        if(config->sessionPKI.verifyCertificate) {
677
0
            ac->userTokenPolicies[policies].tokenType = UA_USERTOKENTYPE_CERTIFICATE;
678
0
            ac->userTokenPolicies[policies].policyId = UA_STRING_ALLOC(CERTIFICATE_POLICY);
679
#if UA_LOGLEVEL <= 400
680
            if(UA_String_equal(utpUri, &UA_SECURITY_POLICY_NONE_URI)) {
681
                UA_LOG_WARNING(config->logging, UA_LOGCATEGORY_SERVER,
682
                               "x509 Certificate Authentication configured, "
683
                               "but no encrypting SecurityPolicy. "
684
                               "This can leak credentials on the network.");
685
            }
686
#endif
687
0
            UA_String_copy(utpUri,
688
0
                               &ac->userTokenPolicies[policies].securityPolicyUri);
689
0
            policies++;
690
0
        }
691
692
0
        if(usernamePasswordLoginSize > 0) {
693
0
            ac->userTokenPolicies[policies].tokenType = UA_USERTOKENTYPE_USERNAME;
694
0
            ac->userTokenPolicies[policies].policyId = UA_STRING_ALLOC(USERNAME_POLICY);
695
#if UA_LOGLEVEL <= 400
696
            if(UA_String_equal(utpUri, &UA_SECURITY_POLICY_NONE_URI)) {
697
                UA_LOG_WARNING(config->logging, UA_LOGCATEGORY_SERVER,
698
                               "Username/Password Authentication configured, "
699
                               "but no encrypting SecurityPolicy. "
700
                               "This can leak credentials on the network.");
701
            }
702
#endif
703
0
            UA_String_copy(utpUri,
704
0
                               &ac->userTokenPolicies[policies].securityPolicyUri);
705
0
            policies++;
706
0
        }
707
0
    }
708
0
    return UA_STATUSCODE_GOOD;
709
0
}
710
711
UA_StatusCode
712
UA_AccessControl_defaultWithLoginCallback(UA_ServerConfig *config,
713
                                          UA_Boolean allowAnonymous,
714
                                          const UA_String *userTokenPolicyUri,
715
                                          size_t usernamePasswordLoginSize,
716
                                          const UA_UsernamePasswordLogin *usernamePasswordLogin,
717
                                          UA_UsernamePasswordLoginCallback loginCallback,
718
0
                                          void *loginContext) {
719
0
    AccessControlContext *context;
720
0
    UA_StatusCode sc =
721
0
        UA_AccessControl_default(config, allowAnonymous, userTokenPolicyUri,
722
0
                                 usernamePasswordLoginSize, usernamePasswordLogin);
723
0
    if(sc != UA_STATUSCODE_GOOD)
724
0
        return sc;
725
726
0
    context = (AccessControlContext *)config->accessControl.context;
727
0
    context->loginCallback = loginCallback;
728
0
    context->loginContext = loginContext;
729
730
0
    return UA_STATUSCODE_GOOD;
731
0
}