fpasn.pp 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. unit fpasn;
  2. {$mode ObjFPC}{$H+}
  3. {$modeswitch advancedrecords}
  4. interface
  5. uses
  6. Basenenc, Classes, SysUtils, fphashutils;
  7. const
  8. ASN1_BOOL = $01;
  9. ASN1_INT = $02;
  10. ASN1_BITSTR = $03;
  11. ASN1_OCTSTR = $04;
  12. ASN1_NULL = $05;
  13. ASN1_OBJID = $06;
  14. ASN1_ENUM = $0A;
  15. ASN1_UTF8STRING = $0C;
  16. ASN1_PRINTABLESTRING = $13;
  17. ASN1_IA5STRING = $16;
  18. ASN1_UTCTIME = $17;
  19. ASN1_SEQ = $30;
  20. ASN1_SETOF = $31;
  21. ASN1_IPADDR = $40;
  22. ASN1_COUNTER = $41;
  23. ASN1_GAUGE = $42;
  24. ASN1_TIMETICKS = $43;
  25. ASN1_OPAQUE = $44;
  26. ASN1_COUNTER64 = $46;
  27. ASN_emailAddress = '1.2.840.113549.1.9.1';
  28. ASN_commonName = '2.5.4.3';
  29. ASN_subjectAltName = '2.5.29.17';
  30. // ASN_organizationName = '2.5.4.10';
  31. // ASN_organizationalUnitName = '2.5.4.11';
  32. // ASN_countryName = '2.5.4.6';
  33. // ASN_stateOrProvince Name = '2.5.4.8';
  34. // ASN_localityName = '2.5.4.7';
  35. ASN_ecPublicKey = '1.2.840.10045.2.1';
  36. // ASN_prime256v1 = '1.2.840.10045.3.1.7';
  37. ASN_secp256r1 = '1.2.840.10045.3.1.7';
  38. ASN_ecdsa_with_SHA256 = '1.2.840.10045.4.3.2';
  39. ASN_ecdsa_with_SHA512 = '1.2.840.10045.4.3.4';
  40. ASN_ecdsa_with_SHA384 = '1.2.840.10045.4.3.3';
  41. ASN_ecdsa_with_SHA224 = '1.2.840.10045.4.3.1';
  42. ASN_MaxOIDSize = 1000;
  43. //------------------------------------------------------------------------------
  44. // ASN
  45. //------------------------------------------------------------------------------
  46. procedure ASNEncodeOID(const Value: Int64; var Result: AnsiString);
  47. function ASNDecodeOID(var Start: Integer; const S: AnsiString): Int64; overload;
  48. function ASNDecodeOID(var Buffer: PByte; BufferEnd: PByte): Int64; overload;
  49. function ASNGetEncodedLen(const Len: Integer): Integer;
  50. procedure ASNEncodeLen(const Len: Integer; var Buffer: TBytes);
  51. function ASNReadLen(var Buffer: PByte; BufferEnd: PByte): Int32;
  52. procedure ASNEncodeInt(Value: Int64; var Result: TBytes);
  53. procedure ASNEncodeUInt(Value: Integer; var Result: TBytes);
  54. procedure ASNWriteNull(s: TStream);
  55. procedure ASNWriteInt(Value: Int64; s: TStream);
  56. procedure ASNWriteBigInt(Value: TBytes; s: TStream);
  57. procedure ASNWriteObjID(const ObjID: string; s: TStream);
  58. function ASNWriteSequenceBegin(s: TMemoryStream): int64;
  59. procedure ASNWriteSequenceEnd(SeqBegin: int64; s: TMemoryStream);
  60. function ASNWriteBitStrBegin(s: TMemoryStream): int64;
  61. procedure ASNWriteBitStrEnd(BitStrBegin: int64; s: TMemoryStream);
  62. // Encodes ASN.1 object to binary form
  63. procedure ASNObject(const Data: AnsiString; const ASNType: Integer; var Buffer: TBytes);
  64. // Encodes an MIB OID String to binary form
  65. procedure MibToId(Mib: AnsiString; var Result: AnsiString);
  66. // Decodes MIB OID from binary form to String form.
  67. procedure IdToMib(const Id: AnsiString; var Result: AnsiString); overload;
  68. function IdToMib(Buffer, BufferEnd: PByte): string; overload;
  69. procedure ASNDebug(const Buffer: TBytes; var Output: TBytes);
  70. procedure ASNDebugList(const Prefix: string; List: TStrings);
  71. procedure ASNParse(const Buffer: TBytes; List: TStrings);
  72. procedure ASNParse_GetItem(List: TStrings; Index: integer; out ASNType, ASNSize: integer);
  73. function ASNParse_GetIntBytes(List: TStrings; ListIndex: integer; ID: int64): TBytes;
  74. function ASNFetch(var Buffer: PByte; BufferEnd: PByte; Out ASNType, ASNSize: Int32): Boolean; overload;
  75. function ASNFetchOID(var Buffer: PByte; BufferEnd: PByte; out OID: UnicodeString): Boolean; overload;
  76. function ASNFetchOID(var Buffer: PByte; BufferEnd: PByte; out OID: AnsiString): Boolean; overload;
  77. implementation
  78. //------------------------------------------------------------------------------
  79. // ASN
  80. //------------------------------------------------------------------------------
  81. procedure ASNEncodeOID(const Value: Int64; var Result: AnsiString);
  82. var
  83. B: Boolean;
  84. I: Integer;
  85. x: Int64;
  86. Modulo: Byte;
  87. S: AnsiString;
  88. begin
  89. S:='';
  90. X := Value;
  91. B := False;
  92. repeat
  93. Modulo := X mod 128;
  94. X := X div 128;
  95. if B then
  96. Modulo := Modulo or $80;
  97. if x > 0 then
  98. B := True;
  99. S:=S+AnsiChar(Modulo);
  100. until x = 0;
  101. for I:=Length(S) downto 1 do
  102. Result:=Result+S[I];
  103. end;
  104. // @Start=0
  105. function ASNDecodeOID(var Start: Integer; const S: AnsiString): Int64;
  106. var
  107. x: Integer;
  108. begin
  109. Result := 0;
  110. repeat
  111. x := Ord(S[Start]);
  112. Inc(Start);
  113. Result := (Result shl 7) + (x and $7F);
  114. until (x and $80) = 0;
  115. end;
  116. function ASNDecodeOID(var Buffer: PByte; BufferEnd: PByte): Int64;
  117. var
  118. x: Byte;
  119. begin
  120. Result := 0;
  121. repeat
  122. if Buffer>=BufferEnd then
  123. exit(-1);
  124. x := Buffer^;
  125. Inc(Buffer);
  126. Result := (Result shl 7) + (x and $7F);
  127. if Result>high(dword) then
  128. exit(-1);
  129. until (x and $80) = 0;
  130. end;
  131. procedure ASNEncodeLen(const Len: Integer; var Buffer: TBytes);
  132. var
  133. x, y: Integer;
  134. S: String;
  135. begin
  136. if Len < $80 then
  137. begin
  138. Buffer:=Concat(Buffer,[Len]);
  139. Exit;
  140. end;
  141. S:='';
  142. x := Len;
  143. repeat
  144. y := x mod 256;
  145. x := x div 256;
  146. S:=S+AnsiChar(y);
  147. until x = 0;
  148. y := Length(S);
  149. y := y or $80;
  150. S:=S+AnsiChar(y);
  151. for x := Length(S) downto 1 do
  152. Buffer:=Concat(Buffer,[Ord(S[x])]);
  153. end;
  154. function ASNGetEncodedLen(const Len: Integer): Integer;
  155. var
  156. x: Integer;
  157. begin
  158. Result := 1;
  159. if Len < $80 then
  160. Exit;
  161. x := Len;
  162. while x > 0 do
  163. begin
  164. x := x div 256;
  165. Inc(Result);
  166. end;
  167. end;
  168. function ASNReadLen(var Buffer: PByte; BufferEnd: PByte): Int32;
  169. var
  170. Len: Integer;
  171. begin
  172. if Buffer>BufferEnd then
  173. raise Exception.Create('20220428135218');
  174. Result := Buffer^;
  175. Inc(Buffer);
  176. if Result < $80 then
  177. Exit;
  178. Len := Result and $7F;
  179. if (Len>4) or (BufferEnd-Buffer < Len) then
  180. raise Exception.Create('20220428135333');
  181. Result := 0;
  182. while Len > 0 do
  183. begin
  184. Result := Result*256 + Buffer^;
  185. Inc(Buffer);
  186. Dec(Len);
  187. end;
  188. end;
  189. procedure ASNEncodeInt(Value: Int64; var Result: TBytes);
  190. var
  191. x: Int64;
  192. y: byte;
  193. neg: Boolean;
  194. S : AnsiString;
  195. begin
  196. S:='';
  197. neg := Value < 0;
  198. x := Abs(Value);
  199. if neg then
  200. x := x - 1;
  201. repeat
  202. y := x mod 256;
  203. x := x div 256;
  204. if neg then
  205. y := not y;
  206. S:=S+AnsiChar(y);
  207. until x = 0;
  208. if (not neg) and (S[Length(S)] > #$7F) then
  209. S:=S+#0
  210. else if neg and (S[Length(S)] < #$80) then
  211. S:=S+#$FF;
  212. for y := S.Length downto 1 do
  213. Result:=Concat(Result,[Ord(S[y])]);
  214. end;
  215. procedure ASNEncodeUInt(Value: Integer; var Result: TBytes);
  216. var
  217. x, y: Integer;
  218. neg: Boolean;
  219. S : String;
  220. begin
  221. neg := Value < 0;
  222. x := Value;
  223. if neg then
  224. x := x and $7FFFFFFF;
  225. S:='';
  226. repeat
  227. y := x mod 256;
  228. x := x div 256;
  229. S:=AnsiChar(y);
  230. until x = 0;
  231. if neg then
  232. S[Length(S)]:=AnsiChar(Ord(S[Length(S)]) or $80);
  233. for y := Length(S) downto 1 do
  234. Result:=Concat(Result,[Ord(S[y])]);
  235. end;
  236. procedure ASNWriteNull(s: TStream);
  237. begin
  238. s.WriteByte(ASN1_NULL);
  239. s.WriteByte(0);
  240. end;
  241. procedure ASNWriteInt(Value: Int64; s: TStream);
  242. var
  243. aBytes, aLen: TBytes;
  244. begin
  245. aBytes:=[];
  246. ASNEncodeInt(Value,aBytes);
  247. aLen:=[];
  248. ASNEncodeLen(length(aBytes),aLen);
  249. s.WriteByte(ASN1_INT);
  250. s.Write(aLen[0],length(aLen));
  251. s.Write(aBytes[0],length(aBytes));
  252. end;
  253. procedure ASNWriteBigInt(Value: TBytes; s: TStream);
  254. var
  255. EndIndex: SizeInt;
  256. aLen: TBytes;
  257. StartIndex: Integer;
  258. begin
  259. EndIndex:=length(Value);
  260. if EndIndex=0 then
  261. raise Exception.Create('20220501115642');
  262. StartIndex:=0;
  263. while (StartIndex<EndIndex) and (Value[StartIndex]=0) do
  264. inc(StartIndex);
  265. if StartIndex=EndIndex then
  266. begin
  267. ASNWriteInt(0,s);
  268. exit;
  269. end;
  270. if Value[StartIndex]>=$80 then
  271. dec(StartIndex);
  272. aLen:=[];
  273. ASNEncodeLen(EndIndex-StartIndex,aLen);
  274. s.WriteByte(ASN1_INT);
  275. s.Write(aLen[0],length(aLen));
  276. if StartIndex<0 then
  277. begin
  278. s.WriteByte(0);
  279. StartIndex:=0;
  280. end;
  281. s.Write(Value[StartIndex],EndIndex-StartIndex);
  282. end;
  283. procedure ASNWriteObjID(const ObjID: string; s: TStream);
  284. var
  285. Mib: Ansistring;
  286. aLen: TBytes;
  287. begin
  288. Mib:='';
  289. MibToId(ObjID,Mib);
  290. aLen:=[];
  291. ASNEncodeLen(length(Mib),aLen);
  292. s.WriteByte(ASN1_OBJID);
  293. s.Write(aLen[0],length(aLen));
  294. s.Write(Mib[1],length(Mib));
  295. end;
  296. function ASNWriteSequenceBegin(s: TMemoryStream): int64;
  297. begin
  298. s.WriteByte(ASN1_SEQ);
  299. s.WriteByte(0);
  300. Result:=s.Position;
  301. end;
  302. procedure ASNWriteSequenceEnd(SeqBegin: int64; s: TMemoryStream);
  303. var
  304. SeqLen: Int64;
  305. aLen: TBytes;
  306. l: SizeInt;
  307. p: PByte;
  308. begin
  309. SeqLen:=s.Position-SeqBegin;
  310. aLen:=[];
  311. ASNEncodeLen(SeqLen,aLen);
  312. l:=length(aLen);
  313. if l>1 then
  314. begin
  315. s.Write(aLen[1],l-1);
  316. p:=PByte(s.Memory);
  317. System.Move(p[SeqBegin],p[SeqBegin+l-1],SeqLen);
  318. System.Move(aLen[0],p[SeqBegin-1],l);
  319. end else
  320. PByte(s.Memory)[SeqBegin-1]:=aLen[0];
  321. end;
  322. function ASNWriteBitStrBegin(s: TMemoryStream): int64;
  323. begin
  324. s.WriteByte(ASN1_BITSTR);
  325. s.WriteByte(0); // length
  326. Result:=s.Position;
  327. s.WriteByte(0); // trailing bit length
  328. end;
  329. procedure ASNWriteBitStrEnd(BitStrBegin: int64; s: TMemoryStream);
  330. begin
  331. ASNWriteSequenceEnd(BitStrBegin,s);
  332. end;
  333. Procedure AppendStringToBuffer(var Buffer: TBytes; const aString : AnsiString);
  334. Var
  335. Buflen,sLen : integer;
  336. begin
  337. bufLen:=Length(Buffer);
  338. sLen:=Length(aString);
  339. SetLength(Buffer,BufLen+sLen);
  340. If (sLen>0) then
  341. Move(aString[1],Buffer[Buflen],sLen);
  342. end;
  343. procedure ASNObject(const Data: AnsiString; const ASNType: Integer; var Buffer: TBytes);
  344. begin
  345. Buffer:=Concat(Buffer,[ASNType]);
  346. ASNEncodeLen(Length(Data), Buffer);
  347. AppendStringToBuffer(Buffer,Data);
  348. end;
  349. procedure DumpExStr(const S: String; var Output: TBytes);
  350. var
  351. I: Integer;
  352. x: Byte;
  353. begin
  354. for I := 1 to Length(S) do
  355. begin
  356. x := Ord(S[I]);
  357. if x in [65..90, 97..122] then
  358. begin
  359. AppendStringToBuffer(Output, ' +''');
  360. AppendStringToBuffer(Output, AnsiChar(x)+'''');
  361. end else
  362. begin
  363. AppendStringToBuffer(Output, ' +#$');
  364. AppendStringToBuffer(Output, HexStr(X,2));
  365. end;
  366. end;
  367. end;
  368. procedure OutputHexa(var Output: TBytes; const S: AnsiString);
  369. var
  370. I: Integer;
  371. P: PByte;
  372. begin
  373. P := PByte(PAnsiChar(S));
  374. for I := 1 to Length(S) do
  375. begin
  376. AppendStringToBuffer(Output, HexStr(P^,2));
  377. Inc(P);
  378. end;
  379. end;
  380. procedure MibToId(Mib: AnsiString; var Result: AnsiString);
  381. function WalkInt(var S: AnsiString): Integer;
  382. var
  383. P : Integer;
  384. begin
  385. P:=Pos('.',S);
  386. If P=0 then
  387. P:=Length(S)+1;
  388. Result:=StrToIntDef(Copy(S,1,P-1),0);
  389. S:=Copy(S,P+1,Length(S));
  390. end;
  391. var
  392. x: Integer;
  393. begin
  394. x := WalkInt(Mib);
  395. x := x*40 + WalkInt(Mib);
  396. ASNEncodeOID(x, Result);
  397. while (Mib<>'') do
  398. begin
  399. x := WalkInt(Mib);
  400. ASNEncodeOID(x, Result);
  401. end;
  402. end;
  403. procedure IdToMib(const Id: AnsiString; var Result: AnsiString);
  404. var
  405. x, y, Index: Integer;
  406. begin
  407. Index := 1;
  408. while Index <= Length(ID) do
  409. begin
  410. x := ASNDecodeOID(Index, ID);
  411. if Index = 2 then
  412. begin
  413. y := x div 40;
  414. x := x mod 40;
  415. Result:=IntToStr(y);
  416. end;
  417. Result:=Result+'.';
  418. Result:=Result+IntToStr(x);
  419. end;
  420. end;
  421. function ASNParseInt(var Buffer: PByte; BufferEnd: PByte; const ASNSize: Integer): Int64;
  422. var
  423. I: Integer;
  424. Negative: Boolean;
  425. X: Byte;
  426. begin
  427. Result := 0;
  428. Negative := False;
  429. for I := 1 to ASNSize do
  430. begin
  431. if Buffer>=BufferEnd then
  432. raise Exception.Create('20220428134948');
  433. X := Buffer^;
  434. if (I = 1) and (X > $7F) then
  435. Negative := True;
  436. if Negative then
  437. X := not X;
  438. Result := Result*256 + X;
  439. if Result>high(longint) then
  440. raise Exception.Create('20220428135614');
  441. Inc(Buffer);
  442. end;
  443. if Negative then
  444. Result := -(Result + 1);
  445. end;
  446. function ASNParseUInt(var Buffer: PByte; BufferEnd: PByte; const ASNSize: Integer): Int64;
  447. var
  448. I: Integer;
  449. begin
  450. Result := 0;
  451. for I := 1 to ASNSize do
  452. begin
  453. if Buffer>=BufferEnd then
  454. raise Exception.Create('20220428135002');
  455. Result := Result*256 + Buffer^;
  456. if Result>high(dword) then
  457. raise Exception.Create('20220428135614');
  458. Inc(Buffer);
  459. end;
  460. end;
  461. // Decode the ASN.1 item of the next element in @Buffer. Type of item is stored in @ASNType
  462. procedure ASNDebugItem(var Buffer: PByte; BufferEnd: PByte; Out ASNType, ASNSize: Integer; var Output: TBytes);
  463. procedure BufToString(out S : AnsiString);
  464. var
  465. SA : AnsiString;
  466. begin
  467. SetLength(SA,ASNSize);
  468. if ASNSize>0 then
  469. begin
  470. Move(Buffer^,SA[1],ASNSize);
  471. inc(Buffer,ASNSize);
  472. end;
  473. S:=SA;
  474. end;
  475. var
  476. n: Integer;
  477. S, S2: AnsiString;
  478. y: Int64;
  479. OldBuffer: PByte;
  480. begin
  481. S:='';
  482. S2:='';
  483. ASNType := ASN1_NULL;
  484. if Buffer>=BufferEnd then
  485. Exit;
  486. ASNType := Buffer^;
  487. Inc(Buffer);
  488. ASNSize := ASNReadLen(Buffer, BufferEnd);
  489. if BufferEnd-Buffer < ASNSize then
  490. Exit;
  491. AppendStringToBuffer(Output,'$');
  492. AppendStringToBuffer(Output, HexStr(ASNType,2));
  493. if (ASNType and $20) > 0 then
  494. begin
  495. if ASNType = ASN1_SEQ then
  496. AppendStringToBuffer(Output, ' SEQUENCE: length ')
  497. else if ASNType = ASN1_SETOF then
  498. AppendStringToBuffer(Output, ' SET: length ')
  499. else
  500. AppendStringToBuffer(Output, ' constructed: length ');
  501. AppendStringToBuffer(Output, IntToStr(ASNSize));
  502. Exit;
  503. end;
  504. case ASNType of
  505. ASN1_INT, ASN1_ENUM, ASN1_BOOL:
  506. begin
  507. if ASNType = ASN1_BOOL then
  508. AppendStringToBuffer(Output, ' BOOL: ')
  509. else if ASNType = ASN1_INT then
  510. AppendStringToBuffer(Output, ' INT: ')
  511. else if ASNType = ASN1_ENUM then
  512. AppendStringToBuffer(Output, ' ENUM: ');
  513. if ASNSize < 8 then
  514. begin
  515. y := ASNParseInt(Buffer, BufferEnd, ASNSize);
  516. AppendStringToBuffer(Output, IntToStr(y));
  517. end else
  518. begin
  519. BufToString(S);
  520. if S[1] = Char(#00) then
  521. begin
  522. Delete(S,1,1);
  523. end;
  524. AppendStringToBuffer(Output, '$');
  525. OutputHexa(Output, S);
  526. end;
  527. end;
  528. ASN1_COUNTER, ASN1_GAUGE, ASN1_TIMETICKS, ASN1_COUNTER64:
  529. begin
  530. if ASNType = ASN1_COUNTER then
  531. AppendStringToBuffer(Output, ' COUNTER: ')
  532. else if ASNType = ASN1_GAUGE then
  533. AppendStringToBuffer(Output, ' GAUGE: ')
  534. else if ASNType = ASN1_TIMETICKS then
  535. AppendStringToBuffer(Output, ' TIMETICKS: ')
  536. else if ASNType = ASN1_COUNTER64 then
  537. AppendStringToBuffer(Output, ' COUNTER64: ');
  538. if ASNSize < 8 then
  539. begin
  540. y := ASNParseUInt(Buffer, BufferEnd, ASNSize);
  541. AppendStringToBuffer(Output, IntToStr(y));
  542. end else
  543. begin
  544. BufToString(S);
  545. AppendStringToBuffer(Output, '$');
  546. OutputHexa(Output, S);
  547. end;
  548. end;
  549. ASN1_OCTSTR, ASN1_OPAQUE:
  550. begin
  551. if ASNType = ASN1_OCTSTR then
  552. AppendStringToBuffer(Output, ' OCTSTR: ')
  553. else if ASNType = ASN1_OPAQUE then
  554. AppendStringToBuffer(Output, ' OPAQUE: ');
  555. BufToString(S);
  556. OutputHexa(Output, S);
  557. end;
  558. ASN1_UTCTIME:
  559. begin // 180131123456Z -> 2018-01-31 12:34:56
  560. AppendStringToBuffer(Output, ' UTCTIME: ');
  561. BufToString(S);
  562. AppendStringToBuffer(Output, S);
  563. end;
  564. ASN1_BITSTR:
  565. begin
  566. AppendStringToBuffer(Output, ' BITSTR: len='+IntToStr(ASNSize)+' TrailBits='+IntToStr(Ord(Buffer^))+' ');
  567. Inc(Buffer); // this is the Trailing Length in bits
  568. Dec(ASNSize);
  569. OldBuffer:=Buffer;
  570. BufToString(S);
  571. OutputHexa(Output, S);
  572. if (ASNType = ASN1_BITSTR) and (OldBuffer^ = ASN1_SEQ) then
  573. begin
  574. // continue to decode the bitstring as ASN.1 formatted content
  575. Buffer:=OldBuffer;
  576. end;
  577. end;
  578. ASN1_UTF8STRING, ASN1_PRINTABLESTRING, ASN1_IA5STRING:
  579. begin
  580. if ASNType = ASN1_UTF8STRING then
  581. AppendStringToBuffer(Output, ' UTF8STRING: ')
  582. else if ASNType = ASN1_PRINTABLESTRING then
  583. AppendStringToBuffer(Output, ' PRINTABLESTRING: ')
  584. else if ASNType = ASN1_IA5STRING then
  585. AppendStringToBuffer(Output, ' IA5STRING: ');
  586. BufToString(S);
  587. AppendStringToBuffer(Output, S);
  588. end;
  589. ASN1_OBJID:
  590. begin
  591. AppendStringToBuffer(Output, ' OBJID: ');
  592. BufToString(S2);
  593. S:='';
  594. IdToMib(S2, S);
  595. AppendStringToBuffer(Output, S);
  596. end;
  597. ASN1_IPADDR:
  598. begin
  599. AppendStringToBuffer(Output, ' IPADDR: ');
  600. for n := 1 to ASNSize do
  601. begin
  602. if n > 1 then
  603. AppendStringToBuffer(Output, '.');
  604. y := Buffer^;
  605. Inc(Buffer);
  606. AppendStringToBuffer(Output, IntToStr(y));
  607. end;
  608. end;
  609. ASN1_NULL:
  610. begin
  611. AppendStringToBuffer(Output, ' NULL: ');
  612. Inc(Buffer, ASNSize);
  613. end;
  614. else // unknown
  615. begin
  616. AppendStringToBuffer(Output, ' unknown: ');
  617. BufToString(S);
  618. OutputHexa(Output, S);
  619. end;
  620. end;
  621. end;
  622. function IdToMib(Buffer, BufferEnd: PByte): string;
  623. var
  624. x: Int64;
  625. begin
  626. Result:='';
  627. while Buffer<BufferEnd do
  628. begin
  629. x := ASNDecodeOID(Buffer, BufferEnd);
  630. if x<0 then
  631. raise Exception.Create('20220427114808');
  632. if Result='' then
  633. begin
  634. Result:=IntToStr(x div 40);
  635. x := x mod 40;
  636. end;
  637. Result:=Result+'.'+IntToStr(x);
  638. end;
  639. end;
  640. // Convert ASN.1 DER encoded buffer to human readable form for debugging
  641. procedure ASNDebug(const Buffer: TBytes; var Output: TBytes);
  642. const
  643. SSpaces: AnsiString = ' ';
  644. var
  645. ASNSize, ASNType, n: Integer;
  646. Indent: Integer;
  647. IndentList: Array of Integer;
  648. StartP, p, EndP: PByte;
  649. begin
  650. if length(Buffer)=0 then exit;
  651. IndentList:=[];
  652. Indent:=0;
  653. StartP:=@Buffer[0];
  654. p:=StartP;
  655. EndP:=StartP+length(Buffer);
  656. while p<EndP do
  657. begin
  658. writeln('ASNDebug p=',p-StartP,' Type=',hexstr(p^,2),' Indent=',length(IndentList));
  659. // check if any sequence/set has ended and unindent
  660. for n := Length(IndentList)-1 downto 0 do
  661. begin
  662. ASNSize := IndentList[n];
  663. if p-StartP >= ASNSize then
  664. begin
  665. Delete(IndentList,n,1);
  666. Dec(Indent, 2);
  667. end;
  668. end;
  669. AppendStringToBuffer(Output, Copy(SSpaces,1,Indent));
  670. ASNDebugItem(p, EndP, ASNType, ASNSize, Output);
  671. if (ASNType and $20) > 0 then
  672. begin
  673. // sequence/set -> indent
  674. Inc(Indent, 2);
  675. IndentList:=Concat(IndentList,[ASNSize+integer(p-StartP)]);
  676. end;
  677. AppendStringToBuffer(Output, #13#10);
  678. end;
  679. end;
  680. procedure ASNParseAdd(List: TStrings; const S: String; const ASNType, ASNSize: Integer);
  681. begin
  682. if ASNSize>high(word) then
  683. raise Exception.Create('20220428160845');
  684. if ASNType>high(word) then
  685. raise Exception.Create('20220428160853');
  686. List.AddObject(S, TObject(PtrInt (ASNType shl 16) or (ASNSize)));
  687. end;
  688. procedure ASNParseAddInt(var Buffer: PByte; BufferEnd: PByte; List: TStrings; const ASNType, ASNSize: Integer; Signed: boolean);
  689. procedure BufToString(var S : AnsiString);
  690. begin
  691. SetLength(S,ASNSize);
  692. if ASNSize=0 then
  693. exit;
  694. Move(Buffer^,S[1],ASNSize);
  695. inc(Buffer, ASNSize);
  696. end;
  697. var
  698. S, S2: AnsiString;
  699. y: Int64;
  700. begin
  701. S:='';
  702. S2:='';
  703. if ASNSize < 8 then
  704. begin
  705. if Signed then
  706. y := ASNParseInt(Buffer, BufferEnd, ASNSize)
  707. else
  708. y := ASNParseUInt(Buffer, BufferEnd, ASNSize);
  709. S:=IntToStr(y);
  710. end else
  711. begin
  712. BufToString(S2);
  713. if S2[1] = AnsiChar(#00) then
  714. Delete(S2,1,1);
  715. BytesToHexStr(S,GetRawStringBytes(S2));
  716. end;
  717. ASNParseAdd(List, S, ASNType, ASNSize);
  718. end;
  719. function ASNFetch(var Buffer: PByte; BufferEnd: PByte; out ASNType,
  720. ASNSize: Int32): Boolean;
  721. var
  722. Len: byte;
  723. begin
  724. Result:=false;
  725. if Buffer>=BufferEnd then exit;
  726. ASNType := Buffer^;
  727. inc(Buffer);
  728. if Buffer>=BufferEnd then exit;
  729. ASNSize := Buffer^;
  730. Inc(Buffer);
  731. if ASNSize < $80 then
  732. Exit(true);
  733. Len := ASNSize and $7F;
  734. if (Len>4) or ((BufferEnd-Buffer)<Len) then
  735. exit;
  736. ASNSize := 0;
  737. while Len > 0 do
  738. begin
  739. ASNSize := ASNSize*256 + Buffer^;
  740. Inc(Buffer);
  741. Dec(Len);
  742. end;
  743. Result:=true;
  744. end;
  745. function ASNFetchOID(var Buffer: PByte; BufferEnd: PByte; out OID: AnsiString): Boolean; overload;
  746. Var
  747. OIDS : String;
  748. begin
  749. Result:=ASNFetchOID(Buffer,BufferEnd,OIDS);
  750. OID:=OIDS;
  751. end;
  752. function ASNFetchOID(var Buffer: PByte; BufferEnd: PByte; out OID: UnicodeString): Boolean;
  753. var
  754. ASNType, ASNSize: Int32;
  755. OIDEnd: PByte;
  756. begin
  757. OID:='';
  758. Result := ASNFetch(Buffer, BufferEnd, ASNType, ASNSize);
  759. if not Result then
  760. Exit;
  761. Result := ASNType = ASN1_OBJID;
  762. if not Result then
  763. Exit;
  764. if ASNSize=0 then
  765. Exit;
  766. if ASNSize>ASN_MaxOIDSize then
  767. Exit;
  768. if (BufferEnd-Buffer)<ASNSize then
  769. Exit;
  770. OIDEnd:=Buffer+ASNSize;
  771. OID:=IdToMib(Buffer, OIDEnd);
  772. Buffer:=OIDEnd;
  773. Result := OID<>'';
  774. end;
  775. // Beginning with the @Start position, decode the ASN.1 item of the next element in @Buffer. Type of item is stored in @ASNType
  776. // @Offset starts at 0
  777. function ASNParseItem(var Buffer: PByte; BufferEnd: PByte; List: TStrings): boolean;
  778. function BufToString(Len : Integer): AnsiString;
  779. begin
  780. SetLength(Result{%H-},Len);
  781. if Len=0 then exit;
  782. Move(Buffer^,Result[1],Len);
  783. inc(Buffer, Len);
  784. end;
  785. var
  786. ASNType, ASNSize: Integer;
  787. n: Integer;
  788. S,S2: AnsiString;
  789. y: Int64;
  790. OldBuffer: PByte;
  791. begin
  792. Result:=false;
  793. if not ASNFetch(Buffer, BufferEnd, ASNType, ASNSize) then
  794. Exit;
  795. if (ASNType and $20) > 0 then
  796. begin // constructed
  797. ASNParseAdd(List, '', ASNType, ASNSize);
  798. Exit;
  799. end;
  800. if (BufferEnd-Buffer) < ASNSize then
  801. Exit;
  802. S:='';
  803. S2:='';
  804. case ASNType of
  805. ASN1_INT, ASN1_ENUM, ASN1_BOOL:
  806. begin
  807. ASNParseAddInt(Buffer, BufferEnd, List, ASNType, ASNSize, true);
  808. end;
  809. ASN1_COUNTER, ASN1_GAUGE, ASN1_TIMETICKS, ASN1_COUNTER64:
  810. begin
  811. ASNParseAddInt(Buffer, BufferEnd, List, ASNType, ASNSize, false);
  812. end;
  813. ASN1_BITSTR, ASN1_OCTSTR, ASN1_OPAQUE:
  814. begin
  815. if ASNType = ASN1_BITSTR then
  816. begin // this is the Trailing Length in bits
  817. Inc(Buffer);
  818. Dec(ASNSize);
  819. end;
  820. OldBuffer:=Buffer;
  821. S2 := BufToString(ASNSize);
  822. S:=BytesToHexStr(S2);
  823. ASNParseAdd(List, S, ASNType, ASNSize);
  824. if (ASNType = ASN1_BITSTR) and (OldBuffer^ = ASN1_SEQ) then
  825. begin
  826. // continue to decode the bitstring as ASN.1 formatted content
  827. Buffer:=OldBuffer;
  828. end;
  829. end;
  830. ASN1_UTF8STRING, ASN1_PRINTABLESTRING, ASN1_IA5STRING:
  831. begin
  832. S2 := BufToString(ASNSize);
  833. ASNParseAdd(List, S2, ASNType, ASNSize);
  834. end;
  835. ASN1_UTCTIME:
  836. begin // 180131123456Z -> 2018-01-31 12:34:56
  837. S2 := BufToString(ASNSize);
  838. ASNParseAdd(List, S2, ASNType, ASNSize);
  839. end;
  840. ASN1_OBJID:
  841. begin
  842. S2 := BufToString(ASNSize);
  843. IdToMib(S2, S);
  844. ASNParseAdd(List, S, ASNType, ASNSize);
  845. end;
  846. ASN1_IPADDR:
  847. begin
  848. for n := 1 to ASNSize do
  849. begin
  850. if n <> 1 then
  851. S:=S+'.';
  852. y := Buffer^;
  853. Inc(Buffer);
  854. S:=S+IntToStr(y);
  855. end;
  856. ASNParseAdd(List, S, ASNType, ASNSize);
  857. end;
  858. ASN1_NULL:
  859. begin
  860. ASNParseAdd(List, '', ASNType, ASNSize);
  861. Inc(Buffer, ASNSize);
  862. end;
  863. else // unknown
  864. begin
  865. S2 := BufToString(ASNSize);
  866. S:=BytesToHexStr(S2);
  867. ASNParseAdd(List, S, ASNType, ASNSize);
  868. end;
  869. end;
  870. end;
  871. procedure ASNDebugList(const Prefix: string; List: TStrings);
  872. var
  873. i, ASNType, ASNSize: Integer;
  874. begin
  875. for i:=0 to List.Count-1 do begin
  876. ASNParse_GetItem(List,i,ASNType,ASNSize);
  877. writeln(Prefix,' ',i,'/',List.Count,' ASNType=',hexstr(ASNType,2),' ASNSize=',ASNSize,' S="',List[i],'"');
  878. end;
  879. end;
  880. procedure ASNParse(const Buffer: TBytes; List: TStrings);
  881. var
  882. P, EndP: PByte;
  883. O : Tbytes;
  884. begin
  885. ASNDebug(Buffer,O);
  886. Writeln(TEncoding.UTF8.GetAnsiString(O));
  887. if length(Buffer)=0 then exit;
  888. P:=@Buffer[0];
  889. EndP:=P+length(Buffer);
  890. while P < EndP do
  891. ASNParseItem(p, EndP, List);
  892. end;
  893. procedure ASNParse_GetItem(List: TStrings; Index: integer; out ASNType,
  894. ASNSize: integer);
  895. var
  896. h: PtrUInt;
  897. begin
  898. h:=PtrUInt(List.Objects[Index]);
  899. ASNType:=h shr 16;
  900. ASNSize:=h and $ffff;
  901. end;
  902. function ASNParse_GetIntBytes(List: TStrings; ListIndex: integer; ID: int64
  903. ): TBytes;
  904. var
  905. ASNType, ASNSize, i: Integer;
  906. Value: Int64;
  907. begin
  908. ASNParse_GetItem(List,ListIndex,ASNType,ASNSize);
  909. if ASNType<>ASN1_INT then
  910. raise Exception.Create(IntToStr(Id));
  911. if ASNSize<8 then
  912. begin
  913. SetLength(Result{%H-},ASNSize);
  914. Value:=StrToInt64Def(List[ListIndex],0);
  915. for i:=ASNSize-1 downto 0 do
  916. begin
  917. Result[i]:=Value and $ff;
  918. Value:=Value shr 8;
  919. end;
  920. end else
  921. Result:=HexStrToBytes(List[ListIndex]);
  922. if length(Result)<1 then
  923. raise Exception.Create(IntToStr(Id));
  924. end;
  925. end.