title: Linux Kernel Module for firewall
body: <p>I am trying to block all traffic on all ports except for 443 and 80 for tcp and udp.  Udp works fine but tcp is just blocked completely, what did I do wrong here?</p>
  <p>I tried the tcp on it's own and the code for tcp does not work and I am not entirely sure why.</p>
  <pre><code>#include &lt;linux/init.h&gt;
  #include &lt;linux/module.h&gt;
  #include &lt;linux/kernel.h&gt;
  #include &lt;linux/netfilter.h&gt;
  #include &lt;linux/netfilter_ipv4.h&gt;
  #include &lt;linux/ip.h&gt;
  #include &lt;linux/tcp.h&gt;
  #include &lt;linux/udp.h&gt;
  
  static struct nf_hook_ops *nfho = NULL;
  
  static unsigned int hfunc(void *priv, struct sk_buff *skb, const struct nf_hook_state *state)
  {
      struct iphdr *iph;
      struct udphdr *udph;
      struct tcphdr *tcph;
  
      if (!skb) {
          return NF_ACCEPT;
      }
      iph = ip_hdr(skb);
      if (iph-&gt;protocol == IPPROTO_UDP) {
          udph = udp_hdr(skb);
          if (ntohs(udph-&gt;dest) == 443 || (ntohs(udph-&gt;dest) == 80) {
              return NF_ACCEPT;
          }
      }
      else if (iph-&gt;protocol == IPPROTO_TCP) {
          tcph = tcp_hdr(skb);
          if (ntohs(tcph-&gt;dest) == 443 || (ntohs(tcph-&gt;dest) == 80) {
              return NF_ACCEPT;
          }
      }
      return NF_DROP;
  }
  
  static int __init LKM_init(void)
  {
      nfho = (struct nf_hook_ops*)kcalloc(1, sizeof(struct nf_hook_ops), GFP_KERNEL);
      
      /* Initialize netfilter hook */
      nfho-&gt;hook  = (nf_hookfn*)hfunc;        /* hook function */
      nfho-&gt;hooknum   = NF_INET_PRE_ROUTING;      /* received packets */
      nfho-&gt;pf    = PF_INET;          /* IPv4 */
      nfho-&gt;priority  = NF_IP_PRI_FIRST;      /* max hook priority */
      
      nf_register_net_hook(&amp;init_net, nfho);
  }
  
  static void __exit LKM_exit(void)
  {
      nf_unregister_net_hook(&amp;init_net, nfho);
      kfree(nfho);
  }
  
  module_init(LKM_init);
  module_exit(LKM_exit);
  </code></pre>