File: chkproc.patch

package info (click to toggle)
chkrootkit 0.58b-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,796 kB
  • sloc: sh: 187,089; ansic: 3,779; makefile: 103
file content (862 lines) | stat: -rw-r--r-- 26,299 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
From: Adrian Bridgett <adrian@smop.co.uk>
Date: Fri, 24 Jul 2020 14:59:35 +0200
Subject: chkproc

1. Fix race condition where processes that start/exit between checking
/proc and ps(1) output are flagged as hidden.  This was first written
by Adrian Bridgett <adrian@smop.co.uk> in Fri, 24 Jul 2020 14:59:35
+0200. (Except for a single-line change to set pv to 3, which was from
Giuseppe Iuculano <giuseppe@iuculano.it> Date: Sun, 9 Jul 2017
18:42:55 +0200 -- this is kept, as it seems a suitable default for all
platforms, but in fact chkrootkit explicitly sets pv anyway)

2. Comment out code that sends signals to individual processes. This
is very risky as it is most likely to result in non-rootkits being
killed or resuming. It does slightly reduce functionality -- ideally
such a feature would be done in a separate process to keep
chkproc. This was contributed by Francois Marier <francois@debian.org>
with a date: Mon, 21 Apr 2008 11:17:03 +0000. (This is merged into
this patch to make it easier to maintain).

3. Fix various compilation errors and warnings. These were originally contributed
by =?utf-8?q?Christian_G=C3=B6ttsche?= <cgzones@googlemail.com>
Date: on Fri, 24 Jul 2020 16:08:40 +0200.
Mainly:
a) ignore return value from fgets in readline
b) use size_t not int in readline, dodgy_process
c) use ssize_t in dodgy_process
d) declare ps_cmds and commands that use it as 'const'
(This is merged into this patch to make it easier to maintain).

4. various fixes (Author: richard.lewis.debian@googlemail.com)
a) Support NetBSD
   PID 0 is allowed (although 1 is still init)
   netbsd's ps(1) is incompatible with
   the other ps commands.
	 It does support getpriority(2) (As does FreeBSD?) so enable that check.
	 The contents of /proc/pid are similar to linux (excpet for hidden thread ids)
	  so reuse that code.

b) Also works on __android (termux)
   Android is linux, but many things are not accessible.

c) Simplify and correct checking for linux threads
   We do not need a separate isathread variable, just set psproc snd dirproc to 1
	 for numeric tids (TIDs are always numeric)

d) Allow -p on any OS
   chkrootkit is actually passing -p already, but chkproc only allowed it on linux
   keep the checks for "numeric tids have hidden dirs in /proc" linux-specific
	 This allows you to, eg, use gnu's ps on OpenBSD, or to test parsing

e) replace tabs with spaces

f) New (deliberately undocumented) args to allow using custom commands for ps
   (use -p to choose how to parse output!) or to use a different dir as /proc
	 and to disable the use of getpriority(2). This allows for testing of the logic

g) Ensure a valid return value
   exit codes should be 0...255 not an arbitrary int: so just return 0 or 1

h) Include fnctl.h -- needed on some systems

i) Better output
   When outputting details of processes, include the contents,
   without trailing whitespce, of
    /proc/pid/cmdline
	/proc/pid/comm    (linux only)
	/proc/pid/cgroup  (linux only)
   (Introduce a new function showfile to do this)
   Refactor code to show a symlink target into a function to avoid duplication.
   readdir is section 3 not 2
   Last-Updated: 2024-12-15

Forwarded: yes
 (Forwarded by email: 21 Dec 2024)
Last-Updated: 2024-12-15
---
 chkproc.c | 709 +++++++++++++++++++++++++++++++++++++++-----------------------
 1 file changed, 443 insertions(+), 266 deletions(-)

diff --git a/chkproc.c b/chkproc.c
index 353a269..6c4b6e3 100644
--- a/chkproc.c
+++ b/chkproc.c
@@ -51,16 +51,13 @@
   2006/01/11 - Fix signal 25 on parisc linux and return of kill() -
                Thanks to Lantz Moore
 
-  2014/07/16 -  MAX_PROCESSES now is 999999 - 
-		Thanks to Nico Koenrades
+  2014/07/16 -  MAX_PROCESSES now is 999999 -
+   Thanks to Nico Koenrades
 
-  2017/04/13 -  MAX_PROCESSES now is 4194384 if linux64 
-		Thanks to DS Store
+  2017/04/13 -  MAX_PROCESSES now is 4194384 if linux64
+   Thanks to DS Store
 */
 
-#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__sun)
-int main (){ return 0; }
-#else
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
@@ -70,317 +67,497 @@ int main (){ return 0; }
 #include <stdlib.h>
 #include <unistd.h>
 #include <signal.h>
-#include <sys/stat.h>
+/*#include <sys/stat.h>*/
 #if defined(__sun)
 #include <procfs.h>
+#endif
 #include <fcntl.h>
-#endif
 #include <sys/resource.h>
 
-#define PS_SUN 0
-#define PS_LOL 1
-#define PS_COM 2
-#define PS_LNX 3
-#define PS_MAX 3
 #define ENYELKM "/proc/12345"
 // #define ENYELKM "/tmp/12345"
 
-#if defined(__sun)
+#if defined(__sun) || defined(__NetBSD__)
 #define FIRST_PROCESS 0
 #else
 #define FIRST_PROCESS 1
 #endif
-#define MAX_PROCESSES 9999999 
-#if (defined (__x86_64) > 0  || defined (__amd64) > 0) 
-#undef MAX_PROCESSES
+
+#if (defined (__x86_64) > 0 || defined (__amd64) > 0)
 #define MAX_PROCESSES 4194304
+#else
+#define MAX_PROCESSES 9999999
 #endif
+
 #define MAX_BUF 1024
 
 #if !defined (SIGXFSZ)
 #define SIGXFSZ 25
 #endif
 
-static char *ps_cmds[] = {
-	    "ps -edf",
-	    "ps auxw",
-	    "ps mauxw 2>&1 ",
-            "ps auxw -T|tr -s ' '|cut -d' ' -f2-",
-          };
 
-int psproc [MAX_PROCESSES+1];
-int dirproc[MAX_PROCESSES+1];
-#if defined(__linux__)
-int isathread[MAX_PROCESSES+1];
+#define PS_SUN 0
+#define PS_COM 2
+#define PS_NetBSD 4
+#define PS_LINUX 3
+#define PS_MAX 4
+const char *ps_cmds[] = {
+  "ps -edf", // SUN
+  "ps auxw", // fallback
+  "ps mauxw 2>&1 ", // "COM" - FreeBSD, etc
+  "ps -eTo pid= -o spid=", // linux
+  "ps -axo pid=" // NetBSD
+};
+
+#define PROCDIR "/proc"
+
+// nb: we rely on global vars being initialized to 0
+int psproc [MAX_PROCESSES+1]; // pids in ps(1) output
+int dirproc[MAX_PROCESSES+1]; // pids in /proc/ dir
+int recheck[MAX_PROCESSES+1]; // list of pids to recheck
+
+#if !defined(__FreeBSD__) // however, getpriority does exist on FreeBSD?
+// getpriority(2) may reveal hidden processes
+#define CHECK_PRIORITY 1
+#else
+#define CHECK_PRIORITY 0
+#endif
+
+#ifdef __GNUC__
+__attribute__((__noreturn__))
 #endif
+void usage(void){
+  fprintf(stderr, "Usage: chkproc [-v] [-p ps-syntax] [-N max-pid-to-check]\n");
+  exit(1);
+}
 
-/*
- * read at most the first (size-1) chars into s and terminate with a '\0'.
- * stops reading after a newline or EOF.  if a newline is read, it will be
- * the last char in the string.  if no newline is found in the first
- * (size-1) chars, then keep reading and discarding chars until a newline
- * is found or EOF.
+/* read a line from stream into s. the line is capped at size chars.
+ * read at most (size-1) chars from stream into s and terminate with a
+ * '\0'.  stops reading after a newline (which is retained )or EOF. If
+ * no newline was read, then also keep reading from stream discarding
+ * chars until a newline is found or EOF.
  */
-char *readline(char *s, int size, FILE *stream)
+char *readline(char *s, size_t size, FILE *stream)
 {
   char *rv = fgets(s, size, stream);
 
   if (strlen(s) == (size-1) && s[size-1] != '\n')
-  {
-    char buf[MAX_BUF];
-    fgets(buf, MAX_BUF, stream);
-    while (strlen(buf) == (MAX_BUF-1) && buf[MAX_BUF-1] != '\n')
     {
-      fgets(buf, MAX_BUF, stream);
+      char buf[MAX_BUF];
+      (void) !fgets(buf, MAX_BUF, stream);
+      while (strlen(buf) == (MAX_BUF-1) && buf[MAX_BUF-1] != '\n')
+        {
+          (void) !fgets(buf, MAX_BUF, stream);
+        }
     }
-  }
 
   return rv;
 }
 
+// show target of symlink link (at most MAX_BUF-1 chars). The other
+// args construct the output text. (eg link is relative to dir)
+void showlink(const char * link, const char * prefix, const int i, const char * buf){
+  char path[MAX_BUF];
+  ssize_t ret;
+
+  ret = readlink(link, path, sizeof(path)-1);
+  if (ret < 0)
+    printf("PID %d: %s: cannot read %s/%s: %s\n",
+           i, prefix, buf, link,  strerror(errno));
+  else
+    {
+      path[ret] = 0;
+      printf("PID %d: %s: '%s'\n", i, prefix, path);
+    }
+}
+
+// show contents of file (at most MAX_BUF-1 chars). The other
+// args construct the output text. (eg link is relative to dir)
+void showfile(const char * file, const char * prefix, const int i, const char * buf){
+  int fd;
+  char contents[MAX_BUF];
+  ssize_t ret;
+
+  if ((fd = open(file, O_RDONLY)) < 0)
+    printf("PID %d: %s: cannot open file %s%s: %s\n", i, prefix, buf, file, strerror(errno));
+  else
+    {
+      if ((ret = read(fd, contents, sizeof(contents)-1)) < 0)
+        printf("PID %d: %s: cannot read file %s%s: %s\n", i, prefix, buf, file, strerror(errno));
+      else
+        {
+          while (ret >=1 && ( contents[ret-1]==0 || contents[ret-1]=='\n' || contents[ret-1]==' '))
+            --ret; // remove trailing cruft)
+          for (ssize_t j = 0; j < ret; ++j)
+            // replace embedded \0 and \n (especially present in cmdline)
+            if (contents[j]==0 || contents[j]=='\n') contents[j]=' ';
+          contents[ret]=0; // ensure a terminator
+          printf("PID %d: %s: '%s'\n", i, prefix, contents);
+        }
+      close(fd);
+    }
+}
+
+/* see if pid i (which has a /proc/i directory) is missing from
+   readdir or ps output. if so, increment retdir and/or retps as
+   appropriate andntry and read info from proc. the string buf holds
+   /proc/i. You need to have run populate_psdir and populate_psproc first to set the global vars dirproc and psproc */
+void dodgy_process(int i, const char * buf, int * retdir, int * retps)
+{
+#if defined(__sun)
+  int fd;
+  psinfo_t psbuf;
+#endif
+  int bad = 0;
+
+  if (!dirproc[i])
+    {
+      bad = 1;
+      (*retdir)++;
+      printf("PID %d: hidden from readdir(3) but %s exists\n", i, buf);
+    }
+
+  if (!psproc[i])
+    {
+      bad = 1;
+      (*retps)++;
+      printf("PID %d: hidden from ps(1) output but %s exists\n", i, buf);
+    }
+
+  if (bad)
+    {
+#if defined(__linux__) || defined(__NetBSD__)
+      // symlink to the executable
+      showlink("exe", "EXE", i, buf);
+
+      // cmdline holds argv
+      showfile("cmdline", "CMDLINE", i, buf);
+#if defined(__linux__)
+      // comm is (usually) the basename of the command: see https://lwn.net/Articles/999770/
+      showfile("comm","COMM", i, buf);
+      showfile("cgroup","CGROUP", i, buf);
+      // systemd unit that launched the process
+#endif
+#elif defined(__FreeBSD__)
+      showlink("file", "FILE", i, buf);
+#elif defined(__sun)
+      if ((fd = open("./psinfo", O_RDONLY)) < 0)
+        {
+          if (read(fd, &psbuf, sizeof(psbuf)) == sizeof(psbuf))
+            printf("PSINFO %d: %s\n", i, psbuf.pr_psargs);
+          else
+            printf("PSINFO %d: unknown\n", i);
+          close(fd);
+        }
+      else
+        printf("PSINFO %d: unknown\n", i);
+#else
+      printf("(Getting info about PID %d not implemented on this OS)\n", i);
+#endif
+        }
+}
+
+#if CHECK_PRIORITY
+/* check if we can find PID by checking getpriority.
+   returns 1 if we can, 0 if not */
+int check_priority(int pid)
+{
+  errno = 0;
+  getpriority(PRIO_PROCESS, pid);
+  return(!errno);
+}
+#endif
+
+/* run ps_cmd and set psproc[pid]=1 for every pid we find (and also
+   dirproc[tid]=1 if pv is PS_LINUX). pv determines how we parse the
+   output: pv=n means we assume that ps_cmd is output from
+   ps_cmds[pv] */
+void populate_psproc(const char *ps_cmd, int pv, int verbose)
+{
+  char buf[MAX_BUF], *p;
+  int pid = 0, tid = 0;
+  FILE *ps;
+
+  if (!ps_cmd) exit(3); // cannot happen!
+  if (verbose) printf("Running ps(1): %s\n", ps_cmd);
+  if (!(ps = popen(ps_cmd, "r")))
+    {
+      perror("ps");
+      exit(errno);
+    }
+
+  // skip header (if there should be one)
+  if (pv != PS_LINUX && pv != PS_NetBSD)
+    {
+      readline(buf, MAX_BUF, ps); /* should be header (except Sun)*/
+      if (verbose) printf("<<%s>>\n", buf);
+#if defined(__sun)
+      if (!isspace(*buf))
+#else
+      if (!isalpha(*buf))
+#endif
+        {
+          readline(buf, MAX_BUF, ps); /* Look again for header */
+          if (verbose) printf("<<%s>>\n",buf);
+          if (!isalpha(*buf))
+            {
+              fprintf(stderr, "OooPS! failed to parse ps output: '%s'\n", buf);
+              exit(2);
+            }
+        }
+    }
+  if (!memcmp(buf, "ps:", 3))
+    {
+      fprintf(stderr, "OooPS! failed to parse ps output: '%s'\n", buf);
+      exit(2);
+    }
+
+  // main output
+  while (readline(buf, MAX_BUF, ps))
+    {
+      if (verbose) printf("<<%s>>\n", buf);
+      p = buf;
+#if defined(__sun)
+      while (isspace(*p)) /* Skip spaces */
+        p++;
+#endif
+      if (pv != PS_LINUX && pv != PS_NetBSD)
+        while (!isspace(*p)) /* Skip username */
+          p++;
+      while (isspace(*p)) /* Skip spaces */
+        p++;
+      if (!isdigit(*p))
+        fprintf(stderr,"Skipping unexpected pid (not numeric) in ps outout: '%s' while looking at: '%s'\n", buf, p);
+      else
+        {
+          pid = atoi(p);
+          if (pid < FIRST_PROCESS || pid > MAX_PROCESSES)
+            fprintf(stderr, "Unexpected pid (out of range) in ps outout: expected 'pid' got: '%s' looking at '%s'\n", buf, p);
+          else
+            {
+              if (verbose) printf("ps sees: pid=%d\n",pid);
+              psproc[pid] = 1;
+
+              if (pv == PS_LINUX && pid != -1)
+                {
+                  while (isdigit(*p)) /* skip pid */
+                    p++;
+                  while (isspace(*p)) /* Skip spaces between pid and tid */
+                    p++;
+                  if (!isdigit(*p))
+                    fprintf(stderr,"Skipping unexpected tid (not numeric) in ps outout (pid=%d): '%s' looking at '%s'\n", pid, buf, p);
+                  else
+                    {
+                      tid = atoi(p);
+                      if (tid < FIRST_PROCESS || tid > MAX_PROCESSES)
+                        fprintf(stderr, "Skipping unexpected tid (out of range, or non-numeric) in ps output: expected 'pid tid' got: '%s' (pid=%d) lookong at '%s'\n", buf, pid, p);
+                      else
+                        {
+                          if (verbose) printf("ps sees: tid=%d (pid=%d)\n", tid, pid);
+                          psproc[tid] = 1;
+                          dirproc[tid] = 1;
+                        }
+                    }
+                }
+            }
+        }
+    }
+  if (verbose) printf("Done checking ps\n");
+  pclose(ps);
+}
+
+// see which directories /proc/i exist using readdir(3). Set dirproc[i] to 1 if /proc/i is found.
+// found.
+void populate_psdir(const char * proc_dir, int verbose)
+{
+  char *d_name;
+  DIR *proc;
+  struct dirent *dir;
+  int pid;
+
+  if (!proc_dir) exit(3); // cannot happen!
+  if ((proc = opendir(proc_dir)) == NULL)
+    {
+      perror(proc_dir);
+      exit(1);
+    }
+  if (verbose) printf("Reading directory: %s\n", proc_dir);
+  while ((dir = readdir(proc)))
+    {
+      d_name = dir->d_name;
+      if (!isdigit(*d_name))
+        {
+          if (verbose) printf("Skipping non-pid: %s\n", d_name);
+          continue;
+        }
+
+      pid = atoi(d_name);
+      if (pid < FIRST_PROCESS || pid > MAX_PROCESSES)
+        fprintf(stderr, "Ignoring pid %s/%s (out of bounds)\n", proc_dir, d_name);
+      else
+        {
+          if (verbose) printf("Entry exists for pid %d: %s/%s\n",pid, proc_dir, d_name);
+          dirproc[pid] = 1;
+        }
+    }
+  closedir(proc);
+}
+
 int main(int argc, char **argv)
 {
-   char buf[MAX_BUF], *p, path[MAX_BUF];
-   char *pscmd = (char *)0;
-   FILE *ps;
-   DIR *proc = opendir("/proc");
-   struct dirent *dir;
-   struct stat sb;
-   int i, j, retps, retdir, pv, verbose;
-   long ret = 0L;
-   char * tmp_d_name;
-#if defined(__linux__)
-   int maybeathread;
-#endif
+  char buf[MAX_BUF];
+  int i, retps=0, retdir=0, retpri=0, ret=0;
+
+  int verbose=0;
+
 #if defined(__sun)
-   psinfo_t psbuf;
+  int pv = PS_SUN;
+#elif defined(__linux__)
+  int pv = PS_LINUX;
+#elif defined(__NetBSD__)
+  int pv = PS_NetBSD;
+#else
+  int pv = PS_COM;
 #endif
+  const char *ps_cmd=0; // for testing
+  const char *proc_dir=PROCDIR; // for testing
+  int get_priority=1; // for testing: 0=disable, 1=enable (supported platforms only)
+  int len; // usually 5 - we add pid to buf at this position
 
-   pv = verbose = 0;
+  int max_pid=MAX_PROCESSES;
+  int to_recheck=-1; // incremented each time we find a pid to recheck
 
-   if (!proc)
-   {
-      perror("proc");
-      exit (1);
-   }
-   for (i = 1; i < argc; i++)
-   {
+  for (i = 1; i < argc; ++i)
+    {
       if (!memcmp(argv[i], "-v", 2))
-	verbose++;
-      else if (!memcmp(argv[i], "-?", 2))
-      {
-	printf("Usage: %s [-v] [-v] -p <num>\n", argv[0]);
-	return 0;
-      }
-#if defined(__linux__)
+        verbose = 1;
       else if (!memcmp(argv[i], "-p", 2))
-      {
-         if (i+1 < argc)
+        {
+          if (i+1 < argc)
             pv = atoi(argv[++i]);
-         else
-         {
-	    printf("Usage: %s [-v] [-v] [-p procps version]\n", argv[0]);
-	    return 0;
-         }
-      }
-#endif
-   }
-#if defined(__sun)
-   pscmd = ps_cmds[PS_SUN];
-#elif !defined (__linux__)
-   pscmd = ps_cmds[PS_COM];
-#endif
-#if defined(__linux__)
-   if (pv < 1 || pv > PS_MAX)
-      pv = 1;
-   pscmd = ps_cmds[pv];
-/*  printf("pv = %d\n\r", pv); /* -- DEBUG */
-#endif
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "-N", 2))
+        {
+          if (i+1 < argc)
+            max_pid = atoi(argv[++i]);
+          else
+            usage();
+        }
+       // Some undocumented options to test the parser
+      else if (!memcmp(argv[i], "--ps-cmd", 8))
+        {
+          /* use custom ps+args.
+             -p still determines how to parse the output */
+          if (i+1 < argc)
+            ps_cmd=argv[++i];
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "--proc-dir", 10))
+        {
+          /* treat a custom dir as /proc  */
+          if (i+1 < argc)
+            proc_dir=argv[++i];
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "--no-getpriority", 16))
+        // skip use of getpriority(2)
+        get_priority=0;
+      else usage();
+    }
 
-/* printf("pscmd = %s\n\r", pscmd); /* -- DEBUG */
-   if (!(ps = popen(pscmd, "r")))
-   {
-       perror("ps");
-       exit(errno);
-   }
+  if (max_pid < FIRST_PROCESS || max_pid > MAX_PROCESSES)
+    max_pid = MAX_PROCESSES;
 
-   *buf = 0;
-   readline(buf, MAX_BUF, ps); /* Skip header */
-#if defined(__sun)
-   if (!isspace(*buf))
-#else
-   if (!isalpha(*buf))
-#endif
-   {
-     readline(buf, MAX_BUF, ps); /* Skip header */
-     if (!isalpha(*buf) && pv != PS_LNX)
-     {
-	if (pv != PS_LOL)
-	   execlp(argv[0], argv[0], "-p 1", NULL);
-        fprintf(stderr, "OooPS!\n");
-        exit(2);
-     }
-   }
-   if (!memcmp(buf, "ps:", 3) && (pv != PS_LOL))
-      execlp(argv[0], argv[0], "-p 1", NULL);
+  if (pv < 0 || pv > PS_MAX)
+    pv = PS_COM;
 
-   for (i = FIRST_PROCESS; i <= MAX_PROCESSES; i++) { /* Init matrix */
-     psproc[i] = dirproc[i] = 0;
-#if defined(__linux__)
-     isathread[i] = 0;
-#endif
-   }
+  if (!ps_cmd) ps_cmd=ps_cmds[pv];
+  if (!proc_dir) proc_dir=PROCDIR;
 
-   while (readline(buf, MAX_BUF, ps))
-   {
-      p = buf;
-#if defined(__sun)
-      while (isspace(*p)) /* Skip spaces */
-          p++;
-#endif
-      while (!isspace(*p)) /* Skip User */
-          p++;
-      while (isspace(*p)) /* Skip spaces */
-          p++;
-/*  printf(">>PS %s<<\n", p);  /* -- DEBUG */
-      ret = atol(p);
-      if ( ret < 0 || ret > MAX_PROCESSES )
-      {
-         fprintf (stderr, " OooPS, not expected %ld value\n", ret);
-         exit (2);
-      }
-      psproc[ret] = 1;
-   }
-   pclose(ps);
+  len=strlen(proc_dir);
+  if (len+22 >= MAX_BUF) {
+	// unlikely, but avoid possibility for proc_dir+/+PID+\0 to overflow buf
+	// nb: the largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+	printf("ERROR: %s too long to use as /proc\n", proc_dir);
+	exit(2);
+  }
+  strcpy(buf, proc_dir);
 
-   while ((dir = readdir(proc)))
-   {
-#if defined(__linux__)
-      maybeathread = 0;
-#endif
-      tmp_d_name = dir->d_name;
-      if (!strcmp(tmp_d_name, ".") || !strcmp(tmp_d_name, ".."))
-         continue;
-#if defined(__linux__)
-      if (*tmp_d_name == '.') { /* here we catch the new NTPL threads in linux.  They are listed in /proc as PIDs with a period prepended */
-         tmp_d_name++;
-         maybeathread = 1;
-      }
-#endif
-      if(!isdigit(*tmp_d_name))
-         continue;
-#if defined(__linux__)
-      else if (maybeathread) {
-         isathread[atol(tmp_d_name)] = 1; /* mark it as a linux NTPL thread if it's in the form of "\.[0-9]*" */
-         if (verbose)
-            printf("%ld is a Linux Thread, marking as such...\n", atol(tmp_d_name));
-      }
-#endif
+  populate_psproc(ps_cmd, pv, verbose);
+  populate_psdir(proc_dir, verbose);
 
-/*      printf("%s\n", tmp_d_name); /* -- DEBUG */
-      dirproc[atol(tmp_d_name)] = 1;
-   }
-   closedir(proc);
-
-   /* Brute force */
-   strcpy(buf, "/proc/");
-   retps = retdir = 0;
-   for (i = FIRST_PROCESS; i <= MAX_PROCESSES; i++)
-   {
-      // snprintf(&buf[6], 6, "%d", i);
-       snprintf(&buf[6], 8, "%d", i);
+  for (i = FIRST_PROCESS; i <= max_pid; ++i)
+    {
+      if (verbose && i%100000 == 0)
+        {
+          printf("Checking for PIDS: %d/%d\n", i, max_pid);
+          fflush(stdout);
+        }
+	  // largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+      snprintf(&buf[len], 22, "/%d", i);
       if (!chdir(buf))
-      {
-         if (!dirproc[i] && !psproc[i])
-         {
-#if defined(__linux__)
-            if (!isathread[i]) {
-#endif
-            retdir++;
-            if (verbose)
-	       printf ("PID %5d(%s): not in readdir output\n", i, buf);
-#if defined(__linux__)
-            }
-#endif
-         }
-         if (!psproc[i] ) /* && !kill(i, 0)) */
-         {
-#if defined(__linux__)
-            if(!isathread[i]) {
-#endif
-            retps++;
-            if (verbose)
-	       printf ("PID %5d: not in ps output\n", i);
-#if defined(__linux__)
+        {
+          /* cd /proc/i worked: pid i should be in both dirproc and
+             psproc (unless it is a linux tid) */
+          if (verbose) printf("Looking at %d (ps=%d, dir=%d): ", i, psproc[i], dirproc[i]);
+          if (!psproc[i] || !dirproc[i])
+            {
+              if (verbose) printf("To recheck: %d\n", i);
+              recheck[++to_recheck] = i;
             }
-#endif
-	 }
-#if defined(__linux__)
-         if(!isathread[i]) {
-#endif
-/*	 if ((!dirproc[i] || !psproc[i]) && !kill(i, 0) && (verbose > 1)) */
-	 if ((!dirproc[i] || !psproc[i]) && (verbose > 1))
-	 {
-#if defined(__linux__)
-	    j = readlink ("./cwd", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("CWD %5d: %s\n", i, path);
-	    j = readlink ("./exe", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("EXE %5d: %s\n", i, path);
-#elif defined(__FreeBSD__)
-	    j = readlink ("./file", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("FILE %5d: %s\n", i, path);
-#elif defined(__sun)
-	    if ((j = open("./psinfo", O_RDONLY)) != -1)
+          else if (verbose) printf("OK\n");
+        }
+#if CHECK_PRIORITY
+      else if (get_priority && check_priority(i))
+        {
+          /* no /proc/i so getpriority should fail */
+          if (verbose) printf("To recheck (due to getpriority): %d\n", i);
+          recheck[++to_recheck] = i;
+        }
+#endif
+    }
+  if (verbose) printf("Checked for PIDs up to: %d (done: %d to recheck)\n", max_pid, to_recheck + 1);
+
+  /* second pass - repopulate psproc, psdir and retry */
+  if (to_recheck >= 0)
+    {
+      if (verbose) printf("To recheck: %d PID(s)\n", to_recheck + 1);
+      for (i = 0; i <= MAX_PROCESSES; ++i)
+        psproc[i] = dirproc[i] = 0;
+      populate_psproc(ps_cmd, pv, verbose);
+      populate_psdir(proc_dir, verbose);
+
+      for (i = 0; i <= to_recheck; ++i)
+        {
+          // largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+          snprintf(&buf[len], 22, "/%d", recheck[i]);
+          if (!chdir(buf))
+            dodgy_process(recheck[i], buf, &retdir, &retps);
+#if CHECK_PRIORITY
+          else if (get_priority && check_priority(recheck[i]))
             {
-               if (read(j, &psbuf, sizeof(psbuf)) == sizeof(psbuf))
-                  printf ("PSINFO %5d: %s\n", i, psbuf.pr_psargs);
-               else
-                  printf ("PSINFO %5d: unknown\n", i);
-               close(j);
+              retpri++;
+              printf("PID %d: is hidden: it has getpriority(2) information but no %s entry\n", recheck[i], buf);
             }
-            else
-               printf ("PSINFO %5d: unknown\n", i);
-#endif
-         }
-#if defined(__linux__)
-         }
-#endif
-      }
-#ifndef __FreeBSD__
-      else
-      {
-         errno = 0;
-         getpriority(PRIO_PROCESS, i);
-         if (!errno)
-         {
-            retdir++;
-            if (verbose)
-	       printf ("PID %5d(%s): not in getpriority readdir output\n", i, buf);
-	 }
-      }
-#endif
-   }
-   if (retdir)
-      printf("You have % 5d process hidden for readdir command\n", retdir);
-   if (retps)
-      printf("You have % 5d process hidden for ps command\n", retps);
-#if defined(__linux__)
-   kill(1, 100); /*  Check for SIGINVISIBLE Adore signal */
-   if (kill (1, SIGXFSZ) < 0  && errno == 3)
-   {
-      printf("SIGINVISIBLE Adore found\n");
-      retdir+= errno;
-   }
-   /* Check for Enye LKM */
-   if (stat(ENYELKM, &sb) && kill (12345, 58) >= 0)
-   {
-      printf("Enye LKM found\n");
-      retdir+= errno;
-   }
 #endif
-   return (retdir+retps);
+        }
+    }
+
+  if ((ret = retdir + retps + retpri)) printf("\n");
+
+  if (retdir)
+    printf("You have %d process(es) hidden from readdir(3)\n", retdir);
+  if (retps)
+    printf("You have %d process(es) hidden from ps(1)\n", retps);
+#if defined(CHECK_PRIORITY)
+  if (retpri)
+    printf("You have %d hidden process(es) with getpriority(2) information\n", retpri);
+#endif
+
+  fflush(stdout);
+  return (ret>0);
 }
-#endif