]> rtime.felk.cvut.cz Git - lisovros/iproute2_canprio.git/blob - ip/xfrm_state.c
xfrm: add support for SA by mark
[lisovros/iproute2_canprio.git] / ip / xfrm_state.c
1 /* $USAGI: $ */
2
3 /*
4  * Copyright (C)2004 USAGI/WIDE Project
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 /*
21  * based on iproute.c
22  */
23 /*
24  * Authors:
25  *      Masahide NAKAMURA @USAGI
26  */
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <netdb.h>
32 #include <linux/xfrm.h>
33 #include "utils.h"
34 #include "xfrm.h"
35 #include "ip_common.h"
36
37 //#define NLMSG_DELETEALL_BUF_SIZE (4096-512)
38 #define NLMSG_DELETEALL_BUF_SIZE 8192
39
40 /*
41  * Receiving buffer defines:
42  * nlmsg
43  *   data = struct xfrm_usersa_info
44  *   rtattr
45  *   rtattr
46  *   ... (max count of rtattr is XFRM_MAX+1
47  *
48  *  each rtattr data = struct xfrm_algo(dynamic size) or xfrm_address_t
49  */
50 #define NLMSG_BUF_SIZE 4096
51 #define RTA_BUF_SIZE 2048
52 #define XFRM_ALGO_KEY_BUF_SIZE 512
53
54 static void usage(void) __attribute__((noreturn));
55
56 static void usage(void)
57 {
58         fprintf(stderr, "Usage: ip xfrm state { add | update } ID [ XFRM_OPT ] [ mode MODE ]\n");
59         fprintf(stderr, "        [ reqid REQID ] [ seq SEQ ] [ replay-window SIZE ] [ flag FLAG-LIST ]\n");
60         fprintf(stderr, "        [ encap ENCAP ] [ sel SELECTOR ] [ replay-seq SEQ ]\n");
61         fprintf(stderr, "        [ replay-oseq SEQ ] [ LIMIT-LIST ]\n");
62         fprintf(stderr, "Usage: ip xfrm state allocspi ID [ mode MODE ] [ reqid REQID ] [ seq SEQ ]\n");
63         fprintf(stderr, "        [ min SPI max SPI ]\n");
64         fprintf(stderr, "Usage: ip xfrm state { delete | get } ID\n");
65         fprintf(stderr, "Usage: ip xfrm state { deleteall | list } [ ID ] [ mode MODE ] [ reqid REQID ]\n");
66         fprintf(stderr, "        [ flag FLAG-LIST ]\n");
67         fprintf(stderr, "Usage: ip xfrm state flush [ proto XFRM_PROTO ]\n");
68         fprintf(stderr, "Usage: ip xfrm state count \n");
69
70         fprintf(stderr, "ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM_PROTO ] [ spi SPI ] [mark MARK [mask MASK]]\n");
71         //fprintf(stderr, "XFRM_PROTO := [ esp | ah | comp ]\n");
72         fprintf(stderr, "XFRM_PROTO := [ ");
73         fprintf(stderr, "%s | ", strxf_xfrmproto(IPPROTO_ESP));
74         fprintf(stderr, "%s | ", strxf_xfrmproto(IPPROTO_AH));
75         fprintf(stderr, "%s | ", strxf_xfrmproto(IPPROTO_COMP));
76         fprintf(stderr, "%s | ", strxf_xfrmproto(IPPROTO_ROUTING));
77         fprintf(stderr, "%s ", strxf_xfrmproto(IPPROTO_DSTOPTS));
78         fprintf(stderr, "]\n");
79
80         //fprintf(stderr, "SPI - security parameter index(default=0)\n");
81
82         fprintf(stderr, "MODE := [ transport | tunnel | ro | beet ](default=transport)\n");
83         //fprintf(stderr, "REQID - number(default=0)\n");
84
85         fprintf(stderr, "FLAG-LIST := [ FLAG-LIST ] FLAG\n");
86         fprintf(stderr, "FLAG := [ noecn | decap-dscp | nopmtudisc | wildrecv | icmp | af-unspec ]\n");
87
88         fprintf(stderr, "ENCAP := ENCAP-TYPE SPORT DPORT OADDR\n");
89         fprintf(stderr, "ENCAP-TYPE := espinudp | espinudp-nonike\n");
90
91         fprintf(stderr, "ALGO-LIST := [ ALGO-LIST ] | [ ALGO ]\n");
92         fprintf(stderr, "ALGO := ALGO_TYPE ALGO_NAME ALGO_KEY "
93                         "[ ALGO_ICV_LEN ]\n");
94         fprintf(stderr, "ALGO_TYPE := [ ");
95         fprintf(stderr, "%s | ", strxf_algotype(XFRMA_ALG_AEAD));
96         fprintf(stderr, "%s | ", strxf_algotype(XFRMA_ALG_CRYPT));
97         fprintf(stderr, "%s | ", strxf_algotype(XFRMA_ALG_AUTH));
98         fprintf(stderr, "%s ", strxf_algotype(XFRMA_ALG_COMP));
99         fprintf(stderr, "]\n");
100
101         //fprintf(stderr, "ALGO_NAME - algorithm name\n");
102         //fprintf(stderr, "ALGO_KEY - algorithm key\n");
103
104         fprintf(stderr, "SELECTOR := src ADDR[/PLEN] dst ADDR[/PLEN] [ UPSPEC ] [ dev DEV ]\n");
105
106         fprintf(stderr, "UPSPEC := proto PROTO [ [ sport PORT ] [ dport PORT ] |\n");
107         fprintf(stderr, "                        [ type NUMBER ] [ code NUMBER ] ]\n");
108
109
110         //fprintf(stderr, "DEV - device name(default=none)\n");
111         fprintf(stderr, "LIMIT-LIST := [ LIMIT-LIST ] | [ limit LIMIT ]\n");
112         fprintf(stderr, "LIMIT := [ [time-soft|time-hard|time-use-soft|time-use-hard] SECONDS ] |\n");
113         fprintf(stderr, "         [ [byte-soft|byte-hard] SIZE ] | [ [packet-soft|packet-hard] COUNT ]\n");
114         exit(-1);
115 }
116
117 static int xfrm_algo_parse(struct xfrm_algo *alg, enum xfrm_attr_type_t type,
118                            char *name, char *key, char *buf, int max)
119 {
120         int len;
121         int slen = strlen(key);
122
123 #if 0
124         /* XXX: verifying both name and key is required! */
125         fprintf(stderr, "warning: ALGONAME/ALGOKEY will send to kernel promiscuously!(verifying them isn't implemented yet)\n");
126 #endif
127
128         strncpy(alg->alg_name, name, sizeof(alg->alg_name));
129
130         if (slen > 2 && strncmp(key, "0x", 2) == 0) {
131                 /* split two chars "0x" from the top */
132                 char *p = key + 2;
133                 int plen = slen - 2;
134                 int i;
135                 int j;
136
137                 /* Converting hexadecimal numbered string into real key;
138                  * Convert each two chars into one char(value). If number
139                  * of the length is odd, add zero on the top for rounding.
140                  */
141
142                 /* calculate length of the converted values(real key) */
143                 len = (plen + 1) / 2;
144                 if (len > max)
145                         invarg("\"ALGOKEY\" makes buffer overflow\n", key);
146
147                 for (i = - (plen % 2), j = 0; j < len; i += 2, j++) {
148                         char vbuf[3];
149                         __u8 val;
150
151                         vbuf[0] = i >= 0 ? p[i] : '0';
152                         vbuf[1] = p[i + 1];
153                         vbuf[2] = '\0';
154
155                         if (get_u8(&val, vbuf, 16))
156                                 invarg("\"ALGOKEY\" is invalid", key);
157
158                         buf[j] = val;
159                 }
160         } else {
161                 len = slen;
162                 if (len > 0) {
163                         if (len > max)
164                                 invarg("\"ALGOKEY\" makes buffer overflow\n", key);
165
166                         strncpy(buf, key, len);
167                 }
168         }
169
170         alg->alg_key_len = len * 8;
171
172         return 0;
173 }
174
175 static int xfrm_seq_parse(__u32 *seq, int *argcp, char ***argvp)
176 {
177         int argc = *argcp;
178         char **argv = *argvp;
179
180         if (get_u32(seq, *argv, 0))
181                 invarg("\"SEQ\" is invalid", *argv);
182
183         *seq = htonl(*seq);
184
185         *argcp = argc;
186         *argvp = argv;
187
188         return 0;
189 }
190
191 static int xfrm_state_flag_parse(__u8 *flags, int *argcp, char ***argvp)
192 {
193         int argc = *argcp;
194         char **argv = *argvp;
195         int len = strlen(*argv);
196
197         if (len > 2 && strncmp(*argv, "0x", 2) == 0) {
198                 __u8 val = 0;
199
200                 if (get_u8(&val, *argv, 16))
201                         invarg("\"FLAG\" is invalid", *argv);
202                 *flags = val;
203         } else {
204                 while (1) {
205                         if (strcmp(*argv, "noecn") == 0)
206                                 *flags |= XFRM_STATE_NOECN;
207                         else if (strcmp(*argv, "decap-dscp") == 0)
208                                 *flags |= XFRM_STATE_DECAP_DSCP;
209                         else if (strcmp(*argv, "nopmtudisc") == 0)
210                                 *flags |= XFRM_STATE_NOPMTUDISC;
211                         else if (strcmp(*argv, "wildrecv") == 0)
212                                 *flags |= XFRM_STATE_WILDRECV;
213                         else if (strcmp(*argv, "icmp") == 0)
214                                 *flags |= XFRM_STATE_ICMP;
215                         else if (strcmp(*argv, "af-unspec") == 0)
216                                 *flags |= XFRM_STATE_AF_UNSPEC;
217                         else {
218                                 PREV_ARG(); /* back track */
219                                 break;
220                         }
221
222                         if (!NEXT_ARG_OK())
223                                 break;
224                         NEXT_ARG();
225                 }
226         }
227
228         *argcp = argc;
229         *argvp = argv;
230
231         return 0;
232 }
233
234 static int xfrm_state_modify(int cmd, unsigned flags, int argc, char **argv)
235 {
236         struct rtnl_handle rth;
237         struct {
238                 struct nlmsghdr         n;
239                 struct xfrm_usersa_info xsinfo;
240                 char                    buf[RTA_BUF_SIZE];
241         } req;
242         struct xfrm_replay_state replay;
243         char *idp = NULL;
244         char *aeadop = NULL;
245         char *ealgop = NULL;
246         char *aalgop = NULL;
247         char *calgop = NULL;
248         char *coap = NULL;
249         struct xfrm_mark mark = {0, 0};
250
251         memset(&req, 0, sizeof(req));
252         memset(&replay, 0, sizeof(replay));
253
254         req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsinfo));
255         req.n.nlmsg_flags = NLM_F_REQUEST|flags;
256         req.n.nlmsg_type = cmd;
257         req.xsinfo.family = preferred_family;
258
259         req.xsinfo.lft.soft_byte_limit = XFRM_INF;
260         req.xsinfo.lft.hard_byte_limit = XFRM_INF;
261         req.xsinfo.lft.soft_packet_limit = XFRM_INF;
262         req.xsinfo.lft.hard_packet_limit = XFRM_INF;
263
264         while (argc > 0) {
265                 if (strcmp(*argv, "mode") == 0) {
266                         NEXT_ARG();
267                         xfrm_mode_parse(&req.xsinfo.mode, &argc, &argv);
268                 } else if (strcmp(*argv, "mark") == 0) {
269                         xfrm_parse_mark(&mark, &argc, &argv);
270                 } else if (strcmp(*argv, "reqid") == 0) {
271                         NEXT_ARG();
272                         xfrm_reqid_parse(&req.xsinfo.reqid, &argc, &argv);
273                 } else if (strcmp(*argv, "seq") == 0) {
274                         NEXT_ARG();
275                         xfrm_seq_parse(&req.xsinfo.seq, &argc, &argv);
276                 } else if (strcmp(*argv, "replay-window") == 0) {
277                         NEXT_ARG();
278                         if (get_u8(&req.xsinfo.replay_window, *argv, 0))
279                                 invarg("\"replay-window\" value is invalid", *argv);
280                 } else if (strcmp(*argv, "replay-seq") == 0) {
281                         NEXT_ARG();
282                         if (get_u32(&replay.seq, *argv, 0))
283                                 invarg("\"replay-seq\" value is invalid", *argv);
284                 } else if (strcmp(*argv, "replay-oseq") == 0) {
285                         NEXT_ARG();
286                         if (get_u32(&replay.oseq, *argv, 0))
287                                 invarg("\"replay-oseq\" value is invalid", *argv);
288                 } else if (strcmp(*argv, "flag") == 0) {
289                         NEXT_ARG();
290                         xfrm_state_flag_parse(&req.xsinfo.flags, &argc, &argv);
291                 } else if (strcmp(*argv, "sel") == 0) {
292                         NEXT_ARG();
293                         xfrm_selector_parse(&req.xsinfo.sel, &argc, &argv);
294                 } else if (strcmp(*argv, "limit") == 0) {
295                         NEXT_ARG();
296                         xfrm_lifetime_cfg_parse(&req.xsinfo.lft, &argc, &argv);
297                 } else if (strcmp(*argv, "encap") == 0) {
298                         struct xfrm_encap_tmpl encap;
299                         inet_prefix oa;
300                         NEXT_ARG();
301                         xfrm_encap_type_parse(&encap.encap_type, &argc, &argv);
302                         NEXT_ARG();
303                         if (get_u16(&encap.encap_sport, *argv, 0))
304                                 invarg("\"encap\" sport value is invalid", *argv);
305                         encap.encap_sport = htons(encap.encap_sport);
306                         NEXT_ARG();
307                         if (get_u16(&encap.encap_dport, *argv, 0))
308                                 invarg("\"encap\" dport value is invalid", *argv);
309                         encap.encap_dport = htons(encap.encap_dport);
310                         NEXT_ARG();
311                         get_addr(&oa, *argv, AF_UNSPEC);
312                         memcpy(&encap.encap_oa, &oa.data, sizeof(encap.encap_oa));
313                         addattr_l(&req.n, sizeof(req.buf), XFRMA_ENCAP,
314                                   (void *)&encap, sizeof(encap));
315                 } else if (strcmp(*argv, "coa") == 0) {
316                         inet_prefix coa;
317                         xfrm_address_t xcoa;
318
319                         if (coap)
320                                 duparg("coa", *argv);
321                         coap = *argv;
322
323                         NEXT_ARG();
324
325                         get_prefix(&coa, *argv, preferred_family);
326                         if (coa.family == AF_UNSPEC)
327                                 invarg("\"coa\" address family is AF_UNSPEC", *argv);
328                         if (coa.bytelen > sizeof(xcoa))
329                                 invarg("\"coa\" address length is too large", *argv);
330
331                         memset(&xcoa, 0, sizeof(xcoa));
332                         memcpy(&xcoa, &coa.data, coa.bytelen);
333
334                         addattr_l(&req.n, sizeof(req.buf), XFRMA_COADDR,
335                                   (void *)&xcoa, sizeof(xcoa));
336                 } else {
337                         /* try to assume ALGO */
338                         int type = xfrm_algotype_getbyname(*argv);
339                         switch (type) {
340                         case XFRMA_ALG_AEAD:
341                         case XFRMA_ALG_CRYPT:
342                         case XFRMA_ALG_AUTH:
343                         case XFRMA_ALG_COMP:
344                         {
345                                 /* ALGO */
346                                 struct {
347                                         union {
348                                                 struct xfrm_algo alg;
349                                                 struct xfrm_algo_aead aead;
350                                         } u;
351                                         char buf[XFRM_ALGO_KEY_BUF_SIZE];
352                                 } alg = {};
353                                 int len;
354                                 __u32 icvlen;
355                                 char *name;
356                                 char *key;
357                                 char *buf;
358
359                                 switch (type) {
360                                 case XFRMA_ALG_AEAD:
361                                         if (aeadop)
362                                                 duparg("ALGOTYPE", *argv);
363                                         aeadop = *argv;
364                                         break;
365                                 case XFRMA_ALG_CRYPT:
366                                         if (ealgop)
367                                                 duparg("ALGOTYPE", *argv);
368                                         ealgop = *argv;
369                                         break;
370                                 case XFRMA_ALG_AUTH:
371                                         if (aalgop)
372                                                 duparg("ALGOTYPE", *argv);
373                                         aalgop = *argv;
374                                         break;
375                                 case XFRMA_ALG_COMP:
376                                         if (calgop)
377                                                 duparg("ALGOTYPE", *argv);
378                                         calgop = *argv;
379                                         break;
380                                 default:
381                                         /* not reached */
382                                         invarg("\"ALGOTYPE\" is invalid\n", *argv);
383                                 }
384
385                                 if (!NEXT_ARG_OK())
386                                         missarg("ALGONAME");
387                                 NEXT_ARG();
388                                 name = *argv;
389
390                                 if (!NEXT_ARG_OK())
391                                         missarg("ALGOKEY");
392                                 NEXT_ARG();
393                                 key = *argv;
394
395                                 buf = alg.u.alg.alg_key;
396                                 len = sizeof(alg.u.alg);
397
398                                 if (type != XFRMA_ALG_AEAD)
399                                         goto parse_algo;
400
401                                 if (!NEXT_ARG_OK())
402                                         missarg("ALGOICVLEN");
403                                 NEXT_ARG();
404                                 if (get_u32(&icvlen, *argv, 0))
405                                         invarg("\"aead\" ICV length is invalid",
406                                                *argv);
407                                 alg.u.aead.alg_icv_len = icvlen;
408
409                                 buf = alg.u.aead.alg_key;
410                                 len = sizeof(alg.u.aead);
411
412 parse_algo:
413                                 xfrm_algo_parse((void *)&alg, type, name, key,
414                                                 buf, sizeof(alg.buf));
415                                 len += alg.u.alg.alg_key_len;
416
417                                 addattr_l(&req.n, sizeof(req.buf), type,
418                                           (void *)&alg, len);
419                                 break;
420                         }
421                         default:
422                                 /* try to assume ID */
423                                 if (idp)
424                                         invarg("unknown", *argv);
425                                 idp = *argv;
426
427                                 /* ID */
428                                 xfrm_id_parse(&req.xsinfo.saddr, &req.xsinfo.id,
429                                               &req.xsinfo.family, 0, &argc, &argv);
430                                 if (preferred_family == AF_UNSPEC)
431                                         preferred_family = req.xsinfo.family;
432                         }
433                 }
434                 argc--; argv++;
435         }
436
437         if (replay.seq || replay.oseq)
438                 addattr_l(&req.n, sizeof(req.buf), XFRMA_REPLAY_VAL,
439                           (void *)&replay, sizeof(replay));
440
441         if (!idp) {
442                 fprintf(stderr, "Not enough information: \"ID\" is required\n");
443                 exit(1);
444         }
445
446         if (mark.m & mark.v) {
447                 int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
448                                   (void *)&mark, sizeof(mark));
449                 if (r < 0) {
450                         fprintf(stderr, "XFRMA_MARK failed\n");
451                         exit(1);
452                 }
453         }
454
455         switch (req.xsinfo.mode) {
456         case XFRM_MODE_TRANSPORT:
457         case XFRM_MODE_TUNNEL:
458                 if (!xfrm_xfrmproto_is_ipsec(req.xsinfo.id.proto)) {
459                         fprintf(stderr, "\"mode\" is invalid with proto=%s\n",
460                                 strxf_xfrmproto(req.xsinfo.id.proto));
461                         exit(1);
462                 }
463                 break;
464         case XFRM_MODE_ROUTEOPTIMIZATION:
465         case XFRM_MODE_IN_TRIGGER:
466                 if (!xfrm_xfrmproto_is_ro(req.xsinfo.id.proto)) {
467                         fprintf(stderr, "\"mode\" is invalid with proto=%s\n",
468                                 strxf_xfrmproto(req.xsinfo.id.proto));
469                         exit(1);
470                 }
471                 if (req.xsinfo.id.spi != 0) {
472                         fprintf(stderr, "\"spi\" must be 0 with proto=%s\n",
473                                 strxf_xfrmproto(req.xsinfo.id.proto));
474                         exit(1);
475                 }
476                 break;
477         default:
478                 break;
479         }
480
481         if (aeadop || ealgop || aalgop || calgop) {
482                 if (!xfrm_xfrmproto_is_ipsec(req.xsinfo.id.proto)) {
483                         fprintf(stderr, "\"ALGO\" is invalid with proto=%s\n",
484                                 strxf_xfrmproto(req.xsinfo.id.proto));
485                         exit(1);
486                 }
487         } else {
488                 if (xfrm_xfrmproto_is_ipsec(req.xsinfo.id.proto)) {
489                         fprintf(stderr, "\"ALGO\" is required with proto=%s\n",
490                                 strxf_xfrmproto(req.xsinfo.id.proto));
491                         exit (1);
492                 }
493         }
494
495         if (coap) {
496                 if (!xfrm_xfrmproto_is_ro(req.xsinfo.id.proto)) {
497                         fprintf(stderr, "\"coa\" is invalid with proto=%s\n",
498                                 strxf_xfrmproto(req.xsinfo.id.proto));
499                         exit(1);
500                 }
501         } else {
502                 if (xfrm_xfrmproto_is_ro(req.xsinfo.id.proto)) {
503                         fprintf(stderr, "\"coa\" is required with proto=%s\n",
504                                 strxf_xfrmproto(req.xsinfo.id.proto));
505                         exit (1);
506                 }
507         }
508
509         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
510                 exit(1);
511
512         if (req.xsinfo.family == AF_UNSPEC)
513                 req.xsinfo.family = AF_INET;
514
515         if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
516                 exit(2);
517
518         rtnl_close(&rth);
519
520         return 0;
521 }
522
523 static int xfrm_state_allocspi(int argc, char **argv)
524 {
525         struct rtnl_handle rth;
526         struct {
527                 struct nlmsghdr         n;
528                 struct xfrm_userspi_info xspi;
529                 char                    buf[RTA_BUF_SIZE];
530         } req;
531         char *idp = NULL;
532         char *minp = NULL;
533         char *maxp = NULL;
534         struct xfrm_mark mark = {0, 0};
535         char res_buf[NLMSG_BUF_SIZE];
536         struct nlmsghdr *res_n = (struct nlmsghdr *)res_buf;
537
538         memset(res_buf, 0, sizeof(res_buf));
539
540         memset(&req, 0, sizeof(req));
541
542         req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xspi));
543         req.n.nlmsg_flags = NLM_F_REQUEST;
544         req.n.nlmsg_type = XFRM_MSG_ALLOCSPI;
545         req.xspi.info.family = preferred_family;
546
547 #if 0
548         req.xsinfo.lft.soft_byte_limit = XFRM_INF;
549         req.xsinfo.lft.hard_byte_limit = XFRM_INF;
550         req.xsinfo.lft.soft_packet_limit = XFRM_INF;
551         req.xsinfo.lft.hard_packet_limit = XFRM_INF;
552 #endif
553
554         while (argc > 0) {
555                 if (strcmp(*argv, "mode") == 0) {
556                         NEXT_ARG();
557                         xfrm_mode_parse(&req.xspi.info.mode, &argc, &argv);
558                 } else if (strcmp(*argv, "mark") == 0) {
559                         xfrm_parse_mark(&mark, &argc, &argv);
560                 } else if (strcmp(*argv, "reqid") == 0) {
561                         NEXT_ARG();
562                         xfrm_reqid_parse(&req.xspi.info.reqid, &argc, &argv);
563                 } else if (strcmp(*argv, "seq") == 0) {
564                         NEXT_ARG();
565                         xfrm_seq_parse(&req.xspi.info.seq, &argc, &argv);
566                 } else if (strcmp(*argv, "min") == 0) {
567                         if (minp)
568                                 duparg("min", *argv);
569                         minp = *argv;
570
571                         NEXT_ARG();
572
573                         if (get_u32(&req.xspi.min, *argv, 0))
574                                 invarg("\"min\" value is invalid", *argv);
575                 } else if (strcmp(*argv, "max") == 0) {
576                         if (maxp)
577                                 duparg("max", *argv);
578                         maxp = *argv;
579
580                         NEXT_ARG();
581
582                         if (get_u32(&req.xspi.max, *argv, 0))
583                                 invarg("\"max\" value is invalid", *argv);
584                 } else {
585                         /* try to assume ID */
586                         if (idp)
587                                 invarg("unknown", *argv);
588                         idp = *argv;
589
590                         /* ID */
591                         xfrm_id_parse(&req.xspi.info.saddr, &req.xspi.info.id,
592                                       &req.xspi.info.family, 0, &argc, &argv);
593                         if (req.xspi.info.id.spi) {
594                                 fprintf(stderr, "\"SPI\" must be zero\n");
595                                 exit(1);
596                         }
597                         if (preferred_family == AF_UNSPEC)
598                                 preferred_family = req.xspi.info.family;
599                 }
600                 argc--; argv++;
601         }
602
603         if (!idp) {
604                 fprintf(stderr, "Not enough information: \"ID\" is required\n");
605                 exit(1);
606         }
607
608         if (minp) {
609                 if (!maxp) {
610                         fprintf(stderr, "\"max\" is missing\n");
611                         exit(1);
612                 }
613                 if (req.xspi.min > req.xspi.max) {
614                         fprintf(stderr, "\"min\" valie is larger than \"max\" one\n");
615                         exit(1);
616                 }
617         } else {
618                 if (maxp) {
619                         fprintf(stderr, "\"min\" is missing\n");
620                         exit(1);
621                 }
622
623                 /* XXX: Default value defined in PF_KEY;
624                  * See kernel's net/key/af_key.c(pfkey_getspi).
625                  */
626                 req.xspi.min = 0x100;
627                 req.xspi.max = 0x0fffffff;
628
629                 /* XXX: IPCOMP spi is 16-bits;
630                  * See kernel's net/xfrm/xfrm_user(verify_userspi_info).
631                  */
632                 if (req.xspi.info.id.proto == IPPROTO_COMP)
633                         req.xspi.max = 0xffff;
634         }
635
636         if (mark.m & mark.v) {
637                 int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
638                                   (void *)&mark, sizeof(mark));
639                 if (r < 0) {
640                         fprintf(stderr, "XFRMA_MARK failed\n");
641                         exit(1);
642                 }
643         }
644
645         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
646                 exit(1);
647
648         if (req.xspi.info.family == AF_UNSPEC)
649                 req.xspi.info.family = AF_INET;
650
651
652         if (rtnl_talk(&rth, &req.n, 0, 0, res_n, NULL, NULL) < 0)
653                 exit(2);
654
655         if (xfrm_state_print(NULL, res_n, (void*)stdout) < 0) {
656                 fprintf(stderr, "An error :-)\n");
657                 exit(1);
658         }
659
660         rtnl_close(&rth);
661
662         return 0;
663 }
664
665 static int xfrm_state_filter_match(struct xfrm_usersa_info *xsinfo)
666 {
667         if (!filter.use)
668                 return 1;
669
670         if (filter.id_src_mask)
671                 if (xfrm_addr_match(&xsinfo->saddr, &filter.xsinfo.saddr,
672                                     filter.id_src_mask))
673                         return 0;
674         if (filter.id_dst_mask)
675                 if (xfrm_addr_match(&xsinfo->id.daddr, &filter.xsinfo.id.daddr,
676                                     filter.id_dst_mask))
677                         return 0;
678         if ((xsinfo->id.proto^filter.xsinfo.id.proto)&filter.id_proto_mask)
679                 return 0;
680         if ((xsinfo->id.spi^filter.xsinfo.id.spi)&filter.id_spi_mask)
681                 return 0;
682         if ((xsinfo->mode^filter.xsinfo.mode)&filter.mode_mask)
683                 return 0;
684         if ((xsinfo->reqid^filter.xsinfo.reqid)&filter.reqid_mask)
685                 return 0;
686         if (filter.state_flags_mask)
687                 if ((xsinfo->flags & filter.xsinfo.flags) == 0)
688                         return 0;
689
690         return 1;
691 }
692
693 int xfrm_state_print(const struct sockaddr_nl *who, struct nlmsghdr *n,
694                      void *arg)
695 {
696         FILE *fp = (FILE*)arg;
697         struct rtattr * tb[XFRMA_MAX+1];
698         struct rtattr * rta;
699         struct xfrm_usersa_info *xsinfo = NULL;
700         struct xfrm_user_expire *xexp = NULL;
701         struct xfrm_usersa_id   *xsid = NULL;
702         int len = n->nlmsg_len;
703
704         if (n->nlmsg_type != XFRM_MSG_NEWSA &&
705             n->nlmsg_type != XFRM_MSG_DELSA &&
706             n->nlmsg_type != XFRM_MSG_UPDSA &&
707             n->nlmsg_type != XFRM_MSG_EXPIRE) {
708                 fprintf(stderr, "Not a state: %08x %08x %08x\n",
709                         n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
710                 return 0;
711         }
712
713         if (n->nlmsg_type == XFRM_MSG_DELSA) {
714                 /* Dont blame me for this .. Herbert made me do it */
715                 xsid = NLMSG_DATA(n);
716                 len -= NLMSG_SPACE(sizeof(*xsid));
717         } else if (n->nlmsg_type == XFRM_MSG_EXPIRE) {
718                 xexp = NLMSG_DATA(n);
719                 xsinfo = &xexp->state;
720                 len -= NLMSG_SPACE(sizeof(*xexp));
721         } else {
722                 xexp = NULL;
723                 xsinfo = NLMSG_DATA(n);
724                 len -= NLMSG_SPACE(sizeof(*xsinfo));
725         }
726
727         if (len < 0) {
728                 fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
729                 return -1;
730         }
731
732         if (xsinfo && !xfrm_state_filter_match(xsinfo))
733                 return 0;
734
735         if (n->nlmsg_type == XFRM_MSG_DELSA)
736                 fprintf(fp, "Deleted ");
737         else if (n->nlmsg_type == XFRM_MSG_UPDSA)
738                 fprintf(fp, "Updated ");
739         else if (n->nlmsg_type == XFRM_MSG_EXPIRE)
740                 fprintf(fp, "Expired ");
741
742         if (n->nlmsg_type == XFRM_MSG_DELSA)
743                 rta = XFRMSID_RTA(xsid);
744         else if (n->nlmsg_type == XFRM_MSG_EXPIRE)
745                 rta = XFRMEXP_RTA(xexp);
746         else
747                 rta = XFRMS_RTA(xsinfo);
748
749         parse_rtattr(tb, XFRMA_MAX, rta, len);
750
751         if (n->nlmsg_type == XFRM_MSG_DELSA) {
752                 //xfrm_policy_id_print();
753
754                 if (!tb[XFRMA_SA]) {
755                         fprintf(stderr, "Buggy XFRM_MSG_DELSA: no XFRMA_SA\n");
756                         return -1;
757                 }
758                 if (RTA_PAYLOAD(tb[XFRMA_SA]) < sizeof(*xsinfo)) {
759                         fprintf(stderr, "Buggy XFRM_MSG_DELPOLICY: too short XFRMA_POLICY len\n");
760                         return -1;
761                 }
762                 xsinfo = RTA_DATA(tb[XFRMA_SA]);
763         }
764
765         xfrm_state_info_print(xsinfo, tb, fp, NULL, NULL);
766
767         if (n->nlmsg_type == XFRM_MSG_EXPIRE) {
768                 fprintf(fp, "\t");
769                 fprintf(fp, "hard %u", xexp->hard);
770                 fprintf(fp, "%s", _SL_);
771         }
772
773         if (oneline)
774                 fprintf(fp, "\n");
775         fflush(fp);
776
777         return 0;
778 }
779
780 static int xfrm_state_get_or_delete(int argc, char **argv, int delete)
781 {
782         struct rtnl_handle rth;
783         struct {
784                 struct nlmsghdr         n;
785                 struct xfrm_usersa_id   xsid;
786                 char                    buf[RTA_BUF_SIZE];
787         } req;
788         struct xfrm_id id;
789         char *idp = NULL;
790         struct xfrm_mark mark = {0, 0};
791
792         memset(&req, 0, sizeof(req));
793
794         req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsid));
795         req.n.nlmsg_flags = NLM_F_REQUEST;
796         req.n.nlmsg_type = delete ? XFRM_MSG_DELSA : XFRM_MSG_GETSA;
797         req.xsid.family = preferred_family;
798
799         while (argc > 0) {
800                 xfrm_address_t saddr;
801
802                 if (strcmp(*argv, "mark") == 0) {
803                         xfrm_parse_mark(&mark, &argc, &argv);
804                 } else {
805                         if (idp)
806                                 invarg("unknown", *argv);
807                         idp = *argv;
808
809                         /* ID */
810                         memset(&id, 0, sizeof(id));
811                         memset(&saddr, 0, sizeof(saddr));
812                         xfrm_id_parse(&saddr, &id, &req.xsid.family, 0,
813                                       &argc, &argv);
814
815                         memcpy(&req.xsid.daddr, &id.daddr, sizeof(req.xsid.daddr));
816                         req.xsid.spi = id.spi;
817                         req.xsid.proto = id.proto;
818
819                         addattr_l(&req.n, sizeof(req.buf), XFRMA_SRCADDR,
820                                   (void *)&saddr, sizeof(saddr));
821                 }
822
823                 argc--; argv++;
824         }
825
826         if (mark.m & mark.v) {
827                 int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
828                                   (void *)&mark, sizeof(mark));
829                 if (r < 0) {
830                         fprintf(stderr, "XFRMA_MARK failed\n");
831                         exit(1);
832                 }
833         }
834
835         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
836                 exit(1);
837
838         if (req.xsid.family == AF_UNSPEC)
839                 req.xsid.family = AF_INET;
840
841         if (delete) {
842                 if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
843                         exit(2);
844         } else {
845                 char buf[NLMSG_BUF_SIZE];
846                 struct nlmsghdr *res_n = (struct nlmsghdr *)buf;
847
848                 memset(buf, 0, sizeof(buf));
849
850                 if (rtnl_talk(&rth, &req.n, 0, 0, res_n, NULL, NULL) < 0)
851                         exit(2);
852
853                 if (xfrm_state_print(NULL, res_n, (void*)stdout) < 0) {
854                         fprintf(stderr, "An error :-)\n");
855                         exit(1);
856                 }
857         }
858
859         rtnl_close(&rth);
860
861         return 0;
862 }
863
864 /*
865  * With an existing state of nlmsg, make new nlmsg for deleting the state
866  * and store it to buffer.
867  */
868 static int xfrm_state_keep(const struct sockaddr_nl *who,
869                            struct nlmsghdr *n,
870                            void *arg)
871 {
872         struct xfrm_buffer *xb = (struct xfrm_buffer *)arg;
873         struct rtnl_handle *rth = xb->rth;
874         struct xfrm_usersa_info *xsinfo = NLMSG_DATA(n);
875         int len = n->nlmsg_len;
876         struct nlmsghdr *new_n;
877         struct xfrm_usersa_id *xsid;
878
879         if (n->nlmsg_type != XFRM_MSG_NEWSA) {
880                 fprintf(stderr, "Not a state: %08x %08x %08x\n",
881                         n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
882                 return 0;
883         }
884
885         len -= NLMSG_LENGTH(sizeof(*xsinfo));
886         if (len < 0) {
887                 fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
888                 return -1;
889         }
890
891         if (!xfrm_state_filter_match(xsinfo))
892                 return 0;
893
894         if (xb->offset > xb->size) {
895                 fprintf(stderr, "State buffer overflow\n");
896                 return -1;
897         }
898
899         new_n = (struct nlmsghdr *)(xb->buf + xb->offset);
900         new_n->nlmsg_len = NLMSG_LENGTH(sizeof(*xsid));
901         new_n->nlmsg_flags = NLM_F_REQUEST;
902         new_n->nlmsg_type = XFRM_MSG_DELSA;
903         new_n->nlmsg_seq = ++rth->seq;
904
905         xsid = NLMSG_DATA(new_n);
906         xsid->family = xsinfo->family;
907         memcpy(&xsid->daddr, &xsinfo->id.daddr, sizeof(xsid->daddr));
908         xsid->spi = xsinfo->id.spi;
909         xsid->proto = xsinfo->id.proto;
910
911         addattr_l(new_n, xb->size, XFRMA_SRCADDR, &xsinfo->saddr,
912                   sizeof(xsid->daddr));
913
914         xb->offset += new_n->nlmsg_len;
915         xb->nlmsg_count ++;
916
917         return 0;
918 }
919
920 static int xfrm_state_list_or_deleteall(int argc, char **argv, int deleteall)
921 {
922         char *idp = NULL;
923         struct rtnl_handle rth;
924
925         if(argc > 0)
926                 filter.use = 1;
927         filter.xsinfo.family = preferred_family;
928
929         while (argc > 0) {
930                 if (strcmp(*argv, "mode") == 0) {
931                         NEXT_ARG();
932                         xfrm_mode_parse(&filter.xsinfo.mode, &argc, &argv);
933
934                         filter.mode_mask = XFRM_FILTER_MASK_FULL;
935
936                 } else if (strcmp(*argv, "reqid") == 0) {
937                         NEXT_ARG();
938                         xfrm_reqid_parse(&filter.xsinfo.reqid, &argc, &argv);
939
940                         filter.reqid_mask = XFRM_FILTER_MASK_FULL;
941
942                 } else if (strcmp(*argv, "flag") == 0) {
943                         NEXT_ARG();
944                         xfrm_state_flag_parse(&filter.xsinfo.flags, &argc, &argv);
945
946                         filter.state_flags_mask = XFRM_FILTER_MASK_FULL;
947
948                 } else {
949                         if (idp)
950                                 invarg("unknown", *argv);
951                         idp = *argv;
952
953                         /* ID */
954                         xfrm_id_parse(&filter.xsinfo.saddr, &filter.xsinfo.id,
955                                       &filter.xsinfo.family, 1, &argc, &argv);
956                         if (preferred_family == AF_UNSPEC)
957                                 preferred_family = filter.xsinfo.family;
958                 }
959                 argc--; argv++;
960         }
961
962         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
963                 exit(1);
964
965         if (deleteall) {
966                 struct xfrm_buffer xb;
967                 char buf[NLMSG_DELETEALL_BUF_SIZE];
968                 int i;
969
970                 xb.buf = buf;
971                 xb.size = sizeof(buf);
972                 xb.rth = &rth;
973
974                 for (i = 0; ; i++) {
975                         xb.offset = 0;
976                         xb.nlmsg_count = 0;
977
978                         if (show_stats > 1)
979                                 fprintf(stderr, "Delete-all round = %d\n", i);
980
981                         if (rtnl_wilddump_request(&rth, preferred_family, XFRM_MSG_GETSA) < 0) {
982                                 perror("Cannot send dump request");
983                                 exit(1);
984                         }
985
986                         if (rtnl_dump_filter(&rth, xfrm_state_keep, &xb, NULL, NULL) < 0) {
987                                 fprintf(stderr, "Delete-all terminated\n");
988                                 exit(1);
989                         }
990                         if (xb.nlmsg_count == 0) {
991                                 if (show_stats > 1)
992                                         fprintf(stderr, "Delete-all completed\n");
993                                 break;
994                         }
995
996                         if (rtnl_send_check(&rth, xb.buf, xb.offset) < 0) {
997                                 perror("Failed to send delete-all request\n");
998                                 exit(1);
999                         }
1000                         if (show_stats > 1)
1001                                 fprintf(stderr, "Delete-all nlmsg count = %d\n", xb.nlmsg_count);
1002
1003                         xb.offset = 0;
1004                         xb.nlmsg_count = 0;
1005                 }
1006
1007         } else {
1008                 if (rtnl_wilddump_request(&rth, preferred_family, XFRM_MSG_GETSA) < 0) {
1009                         perror("Cannot send dump request");
1010                         exit(1);
1011                 }
1012
1013                 if (rtnl_dump_filter(&rth, xfrm_state_print, stdout, NULL, NULL) < 0) {
1014                         fprintf(stderr, "Dump terminated\n");
1015                         exit(1);
1016                 }
1017         }
1018
1019         rtnl_close(&rth);
1020
1021         exit(0);
1022 }
1023
1024 int print_sadinfo(struct nlmsghdr *n, void *arg)
1025 {
1026         FILE *fp = (FILE*)arg;
1027         __u32 *f = NLMSG_DATA(n);
1028         struct rtattr *tb[XFRMA_SAD_MAX+1];
1029         struct rtattr *rta;
1030         __u32 *cnt;
1031
1032         int len = n->nlmsg_len;
1033
1034         len -= NLMSG_LENGTH(sizeof(__u32));
1035         if (len < 0) {
1036                 fprintf(stderr, "SADinfo: Wrong len %d\n", len);
1037                 return -1;
1038         }
1039
1040         rta = XFRMSAPD_RTA(f);
1041         parse_rtattr(tb, XFRMA_SAD_MAX, rta, len);
1042
1043         if (tb[XFRMA_SAD_CNT]) {
1044                 fprintf(fp,"\t SAD");
1045                 cnt = (__u32 *)RTA_DATA(tb[XFRMA_SAD_CNT]);
1046                 fprintf(fp," count %d", *cnt);
1047         } else {
1048                 fprintf(fp,"BAD SAD info returned\n");
1049                 return -1;
1050         }
1051
1052         if (show_stats) {
1053                 if (tb[XFRMA_SAD_HINFO]) {
1054                         struct xfrmu_sadhinfo *si;
1055
1056                         if (RTA_PAYLOAD(tb[XFRMA_SAD_HINFO]) < sizeof(*si)) {
1057                                 fprintf(fp,"BAD SAD length returned\n");
1058                                 return -1;
1059                         }
1060                                 
1061                         si = RTA_DATA(tb[XFRMA_SAD_HINFO]);
1062                         fprintf(fp," (buckets ");
1063                         fprintf(fp,"count %d", si->sadhcnt);
1064                         fprintf(fp," Max %d", si->sadhmcnt);
1065                         fprintf(fp,")");
1066                 }
1067         }
1068         fprintf(fp,"\n");
1069
1070         return 0;
1071 }
1072
1073 static int xfrm_sad_getinfo(int argc, char **argv)
1074 {
1075         struct rtnl_handle rth;
1076         struct {
1077                 struct nlmsghdr                 n;
1078                 __u32                           flags;
1079                 char                            ans[64];
1080         } req;
1081
1082         memset(&req, 0, sizeof(req));
1083         req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.flags));
1084         req.n.nlmsg_flags = NLM_F_REQUEST;
1085         req.n.nlmsg_type = XFRM_MSG_GETSADINFO;
1086         req.flags = 0XFFFFFFFF;
1087
1088         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1089                 exit(1);
1090
1091         if (rtnl_talk(&rth, &req.n, 0, 0, &req.n, NULL, NULL) < 0)
1092                 exit(2);
1093
1094         print_sadinfo(&req.n, (void*)stdout);
1095
1096         rtnl_close(&rth);
1097
1098         return 0;
1099 }
1100
1101 static int xfrm_state_flush(int argc, char **argv)
1102 {
1103         struct rtnl_handle rth;
1104         struct {
1105                 struct nlmsghdr                 n;
1106                 struct xfrm_usersa_flush        xsf;
1107         } req;
1108         char *protop = NULL;
1109
1110         memset(&req, 0, sizeof(req));
1111
1112         req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsf));
1113         req.n.nlmsg_flags = NLM_F_REQUEST;
1114         req.n.nlmsg_type = XFRM_MSG_FLUSHSA;
1115         req.xsf.proto = 0;
1116
1117         while (argc > 0) {
1118                 if (strcmp(*argv, "proto") == 0) {
1119                         int ret;
1120
1121                         if (protop)
1122                                 duparg("proto", *argv);
1123                         protop = *argv;
1124
1125                         NEXT_ARG();
1126
1127                         ret = xfrm_xfrmproto_getbyname(*argv);
1128                         if (ret < 0)
1129                                 invarg("\"XFRM_PROTO\" is invalid", *argv);
1130
1131                         req.xsf.proto = (__u8)ret;
1132                 } else
1133                         invarg("unknown", *argv);
1134
1135                 argc--; argv++;
1136         }
1137
1138         if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1139                 exit(1);
1140
1141         if (show_stats > 1)
1142                 fprintf(stderr, "Flush state proto=%s\n",
1143                         strxf_xfrmproto(req.xsf.proto));
1144
1145         if (rtnl_talk(&rth, &req.n, 0, 0, NULL, NULL, NULL) < 0)
1146                 exit(2);
1147
1148         rtnl_close(&rth);
1149
1150         return 0;
1151 }
1152
1153 int do_xfrm_state(int argc, char **argv)
1154 {
1155         if (argc < 1)
1156                 return xfrm_state_list_or_deleteall(0, NULL, 0);
1157
1158         if (matches(*argv, "add") == 0)
1159                 return xfrm_state_modify(XFRM_MSG_NEWSA, 0,
1160                                          argc-1, argv+1);
1161         if (matches(*argv, "update") == 0)
1162                 return xfrm_state_modify(XFRM_MSG_UPDSA, 0,
1163                                          argc-1, argv+1);
1164         if (matches(*argv, "allocspi") == 0)
1165                 return xfrm_state_allocspi(argc-1, argv+1);
1166         if (matches(*argv, "delete") == 0)
1167                 return xfrm_state_get_or_delete(argc-1, argv+1, 1);
1168         if (matches(*argv, "deleteall") == 0 || matches(*argv, "delall") == 0)
1169                 return xfrm_state_list_or_deleteall(argc-1, argv+1, 1);
1170         if (matches(*argv, "list") == 0 || matches(*argv, "show") == 0
1171             || matches(*argv, "lst") == 0)
1172                 return xfrm_state_list_or_deleteall(argc-1, argv+1, 0);
1173         if (matches(*argv, "get") == 0)
1174                 return xfrm_state_get_or_delete(argc-1, argv+1, 0);
1175         if (matches(*argv, "flush") == 0)
1176                 return xfrm_state_flush(argc-1, argv+1);
1177         if (matches(*argv, "count") == 0) {
1178                 return xfrm_sad_getinfo(argc, argv);
1179         }
1180         if (matches(*argv, "help") == 0)
1181                 usage();
1182         fprintf(stderr, "Command \"%s\" is unknown, try \"ip xfrm state help\".\n", *argv);
1183         exit(-1);
1184 }