1 #include "asn1.h"
2 
scan_asn1BITSTRING(const char * src,const char * max,const char ** s,size_t * l)3 size_t scan_asn1BITSTRING(const char* src,const char* max,const char** s,size_t* l) {
4   size_t tmp;
5   unsigned long tag;
6   enum asn1_tagclass tc;
7   enum asn1_tagtype tt;
8   if ((tmp=scan_asn1string(src,max,&tc,&tt,&tag,s,l)))
9     if (tc==UNIVERSAL && tt==PRIMITIVE && tag==BIT_STRING) {
10       unsigned char lastbyte;
11       if (*l==0 ||	/* length must be at least 1 because for bit strings, the first octet contains the number of unused bits in the last octet */
12 	  (unsigned char)(**s)>7)	/* the number of unused bits in the last octet must not be negative and can be at most 7 */
13 	return 0;
14       /* these are DER checks */
15       /* can't have unused bits if the length is 0 */
16       if (*l==1 && **s)
17 	return 0;
18       /* now check if the unused bits are 0 */
19       lastbyte=(*s)[*l+1];
20       if (lastbyte & (0xff >> (8-**s)))
21 	return 0;
22       *l=(*l-1)*8-(unsigned char)(**s);
23       ++*s;
24       return tmp;
25     }
26   return 0;
27 }
28