Back to home page

OSCL-LXR

 
 

    


0001 /* Copyright (c) 2016 Sargun Dhillon <sargun@sargun.me>
0002  *
0003  * This program is free software; you can redistribute it and/or
0004  * modify it under the terms of version 2 of the GNU General Public
0005  * License as published by the Free Software Foundation.
0006  */
0007 #include <linux/skbuff.h>
0008 #include <linux/netdevice.h>
0009 #include <uapi/linux/bpf.h>
0010 #include <linux/version.h>
0011 #include <bpf/bpf_helpers.h>
0012 #include <bpf/bpf_tracing.h>
0013 #include <bpf/bpf_core_read.h>
0014 #include "trace_common.h"
0015 
0016 struct {
0017     __uint(type, BPF_MAP_TYPE_HASH);
0018     __type(key, struct sockaddr_in);
0019     __type(value, struct sockaddr_in);
0020     __uint(max_entries, 256);
0021 } dnat_map SEC(".maps");
0022 
0023 /* kprobe is NOT a stable ABI
0024  * kernel functions can be removed, renamed or completely change semantics.
0025  * Number of arguments and their positions can change, etc.
0026  * In such case this bpf+kprobe example will no longer be meaningful
0027  *
0028  * This example sits on a syscall, and the syscall ABI is relatively stable
0029  * of course, across platforms, and over time, the ABI may change.
0030  */
0031 SEC("kprobe/" SYSCALL(sys_connect))
0032 int bpf_prog1(struct pt_regs *ctx)
0033 {
0034     struct pt_regs *real_regs = (struct pt_regs *)PT_REGS_PARM1_CORE(ctx);
0035     void *sockaddr_arg = (void *)PT_REGS_PARM2_CORE(real_regs);
0036     int sockaddr_len = (int)PT_REGS_PARM3_CORE(real_regs);
0037     struct sockaddr_in new_addr, orig_addr = {};
0038     struct sockaddr_in *mapped_addr;
0039 
0040     if (sockaddr_len > sizeof(orig_addr))
0041         return 0;
0042 
0043     if (bpf_probe_read_user(&orig_addr, sizeof(orig_addr), sockaddr_arg) != 0)
0044         return 0;
0045 
0046     mapped_addr = bpf_map_lookup_elem(&dnat_map, &orig_addr);
0047     if (mapped_addr != NULL) {
0048         memcpy(&new_addr, mapped_addr, sizeof(new_addr));
0049         bpf_probe_write_user(sockaddr_arg, &new_addr,
0050                      sizeof(new_addr));
0051     }
0052     return 0;
0053 }
0054 
0055 char _license[] SEC("license") = "GPL";
0056 u32 _version SEC("version") = LINUX_VERSION_CODE;