xref: /btstack/3rd-party/lwip/core/src/apps/snmp/snmp_msg.c (revision 97dc5e692c7d94a280158af58036a0efee5b0e56)
1 /**
2  * @file
3  * SNMP message processing (RFC1157).
4  */
5 
6 /*
7  * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
8  * Copyright (c) 2016 Elias Oenal.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * Author: Christiaan Simons <[email protected]>
34  *         Martin Hentschel <[email protected]>
35  *         Elias Oenal <[email protected]>
36  */
37 
38 #include "lwip/apps/snmp_opts.h"
39 
40 #if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */
41 
42 #include "snmp_msg.h"
43 #include "snmp_asn1.h"
44 #include "snmp_core_priv.h"
45 #include "lwip/ip_addr.h"
46 #include "lwip/stats.h"
47 
48 #if LWIP_SNMP_V3
49 #include "lwip/apps/snmpv3.h"
50 #include "snmpv3_priv.h"
51 #ifdef LWIP_HOOK_FILENAME
52 #include LWIP_HOOK_FILENAME
53 #endif
54 #endif
55 
56 #include <string.h>
57 
58 #define SNMP_V3_AUTH_FLAG      0x01
59 #define SNMP_V3_PRIV_FLAG      0x02
60 
61 /* Security levels */
62 #define SNMP_V3_NOAUTHNOPRIV   0x00
63 #define SNMP_V3_AUTHNOPRIV     SNMP_V3_AUTH_FLAG
64 #define SNMP_V3_AUTHPRIV       (SNMP_V3_AUTH_FLAG | SNMP_V3_PRIV_FLAG)
65 
66 /* public (non-static) constants */
67 /** SNMP community string */
68 const char *snmp_community = SNMP_COMMUNITY;
69 /** SNMP community string for write access */
70 const char *snmp_community_write = SNMP_COMMUNITY_WRITE;
71 /** SNMP community string for sending traps */
72 const char *snmp_community_trap = SNMP_COMMUNITY_TRAP;
73 
74 snmp_write_callback_fct snmp_write_callback;
75 void *snmp_write_callback_arg;
76 
77 snmp_inform_callback_fct snmp_inform_callback;
78 void *snmp_inform_callback_arg;
79 
80 #if LWIP_SNMP_CONFIGURE_VERSIONS
81 
82 static u8_t v1_enabled = 1;
83 static u8_t v2c_enabled = 1;
84 static u8_t v3_enabled = 1;
85 
86 static u8_t
snmp_version_enabled(u8_t version)87 snmp_version_enabled(u8_t version)
88 {
89   if (version == SNMP_VERSION_1) {
90     return v1_enabled;
91   } else if (version == SNMP_VERSION_2c) {
92     return v2c_enabled;
93   }
94 #if LWIP_SNMP_V3
95   else if (version == SNMP_VERSION_3) {
96     return v3_enabled;
97   }
98 #endif
99   else {
100     LWIP_ASSERT("Invalid SNMP version", 0);
101     return 0;
102   }
103 }
104 
105 u8_t
snmp_v1_enabled(void)106 snmp_v1_enabled(void)
107 {
108   return snmp_version_enabled(SNMP_VERSION_1);
109 }
110 
111 u8_t
snmp_v2c_enabled(void)112 snmp_v2c_enabled(void)
113 {
114   return snmp_version_enabled(SNMP_VERSION_2c);
115 }
116 
117 u8_t
snmp_v3_enabled(void)118 snmp_v3_enabled(void)
119 {
120   return snmp_version_enabled(SNMP_VERSION_3);
121 }
122 
123 static void
snmp_version_enable(u8_t version,u8_t enable)124 snmp_version_enable(u8_t version, u8_t enable)
125 {
126   if (version == SNMP_VERSION_1) {
127     v1_enabled = enable;
128   } else if (version == SNMP_VERSION_2c) {
129     v2c_enabled = enable;
130   }
131 #if LWIP_SNMP_V3
132   else if (version == SNMP_VERSION_3) {
133     v3_enabled = enable;
134   }
135 #endif
136   else {
137     LWIP_ASSERT("Invalid SNMP version", 0);
138   }
139 }
140 
141 void
snmp_v1_enable(u8_t enable)142 snmp_v1_enable(u8_t enable)
143 {
144   snmp_version_enable(SNMP_VERSION_1, enable);
145 }
146 
147 void
snmp_v2c_enable(u8_t enable)148 snmp_v2c_enable(u8_t enable)
149 {
150   snmp_version_enable(SNMP_VERSION_2c, enable);
151 }
152 
153 void
snmp_v3_enable(u8_t enable)154 snmp_v3_enable(u8_t enable)
155 {
156   snmp_version_enable(SNMP_VERSION_3, enable);
157 }
158 
159 #endif
160 
161 /**
162  * @ingroup snmp_core
163  * Returns current SNMP community string.
164  * @return current SNMP community string
165  */
166 const char *
snmp_get_community(void)167 snmp_get_community(void)
168 {
169   return snmp_community;
170 }
171 
172 /**
173  * @ingroup snmp_core
174  * Sets SNMP community string.
175  * The string itself (its storage) must be valid throughout the whole life of
176  * program (or until it is changed to sth else).
177  *
178  * @param community is a pointer to new community string
179  */
180 void
snmp_set_community(const char * const community)181 snmp_set_community(const char *const community)
182 {
183   LWIP_ASSERT_CORE_LOCKED();
184   LWIP_ASSERT("community string is too long!", strlen(community) <= SNMP_MAX_COMMUNITY_STR_LEN);
185   snmp_community = community;
186 }
187 
188 /**
189  * @ingroup snmp_core
190  * Returns current SNMP write-access community string.
191  * @return current SNMP write-access community string
192  */
193 const char *
snmp_get_community_write(void)194 snmp_get_community_write(void)
195 {
196   return snmp_community_write;
197 }
198 
199 /**
200  * @ingroup snmp_traps
201  * Returns current SNMP community string used for sending traps.
202  * @return current SNMP community string used for sending traps
203  */
204 const char *
snmp_get_community_trap(void)205 snmp_get_community_trap(void)
206 {
207   return snmp_community_trap;
208 }
209 
210 /**
211  * @ingroup snmp_core
212  * Sets SNMP community string for write-access.
213  * The string itself (its storage) must be valid throughout the whole life of
214  * program (or until it is changed to sth else).
215  *
216  * @param community is a pointer to new write-access community string
217  */
218 void
snmp_set_community_write(const char * const community)219 snmp_set_community_write(const char *const community)
220 {
221   LWIP_ASSERT_CORE_LOCKED();
222   LWIP_ASSERT("community string must not be NULL", community != NULL);
223   LWIP_ASSERT("community string is too long!", strlen(community) <= SNMP_MAX_COMMUNITY_STR_LEN);
224   snmp_community_write = community;
225 }
226 
227 /**
228  * @ingroup snmp_traps
229  * Sets SNMP community string used for sending traps.
230  * The string itself (its storage) must be valid throughout the whole life of
231  * program (or until it is changed to sth else).
232  *
233  * @param community is a pointer to new trap community string
234  */
235 void
snmp_set_community_trap(const char * const community)236 snmp_set_community_trap(const char *const community)
237 {
238   LWIP_ASSERT_CORE_LOCKED();
239   LWIP_ASSERT("community string is too long!", strlen(community) <= SNMP_MAX_COMMUNITY_STR_LEN);
240   snmp_community_trap = community;
241 }
242 
243 /**
244  * @ingroup snmp_core
245  * Callback fired on every successful write access
246  */
247 void
snmp_set_write_callback(snmp_write_callback_fct write_callback,void * callback_arg)248 snmp_set_write_callback(snmp_write_callback_fct write_callback, void *callback_arg)
249 {
250   LWIP_ASSERT_CORE_LOCKED();
251   snmp_write_callback     = write_callback;
252   snmp_write_callback_arg = callback_arg;
253 }
254 
255 /**
256  * @ingroup snmp_core
257  * Callback fired on every received INFORM confirmation (get-response)
258  */
259 void
snmp_set_inform_callback(snmp_inform_callback_fct inform_callback,void * callback_arg)260 snmp_set_inform_callback(snmp_inform_callback_fct inform_callback, void* callback_arg)
261 {
262   snmp_inform_callback     = inform_callback;
263   snmp_inform_callback_arg = callback_arg;
264 }
265 
266 /* ----------------------------------------------------------------------- */
267 /* forward declarations */
268 /* ----------------------------------------------------------------------- */
269 
270 static err_t snmp_process_get_request(struct snmp_request *request);
271 static err_t snmp_process_getnext_request(struct snmp_request *request);
272 static err_t snmp_process_getbulk_request(struct snmp_request *request);
273 static err_t snmp_process_set_request(struct snmp_request *request);
274 
275 static err_t snmp_parse_inbound_frame(struct snmp_request *request);
276 static err_t snmp_prepare_outbound_frame(struct snmp_request *request);
277 static err_t snmp_complete_outbound_frame(struct snmp_request *request);
278 static void snmp_execute_write_callbacks(struct snmp_request *request);
279 
280 
281 /* ----------------------------------------------------------------------- */
282 /* implementation */
283 /* ----------------------------------------------------------------------- */
284 
285 void
snmp_receive(void * handle,struct pbuf * p,const ip_addr_t * source_ip,u16_t port)286 snmp_receive(void *handle, struct pbuf *p, const ip_addr_t *source_ip, u16_t port)
287 {
288   err_t err;
289   struct snmp_request request;
290 
291   memset(&request, 0, sizeof(request));
292   request.handle       = handle;
293   request.source_ip    = source_ip;
294   request.source_port  = port;
295   request.inbound_pbuf = p;
296 
297   snmp_stats.inpkts++;
298 
299   err = snmp_parse_inbound_frame(&request);
300   if (err == ERR_OK) {
301     if (request.request_type == SNMP_ASN1_CONTEXT_PDU_GET_RESP) {
302       if (request.error_status == SNMP_ERR_NOERROR) {
303         /* If callback function has been defined call it. */
304         if (snmp_inform_callback != NULL) {
305           snmp_inform_callback(&request, snmp_inform_callback_arg);
306         }
307       }
308       /* stop further handling of GET RESP PDU, we are an agent */
309       return;
310     }
311     err = snmp_prepare_outbound_frame(&request);
312     if (err == ERR_OK) {
313 
314       if (request.error_status == SNMP_ERR_NOERROR) {
315         /* only process frame if we do not already have an error to return (e.g. all readonly) */
316         if (request.request_type == SNMP_ASN1_CONTEXT_PDU_GET_REQ) {
317           err = snmp_process_get_request(&request);
318         } else if (request.request_type == SNMP_ASN1_CONTEXT_PDU_GET_NEXT_REQ) {
319           err = snmp_process_getnext_request(&request);
320         } else if (request.request_type == SNMP_ASN1_CONTEXT_PDU_GET_BULK_REQ) {
321           err = snmp_process_getbulk_request(&request);
322         } else if (request.request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ) {
323           err = snmp_process_set_request(&request);
324         }
325       }
326 #if LWIP_SNMP_V3
327       else {
328         struct snmp_varbind vb;
329 
330         vb.next = NULL;
331         vb.prev = NULL;
332         vb.type = SNMP_ASN1_TYPE_COUNTER32;
333         vb.value_len = sizeof(u32_t);
334 
335         switch (request.error_status) {
336           case SNMP_ERR_AUTHORIZATIONERROR: {
337             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 };
338             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
339             vb.value = &snmp_stats.wrongdigests;
340           }
341           break;
342           case SNMP_ERR_UNKNOWN_ENGINEID: {
343             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 };
344             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
345             vb.value = &snmp_stats.unknownengineids;
346           }
347           break;
348           case SNMP_ERR_UNKNOWN_SECURITYNAME: {
349             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 };
350             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
351             vb.value = &snmp_stats.unknownusernames;
352           }
353           break;
354           case SNMP_ERR_UNSUPPORTED_SECLEVEL: {
355             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 };
356             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
357             vb.value = &snmp_stats.unsupportedseclevels;
358           }
359           break;
360           case SNMP_ERR_NOTINTIMEWINDOW: {
361             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 };
362             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
363             vb.value = &snmp_stats.notintimewindows;
364           }
365           break;
366           case SNMP_ERR_DECRYIPTION_ERROR: {
367             static const u32_t oid[] = { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 };
368             snmp_oid_assign(&vb.oid, oid, LWIP_ARRAYSIZE(oid));
369             vb.value = &snmp_stats.decryptionerrors;
370           }
371           break;
372           default:
373             /* Unknown or unhandled error_status */
374             err = ERR_ARG;
375         }
376 
377         if (err == ERR_OK) {
378           snmp_append_outbound_varbind(&(request.outbound_pbuf_stream), &vb);
379           request.error_status = SNMP_ERR_NOERROR;
380         }
381 
382         request.request_out_type = (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_REPORT);
383         request.request_id = request.msg_id;
384       }
385 #endif
386 
387       if (err == ERR_OK) {
388         err = snmp_complete_outbound_frame(&request);
389 
390         if (err == ERR_OK) {
391           err = snmp_sendto(request.handle, request.outbound_pbuf, request.source_ip, request.source_port);
392 
393           if ((request.request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ)
394               && (request.error_status == SNMP_ERR_NOERROR)
395               && (snmp_write_callback != NULL)) {
396             /* raise write notification for all written objects */
397             snmp_execute_write_callbacks(&request);
398           }
399         }
400       }
401     }
402 
403     if (request.outbound_pbuf != NULL) {
404       pbuf_free(request.outbound_pbuf);
405     }
406   }
407 }
408 
409 static u8_t
snmp_msg_getnext_validate_node_inst(struct snmp_node_instance * node_instance,void * validate_arg)410 snmp_msg_getnext_validate_node_inst(struct snmp_node_instance *node_instance, void *validate_arg)
411 {
412   if (((node_instance->access & SNMP_NODE_INSTANCE_ACCESS_READ) != SNMP_NODE_INSTANCE_ACCESS_READ) || (node_instance->get_value == NULL)) {
413     return SNMP_ERR_NOSUCHINSTANCE;
414   }
415 
416 #if LWIP_HAVE_INT64
417   if ((node_instance->asn1_type == SNMP_ASN1_TYPE_COUNTER64) && (((struct snmp_request *)validate_arg)->version == SNMP_VERSION_1)) {
418     /* according to RFC 2089 skip Counter64 objects in GetNext requests from v1 clients */
419     return SNMP_ERR_NOSUCHINSTANCE;
420   }
421 #endif
422 
423   return SNMP_ERR_NOERROR;
424 }
425 
426 static void
snmp_process_varbind(struct snmp_request * request,struct snmp_varbind * vb,u8_t get_next)427 snmp_process_varbind(struct snmp_request *request, struct snmp_varbind *vb, u8_t get_next)
428 {
429   err_t err;
430   struct snmp_node_instance node_instance;
431   memset(&node_instance, 0, sizeof(node_instance));
432 
433   if (get_next) {
434     struct snmp_obj_id result_oid;
435     request->error_status = snmp_get_next_node_instance_from_oid(vb->oid.id, vb->oid.len, snmp_msg_getnext_validate_node_inst, request,  &result_oid, &node_instance);
436 
437     if (request->error_status == SNMP_ERR_NOERROR) {
438       snmp_oid_assign(&vb->oid, result_oid.id, result_oid.len);
439     }
440   } else {
441     request->error_status = snmp_get_node_instance_from_oid(vb->oid.id, vb->oid.len, &node_instance);
442 
443     if (request->error_status == SNMP_ERR_NOERROR) {
444       /* use 'getnext_validate' method for validation to avoid code duplication (some checks have to be executed here) */
445       request->error_status = snmp_msg_getnext_validate_node_inst(&node_instance, request);
446 
447       if (request->error_status != SNMP_ERR_NOERROR) {
448         if (node_instance.release_instance != NULL) {
449           node_instance.release_instance(&node_instance);
450         }
451       }
452     }
453   }
454 
455   if (request->error_status != SNMP_ERR_NOERROR)  {
456     if (request->error_status >= SNMP_VARBIND_EXCEPTION_OFFSET) {
457       if ((request->version == SNMP_VERSION_2c) || request->version == SNMP_VERSION_3) {
458         /* in SNMP v2c a varbind related exception is stored in varbind and not in frame header */
459         vb->type = (SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_CLASS_CONTEXT | (request->error_status & SNMP_VARBIND_EXCEPTION_MASK));
460         vb->value_len = 0;
461 
462         err = snmp_append_outbound_varbind(&(request->outbound_pbuf_stream), vb);
463         if (err == ERR_OK) {
464           /* we stored the exception in varbind -> go on */
465           request->error_status = SNMP_ERR_NOERROR;
466         } else if (err == ERR_BUF) {
467           request->error_status = SNMP_ERR_TOOBIG;
468         } else {
469           request->error_status = SNMP_ERR_GENERROR;
470         }
471       }
472     } else {
473       /* according to RFC 1157/1905, all other errors only return genError */
474       request->error_status = SNMP_ERR_GENERROR;
475     }
476   } else {
477     s16_t len = node_instance.get_value(&node_instance, vb->value);
478 
479     if (len >= 0) {
480       vb->value_len = (u16_t)len; /* cast is OK because we checked >= 0 above */
481       vb->type = node_instance.asn1_type;
482 
483       LWIP_ASSERT("SNMP_MAX_VALUE_SIZE is configured too low", (vb->value_len & ~SNMP_GET_VALUE_RAW_DATA) <= SNMP_MAX_VALUE_SIZE);
484       err = snmp_append_outbound_varbind(&request->outbound_pbuf_stream, vb);
485 
486       if (err == ERR_BUF) {
487         request->error_status = SNMP_ERR_TOOBIG;
488       } else if (err != ERR_OK) {
489         request->error_status = SNMP_ERR_GENERROR;
490       }
491     } else {
492       request->error_status = SNMP_ERR_GENERROR;
493     }
494 
495     if (node_instance.release_instance != NULL) {
496       node_instance.release_instance(&node_instance);
497     }
498   }
499 }
500 
501 
502 /**
503  * Service an internal or external event for SNMP GET.
504  *
505  * @param request points to the associated message process state
506  */
507 static err_t
snmp_process_get_request(struct snmp_request * request)508 snmp_process_get_request(struct snmp_request *request)
509 {
510   snmp_vb_enumerator_err_t err;
511   struct snmp_varbind vb;
512   vb.value = request->value_buffer;
513 
514   LWIP_DEBUGF(SNMP_DEBUG, ("SNMP get request\n"));
515 
516   while (request->error_status == SNMP_ERR_NOERROR) {
517     err = snmp_vb_enumerator_get_next(&request->inbound_varbind_enumerator, &vb);
518     if (err == SNMP_VB_ENUMERATOR_ERR_OK) {
519       if ((vb.type == SNMP_ASN1_TYPE_NULL) && (vb.value_len == 0)) {
520         snmp_process_varbind(request, &vb, 0);
521       } else {
522         request->error_status = SNMP_ERR_GENERROR;
523       }
524     } else if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
525       /* no more varbinds in request */
526       break;
527     } else if (err == SNMP_VB_ENUMERATOR_ERR_ASN1ERROR) {
528       /* malformed ASN.1, don't answer */
529       return ERR_ARG;
530     } else {
531       request->error_status = SNMP_ERR_GENERROR;
532     }
533   }
534 
535   return ERR_OK;
536 }
537 
538 /**
539  * Service an internal or external event for SNMP GET.
540  *
541  * @param request points to the associated message process state
542  */
543 static err_t
snmp_process_getnext_request(struct snmp_request * request)544 snmp_process_getnext_request(struct snmp_request *request)
545 {
546   snmp_vb_enumerator_err_t err;
547   struct snmp_varbind vb;
548   vb.value = request->value_buffer;
549 
550   LWIP_DEBUGF(SNMP_DEBUG, ("SNMP get-next request\n"));
551 
552   while (request->error_status == SNMP_ERR_NOERROR) {
553     err = snmp_vb_enumerator_get_next(&request->inbound_varbind_enumerator, &vb);
554     if (err == SNMP_VB_ENUMERATOR_ERR_OK) {
555       if ((vb.type == SNMP_ASN1_TYPE_NULL) && (vb.value_len == 0)) {
556         snmp_process_varbind(request, &vb, 1);
557       } else {
558         request->error_status = SNMP_ERR_GENERROR;
559       }
560     } else if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
561       /* no more varbinds in request */
562       break;
563     } else if (err == SNMP_VB_ENUMERATOR_ERR_ASN1ERROR) {
564       /* malformed ASN.1, don't answer */
565       return ERR_ARG;
566     } else {
567       request->error_status = SNMP_ERR_GENERROR;
568     }
569   }
570 
571   return ERR_OK;
572 }
573 
574 /**
575  * Service an internal or external event for SNMP GETBULKT.
576  *
577  * @param request points to the associated message process state
578  */
579 static err_t
snmp_process_getbulk_request(struct snmp_request * request)580 snmp_process_getbulk_request(struct snmp_request *request)
581 {
582   snmp_vb_enumerator_err_t err;
583   s32_t non_repeaters     = request->non_repeaters;
584   s32_t repetitions;
585   u16_t repetition_offset = 0;
586   struct snmp_varbind_enumerator repetition_varbind_enumerator;
587   struct snmp_varbind vb;
588   vb.value = request->value_buffer;
589 
590   if (SNMP_LWIP_GETBULK_MAX_REPETITIONS > 0) {
591     repetitions = LWIP_MIN(request->max_repetitions, SNMP_LWIP_GETBULK_MAX_REPETITIONS);
592   } else {
593     repetitions = request->max_repetitions;
594   }
595 
596   LWIP_DEBUGF(SNMP_DEBUG, ("SNMP get-bulk request\n"));
597 
598   /* process non repeaters and first repetition */
599   while (request->error_status == SNMP_ERR_NOERROR) {
600     if (non_repeaters == 0) {
601       repetition_offset = request->outbound_pbuf_stream.offset;
602 
603       if (repetitions == 0) {
604         /* do not resolve repeaters when repetitions is set to 0 */
605         break;
606       }
607       repetitions--;
608     }
609 
610     err = snmp_vb_enumerator_get_next(&request->inbound_varbind_enumerator, &vb);
611     if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
612       /* no more varbinds in request */
613       break;
614     } else if (err == SNMP_VB_ENUMERATOR_ERR_ASN1ERROR) {
615       /* malformed ASN.1, don't answer */
616       return ERR_ARG;
617     } else if ((err != SNMP_VB_ENUMERATOR_ERR_OK) || (vb.type != SNMP_ASN1_TYPE_NULL) || (vb.value_len != 0)) {
618       request->error_status = SNMP_ERR_GENERROR;
619     } else {
620       snmp_process_varbind(request, &vb, 1);
621       non_repeaters--;
622     }
623   }
624 
625   /* process repetitions > 1 */
626   while ((request->error_status == SNMP_ERR_NOERROR) && (repetitions > 0) && (request->outbound_pbuf_stream.offset != repetition_offset)) {
627 
628     u8_t all_endofmibview = 1;
629 
630     snmp_vb_enumerator_init(&repetition_varbind_enumerator, request->outbound_pbuf, repetition_offset, request->outbound_pbuf_stream.offset - repetition_offset);
631     repetition_offset = request->outbound_pbuf_stream.offset; /* for next loop */
632 
633     while (request->error_status == SNMP_ERR_NOERROR) {
634       vb.value = NULL; /* do NOT decode value (we enumerate outbound buffer here, so all varbinds have values assigned) */
635       err = snmp_vb_enumerator_get_next(&repetition_varbind_enumerator, &vb);
636       if (err == SNMP_VB_ENUMERATOR_ERR_OK) {
637         vb.value = request->value_buffer;
638         snmp_process_varbind(request, &vb, 1);
639 
640         if (request->error_status != SNMP_ERR_NOERROR) {
641           /* already set correct error-index (here it cannot be taken from inbound varbind enumerator) */
642           request->error_index = request->non_repeaters + repetition_varbind_enumerator.varbind_count;
643         } else if (vb.type != (SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTEXT_VARBIND_END_OF_MIB_VIEW)) {
644           all_endofmibview = 0;
645         }
646       } else if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
647         /* no more varbinds in request */
648         break;
649       } else {
650         LWIP_DEBUGF(SNMP_DEBUG, ("Very strange, we cannot parse the varbind output that we created just before!"));
651         request->error_status = SNMP_ERR_GENERROR;
652         request->error_index  = request->non_repeaters + repetition_varbind_enumerator.varbind_count;
653       }
654     }
655 
656     if ((request->error_status == SNMP_ERR_NOERROR) && all_endofmibview) {
657       /* stop when all varbinds in a loop return EndOfMibView */
658       break;
659     }
660 
661     repetitions--;
662   }
663 
664   if (request->error_status == SNMP_ERR_TOOBIG) {
665     /* for GetBulk it is ok, if not all requested variables fit into the response -> just return the varbinds added so far */
666     request->error_status = SNMP_ERR_NOERROR;
667   }
668 
669   return ERR_OK;
670 }
671 
672 /**
673  * Service an internal or external event for SNMP SET.
674  *
675  * @param request points to the associated message process state
676  */
677 static err_t
snmp_process_set_request(struct snmp_request * request)678 snmp_process_set_request(struct snmp_request *request)
679 {
680   snmp_vb_enumerator_err_t err;
681   struct snmp_varbind vb;
682   vb.value = request->value_buffer;
683 
684   LWIP_DEBUGF(SNMP_DEBUG, ("SNMP set request\n"));
685 
686   /* perform set test on all objects */
687   while (request->error_status == SNMP_ERR_NOERROR) {
688     err = snmp_vb_enumerator_get_next(&request->inbound_varbind_enumerator, &vb);
689     if (err == SNMP_VB_ENUMERATOR_ERR_OK) {
690       struct snmp_node_instance node_instance;
691       memset(&node_instance, 0, sizeof(node_instance));
692 
693       request->error_status = snmp_get_node_instance_from_oid(vb.oid.id, vb.oid.len, &node_instance);
694       if (request->error_status == SNMP_ERR_NOERROR) {
695         if (node_instance.asn1_type != vb.type) {
696           request->error_status = SNMP_ERR_WRONGTYPE;
697         } else if (((node_instance.access & SNMP_NODE_INSTANCE_ACCESS_WRITE) != SNMP_NODE_INSTANCE_ACCESS_WRITE) || (node_instance.set_value == NULL)) {
698           request->error_status = SNMP_ERR_NOTWRITABLE;
699         } else {
700           if (node_instance.set_test != NULL) {
701             request->error_status = node_instance.set_test(&node_instance, vb.value_len, vb.value);
702           }
703         }
704 
705         if (node_instance.release_instance != NULL) {
706           node_instance.release_instance(&node_instance);
707         }
708       }
709     } else if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
710       /* no more varbinds in request */
711       break;
712     } else if (err == SNMP_VB_ENUMERATOR_ERR_INVALIDLENGTH) {
713       request->error_status = SNMP_ERR_WRONGLENGTH;
714     } else if (err == SNMP_VB_ENUMERATOR_ERR_ASN1ERROR) {
715       /* malformed ASN.1, don't answer */
716       return ERR_ARG;
717     } else {
718       request->error_status = SNMP_ERR_GENERROR;
719     }
720   }
721 
722   /* perform real set operation on all objects */
723   if (request->error_status == SNMP_ERR_NOERROR) {
724     snmp_vb_enumerator_init(&request->inbound_varbind_enumerator, request->inbound_pbuf, request->inbound_varbind_offset, request->inbound_varbind_len);
725     while (request->error_status == SNMP_ERR_NOERROR) {
726       err = snmp_vb_enumerator_get_next(&request->inbound_varbind_enumerator, &vb);
727       if (err == SNMP_VB_ENUMERATOR_ERR_OK) {
728         struct snmp_node_instance node_instance;
729         memset(&node_instance, 0, sizeof(node_instance));
730         request->error_status = snmp_get_node_instance_from_oid(vb.oid.id, vb.oid.len, &node_instance);
731         if (request->error_status == SNMP_ERR_NOERROR) {
732           if (node_instance.set_value(&node_instance, vb.value_len, vb.value) != SNMP_ERR_NOERROR) {
733             if (request->inbound_varbind_enumerator.varbind_count == 1) {
734               request->error_status = SNMP_ERR_COMMITFAILED;
735             } else {
736               /* we cannot undo the set operations done so far */
737               request->error_status = SNMP_ERR_UNDOFAILED;
738             }
739           }
740 
741           if (node_instance.release_instance != NULL) {
742             node_instance.release_instance(&node_instance);
743           }
744         }
745       } else if (err == SNMP_VB_ENUMERATOR_ERR_EOVB) {
746         /* no more varbinds in request */
747         break;
748       } else {
749         /* first time enumerating varbinds work but second time not, although nothing should have changed in between ??? */
750         request->error_status = SNMP_ERR_GENERROR;
751       }
752     }
753   }
754 
755   return ERR_OK;
756 }
757 
758 #define PARSE_EXEC(code, retValue) \
759   if ((code) != ERR_OK) { \
760     LWIP_DEBUGF(SNMP_DEBUG, ("Malformed ASN.1 detected.\n")); \
761     snmp_stats.inasnparseerrs++; \
762     return retValue; \
763   }
764 
765 #define PARSE_ASSERT(cond, retValue) \
766   if (!(cond)) { \
767     LWIP_DEBUGF(SNMP_DEBUG, ("SNMP parse assertion failed!: " # cond)); \
768     snmp_stats.inasnparseerrs++; \
769     return retValue; \
770   }
771 
772 #define BUILD_EXEC(code, retValue) \
773   if ((code) != ERR_OK) { \
774     LWIP_DEBUGF(SNMP_DEBUG, ("SNMP error during creation of outbound frame!: " # code)); \
775     return retValue; \
776   }
777 
778 #define IF_PARSE_EXEC(code)   PARSE_EXEC(code, ERR_ARG)
779 #define IF_PARSE_ASSERT(code) PARSE_ASSERT(code, ERR_ARG)
780 
781 /**
782  * Checks and decodes incoming SNMP message header, logs header errors.
783  *
784  * @param request points to the current message request state return
785  * @return
786  * - ERR_OK SNMP header is sane and accepted
787  * - ERR_VAL SNMP header is either malformed or rejected
788  */
789 static err_t
snmp_parse_inbound_frame(struct snmp_request * request)790 snmp_parse_inbound_frame(struct snmp_request *request)
791 {
792   struct snmp_pbuf_stream pbuf_stream;
793   struct snmp_asn1_tlv tlv;
794   s32_t parent_tlv_value_len;
795   s32_t s32_value;
796   err_t err;
797 #if LWIP_SNMP_V3
798   snmpv3_auth_algo_t auth;
799   snmpv3_priv_algo_t priv;
800 #endif
801 
802   IF_PARSE_EXEC(snmp_pbuf_stream_init(&pbuf_stream, request->inbound_pbuf, 0, request->inbound_pbuf->tot_len));
803 
804   /* decode main container consisting of version, community and PDU */
805   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
806   IF_PARSE_ASSERT((tlv.type == SNMP_ASN1_TYPE_SEQUENCE) && (tlv.value_len == pbuf_stream.length));
807   parent_tlv_value_len = tlv.value_len;
808 
809   /* decode version */
810   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
811   IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
812   parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
813   IF_PARSE_ASSERT(parent_tlv_value_len > 0);
814 
815   IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
816 
817   if (((s32_value != SNMP_VERSION_1) &&
818        (s32_value != SNMP_VERSION_2c)
819 #if LWIP_SNMP_V3
820        && (s32_value != SNMP_VERSION_3)
821 #endif
822       )
823 #if LWIP_SNMP_CONFIGURE_VERSIONS
824       || (!snmp_version_enabled(s32_value))
825 #endif
826      ) {
827     /* unsupported SNMP version */
828     snmp_stats.inbadversions++;
829     return ERR_ARG;
830   }
831   request->version = (u8_t)s32_value;
832 
833 #if LWIP_SNMP_V3
834   if (request->version == SNMP_VERSION_3) {
835     u16_t u16_value;
836     u16_t inbound_msgAuthenticationParameters_offset;
837 
838     /* SNMPv3 doesn't use communities */
839     /* @todo: Differentiate read/write access */
840     strncpy((char *)request->community, snmp_community, SNMP_MAX_COMMUNITY_STR_LEN);
841     request->community[SNMP_MAX_COMMUNITY_STR_LEN] = 0; /* ensure NULL termination (strncpy does NOT guarantee it!) */
842     request->community_strlen = (u16_t)strlen((char *)request->community);
843 
844     /* RFC3414 globalData */
845     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
846     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_SEQUENCE);
847     parent_tlv_value_len -= SNMP_ASN1_TLV_HDR_LENGTH(tlv);
848     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
849 
850     /* decode msgID */
851     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
852     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
853     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
854     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
855 
856     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
857     request->msg_id = s32_value;
858 
859     /* decode msgMaxSize */
860     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
861     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
862     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
863     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
864 
865     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
866     request->msg_max_size = s32_value;
867 
868     /* decode msgFlags */
869     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
870     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
871     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
872     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
873 
874     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
875     request->msg_flags = (u8_t)s32_value;
876 
877     /* decode msgSecurityModel */
878     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
879     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
880     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
881     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
882 
883     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
884     request->msg_security_model = s32_value;
885 
886     /* RFC3414 msgSecurityParameters
887      * The User-based Security Model defines the contents of the OCTET
888      * STRING as a SEQUENCE.
889      *
890      * We skip the protective dummy OCTET STRING header
891      * to access the SEQUENCE header.
892      */
893     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
894     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
895     parent_tlv_value_len -= SNMP_ASN1_TLV_HDR_LENGTH(tlv);
896     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
897 
898     /* msgSecurityParameters SEQUENCE header */
899     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
900     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_SEQUENCE);
901     parent_tlv_value_len -= SNMP_ASN1_TLV_HDR_LENGTH(tlv);
902     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
903 
904     /* decode msgAuthoritativeEngineID */
905     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
906     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
907     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
908     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
909 
910     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->msg_authoritative_engine_id,
911                                     &u16_value, SNMP_V3_MAX_ENGINE_ID_LENGTH));
912     request->msg_authoritative_engine_id_len = (u8_t)u16_value;
913 
914     /* msgAuthoritativeEngineBoots */
915     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
916     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
917     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
918     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
919     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->msg_authoritative_engine_boots));
920 
921     /* msgAuthoritativeEngineTime */
922     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
923     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
924     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
925     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
926     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->msg_authoritative_engine_time));
927 
928     /* msgUserName */
929     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
930     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
931     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
932     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
933 
934     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->msg_user_name,
935                                     &u16_value, SNMP_V3_MAX_USER_LENGTH));
936     request->msg_user_name_len = (u8_t)u16_value;
937 
938     /* msgAuthenticationParameters */
939     memset(request->msg_authentication_parameters, 0, SNMP_V3_MAX_AUTH_PARAM_LENGTH);
940     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
941     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
942     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
943     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
944     /* Remember position */
945     inbound_msgAuthenticationParameters_offset = pbuf_stream.offset;
946     LWIP_UNUSED_ARG(inbound_msgAuthenticationParameters_offset);
947     /* Read auth parameters */
948     /* IF_PARSE_ASSERT(tlv.value_len <= SNMP_V3_MAX_AUTH_PARAM_LENGTH); */
949     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->msg_authentication_parameters,
950                                     &u16_value, tlv.value_len));
951     request->msg_authentication_parameters_len = (u8_t)u16_value;
952 
953     /* msgPrivacyParameters */
954     memset(request->msg_privacy_parameters, 0, SNMP_V3_MAX_PRIV_PARAM_LENGTH);
955     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
956     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
957     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
958     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
959 
960     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->msg_privacy_parameters,
961                                     &u16_value, SNMP_V3_MAX_PRIV_PARAM_LENGTH));
962     request->msg_privacy_parameters_len = (u8_t)u16_value;
963 
964     /* validate securityParameters here (do this after decoding because we don't want to increase other counters for wrong frames)
965      * 1) securityParameters was correctly serialized if we reach here.
966      * 2) securityParameters are already cached.
967      * 3) if msgAuthoritativeEngineID is unknown, zero-length or too long:
968          b) https://tools.ietf.org/html/rfc3414#section-7
969      */
970     {
971       const char *eid;
972       u8_t eid_len;
973 
974       snmpv3_get_engine_id(&eid, &eid_len);
975 
976       if ((request->msg_authoritative_engine_id_len == 0) ||
977           (request->msg_authoritative_engine_id_len != eid_len) ||
978           (memcmp(eid, request->msg_authoritative_engine_id, eid_len) != 0)) {
979         snmp_stats.unknownengineids++;
980         request->msg_flags = 0; /* noauthnopriv */
981         request->error_status = SNMP_ERR_UNKNOWN_ENGINEID;
982         return ERR_OK;
983       }
984     }
985 
986     /* 4) verify username */
987     if (snmpv3_get_user((char *)request->msg_user_name, &auth, NULL, &priv, NULL)) {
988       snmp_stats.unknownusernames++;
989       request->msg_flags = 0; /* noauthnopriv */
990       request->error_status = SNMP_ERR_UNKNOWN_SECURITYNAME;
991       return ERR_OK;
992     }
993 
994     /* 5) verify security level */
995     switch (request->msg_flags & (SNMP_V3_AUTH_FLAG | SNMP_V3_PRIV_FLAG)) {
996       case SNMP_V3_NOAUTHNOPRIV:
997         if ((auth != SNMP_V3_AUTH_ALGO_INVAL) || (priv != SNMP_V3_PRIV_ALGO_INVAL)) {
998           /* Invalid security level for user */
999           snmp_stats.unsupportedseclevels++;
1000           request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1001           request->error_status = SNMP_ERR_UNSUPPORTED_SECLEVEL;
1002           return ERR_OK;
1003         }
1004         break;
1005 #if LWIP_SNMP_V3_CRYPTO
1006       case SNMP_V3_AUTHNOPRIV:
1007         if ((auth == SNMP_V3_AUTH_ALGO_INVAL) || (priv != SNMP_V3_PRIV_ALGO_INVAL)) {
1008           /* Invalid security level for user */
1009           snmp_stats.unsupportedseclevels++;
1010           request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1011           request->error_status = SNMP_ERR_UNSUPPORTED_SECLEVEL;
1012           return ERR_OK;
1013         }
1014         break;
1015       case SNMP_V3_AUTHPRIV:
1016         if ((auth == SNMP_V3_AUTH_ALGO_INVAL) || (priv == SNMP_V3_PRIV_ALGO_INVAL)) {
1017           /* Invalid security level for user */
1018           snmp_stats.unsupportedseclevels++;
1019           request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1020           request->error_status = SNMP_ERR_UNSUPPORTED_SECLEVEL;
1021           return ERR_OK;
1022         }
1023         break;
1024 #endif
1025       default:
1026         snmp_stats.unsupportedseclevels++;
1027         request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1028         request->error_status = SNMP_ERR_UNSUPPORTED_SECLEVEL;
1029         return ERR_OK;
1030     }
1031 
1032     /* 6) if securitylevel specifies authentication, authenticate message. */
1033 #if LWIP_SNMP_V3_CRYPTO
1034     if (request->msg_flags & SNMP_V3_AUTH_FLAG) {
1035       const u8_t zero_arr[SNMP_V3_MAX_AUTH_PARAM_LENGTH] = { 0 };
1036       u8_t key[20];
1037       u8_t hmac[LWIP_MAX(SNMP_V3_SHA_LEN, SNMP_V3_MD5_LEN)];
1038       struct snmp_pbuf_stream auth_stream;
1039 
1040       if (request->msg_authentication_parameters_len > SNMP_V3_MAX_AUTH_PARAM_LENGTH) {
1041         snmp_stats.wrongdigests++;
1042         request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1043         request->error_status = SNMP_ERR_AUTHORIZATIONERROR;
1044         return ERR_OK;
1045       }
1046 
1047       /* Rewind stream */
1048       IF_PARSE_EXEC(snmp_pbuf_stream_init(&auth_stream, request->inbound_pbuf, 0, request->inbound_pbuf->tot_len));
1049       IF_PARSE_EXEC(snmp_pbuf_stream_seek_abs(&auth_stream, inbound_msgAuthenticationParameters_offset));
1050       /* Set auth parameters to zero for verification */
1051       IF_PARSE_EXEC(snmp_asn1_enc_raw(&auth_stream, zero_arr, request->msg_authentication_parameters_len));
1052 
1053       /* Verify authentication */
1054       IF_PARSE_EXEC(snmp_pbuf_stream_init(&auth_stream, request->inbound_pbuf, 0, request->inbound_pbuf->tot_len));
1055 
1056       IF_PARSE_EXEC(snmpv3_get_user((char *)request->msg_user_name, &auth, key, NULL, NULL));
1057       IF_PARSE_EXEC(snmpv3_auth(&auth_stream, request->inbound_pbuf->tot_len, key, auth, hmac));
1058 
1059       if (memcmp(request->msg_authentication_parameters, hmac, SNMP_V3_MAX_AUTH_PARAM_LENGTH)) {
1060         snmp_stats.wrongdigests++;
1061         request->msg_flags = SNMP_V3_NOAUTHNOPRIV;
1062         request->error_status = SNMP_ERR_AUTHORIZATIONERROR;
1063         return ERR_OK;
1064       }
1065 
1066       /* 7) if securitylevel specifies authentication, verify engineboots, enginetime and lastenginetime */
1067       {
1068         s32_t boots = snmpv3_get_engine_boots_internal();
1069         if ((request->msg_authoritative_engine_boots != boots) || (boots == 2147483647UL)) {
1070           snmp_stats.notintimewindows++;
1071           request->msg_flags = SNMP_V3_AUTHNOPRIV;
1072           request->error_status = SNMP_ERR_NOTINTIMEWINDOW;
1073           return ERR_OK;
1074         }
1075       }
1076       {
1077         s32_t time = snmpv3_get_engine_time_internal();
1078         if (request->msg_authoritative_engine_time > (time + 150)) {
1079           snmp_stats.notintimewindows++;
1080           request->msg_flags = SNMP_V3_AUTHNOPRIV;
1081           request->error_status = SNMP_ERR_NOTINTIMEWINDOW;
1082           return ERR_OK;
1083         } else if (time > 150) {
1084           if (request->msg_authoritative_engine_time < (time - 150)) {
1085             snmp_stats.notintimewindows++;
1086             request->msg_flags = SNMP_V3_AUTHNOPRIV;
1087             request->error_status = SNMP_ERR_NOTINTIMEWINDOW;
1088             return ERR_OK;
1089           }
1090         }
1091       }
1092     }
1093 #endif
1094 
1095     /* 8) if securitylevel specifies privacy, decrypt message. */
1096 #if LWIP_SNMP_V3_CRYPTO
1097     if (request->msg_flags & SNMP_V3_PRIV_FLAG) {
1098       /* Decrypt message */
1099 
1100       u8_t key[20];
1101 
1102       IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1103       IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
1104       parent_tlv_value_len -= SNMP_ASN1_TLV_HDR_LENGTH(tlv);
1105       IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1106 
1107       IF_PARSE_EXEC(snmpv3_get_user((char *)request->msg_user_name, NULL, NULL, &priv, key));
1108       if (snmpv3_crypt(&pbuf_stream, tlv.value_len, key,
1109                        request->msg_privacy_parameters, request->msg_authoritative_engine_boots,
1110                        request->msg_authoritative_engine_time, priv, SNMP_V3_PRIV_MODE_DECRYPT) != ERR_OK) {
1111         snmp_stats.decryptionerrors++;
1112         request->msg_flags = SNMP_V3_AUTHNOPRIV;
1113         request->error_status = SNMP_ERR_DECRYIPTION_ERROR;
1114         return ERR_OK;
1115       }
1116     }
1117 #endif
1118     /* 9) calculate max size of scoped pdu?
1119      * 10) securityname for user is retrieved from usertable?
1120      * 11) security data is cached?
1121      * 12)
1122      */
1123 
1124     /* Scoped PDU
1125      * Encryption context
1126      */
1127     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1128     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_SEQUENCE);
1129     parent_tlv_value_len -= SNMP_ASN1_TLV_HDR_LENGTH(tlv);
1130     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1131 
1132     /* contextEngineID */
1133     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1134     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
1135     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1136     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1137 
1138     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->context_engine_id,
1139                                     &u16_value, SNMP_V3_MAX_ENGINE_ID_LENGTH));
1140     request->context_engine_id_len = (u8_t)u16_value;
1141     /* TODO: do we need to verify this contextengineid too? */
1142 
1143     /* contextName */
1144     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1145     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
1146     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1147     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1148 
1149     IF_PARSE_EXEC(snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->context_name,
1150                                     &u16_value, SNMP_V3_MAX_ENGINE_ID_LENGTH));
1151     request->context_name_len = (u8_t)u16_value;
1152     /* TODO: do we need to verify this contextname too? */
1153   } else
1154 #endif
1155   {
1156     /* decode community */
1157     IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1158     IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_OCTET_STRING);
1159     parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1160     IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1161 
1162     err = snmp_asn1_dec_raw(&pbuf_stream, tlv.value_len, request->community, &request->community_strlen, SNMP_MAX_COMMUNITY_STR_LEN);
1163     if (err == ERR_MEM) {
1164       /* community string does not fit in our buffer -> its too long -> its invalid */
1165       request->community_strlen = 0;
1166       snmp_pbuf_stream_seek(&pbuf_stream, tlv.value_len);
1167     } else {
1168       IF_PARSE_ASSERT(err == ERR_OK);
1169     }
1170     /* add zero terminator */
1171     request->community[request->community_strlen] = 0;
1172   }
1173 
1174   /* decode PDU type (next container level) */
1175   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1176   IF_PARSE_ASSERT(tlv.value_len <= pbuf_stream.length);
1177   request->inbound_padding_len = pbuf_stream.length - tlv.value_len;
1178   parent_tlv_value_len = tlv.value_len;
1179 
1180   /* validate PDU type */
1181   switch (tlv.type) {
1182     case (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_GET_REQ):
1183       /* GetRequest PDU */
1184       snmp_stats.ingetrequests++;
1185       break;
1186     case (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_GET_NEXT_REQ):
1187       /* GetNextRequest PDU */
1188       snmp_stats.ingetnexts++;
1189       break;
1190     case (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_GET_BULK_REQ):
1191       /* GetBulkRequest PDU */
1192       if (request->version < SNMP_VERSION_2c) {
1193         /* RFC2089: invalid, drop packet */
1194         return ERR_ARG;
1195       }
1196       break;
1197     case (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_SET_REQ):
1198       /* SetRequest PDU */
1199       snmp_stats.insetrequests++;
1200       break;
1201     case (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_GET_RESP):
1202       /* GetResponse PDU */
1203       snmp_stats.ingetresponses++;
1204       break;
1205     default:
1206       /* unsupported input PDU for this agent (no parse error) */
1207       LWIP_DEBUGF(SNMP_DEBUG, ("Unknown/Invalid SNMP PDU type received: %d", tlv.type)); \
1208       return ERR_ARG;
1209   }
1210   request->request_type = tlv.type & SNMP_ASN1_DATATYPE_MASK;
1211   request->request_out_type = (SNMP_ASN1_CLASS_CONTEXT | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_CONTEXT_PDU_GET_RESP);
1212 
1213   /* validate community (do this after decoding PDU type because we don't want to increase 'inbadcommunitynames' for wrong frame types */
1214   if (request->community_strlen == 0) {
1215     /* community string was too long or really empty*/
1216     snmp_stats.inbadcommunitynames++;
1217     snmp_authfail_trap();
1218     return ERR_ARG;
1219   } else if (request->request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ) {
1220     if (snmp_community_write[0] == 0) {
1221       /* our write community is empty, that means all our objects are readonly */
1222       request->error_status = SNMP_ERR_NOTWRITABLE;
1223       request->error_index  = 1;
1224     } else if (strncmp(snmp_community_write, (const char *)request->community, SNMP_MAX_COMMUNITY_STR_LEN) != 0) {
1225       /* community name does not match */
1226       snmp_stats.inbadcommunitynames++;
1227       snmp_authfail_trap();
1228       return ERR_ARG;
1229     }
1230   } else {
1231     if (strncmp(snmp_community, (const char *)request->community, SNMP_MAX_COMMUNITY_STR_LEN) != 0) {
1232       /* community name does not match */
1233       snmp_stats.inbadcommunitynames++;
1234       snmp_authfail_trap();
1235       return ERR_ARG;
1236     }
1237   }
1238 
1239   /* decode request ID */
1240   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1241   IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
1242   parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1243   IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1244 
1245   IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->request_id));
1246 
1247   /* decode error status / non-repeaters */
1248   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1249   IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
1250   parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1251   IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1252 
1253   if (request->request_type == SNMP_ASN1_CONTEXT_PDU_GET_BULK_REQ) {
1254     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->non_repeaters));
1255     if (request->non_repeaters < 0) {
1256       /* RFC 1905, 4.2.3 */
1257       request->non_repeaters = 0;
1258     }
1259   } else {
1260     /* only check valid value, don't touch 'request->error_status', maybe a response error status was already set to above; */
1261     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &s32_value));
1262     IF_PARSE_ASSERT(s32_value == SNMP_ERR_NOERROR);
1263   }
1264 
1265   /* decode error index / max-repetitions */
1266   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1267   IF_PARSE_ASSERT(tlv.type == SNMP_ASN1_TYPE_INTEGER);
1268   parent_tlv_value_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1269   IF_PARSE_ASSERT(parent_tlv_value_len > 0);
1270 
1271   if (request->request_type == SNMP_ASN1_CONTEXT_PDU_GET_BULK_REQ) {
1272     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->max_repetitions));
1273     if (request->max_repetitions < 0) {
1274       /* RFC 1905, 4.2.3 */
1275       request->max_repetitions = 0;
1276     }
1277   } else {
1278     IF_PARSE_EXEC(snmp_asn1_dec_s32t(&pbuf_stream, tlv.value_len, &request->error_index));
1279     IF_PARSE_ASSERT(s32_value == 0);
1280   }
1281 
1282   /* decode varbind-list type (next container level) */
1283   IF_PARSE_EXEC(snmp_asn1_dec_tlv(&pbuf_stream, &tlv));
1284   IF_PARSE_ASSERT((tlv.type == SNMP_ASN1_TYPE_SEQUENCE) && (tlv.value_len <= pbuf_stream.length));
1285 
1286   request->inbound_varbind_offset = pbuf_stream.offset;
1287   request->inbound_varbind_len    = pbuf_stream.length - request->inbound_padding_len;
1288   snmp_vb_enumerator_init(&(request->inbound_varbind_enumerator), request->inbound_pbuf, request->inbound_varbind_offset, request->inbound_varbind_len);
1289 
1290   return ERR_OK;
1291 }
1292 
1293 #define OF_BUILD_EXEC(code) BUILD_EXEC(code, ERR_ARG)
1294 
1295 static err_t
snmp_prepare_outbound_frame(struct snmp_request * request)1296 snmp_prepare_outbound_frame(struct snmp_request *request)
1297 {
1298   struct snmp_asn1_tlv tlv;
1299   struct snmp_pbuf_stream *pbuf_stream = &(request->outbound_pbuf_stream);
1300 
1301   /* try allocating pbuf(s) for maximum response size */
1302   request->outbound_pbuf = pbuf_alloc(PBUF_TRANSPORT, 1472, PBUF_RAM);
1303   if (request->outbound_pbuf == NULL) {
1304     return ERR_MEM;
1305   }
1306 
1307   snmp_pbuf_stream_init(pbuf_stream, request->outbound_pbuf, 0, request->outbound_pbuf->tot_len);
1308 
1309   /* 'Message' sequence */
1310   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, 0);
1311   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1312 
1313   /* version */
1314   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 0);
1315   snmp_asn1_enc_s32t_cnt(request->version, &tlv.value_len);
1316   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1317   OF_BUILD_EXEC( snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->version) );
1318 
1319 #if LWIP_SNMP_V3
1320   if (request->version < SNMP_VERSION_3) {
1321 #endif
1322     /* community */
1323     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, request->community_strlen);
1324     OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1325     OF_BUILD_EXEC( snmp_asn1_enc_raw(pbuf_stream, request->community, request->community_strlen) );
1326 #if LWIP_SNMP_V3
1327   } else {
1328     const char *id;
1329 
1330     /* globalData */
1331     request->outbound_msg_global_data_offset = pbuf_stream->offset;
1332     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 1, 0);
1333     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1334 
1335     /* msgID */
1336     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 1);
1337     snmp_asn1_enc_s32t_cnt(request->msg_id, &tlv.value_len);
1338     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1339     OF_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->msg_id));
1340 
1341     /* msgMaxSize */
1342     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 1);
1343     snmp_asn1_enc_s32t_cnt(request->msg_max_size, &tlv.value_len);
1344     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1345     OF_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->msg_max_size));
1346 
1347     /* msgFlags */
1348     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, 1);
1349     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1350     OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, &request->msg_flags, 1));
1351 
1352     /* msgSecurityModel */
1353     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 1);
1354     snmp_asn1_enc_s32t_cnt(request->msg_security_model, &tlv.value_len);
1355     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1356     OF_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->msg_security_model));
1357 
1358     /* end of msgGlobalData */
1359     request->outbound_msg_global_data_end = pbuf_stream->offset;
1360 
1361     /* msgSecurityParameters */
1362     request->outbound_msg_security_parameters_str_offset = pbuf_stream->offset;
1363     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 1, 0);
1364     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1365 
1366     request->outbound_msg_security_parameters_seq_offset = pbuf_stream->offset;
1367     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 1, 0);
1368     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1369 
1370     /* msgAuthoritativeEngineID */
1371     snmpv3_get_engine_id(&id, &request->msg_authoritative_engine_id_len);
1372     MEMCPY(request->msg_authoritative_engine_id, id, request->msg_authoritative_engine_id_len);
1373     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, request->msg_authoritative_engine_id_len);
1374     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1375     OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->msg_authoritative_engine_id, request->msg_authoritative_engine_id_len));
1376 
1377     request->msg_authoritative_engine_time = snmpv3_get_engine_time();
1378     request->msg_authoritative_engine_boots = snmpv3_get_engine_boots();
1379 
1380     /* msgAuthoritativeEngineBoots */
1381     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 0);
1382     snmp_asn1_enc_s32t_cnt(request->msg_authoritative_engine_boots, &tlv.value_len);
1383     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1384     OF_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->msg_authoritative_engine_boots));
1385 
1386     /* msgAuthoritativeEngineTime */
1387     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 0);
1388     snmp_asn1_enc_s32t_cnt(request->msg_authoritative_engine_time, &tlv.value_len);
1389     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1390     OF_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->msg_authoritative_engine_time));
1391 
1392     /* msgUserName */
1393     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, request->msg_user_name_len);
1394     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1395     OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->msg_user_name, request->msg_user_name_len));
1396 
1397 #if LWIP_SNMP_V3_CRYPTO
1398     /* msgAuthenticationParameters */
1399     if (request->msg_flags & SNMP_V3_AUTH_FLAG) {
1400       memset(request->msg_authentication_parameters, 0, SNMP_V3_MAX_AUTH_PARAM_LENGTH);
1401       request->outbound_msg_authentication_parameters_offset = pbuf_stream->offset;
1402       SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 1, SNMP_V3_MAX_AUTH_PARAM_LENGTH);
1403       OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1404       OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->msg_authentication_parameters, SNMP_V3_MAX_AUTH_PARAM_LENGTH));
1405     } else
1406 #endif
1407     {
1408       SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, 0);
1409       OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1410     }
1411 
1412 #if LWIP_SNMP_V3_CRYPTO
1413     /* msgPrivacyParameters */
1414     if (request->msg_flags & SNMP_V3_PRIV_FLAG) {
1415       snmpv3_build_priv_param(request->msg_privacy_parameters);
1416 
1417       SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, SNMP_V3_MAX_PRIV_PARAM_LENGTH);
1418       OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1419       OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->msg_privacy_parameters, SNMP_V3_MAX_PRIV_PARAM_LENGTH));
1420     } else
1421 #endif
1422     {
1423       SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, 0);
1424       OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1425     }
1426 
1427     /* End of msgSecurityParameters, so we can calculate the length of this sequence later */
1428     request->outbound_msg_security_parameters_end = pbuf_stream->offset;
1429 
1430 #if LWIP_SNMP_V3_CRYPTO
1431     /* For encryption we have to encapsulate the payload in an octet string */
1432     if (request->msg_flags & SNMP_V3_PRIV_FLAG) {
1433       request->outbound_scoped_pdu_string_offset = pbuf_stream->offset;
1434       SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 3, 0);
1435       OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1436     }
1437 #endif
1438     /* Scoped PDU
1439      * Encryption context
1440      */
1441     request->outbound_scoped_pdu_seq_offset = pbuf_stream->offset;
1442     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, 0);
1443     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1444 
1445     /* contextEngineID */
1446     snmpv3_get_engine_id(&id, &request->context_engine_id_len);
1447     MEMCPY(request->context_engine_id, id, request->context_engine_id_len);
1448     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, request->context_engine_id_len);
1449     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1450     OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->context_engine_id, request->context_engine_id_len));
1451 
1452     /* contextName */
1453     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 0, request->context_name_len);
1454     OF_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1455     OF_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, request->context_name, request->context_name_len));
1456   }
1457 #endif
1458 
1459   /* 'PDU' sequence */
1460   request->outbound_pdu_offset = pbuf_stream->offset;
1461   SNMP_ASN1_SET_TLV_PARAMS(tlv, request->request_out_type, 3, 0);
1462   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1463 
1464   /* request ID */
1465   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 0);
1466   snmp_asn1_enc_s32t_cnt(request->request_id, &tlv.value_len);
1467   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1468   OF_BUILD_EXEC( snmp_asn1_enc_s32t(pbuf_stream, tlv.value_len, request->request_id) );
1469 
1470   /* error status */
1471   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 1);
1472   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1473   request->outbound_error_status_offset = pbuf_stream->offset;
1474   OF_BUILD_EXEC( snmp_pbuf_stream_write(pbuf_stream, 0) );
1475 
1476   /* error index */
1477   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_INTEGER, 0, 1);
1478   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1479   request->outbound_error_index_offset = pbuf_stream->offset;
1480   OF_BUILD_EXEC( snmp_pbuf_stream_write(pbuf_stream, 0) );
1481 
1482   /* 'VarBindList' sequence */
1483   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, 0);
1484   OF_BUILD_EXEC( snmp_ans1_enc_tlv(pbuf_stream, &tlv) );
1485 
1486   request->outbound_varbind_offset = pbuf_stream->offset;
1487 
1488   return ERR_OK;
1489 }
1490 
1491 /** Calculate the length of a varbind list */
1492 err_t
snmp_varbind_length(struct snmp_varbind * varbind,struct snmp_varbind_len * len)1493 snmp_varbind_length(struct snmp_varbind *varbind, struct snmp_varbind_len *len)
1494 {
1495   /* calculate required lengths */
1496   snmp_asn1_enc_oid_cnt(varbind->oid.id, varbind->oid.len, &len->oid_value_len);
1497   snmp_asn1_enc_length_cnt(len->oid_value_len, &len->oid_len_len);
1498 
1499   if (varbind->value_len == 0) {
1500     len->value_value_len = 0;
1501   } else if (varbind->value_len & SNMP_GET_VALUE_RAW_DATA) {
1502     len->value_value_len = varbind->value_len & (~SNMP_GET_VALUE_RAW_DATA);
1503   } else {
1504     switch (varbind->type) {
1505       case SNMP_ASN1_TYPE_INTEGER:
1506         if (varbind->value_len != sizeof (s32_t)) {
1507           return ERR_VAL;
1508         }
1509         snmp_asn1_enc_s32t_cnt(*((s32_t *) varbind->value), &len->value_value_len);
1510         break;
1511       case SNMP_ASN1_TYPE_COUNTER:
1512       case SNMP_ASN1_TYPE_GAUGE:
1513       case SNMP_ASN1_TYPE_TIMETICKS:
1514         if (varbind->value_len != sizeof (u32_t)) {
1515           return ERR_VAL;
1516         }
1517         snmp_asn1_enc_u32t_cnt(*((u32_t *) varbind->value), &len->value_value_len);
1518         break;
1519       case SNMP_ASN1_TYPE_OCTET_STRING:
1520       case SNMP_ASN1_TYPE_IPADDR:
1521       case SNMP_ASN1_TYPE_OPAQUE:
1522         len->value_value_len = varbind->value_len;
1523         break;
1524       case SNMP_ASN1_TYPE_NULL:
1525         if (varbind->value_len != 0) {
1526           return ERR_VAL;
1527         }
1528         len->value_value_len = 0;
1529         break;
1530       case SNMP_ASN1_TYPE_OBJECT_ID:
1531         if ((varbind->value_len & 0x03) != 0) {
1532           return ERR_VAL;
1533         }
1534         snmp_asn1_enc_oid_cnt((u32_t *) varbind->value, varbind->value_len >> 2, &len->value_value_len);
1535         break;
1536 #if LWIP_HAVE_INT64
1537       case SNMP_ASN1_TYPE_COUNTER64:
1538         if (varbind->value_len != sizeof(u64_t)) {
1539           return ERR_VAL;
1540         }
1541         snmp_asn1_enc_u64t_cnt(*(u64_t *)varbind->value, &len->value_value_len);
1542         break;
1543 #endif
1544       default:
1545         /* unsupported type */
1546         return ERR_VAL;
1547     }
1548   }
1549   snmp_asn1_enc_length_cnt(len->value_value_len, &len->value_len_len);
1550 
1551   len->vb_value_len = 1 + len->oid_len_len + len->oid_value_len + 1 + len->value_len_len + len->value_value_len;
1552   snmp_asn1_enc_length_cnt(len->vb_value_len, &len->vb_len_len);
1553 
1554   return ERR_OK;
1555 }
1556 
1557 #define OVB_BUILD_EXEC(code) BUILD_EXEC(code, ERR_ARG)
1558 
1559 err_t
snmp_append_outbound_varbind(struct snmp_pbuf_stream * pbuf_stream,struct snmp_varbind * varbind)1560 snmp_append_outbound_varbind(struct snmp_pbuf_stream *pbuf_stream, struct snmp_varbind *varbind)
1561 {
1562   struct snmp_asn1_tlv tlv;
1563   struct snmp_varbind_len len;
1564   err_t err;
1565 
1566   err = snmp_varbind_length(varbind, &len);
1567 
1568   if (err != ERR_OK) {
1569     return err;
1570   }
1571 
1572   /* check length already before adding first data because in case of GetBulk,
1573    *  data added so far is returned and therefore no partial data shall be added
1574    */
1575   if ((1 + len.vb_len_len + len.vb_value_len) > pbuf_stream->length) {
1576     return ERR_BUF;
1577   }
1578 
1579   /* 'VarBind' sequence */
1580   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, len.vb_len_len, len.vb_value_len);
1581   OVB_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1582 
1583   /* VarBind OID */
1584   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OBJECT_ID, len.oid_len_len, len.oid_value_len);
1585   OVB_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1586   OVB_BUILD_EXEC(snmp_asn1_enc_oid(pbuf_stream, varbind->oid.id, varbind->oid.len));
1587 
1588   /* VarBind value */
1589   SNMP_ASN1_SET_TLV_PARAMS(tlv, varbind->type, len.value_len_len, len.value_value_len);
1590   OVB_BUILD_EXEC(snmp_ans1_enc_tlv(pbuf_stream, &tlv));
1591 
1592   if (len.value_value_len > 0) {
1593     if (varbind->value_len & SNMP_GET_VALUE_RAW_DATA) {
1594       OVB_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, (u8_t *) varbind->value, len.value_value_len));
1595     } else {
1596       switch (varbind->type) {
1597         case SNMP_ASN1_TYPE_INTEGER:
1598           OVB_BUILD_EXEC(snmp_asn1_enc_s32t(pbuf_stream, len.value_value_len, *((s32_t *) varbind->value)));
1599           break;
1600         case SNMP_ASN1_TYPE_COUNTER:
1601         case SNMP_ASN1_TYPE_GAUGE:
1602         case SNMP_ASN1_TYPE_TIMETICKS:
1603           OVB_BUILD_EXEC(snmp_asn1_enc_u32t(pbuf_stream, len.value_value_len, *((u32_t *) varbind->value)));
1604           break;
1605         case SNMP_ASN1_TYPE_OCTET_STRING:
1606         case SNMP_ASN1_TYPE_IPADDR:
1607         case SNMP_ASN1_TYPE_OPAQUE:
1608           OVB_BUILD_EXEC(snmp_asn1_enc_raw(pbuf_stream, (u8_t *) varbind->value, len.value_value_len));
1609           len.value_value_len = varbind->value_len;
1610           break;
1611         case SNMP_ASN1_TYPE_OBJECT_ID:
1612           OVB_BUILD_EXEC(snmp_asn1_enc_oid(pbuf_stream, (u32_t *) varbind->value, varbind->value_len / sizeof (u32_t)));
1613           break;
1614 #if LWIP_HAVE_INT64
1615         case SNMP_ASN1_TYPE_COUNTER64:
1616           OVB_BUILD_EXEC(snmp_asn1_enc_u64t(pbuf_stream, len.value_value_len, *(u64_t *) varbind->value));
1617           break;
1618 #endif
1619         default:
1620           LWIP_ASSERT("Unknown variable type", 0);
1621           break;
1622       }
1623     }
1624   }
1625 
1626   return ERR_OK;
1627 }
1628 
1629 static err_t
snmp_complete_outbound_frame(struct snmp_request * request)1630 snmp_complete_outbound_frame(struct snmp_request *request)
1631 {
1632   struct snmp_asn1_tlv tlv;
1633   u16_t frame_size;
1634   u8_t outbound_padding = 0;
1635 
1636   if (request->version == SNMP_VERSION_1) {
1637     if (request->error_status != SNMP_ERR_NOERROR) {
1638       /* map v2c error codes to v1 compliant error code (according to RFC 2089) */
1639       switch (request->error_status) {
1640         /* mapping of implementation specific "virtual" error codes
1641          * (during processing of frame we already stored them in error_status field,
1642          * so no need to check all varbinds here for those exceptions as suggested by RFC) */
1643         case SNMP_ERR_NOSUCHINSTANCE:
1644         case SNMP_ERR_NOSUCHOBJECT:
1645         case SNMP_ERR_ENDOFMIBVIEW:
1646           request->error_status = SNMP_ERR_NOSUCHNAME;
1647           break;
1648         /* mapping according to RFC */
1649         case SNMP_ERR_WRONGVALUE:
1650         case SNMP_ERR_WRONGENCODING:
1651         case SNMP_ERR_WRONGTYPE:
1652         case SNMP_ERR_WRONGLENGTH:
1653         case SNMP_ERR_INCONSISTENTVALUE:
1654           request->error_status = SNMP_ERR_BADVALUE;
1655           break;
1656         case SNMP_ERR_NOACCESS:
1657         case SNMP_ERR_NOTWRITABLE:
1658         case SNMP_ERR_NOCREATION:
1659         case SNMP_ERR_INCONSISTENTNAME:
1660         case SNMP_ERR_AUTHORIZATIONERROR:
1661           request->error_status = SNMP_ERR_NOSUCHNAME;
1662           break;
1663         case SNMP_ERR_RESOURCEUNAVAILABLE:
1664         case SNMP_ERR_COMMITFAILED:
1665         case SNMP_ERR_UNDOFAILED:
1666         default:
1667           request->error_status = SNMP_ERR_GENERROR;
1668           break;
1669       }
1670     }
1671   } else {
1672     if (request->request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ) {
1673       /* map error codes to according to RFC 1905 (4.2.5.  The SetRequest-PDU) return 'NotWritable' for unknown OIDs) */
1674       switch (request->error_status) {
1675         case SNMP_ERR_NOSUCHINSTANCE:
1676         case SNMP_ERR_NOSUCHOBJECT:
1677         case SNMP_ERR_ENDOFMIBVIEW:
1678           request->error_status = SNMP_ERR_NOTWRITABLE;
1679           break;
1680         default:
1681           break;
1682       }
1683     }
1684 
1685     if (request->error_status >= SNMP_VARBIND_EXCEPTION_OFFSET) {
1686       /* should never occur because v2 frames store exceptions directly inside varbinds and not as frame error_status */
1687       LWIP_DEBUGF(SNMP_DEBUG, ("snmp_complete_outbound_frame() > Found v2 request with varbind exception code stored as error status!\n"));
1688       return ERR_ARG;
1689     }
1690   }
1691 
1692   if ((request->error_status != SNMP_ERR_NOERROR) || (request->request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ)) {
1693     /* all inbound vars are returned in response without any modification for error responses and successful set requests*/
1694     struct snmp_pbuf_stream inbound_stream;
1695     OF_BUILD_EXEC( snmp_pbuf_stream_init(&inbound_stream, request->inbound_pbuf, request->inbound_varbind_offset, request->inbound_varbind_len) );
1696     OF_BUILD_EXEC( snmp_pbuf_stream_init(&(request->outbound_pbuf_stream), request->outbound_pbuf, request->outbound_varbind_offset, request->outbound_pbuf->tot_len - request->outbound_varbind_offset) );
1697     OF_BUILD_EXEC( snmp_pbuf_stream_writeto(&inbound_stream, &(request->outbound_pbuf_stream), 0) );
1698   }
1699 
1700   frame_size = request->outbound_pbuf_stream.offset;
1701 
1702 #if LWIP_SNMP_V3 && LWIP_SNMP_V3_CRYPTO
1703   /* Calculate padding for encryption */
1704   if (request->version == SNMP_VERSION_3 && (request->msg_flags & SNMP_V3_PRIV_FLAG)) {
1705     u8_t i;
1706     outbound_padding = (8 - (u8_t)((frame_size - request->outbound_scoped_pdu_seq_offset) & 0x07)) & 0x07;
1707     for (i = 0; i < outbound_padding; i++) {
1708       OF_BUILD_EXEC( snmp_pbuf_stream_write(&request->outbound_pbuf_stream, 0) );
1709     }
1710   }
1711 #endif
1712 
1713   /* complete missing length in 'Message' sequence ; 'Message' tlv is located at the beginning (offset 0) */
1714   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, frame_size + outbound_padding - 1 - 3); /* - type - length_len(fixed, see snmp_prepare_outbound_frame()) */
1715   OF_BUILD_EXEC( snmp_pbuf_stream_init(&(request->outbound_pbuf_stream), request->outbound_pbuf, 0, request->outbound_pbuf->tot_len) );
1716   OF_BUILD_EXEC( snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv) );
1717 
1718 #if LWIP_SNMP_V3
1719   if (request->version == SNMP_VERSION_3) {
1720     /* complete missing length in 'globalData' sequence */
1721     /* - type - length_len(fixed, see snmp_prepare_outbound_frame()) */
1722     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 1, request->outbound_msg_global_data_end
1723                              - request->outbound_msg_global_data_offset - 1 - 1);
1724     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_msg_global_data_offset));
1725     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv));
1726 
1727     /* complete missing length in 'msgSecurityParameters' sequence */
1728     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 1, request->outbound_msg_security_parameters_end
1729                              - request->outbound_msg_security_parameters_str_offset - 1 - 1);
1730     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_msg_security_parameters_str_offset));
1731     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv));
1732 
1733     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 1, request->outbound_msg_security_parameters_end
1734                              - request->outbound_msg_security_parameters_seq_offset - 1 - 1);
1735     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_msg_security_parameters_seq_offset));
1736     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv));
1737 
1738     /* complete missing length in scoped PDU sequence */
1739     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, frame_size - request->outbound_scoped_pdu_seq_offset - 1 - 3);
1740     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_scoped_pdu_seq_offset));
1741     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv));
1742   }
1743 #endif
1744 
1745   /* complete missing length in 'PDU' sequence */
1746   SNMP_ASN1_SET_TLV_PARAMS(tlv, request->request_out_type, 3,
1747                            frame_size - request->outbound_pdu_offset - 1 - 3); /* - type - length_len(fixed, see snmp_prepare_outbound_frame()) */
1748   OF_BUILD_EXEC( snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_pdu_offset) );
1749   OF_BUILD_EXEC( snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv) );
1750 
1751   /* process and encode final error status */
1752   if (request->error_status != 0) {
1753     u16_t len;
1754     snmp_asn1_enc_s32t_cnt(request->error_status, &len);
1755     if (len != 1) {
1756       /* error, we only reserved one byte for it */
1757       return ERR_ARG;
1758     }
1759     OF_BUILD_EXEC( snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_error_status_offset) );
1760     OF_BUILD_EXEC( snmp_asn1_enc_s32t(&(request->outbound_pbuf_stream), len, request->error_status) );
1761 
1762     /* for compatibility to v1, log statistics; in v2 (RFC 1907) these statistics are obsoleted */
1763     switch (request->error_status) {
1764       case SNMP_ERR_TOOBIG:
1765         snmp_stats.outtoobigs++;
1766         break;
1767       case SNMP_ERR_NOSUCHNAME:
1768         snmp_stats.outnosuchnames++;
1769         break;
1770       case SNMP_ERR_BADVALUE:
1771         snmp_stats.outbadvalues++;
1772         break;
1773       case SNMP_ERR_GENERROR:
1774       default:
1775         snmp_stats.outgenerrs++;
1776         break;
1777     }
1778 
1779     if (request->error_status == SNMP_ERR_TOOBIG) {
1780       request->error_index = 0; /* defined by RFC 1157 */
1781     } else if (request->error_index == 0) {
1782       /* set index to varbind where error occured (if not already set before, e.g. during GetBulk processing) */
1783       request->error_index = request->inbound_varbind_enumerator.varbind_count;
1784     }
1785   } else {
1786     if (request->request_type == SNMP_ASN1_CONTEXT_PDU_SET_REQ) {
1787       snmp_stats.intotalsetvars += request->inbound_varbind_enumerator.varbind_count;
1788     } else {
1789       snmp_stats.intotalreqvars += request->inbound_varbind_enumerator.varbind_count;
1790     }
1791   }
1792 
1793   /* encode final error index*/
1794   if (request->error_index != 0) {
1795     u16_t len;
1796     snmp_asn1_enc_s32t_cnt(request->error_index, &len);
1797     if (len != 1) {
1798       /* error, we only reserved one byte for it */
1799       return ERR_VAL;
1800     }
1801     OF_BUILD_EXEC( snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_error_index_offset) );
1802     OF_BUILD_EXEC( snmp_asn1_enc_s32t(&(request->outbound_pbuf_stream), len, request->error_index) );
1803   }
1804 
1805   /* complete missing length in 'VarBindList' sequence ; 'VarBindList' tlv is located directly before varbind offset */
1806   SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_SEQUENCE, 3, frame_size - request->outbound_varbind_offset);
1807   OF_BUILD_EXEC( snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_varbind_offset - 1 - 3) ); /* - type - length_len(fixed, see snmp_prepare_outbound_frame()) */
1808   OF_BUILD_EXEC( snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv) );
1809 
1810   /* Authenticate response */
1811 #if LWIP_SNMP_V3 && LWIP_SNMP_V3_CRYPTO
1812   /* Encrypt response */
1813   if (request->version == SNMP_VERSION_3 && (request->msg_flags & SNMP_V3_PRIV_FLAG)) {
1814     u8_t key[20];
1815     snmpv3_priv_algo_t algo;
1816 
1817     /* complete missing length in PDU sequence */
1818     OF_BUILD_EXEC(snmp_pbuf_stream_init(&request->outbound_pbuf_stream, request->outbound_pbuf, 0, request->outbound_pbuf->tot_len));
1819     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&(request->outbound_pbuf_stream), request->outbound_scoped_pdu_string_offset));
1820     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 3, frame_size + outbound_padding
1821                              - request->outbound_scoped_pdu_string_offset - 1 - 3);
1822     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&(request->outbound_pbuf_stream), &tlv));
1823 
1824     OF_BUILD_EXEC(snmpv3_get_user((char *)request->msg_user_name, NULL, NULL, &algo, key));
1825 
1826     OF_BUILD_EXEC(snmpv3_crypt(&request->outbound_pbuf_stream, tlv.value_len, key,
1827                                request->msg_privacy_parameters, request->msg_authoritative_engine_boots,
1828                                request->msg_authoritative_engine_time, algo, SNMP_V3_PRIV_MODE_ENCRYPT));
1829   }
1830 
1831   if (request->version == SNMP_VERSION_3 && (request->msg_flags & SNMP_V3_AUTH_FLAG)) {
1832     u8_t key[20];
1833     snmpv3_auth_algo_t algo;
1834     u8_t hmac[20];
1835 
1836     OF_BUILD_EXEC(snmpv3_get_user((char *)request->msg_user_name, &algo, key, NULL, NULL));
1837     OF_BUILD_EXEC(snmp_pbuf_stream_init(&(request->outbound_pbuf_stream),
1838                                         request->outbound_pbuf, 0, request->outbound_pbuf->tot_len));
1839     OF_BUILD_EXEC(snmpv3_auth(&request->outbound_pbuf_stream, frame_size + outbound_padding, key, algo, hmac));
1840 
1841     MEMCPY(request->msg_authentication_parameters, hmac, SNMP_V3_MAX_AUTH_PARAM_LENGTH);
1842     OF_BUILD_EXEC(snmp_pbuf_stream_init(&request->outbound_pbuf_stream,
1843                                         request->outbound_pbuf, 0, request->outbound_pbuf->tot_len));
1844     OF_BUILD_EXEC(snmp_pbuf_stream_seek_abs(&request->outbound_pbuf_stream,
1845                                             request->outbound_msg_authentication_parameters_offset));
1846 
1847     SNMP_ASN1_SET_TLV_PARAMS(tlv, SNMP_ASN1_TYPE_OCTET_STRING, 1, SNMP_V3_MAX_AUTH_PARAM_LENGTH);
1848     OF_BUILD_EXEC(snmp_ans1_enc_tlv(&request->outbound_pbuf_stream, &tlv));
1849     OF_BUILD_EXEC(snmp_asn1_enc_raw(&request->outbound_pbuf_stream,
1850                                     request->msg_authentication_parameters, SNMP_V3_MAX_AUTH_PARAM_LENGTH));
1851   }
1852 #endif
1853 
1854   pbuf_realloc(request->outbound_pbuf, frame_size + outbound_padding);
1855 
1856   snmp_stats.outgetresponses++;
1857   snmp_stats.outpkts++;
1858 
1859   return ERR_OK;
1860 }
1861 
1862 static void
snmp_execute_write_callbacks(struct snmp_request * request)1863 snmp_execute_write_callbacks(struct snmp_request *request)
1864 {
1865   struct snmp_varbind_enumerator inbound_varbind_enumerator;
1866   struct snmp_varbind vb;
1867 
1868   snmp_vb_enumerator_init(&inbound_varbind_enumerator, request->inbound_pbuf, request->inbound_varbind_offset, request->inbound_varbind_len);
1869   vb.value = NULL; /* do NOT decode value (we enumerate outbound buffer here, so all varbinds have values assigned, which we don't need here) */
1870 
1871   while (snmp_vb_enumerator_get_next(&inbound_varbind_enumerator, &vb) == SNMP_VB_ENUMERATOR_ERR_OK) {
1872     snmp_write_callback(vb.oid.id, vb.oid.len, snmp_write_callback_arg);
1873   }
1874 }
1875 
1876 
1877 /* ----------------------------------------------------------------------- */
1878 /* VarBind enumerator methods */
1879 /* ----------------------------------------------------------------------- */
1880 
1881 void
snmp_vb_enumerator_init(struct snmp_varbind_enumerator * enumerator,struct pbuf * p,u16_t offset,u16_t length)1882 snmp_vb_enumerator_init(struct snmp_varbind_enumerator *enumerator, struct pbuf *p, u16_t offset, u16_t length)
1883 {
1884   snmp_pbuf_stream_init(&(enumerator->pbuf_stream), p, offset, length);
1885   enumerator->varbind_count = 0;
1886 }
1887 
1888 #define VB_PARSE_EXEC(code)   PARSE_EXEC(code, SNMP_VB_ENUMERATOR_ERR_ASN1ERROR)
1889 #define VB_PARSE_ASSERT(code) PARSE_ASSERT(code, SNMP_VB_ENUMERATOR_ERR_ASN1ERROR)
1890 
1891 snmp_vb_enumerator_err_t
snmp_vb_enumerator_get_next(struct snmp_varbind_enumerator * enumerator,struct snmp_varbind * varbind)1892 snmp_vb_enumerator_get_next(struct snmp_varbind_enumerator *enumerator, struct snmp_varbind *varbind)
1893 {
1894   struct snmp_asn1_tlv tlv;
1895   u16_t  varbind_len;
1896   err_t  err;
1897 
1898   if (enumerator->pbuf_stream.length == 0) {
1899     return SNMP_VB_ENUMERATOR_ERR_EOVB;
1900   }
1901   enumerator->varbind_count++;
1902 
1903   /* decode varbind itself (parent container of a varbind) */
1904   VB_PARSE_EXEC(snmp_asn1_dec_tlv(&(enumerator->pbuf_stream), &tlv));
1905   VB_PARSE_ASSERT((tlv.type == SNMP_ASN1_TYPE_SEQUENCE) && (tlv.value_len <= enumerator->pbuf_stream.length));
1906   varbind_len = tlv.value_len;
1907 
1908   /* decode varbind name (object id) */
1909   VB_PARSE_EXEC(snmp_asn1_dec_tlv(&(enumerator->pbuf_stream), &tlv));
1910   VB_PARSE_ASSERT((tlv.type == SNMP_ASN1_TYPE_OBJECT_ID) && (SNMP_ASN1_TLV_LENGTH(tlv) < varbind_len) && (tlv.value_len < enumerator->pbuf_stream.length));
1911 
1912   VB_PARSE_EXEC(snmp_asn1_dec_oid(&(enumerator->pbuf_stream), tlv.value_len, varbind->oid.id, &(varbind->oid.len), SNMP_MAX_OBJ_ID_LEN));
1913   varbind_len -= SNMP_ASN1_TLV_LENGTH(tlv);
1914 
1915   /* decode varbind value (object id) */
1916   VB_PARSE_EXEC(snmp_asn1_dec_tlv(&(enumerator->pbuf_stream), &tlv));
1917   VB_PARSE_ASSERT((SNMP_ASN1_TLV_LENGTH(tlv) == varbind_len) && (tlv.value_len <= enumerator->pbuf_stream.length));
1918   varbind->type = tlv.type;
1919 
1920   /* shall the value be decoded ? */
1921   if (varbind->value != NULL) {
1922     switch (varbind->type) {
1923       case SNMP_ASN1_TYPE_INTEGER:
1924         VB_PARSE_EXEC(snmp_asn1_dec_s32t(&(enumerator->pbuf_stream), tlv.value_len, (s32_t *)varbind->value));
1925         varbind->value_len = sizeof(s32_t);
1926         break;
1927       case SNMP_ASN1_TYPE_COUNTER:
1928       case SNMP_ASN1_TYPE_GAUGE:
1929       case SNMP_ASN1_TYPE_TIMETICKS:
1930         VB_PARSE_EXEC(snmp_asn1_dec_u32t(&(enumerator->pbuf_stream), tlv.value_len, (u32_t *)varbind->value));
1931         varbind->value_len = sizeof(u32_t);
1932         break;
1933       case SNMP_ASN1_TYPE_OCTET_STRING:
1934       case SNMP_ASN1_TYPE_OPAQUE:
1935         err = snmp_asn1_dec_raw(&(enumerator->pbuf_stream), tlv.value_len, (u8_t *)varbind->value, &varbind->value_len, SNMP_MAX_VALUE_SIZE);
1936         if (err == ERR_MEM) {
1937           return SNMP_VB_ENUMERATOR_ERR_INVALIDLENGTH;
1938         }
1939         VB_PARSE_ASSERT(err == ERR_OK);
1940         break;
1941       case SNMP_ASN1_TYPE_NULL:
1942         varbind->value_len = 0;
1943         break;
1944       case SNMP_ASN1_TYPE_OBJECT_ID:
1945         /* misuse tlv.length_len as OID_length transporter */
1946         err = snmp_asn1_dec_oid(&(enumerator->pbuf_stream), tlv.value_len, (u32_t *)varbind->value, &tlv.length_len, SNMP_MAX_OBJ_ID_LEN);
1947         if (err == ERR_MEM) {
1948           return SNMP_VB_ENUMERATOR_ERR_INVALIDLENGTH;
1949         }
1950         VB_PARSE_ASSERT(err == ERR_OK);
1951         varbind->value_len = tlv.length_len * sizeof(u32_t);
1952         break;
1953       case SNMP_ASN1_TYPE_IPADDR:
1954         if (tlv.value_len == 4) {
1955           /* must be exactly 4 octets! */
1956           VB_PARSE_EXEC(snmp_asn1_dec_raw(&(enumerator->pbuf_stream), tlv.value_len, (u8_t *)varbind->value, &varbind->value_len, SNMP_MAX_VALUE_SIZE));
1957         } else {
1958           VB_PARSE_ASSERT(0);
1959         }
1960         break;
1961 #if LWIP_HAVE_INT64
1962       case SNMP_ASN1_TYPE_COUNTER64:
1963         VB_PARSE_EXEC(snmp_asn1_dec_u64t(&(enumerator->pbuf_stream), tlv.value_len, (u64_t *)varbind->value));
1964         varbind->value_len = sizeof(u64_t);
1965         break;
1966 #endif
1967       default:
1968         VB_PARSE_ASSERT(0);
1969         break;
1970     }
1971   } else {
1972     snmp_pbuf_stream_seek(&(enumerator->pbuf_stream), tlv.value_len);
1973     varbind->value_len = tlv.value_len;
1974   }
1975 
1976   return SNMP_VB_ENUMERATOR_ERR_OK;
1977 }
1978 
1979 #endif /* LWIP_SNMP */
1980