Something went wrong. Try again.
forked from cz-nic/bird
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577/* * BIRD Library -- Flow specification (RFC 8955) * * (c) 2016 CZ.NIC z.s.p.o. * * Can be freely distributed and used under the terms of the GNU GPL. */
/** * DOC: Flow specification (flowspec) * * Flowspec are rules (RFC 8955) for firewalls disseminated using BGP protocol. * The |flowspec.c| is a library for handling flowspec binary streams and * flowspec data structures. You will find there functions for validation * incoming flowspec binary streams, iterators for jumping over components, * functions for handling a length and functions for formatting flowspec data * structure into user-friendly text representation. * * In this library, you will find also flowspec builder. In |confbase.Y|, there * are grammar's rules for parsing and building new flowspec data structure * from BIRD's configuration files and from BIRD's command line interface. * Finalize function will assemble final &net_addr_flow4 or &net_addr_flow6 * data structure. * * The data structures &net_addr_flow4 and &net_addr_flow6 are defined in * |net.h| file. The attribute length is size of whole data structure plus * binary stream representation of flowspec including a compressed encoded * length of flowspec. * * Sometimes in code, it is used expression flowspec type, it should mean * flowspec component type. */
#include <stdlib.h>
#include "nest/bird.h"#include "lib/flowspec.h"#include "conf/conf.h"
static const char* flow4_type_str[] = { [FLOW_TYPE_DST_PREFIX] = "dst", [FLOW_TYPE_SRC_PREFIX] = "src", [FLOW_TYPE_IP_PROTOCOL] = "proto", [FLOW_TYPE_PORT] = "port", [FLOW_TYPE_DST_PORT] = "dport", [FLOW_TYPE_SRC_PORT] = "sport", [FLOW_TYPE_ICMP_TYPE] = "icmp type", [FLOW_TYPE_ICMP_CODE] = "icmp code", [FLOW_TYPE_TCP_FLAGS] = "tcp flags", [FLOW_TYPE_PACKET_LENGTH] = "length", [FLOW_TYPE_DSCP] = "dscp", [FLOW_TYPE_FRAGMENT] = "fragment"};
static const char* flow6_type_str[] = { [FLOW_TYPE_DST_PREFIX] = "dst", [FLOW_TYPE_SRC_PREFIX] = "src", [FLOW_TYPE_NEXT_HEADER] = "next header", [FLOW_TYPE_PORT] = "port", [FLOW_TYPE_DST_PORT] = "dport", [FLOW_TYPE_SRC_PORT] = "sport", [FLOW_TYPE_ICMP_TYPE] = "icmp type", [FLOW_TYPE_ICMP_CODE] = "icmp code", [FLOW_TYPE_TCP_FLAGS] = "tcp flags", [FLOW_TYPE_PACKET_LENGTH] = "length", [FLOW_TYPE_DSCP] = "dscp", [FLOW_TYPE_FRAGMENT] = "fragment", [FLOW_TYPE_LABEL] = "label"};
/** * flow_type_str - get stringified flowspec name of component * @type: flowspec component type * @ipv6: IPv4/IPv6 decide flag, use zero for IPv4 and one for IPv6 * * This function returns flowspec name of component @type in string. */const char *flow_type_str(enum flow_type type, int ipv6){ return ipv6 ? flow6_type_str[type] : flow4_type_str[type];}
/* * Length */
/** * flow_write_length - write compressed length value * @data: destination buffer to write * @len: the value of the length (0 to 0xfff) for writing * * This function writes appropriate as (1- or 2-bytes) the value of @len into * buffer @data. The function returns number of written bytes, thus 1 or 2 bytes. */uintflow_write_length(byte *data, u16 len){ if (len >= 0xf0) { put_u16(data, len | 0xf000); return 2; }
*data = len; return 1;}
inline static uintget_value_length(const byte *op){ return (1 << ((*op & 0x30) >> 4));}
/* * Flowspec iterators */
static inline u8 num_op(const byte *op) { return (*op & 0x07); }static inline int isset_and(const byte *op) { return ((*op & 0x40) == 0x40); }static inline int isset_end(const byte *op) { return ((*op & 0x80) == 0x80); }
static const byte *flow_first_part(const byte *data){ if (!data || flow_read_length(data) == 0) return NULL;
/* It is allowed to encode the value of length less then 240 into 2-bytes too */ if ((data[0] & 0xf0) == 0xf0) return data + 2;
return data + 1;}
/** * flow4_first_part - get position of the first flowspec component * @f: flowspec data structure &net_addr_flow4 * * This function return a position to the beginning of the first flowspec * component in IPv4 flowspec @f. */inline const byte *flow4_first_part(const net_addr_flow4 *f){ return f ? flow_first_part(f->data) : NULL;}
/** * flow6_first_part - get position of the first flowspec component * @f: flowspec data structure &net_addr_flow6 * * This function return a position to the beginning of the first flowspec * component in IPv6 flowspec @f. */inline const byte *flow6_first_part(const net_addr_flow6 *f){ return f ? flow_first_part(f->data) : NULL;}
static const byte *flow_next_part(const byte *pos, const byte *end, int ipv6){ switch (*pos++) { case FLOW_TYPE_DST_PREFIX: case FLOW_TYPE_SRC_PREFIX: { uint pxlen = *pos++; uint offset = ipv6 ? *pos++ : 0; pos += BYTES(pxlen - offset); break; }
case FLOW_TYPE_IP_PROTOCOL: /* == FLOW_TYPE_NEXT_HEADER */ case FLOW_TYPE_PORT: case FLOW_TYPE_DST_PORT: case FLOW_TYPE_SRC_PORT: case FLOW_TYPE_ICMP_TYPE: case FLOW_TYPE_ICMP_CODE: case FLOW_TYPE_TCP_FLAGS: case FLOW_TYPE_PACKET_LENGTH: case FLOW_TYPE_DSCP: case FLOW_TYPE_FRAGMENT: case FLOW_TYPE_LABEL: { /* Is this the end of list operator-value pair? */ uint last = 0;
while (!last) { last = isset_end(pos);
/* Value length of operator */ uint len = get_value_length(pos); pos += 1+len; } break; } default: return NULL; }
return (pos < end) ? pos : NULL;}
/** * flow4_next_part - an iterator over flowspec components in flowspec binary stream * @pos: the beginning of a previous or the first component in flowspec binary * stream * @end: the last valid byte in scanned flowspec binary stream * * This function returns a position to the beginning of the next component * (to a component type byte) in flowspec binary stream or %NULL for the end. */inline const byte *flow4_next_part(const byte *pos, const byte *end){ return flow_next_part(pos, end, 0);}
/** * flow6_next_part - an iterator over flowspec components in flowspec binary stream * @pos: the beginning of a previous or the first component in flowspec binary * stream * @end: the last valid byte in scanned flowspec binary stream * * This function returns a position to the beginning of the next component * (to a component type byte) in flowspec binary stream or %NULL for the end. */inline const byte *flow6_next_part(const byte *pos, const byte *end){ return flow_next_part(pos, end, 1);}
static const byte *flow_get_part(const byte *data, uint dlen, uint type, int ipv6){ const byte *part;
for (part = flow_first_part(data); part && (part[0] <= type); part = flow_next_part(part, data+dlen, ipv6)) if (part[0] == type) return part;
return NULL;}
const byte *flow4_get_part(const net_addr_flow4 *f, uint type){ return flow_get_part(f->data, f->length - sizeof(net_addr_flow4), type, 0);}
const byte *flow6_get_part(const net_addr_flow6 *f, uint type){ return flow_get_part(f->data, f->length - sizeof(net_addr_flow6), type, 1);}
/* * Flowspec accessors */
static inline ip4_addrflow_read_ip4(const byte *px, uint pxlen){ ip4_addr ip = IP4_NONE; memcpy(&ip, px, BYTES(pxlen)); return ip4_ntoh(ip);}
ip4_addrflow_read_ip4_part(const byte *part){ return flow_read_ip4(part + 2, part[1]);}
static inline ip6_addrflow_read_ip6(const byte *px, uint pxlen, uint pxoffset){ ip6_addr ip = IP6_NONE; memcpy(&ip, px, BYTES(pxlen - pxoffset)); return ip6_shift_right(ip6_ntoh(ip), pxoffset);}
ip6_addrflow_read_ip6_part(const byte *part){ return flow_read_ip6(part + 3, part[1], part[2]);}
static uintget_value(const byte *val, u8 len){ switch (len) { case 1: return *val; case 2: return get_u16(val); case 4: return get_u32(val); // No component may have length 8 // case 8: return get_u64(val); }
return 0;}
/* * Flowspec validation */
static const char* flow_validated_state_str_[] = { [FLOW_ST_UNKNOWN_COMPONENT] = "Unknown component", [FLOW_ST_VALID] = "Valid", [FLOW_ST_NOT_COMPLETE] = "Not complete", [FLOW_ST_EXCEED_MAX_PREFIX_LENGTH] = "Exceed maximal prefix length", [FLOW_ST_EXCEED_MAX_PREFIX_OFFSET] = "Exceed maximal prefix offset", [FLOW_ST_EXCEED_MAX_VALUE_LENGTH] = "Exceed maximal value length", [FLOW_ST_BAD_TYPE_ORDER] = "Bad component order", [FLOW_ST_NONZERO_PADDING] = "Nonzero prefix padding", [FLOW_ST_FIRST_AND_BIT_SET] = "The first AND-bit is set", [FLOW_ST_ZERO_BIT_SET] = "Zero-bit is set", [FLOW_ST_INVALID_TCP_FLAGS] = "Invalid TCP flags bitmask operand", [FLOW_ST_INVALID_FRAGMENT] = "Invalid fragment bitmask operand",};
/** * flow_validated_state_str - return a textual description of validation process * @code: validation result * * This function return well described validation state in string. */const char *flow_validated_state_str(enum flow_validated_state code){ return flow_validated_state_str_[code];}
/* Maximum length of value fields, as mandated by RFC 8955 */static const u8 flow_max_value_length[FLOW_TYPE_MAX] = { [FLOW_TYPE_TCP_FLAGS] = 2, [FLOW_TYPE_DSCP] = 1, [FLOW_TYPE_FRAGMENT] = 1,};
/* Maximum valid numeric values (in bits), semantically */static const u8 flow_max_valid_value[FLOW_TYPE_MAX] = { [FLOW_TYPE_IP_PROTOCOL] = 8, [FLOW_TYPE_PORT] = 16, [FLOW_TYPE_DST_PORT] = 16, [FLOW_TYPE_SRC_PORT] = 16, [FLOW_TYPE_ICMP_TYPE] = 8, [FLOW_TYPE_ICMP_CODE] = 8, [FLOW_TYPE_PACKET_LENGTH] = 16, [FLOW_TYPE_DSCP] = 6, [FLOW_TYPE_LABEL] = 20,};
/** * flow_check_cf_bitmask_arg - check value/bitmask part of flowspec component * @fb: flow builder instance * @neg: negation operand * @val: value from value/mask pair * @mask: bitmap mask from value/mask pair * * This function checks value/bitmask pair. If some problem will appear, the * function calls cf_error() function with a textual description of reason * to failing of validation. */voidflow_check_cf_bitmask_arg(struct flow_builder *fb, u8 neg, u32 val, u32 mask){ if (neg && !(val == 0 || val == mask)) cf_error("For negation, value must be zero or bitmask");
if ((fb->this_type == FLOW_TYPE_TCP_FLAGS) && (mask & ~0xfff)) cf_error("Invalid mask 0x%x, must not exceed 0xfff", mask);
u32 valid = fb->ipv6 ? 0x0e : 0x0f; if ((fb->this_type == FLOW_TYPE_FRAGMENT) && (mask & ~valid)) cf_error("Invalid mask 0x%x, must not exceed 0x%x", mask, valid);
if (val & ~mask) cf_error("Value 0x%x outside bitmask 0x%x", val, mask);}
/** * flow_check_cf_numeric_arg - check numeric argument of flowspec component * @fb: flow builder instance * @val: value * * This function checks the value of numeric argument to see whether it is in * the range of component's type. If some problem will appear, the function * calls cf_error() function with a textual description of reason to failing of * validation. */voidflow_check_cf_numeric_arg(struct flow_builder *fb, uint val){ enum flow_type t = fb->this_type; u64 max = (U64(1) << flow_max_valid_value[t]) - 1;
if (max && (val > max)) cf_error("%s value %u out of range (0-%lu)", flow_type_str(t, fb->ipv6), val, max);}
/* Bitmask of padding bits in last byte of prefix */static inline u8flow_padding(uint n){ ASSUME(n % 8 != 0); return (1 << (8 - n % 8)) - 1;}
static enum flow_validated_stateflow_decode(byte *nlri, uint length, bool ipv6){ enum flow_type type = 0; byte *pos = nlri; byte *end = nlri + length;
while (pos < end) { /* Check increasing type ordering */ if (*pos <= type) return FLOW_ST_BAD_TYPE_ORDER;
type = *pos++;
switch (type) { case FLOW_TYPE_DST_PREFIX: case FLOW_TYPE_SRC_PREFIX: { uint pxlen, offset = 0;
if (!ipv6) { if (pos + 1 > end) return FLOW_ST_NOT_COMPLETE;
pxlen = *pos++;
if (pxlen > IP4_MAX_PREFIX_LENGTH) return FLOW_ST_EXCEED_MAX_PREFIX_LENGTH; } else { if (pos + 2 > end) return FLOW_ST_NOT_COMPLETE;
pxlen = *pos++; offset = *pos++;
if (pxlen > IP6_MAX_PREFIX_LENGTH) return FLOW_ST_EXCEED_MAX_PREFIX_LENGTH;
if (offset > pxlen) return FLOW_ST_EXCEED_MAX_PREFIX_OFFSET; }
uint bits = pxlen - offset; pos += BYTES(bits);
if (pos > end) return FLOW_ST_NOT_COMPLETE;
/* Padding bits in the last byte MUST be 0 */ if (bits % 8) pos[-1] &= ~flow_padding(bits);
break; }
case FLOW_TYPE_LABEL: if (!ipv6) return FLOW_ST_UNKNOWN_COMPONENT; /* fall through */
case FLOW_TYPE_IP_PROTOCOL: /* == FLOW_TYPE_NEXT_HEADER */ case FLOW_TYPE_PORT: case FLOW_TYPE_DST_PORT: case FLOW_TYPE_SRC_PORT: case FLOW_TYPE_ICMP_TYPE: case FLOW_TYPE_ICMP_CODE: case FLOW_TYPE_TCP_FLAGS: case FLOW_TYPE_PACKET_LENGTH: case FLOW_TYPE_DSCP: case FLOW_TYPE_FRAGMENT: { /* * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 * +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ * | e | a | len | 0 |lt |gt |eq | | e | a | len | 0 | 0 |not| m | * +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ * * Numeric operator Bitmask operator */
bool first = true; bool last = false; while (!last) { if (pos + 1 > end) return FLOW_ST_NOT_COMPLETE;
uint len = get_value_length(pos);
/* Some component values MUST be encoded with limited length */ uint maxlen = flow_max_value_length[type]; if (maxlen && (len > maxlen)) return FLOW_ST_EXCEED_MAX_VALUE_LENGTH;
if (pos + 1 + len > end) return FLOW_ST_NOT_COMPLETE;
/* In first operator of sequence, AND bit ... MUST be ignored during decoding */ if (first) pos[0] &= ~0x40;
/* Zero field MUST be set to 0 on encoding and MUST be ignored during decoding */ pos[0] &= ~0x08;
/* Bitmask operator has additional zero field */ if (type == FLOW_TYPE_TCP_FLAGS || type == FLOW_TYPE_FRAGMENT) pos[0] &= ~0x04;
/* Zero fields in highest nibble of TCP Flags bitmask operand */ if ((type == FLOW_TYPE_TCP_FLAGS) && (len == 2)) pos[1] &= ~0xf0;
/* Zero fields in fragment bitmask operand */ if ((type == FLOW_TYPE_FRAGMENT) && (len == 1)) pos[1] &= ipv6 ? ~0xf1 : ~0xf0;
/* Move to next operator */ first = false; last = isset_end(pos); pos += 1+len; } break; }
default: return FLOW_ST_UNKNOWN_COMPONENT; } }
if (pos != end) return FLOW_ST_NOT_COMPLETE;
return FLOW_ST_VALID;}
/** * flow4_decode - decode incoming BGP IPv4 flowspec data stream * @nlri: flowspec data stream without length header * @len: length of @nlri * * This function checks syntatic correctness of binary flowspec. It returns * %FLOW_ST_VALID, or some other %FLOW_ST_xxx state if the NLRI is malformed. * If the NLRI is valid but not normalized (e.g. some zero bits are set), the * flow4_decode() modify the datastream to normalize it. */inline enum flow_validated_stateflow4_decode(byte *nlri, uint len){ return flow_decode(nlri, len, false);}
/** * flow6_decode - decode incoming BGP IPv6 flowspec data stream * @nlri: flowspec data stream without length header * @len: length of @nlri * * This function checks syntatic correctness of binary flowspec. It returns * %FLOW_ST_VALID, or some other %FLOW_ST_xxx state if the NLRI is malformed. * If the NLRI is valid but not normalized (e.g. some zero bits are set), the * flow6_decode() modify the datastream to normalize it. */inline enum flow_validated_stateflow6_decode(byte *nlri, uint len){ return flow_decode(nlri, len, true);}
static enum flow_validated_stateflow_validate(const byte *nlri, uint len, bool ipv6){ enum flow_type type = 0; const byte *pos = nlri; const byte *end = nlri + len;
while (pos < end) { /* Check increasing type ordering */ if (*pos <= type) return FLOW_ST_BAD_TYPE_ORDER;
type = *pos++;
switch (type) { case FLOW_TYPE_DST_PREFIX: case FLOW_TYPE_SRC_PREFIX: { uint pxlen, offset = 0;
if (!ipv6) { if (pos + 1 > end) return FLOW_ST_NOT_COMPLETE;
pxlen = *pos++;
if (pxlen > IP4_MAX_PREFIX_LENGTH) return FLOW_ST_EXCEED_MAX_PREFIX_LENGTH; } else { if (pos + 2 > end) return FLOW_ST_NOT_COMPLETE;
pxlen = *pos++; offset = *pos++;
if (pxlen > IP6_MAX_PREFIX_LENGTH) return FLOW_ST_EXCEED_MAX_PREFIX_LENGTH;
if (offset > pxlen) return FLOW_ST_EXCEED_MAX_PREFIX_OFFSET; }
uint bits = pxlen - offset; pos += BYTES(bits);
if (pos > end) return FLOW_ST_NOT_COMPLETE;
/* Padding bits in the last byte MUST be 0 */ if (bits % 8) if (pos[-1] & flow_padding(bits)) return FLOW_ST_NONZERO_PADDING;
break; }
case FLOW_TYPE_LABEL: if (!ipv6) return FLOW_ST_UNKNOWN_COMPONENT; /* fall through */
case FLOW_TYPE_IP_PROTOCOL: /* == FLOW_TYPE_NEXT_HEADER */ case FLOW_TYPE_PORT: case FLOW_TYPE_DST_PORT: case FLOW_TYPE_SRC_PORT: case FLOW_TYPE_ICMP_TYPE: case FLOW_TYPE_ICMP_CODE: case FLOW_TYPE_TCP_FLAGS: case FLOW_TYPE_PACKET_LENGTH: case FLOW_TYPE_DSCP: case FLOW_TYPE_FRAGMENT: { /* * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 * +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ * | e | a | len | 0 |lt |gt |eq | | e | a | len | 0 | 0 |not| m | * +---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+ * * Numeric operator Bitmask operator */
bool first = true; bool last = false; while (!last) { if (pos + 1 > end) return FLOW_ST_NOT_COMPLETE;
uint len = get_value_length(pos);
/* Some component values MUST be encoded with limited length */ uint maxlen = flow_max_value_length[type]; if (maxlen && (len > maxlen)) return FLOW_ST_EXCEED_MAX_VALUE_LENGTH;
if (pos + 1 + len > end) return FLOW_ST_NOT_COMPLETE;
/* In first operator of sequence, AND bit ... MUST be ignored during decoding */ if (first && isset_and(pos)) return FLOW_ST_FIRST_AND_BIT_SET;
/* Zero field MUST be set to 0 on encoding and MUST be ignored during decoding */ if (pos[0] & 0x08) return FLOW_ST_ZERO_BIT_SET;
/* Bitmask operator has additional zero field */ if (type == FLOW_TYPE_TCP_FLAGS || type == FLOW_TYPE_FRAGMENT) if (pos[0] & 0x04) return FLOW_ST_ZERO_BIT_SET;
/* Zero fields in highest nibble of TCP Flags bitmask operand */ if ((type == FLOW_TYPE_TCP_FLAGS) && (len == 2)) if (pos[1] & 0xf0) return FLOW_ST_INVALID_TCP_FLAGS;
/* Zero fields in fragment bitmask operand */ if ((type == FLOW_TYPE_FRAGMENT) && (len == 1)) if (pos[1] & (ipv6 ? 0xf1 : 0xf0)) return FLOW_ST_INVALID_FRAGMENT;
/* Move to next operator */ first = false; last = isset_end(pos); pos += 1+len; } break; }
default: return FLOW_ST_UNKNOWN_COMPONENT; } }
if (pos != end) return FLOW_ST_NOT_COMPLETE;
return FLOW_ST_VALID;}
/** * flow4_validate - check untrustworthy IPv4 flowspec data stream * @nlri: flowspec data stream without length header * @len: length of @nlri * * This function checks syntactic correctness of binary flowspec. It returns * %FLOW_ST_VALID, or some other %FLOW_ST_xxx state if the NLRI is malformed * or non-normalized. */inline enum flow_validated_stateflow4_validate(const byte *nlri, uint len){ return flow_validate(nlri, len, false);}
/** * flow6_validate - check untrustworthy IPv6 flowspec data stream * @nlri: flowspec binary stream without length header * @len: length of @nlri * * This function checks syntactic correctness of binary flowspec. It returns * %FLOW_ST_VALID, or some other %FLOW_ST_xxx state if the NLRI is malformed * or non-normalized. */inline enum flow_validated_stateflow6_validate(const byte *nlri, uint len){ return flow_validate(nlri, len, true);}
/** * flow4_validate_cf - validate flowspec data structure &net_addr_flow4 in parsing time * @f: flowspec data structure &net_addr_flow4 * * Check if @f is valid flowspec data structure. Can call cf_error() function * with a textual description of reason to failing of validation. */voidflow4_validate_cf(net_addr_flow4 *f){ enum flow_validated_state r = flow4_validate(flow4_first_part(f), flow_read_length(f->data));
if (r != FLOW_ST_VALID) cf_error("Invalid flow route: %s", flow_validated_state_str(r));}
/** * flow6_validate_cf - validate flowspec data structure &net_addr_flow6 in parsing time * @f: flowspec data structure &net_addr_flow6 * * Check if @f is valid flowspec data structure. Can call cf_error() function * with a textual description of reason to failing of validation. */voidflow6_validate_cf(net_addr_flow6 *f){ enum flow_validated_state r = flow6_validate(flow6_first_part(f), flow_read_length(f->data));
if (r != FLOW_ST_VALID) cf_error("Invalid flow route: %s", flow_validated_state_str(r));}
/* * Flowspec Builder */
/** * flow_builder_init - constructor for flowspec builder instance * @pool: memory pool * * This function prepares flowspec builder instance using memory pool @pool. */struct flow_builder *flow_builder_init(pool *pool){ struct flow_builder *fb = mb_allocz(pool, sizeof(struct flow_builder)); BUFFER_INIT(fb->data, pool, 4); return fb;}
static intis_stackable_type(enum flow_type type){ switch (type) { case FLOW_TYPE_IP_PROTOCOL: case FLOW_TYPE_PORT: case FLOW_TYPE_DST_PORT: case FLOW_TYPE_SRC_PORT: case FLOW_TYPE_ICMP_TYPE: case FLOW_TYPE_ICMP_CODE: case FLOW_TYPE_TCP_FLAGS: case FLOW_TYPE_PACKET_LENGTH: case FLOW_TYPE_DSCP: case FLOW_TYPE_FRAGMENT: case FLOW_TYPE_LABEL: return 1;
default: /* The unknown components are not stack-able in default */ return 0; }}
static intbuilder_add_prepare(struct flow_builder *fb){ if (fb->parts[fb->this_type].length) { if (fb->last_type != fb->this_type) return 0;
if (!is_stackable_type(fb->this_type)) return 0; } else { fb->parts[fb->this_type].offset = fb->data.used; }
return 1;}
static voidbuilder_add_finish(struct flow_builder *fb){ fb->parts[fb->this_type].length = fb->data.used - fb->parts[fb->this_type].offset; flow_builder_set_type(fb, fb->this_type);}
static voidpush_pfx_to_buffer(struct flow_builder *fb, u8 pxlen_bytes, byte *ip){ for (int i = 0; i < pxlen_bytes; i++) BUFFER_PUSH(fb->data) = *ip++;}
/** * flow_builder4_add_pfx - add IPv4 prefix * @fb: flowspec builder instance * @n4: net address of type IPv4 * * This function add IPv4 prefix into flowspec builder instance. */intflow_builder4_add_pfx(struct flow_builder *fb, const net_addr_ip4 *n4){ if (!builder_add_prepare(fb)) return 0;
ip4_addr ip4 = ip4_hton(n4->prefix);
BUFFER_PUSH(fb->data) = fb->this_type; BUFFER_PUSH(fb->data) = n4->pxlen; push_pfx_to_buffer(fb, BYTES(n4->pxlen), (byte *) &ip4);
builder_add_finish(fb); return 1;}
/** * flow_builder6_add_pfx - add IPv6 prefix * @fb: flowspec builder instance * @n6: net address of type IPv4 * @pxoffset: prefix offset for @n6 * * This function add IPv4 prefix into flowspec builder instance. This function * should return 1 for successful adding, otherwise returns %0. */intflow_builder6_add_pfx(struct flow_builder *fb, const net_addr_ip6 *n6, u32 pxoffset){ if (!builder_add_prepare(fb)) return 0;
ip6_addr ip6 = ip6_hton(ip6_shift_left(n6->prefix, pxoffset));
BUFFER_PUSH(fb->data) = fb->this_type; BUFFER_PUSH(fb->data) = n6->pxlen; BUFFER_PUSH(fb->data) = pxoffset; push_pfx_to_buffer(fb, BYTES(n6->pxlen - pxoffset), ((byte *) &ip6));
builder_add_finish(fb); return 1;}
/** * flow_builder_add_op_val - add operator/value pair * @fb: flowspec builder instance * @op: operator * @value: value * * This function add operator/value pair as a part of a flowspec component. It * is required to set appropriate flowspec component type using function * flow_builder_set_type(). This function should return 1 for successful * adding, otherwise returns 0. */intflow_builder_add_op_val(struct flow_builder *fb, byte op, u32 value){ if (!builder_add_prepare(fb)) return 0;
if (fb->this_type == fb->last_type) { /* Remove the end-bit from last operand-value pair of the component */ fb->data.data[fb->last_op_offset] &= 0x7f; } else { BUFFER_PUSH(fb->data) = fb->this_type; }
fb->last_op_offset = fb->data.used;
/* Set the end-bit for operand-value pair of the component */ op |= 0x80;
/* Label component values SHOULD be encoded as 4-octet quantities */ if ((value > 0xffff) || (fb->this_type == FLOW_TYPE_LABEL)) { BUFFER_PUSH(fb->data) = op | 0x20; put_u32(BUFFER_INC(fb->data, 4), value); } else if (value > 0xff) { BUFFER_PUSH(fb->data) = op | 0x10; put_u16(BUFFER_INC(fb->data, 2), value); } else { BUFFER_PUSH(fb->data) = op; BUFFER_PUSH(fb->data) = (u8) value; }
builder_add_finish(fb); return 1;}
/** * flow_builder_add_val_mask - add value/bitmask pair * @fb: flowspec builder instance * @op: operator * @value: value * @mask: bitmask * * It is required to set appropriate flowspec component type using function * flow_builder_set_type(). Note that for negation, value must be zero or equal * to bitmask. */intflow_builder_add_val_mask(struct flow_builder *fb, byte op, u32 value, u32 mask){ u32 a = value & mask; u32 b = ~value & mask;
if (a) { flow_builder_add_op_val(fb, op ^ 0x01, a); op |= FLOW_OP_AND; }
if (b) flow_builder_add_op_val(fb, op ^ 0x02, b);
return 1;}
/** * flow_builder_set_type - set type of next flowspec component * @fb: flowspec builder instance * @type: flowspec component type * * This function sets type of next flowspec component. It is necessary to call * this function before each changing of adding flowspec component. */voidflow_builder_set_type(struct flow_builder *fb, enum flow_type type){ fb->last_type = fb->this_type; fb->this_type = type;}
static voidbuilder_write_parts(struct flow_builder *fb, byte *buf){ for (int i = 1; i < FLOW_TYPE_MAX; i++) { if (fb->parts[i].length) { memcpy(buf, fb->data.data + fb->parts[i].offset, fb->parts[i].length); buf += fb->parts[i].length; } }}
/** * flow_builder4_finalize - assemble final flowspec data structure &net_addr_flow4 * @fb: flowspec builder instance * @lpool: linear memory pool * * This function returns final flowspec data structure &net_addr_flow4 allocated * onto @lpool linear memory pool. */net_addr_flow4 *flow_builder4_finalize(struct flow_builder *fb, linpool *lpool){ uint data_len = fb->data.used + (fb->data.used < 0xf0 ? 1 : 2); net_addr_flow4 *f = lp_alloc(lpool, sizeof(struct net_addr_flow4) + data_len);
ip4_addr prefix = IP4_NONE; uint pxlen = 0;
if (fb->parts[FLOW_TYPE_DST_PREFIX].length) { byte *part = fb->data.data + fb->parts[FLOW_TYPE_DST_PREFIX].offset; prefix = flow_read_ip4_part(part); pxlen = flow_read_pxlen(part); } *f = NET_ADDR_FLOW4(prefix, pxlen, data_len);
builder_write_parts(fb, f->data + flow_write_length(f->data, fb->data.used));
return f;}
/** * flow_builder6_finalize - assemble final flowspec data structure &net_addr_flow6 * @fb: flowspec builder instance * @lpool: linear memory pool for allocation of * * This function returns final flowspec data structure &net_addr_flow6 allocated * onto @lpool linear memory pool. */net_addr_flow6 *flow_builder6_finalize(struct flow_builder *fb, linpool *lpool){ uint data_len = fb->data.used + (fb->data.used < 0xf0 ? 1 : 2); net_addr_flow6 *n = lp_alloc(lpool, sizeof(net_addr_flow6) + data_len);
ip6_addr prefix = IP6_NONE; uint pxlen = 0;
if (fb->parts[FLOW_TYPE_DST_PREFIX].length) { byte *part = fb->data.data + fb->parts[FLOW_TYPE_DST_PREFIX].offset; prefix = flow_read_ip6_part(part); pxlen = flow_read_pxlen(part); } *n = NET_ADDR_FLOW6(prefix, pxlen, data_len);
builder_write_parts(fb, n->data + flow_write_length(n->data, fb->data.used));
return n;}
/** * flow_builder_clear - flush flowspec builder instance for another flowspec creation * @fb: flowspec builder instance * * This function flushes all data from builder but it maintains pre-allocated * buffer space. */voidflow_builder_clear(struct flow_builder *fb){ BUFFER(byte) data; BUFFER_FLUSH(fb->data);
BUFFER_SHALLOW_COPY(data, fb->data); memset(fb, 0, sizeof(struct flow_builder)); BUFFER_SHALLOW_COPY(fb->data, data);}
/* * Flowspec explication */
/** * flow_explicate_buffer_size - return buffer size needed for explication * @part: flowspec part to explicate * * This function computes and returns a required buffer size that has to be * preallocated and passed to flow_explicate_part(). Note that it returns number * of records, not number of bytes. */uintflow_explicate_buffer_size(const byte *part){ const byte *pos = part + 1; uint first = 1; uint len = 0;
while (1) { /* * Conjunction sequences represent (mostly) one interval, do not count * additional AND-ed operators. Ignore AND bit for the first operator. */ if (!isset_and(pos) || first) len++;
/* * The exception is that NEQ operator adds one more interval (by splitting * one of intervals defined by other operators). */ if (num_op(pos) == FLOW_OP_NEQ) len++;
if (isset_end(pos)) break;
first = 0; pos = pos + 1 + get_value_length(pos); }
return len;}
static int flow_uint_cmp(const void *p1, const void *p2){ return uint_cmp(* (const uint *) p1, * (const uint *) p2); }
/** * flow_explicate_part - compute explicit interval list from flowspec part * @part: flowspec part to explicate * @buf: pre-allocated buffer for result * * This function analyzes a flowspec part with numeric operators (e.g. port) and * computes an explicit interval list of allowed values. The result is written * to provided buffer @buf, which must have space for enough interval records as * returned by flow_explicate_buffer_size(). The intervals are represented as * two-sized arrays of lower and upper bound, both including. The return value * is the number of intervals in the buffer. */uintflow_explicate_part(const byte *part, uint (*buf)[2]){ /* * The Flowspec numeric expression is almost in DNF form (as union of * intersections), where each operator represents one elementary interval. * The exception is NEQ operator, which represents union of two intervals, * separated by the excluded value. Naive algorithm would be like: * * A <- empty set of intervals * for each sequence of operators in conjunction * { * B <- empty set of intervals * for each operator in the current sequence * { * C <- one or two elementary intervals from the current operator * B <- intersection(B, C) * } * A <- union(A, B) * } * * We simplify this by representing B just as one interval (vars lo, hi) and a * list of excluded values. After the inner cycle, we expand that to a proper * list of intervals that is added to existing ones from previous cycles. * Finally, we sort and merge intersecting or touching intervals in A. * * The code handles up to 32bit values in numeric operators. Intervals are * represented by lower and upper bound, both including. Intermediate values * use s64 to simplify representation of excluding bounds for 0 and UINT32_MAX. */
const byte *pos = part + 1; const s64 max = 0xffffffff; s64 lo = 0; s64 hi = max; uint num = 0; uint neqs = 0;
/* Step 1 - convert conjunction sequences to lists of intervals */ while (1) { uint op = num_op(pos); uint len = get_value_length(pos); s64 val = get_value(pos + 1, len); uint last = isset_end(pos); const byte *next_pos = pos + 1 + len;
/* Get a new interval from this operator */ s64 nlo = (op & FLOW_OP_LT) ? 0 : ((op & FLOW_OP_EQ) ? val : (val + 1)); s64 nhi = (op & FLOW_OP_GT) ? max : ((op & FLOW_OP_EQ) ? val : (val - 1));
/* Restrict current interval */ lo = MAX(lo, nlo); hi = MIN(hi, nhi);
/* Store NEQs for later */ if (op == FLOW_OP_NEQ) { buf[num + neqs][0] = val; buf[num + neqs][1] = 0; neqs++; }
/* End of conjunction sequence */ if (last || !isset_and(next_pos)) { if (neqs) { /* Sort stored NEQs */ qsort(buf + num, neqs, 2 * sizeof(uint), flow_uint_cmp);
/* Dump stored NEQs as intervals */ uint base = num; for (uint i = 0; i < neqs; i++) { val = buf[base + i][0];
if ((val < lo) || (val > hi)) continue;
if (val == lo) { lo++; continue; }
if (val == hi) { hi--; continue; }
buf[num][0] = lo; buf[num][1] = val - 1; num++;
lo = val + 1; }
neqs = 0; }
/* Save final interval */ if (lo <= hi) { buf[num][0] = lo; buf[num][1] = hi; num++; }
lo = 0; hi = max; }
if (last) break;
pos = next_pos; }
if (num < 2) return num;
/* Step 2 - Sort and merge list of intervals */ qsort(buf, num, 2 * sizeof(uint), flow_uint_cmp);
uint i = 0, j = 0; while (i < num) { lo = buf[i][0]; hi = buf[i][1]; i++;
/* If intervals are intersecting or just touching, merge them */ while ((i < num) && ((s64) buf[i][0] <= (hi + 1))) { hi = MAX(hi, (s64) buf[i][1]); i++; }
buf[j][0] = lo; buf[j][1] = hi; j++; }
return j;}
/* * Net Formatting */
/* Flowspec operators for [op, value]+ pairs */
static const char *num_op_str(const byte *op){ switch (*op & 0x07) { case FLOW_OP_TRUE: return "true"; case FLOW_OP_EQ: return "="; case FLOW_OP_GT: return ">"; case FLOW_OP_GEQ: return ">="; case FLOW_OP_LT: return "<"; case FLOW_OP_LEQ: return "<="; case FLOW_OP_NEQ: return "!="; case FLOW_OP_FALSE: return "false"; }
return NULL;}
static const char *fragment_val_str(u8 val){ switch (val) { case 1: return "dont_fragment"; case 2: return "is_fragment"; case 4: return "first_fragment"; case 8: return "last_fragment"; } return "???";}
static voidnet_format_flow_ip(buffer *b, const byte *part, int ipv6){ uint pxlen = part[1]; if (ipv6) { uint pxoffset = part[2]; if (pxoffset) buffer_print(b, "%I6/%u offset %u; ", flow_read_ip6_part(part), pxlen, pxoffset); else buffer_print(b, "%I6/%u; ", flow_read_ip6_part(part), pxlen); } else { buffer_print(b, "%I4/%u; ", flow_read_ip4_part(part), pxlen); }}
static voidnet_format_flow_num(buffer *b, const byte *part){ const byte *last_op = NULL; const byte *op = part+1; uint val; uint len; uint first = 1;
while (1) { if (!first) { /* XXX: I don't like this so complicated if-tree */ if (!isset_and(op) && ((num_op( op) == FLOW_OP_EQ) || (num_op( op) == FLOW_OP_GEQ)) && ((num_op(last_op) == FLOW_OP_EQ) || (num_op(last_op) == FLOW_OP_LEQ))) { b->pos--; /* Remove last char (it is a space) */ buffer_puts(b, ","); } else { buffer_puts(b, isset_and(op) ? "&& " : "|| "); } } first = 0;
len = get_value_length(op); val = get_value(op+1, len);
if (!isset_end(op) && !isset_and(op) && isset_and(op+1+len) && (num_op(op) == FLOW_OP_GEQ) && (num_op(op+1+len) == FLOW_OP_LEQ)) { /* Display interval */ buffer_print(b, "%u..", val); op += 1 + len; len = get_value_length(op); val = get_value(op+1, len); buffer_print(b, "%u", val); } else if (num_op(op) == FLOW_OP_EQ) { buffer_print(b, "%u", val); } else { buffer_print(b, "%s %u", num_op_str(op), val); }
if (isset_end(op)) { buffer_puts(b, "; "); break; } else { buffer_puts(b, " "); }
last_op = op; op += 1 + len; }}
static voidnet_format_flow_bitmask(buffer *b, const byte *part){ const byte *op = part+1; uint val; uint len; uint first = 1;
while (1) { if (!first) buffer_puts(b, isset_and(op) ? "&& " : "|| ");
first = 0;
len = get_value_length(op); val = get_value(op+1, len);
/* * Not Match Show * ------------------ * 0 0 !0/B * 0 1 B/B * 1 0 0/B * 1 1 !B/B */
if ((*op & 0x3) == 0x3 || (*op & 0x3) == 0) buffer_puts(b, "!");
if (*part == FLOW_TYPE_FRAGMENT && (val == 1 || val == 2 || val == 4 || val == 8)) buffer_print(b, "%s%s", ((*op & 0x1) ? "" : "!"), fragment_val_str(val)); else buffer_print(b, "0x%x/0x%x", ((*op & 0x1) ? val : 0), val);
if (isset_end(op)) { buffer_puts(b, "; "); break; } else { buffer_puts(b, " "); }
op += 1 + len; }}
static uintnet_format_flow(char *buf, uint blen, const byte *data, uint dlen, int ipv6){ buffer b = { .start = buf, .pos = buf, .end = buf + blen, };
const byte *part = flow_first_part(data); *buf = 0;
if (ipv6) buffer_puts(&b, "flow6 { "); else buffer_puts(&b, "flow4 { ");
while (part) { buffer_print(&b, "%s ", flow_type_str(*part, ipv6));
switch (*part) { case FLOW_TYPE_DST_PREFIX: case FLOW_TYPE_SRC_PREFIX: net_format_flow_ip(&b, part, ipv6); break; case FLOW_TYPE_IP_PROTOCOL: /* == FLOW_TYPE_NEXT_HEADER */ case FLOW_TYPE_PORT: case FLOW_TYPE_DST_PORT: case FLOW_TYPE_SRC_PORT: case FLOW_TYPE_ICMP_TYPE: case FLOW_TYPE_ICMP_CODE: case FLOW_TYPE_PACKET_LENGTH: case FLOW_TYPE_DSCP: case FLOW_TYPE_LABEL: net_format_flow_num(&b, part); break; case FLOW_TYPE_TCP_FLAGS: case FLOW_TYPE_FRAGMENT: net_format_flow_bitmask(&b, part); break; }
part = flow_next_part(part, data+dlen, ipv6); }
buffer_puts(&b, "}");
if (b.pos == b.end) { b.pos = b.start + MIN(blen - 6, strlen(b.start)); buffer_puts(&b, " ...}"); }
return b.pos - b.start;}
/** * flow4_net_format - stringify flowspec data structure &net_addr_flow4 * @buf: pre-allocated buffer for writing a stringify net address flowspec * @blen: free allocated space in @buf * @f: flowspec data structure &net_addr_flow4 for stringify * * This function writes stringified @f into @buf. The function returns number * of written chars. If final string is too large, the string will ends the with * ' ...}' sequence and zero-terminator. */uintflow4_net_format(char *buf, uint blen, const net_addr_flow4 *f){ return net_format_flow(buf, blen, f->data, f->length - sizeof(net_addr_flow4), 0);}
/** * flow6_net_format - stringify flowspec data structure &net_addr_flow6 * @buf: pre-allocated buffer for writing a stringify net address flowspec * @blen: free allocated space in @buf * @f: flowspec data structure &net_addr_flow4 for stringify * * This function writes stringified @f into @buf. The function returns number * of written chars. If final string is too large, the string will ends the with * ' ...}' sequence and zero-terminator. */uintflow6_net_format(char *buf, uint blen, const net_addr_flow6 *f){ return net_format_flow(buf, blen, f->data, f->length - sizeof(net_addr_flow6), 1);}