iproute2/ip/xfrm_state.c
<<
>>
Prefs
   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, see <http://www.gnu.org/licenses>.
  18 */
  19/*
  20 * based on iproute.c
  21 */
  22/*
  23 * Authors:
  24 *      Masahide NAKAMURA @USAGI
  25 */
  26
  27#include <stdio.h>
  28#include <stdlib.h>
  29#include <string.h>
  30#include <netdb.h>
  31#include "utils.h"
  32#include "xfrm.h"
  33#include "ip_common.h"
  34
  35/* #define NLMSG_DELETEALL_BUF_SIZE (4096-512) */
  36#define NLMSG_DELETEALL_BUF_SIZE 8192
  37
  38/*
  39 * Receiving buffer defines:
  40 * nlmsg
  41 *   data = struct xfrm_usersa_info
  42 *   rtattr
  43 *   rtattr
  44 *   ... (max count of rtattr is XFRM_MAX+1
  45 *
  46 *  each rtattr data = struct xfrm_algo(dynamic size) or xfrm_address_t
  47 */
  48#define NLMSG_BUF_SIZE 4096
  49#define RTA_BUF_SIZE 2048
  50#define XFRM_ALGO_KEY_BUF_SIZE 512
  51#define CTX_BUF_SIZE 256
  52
  53static void usage(void) __attribute__((noreturn));
  54
  55static void usage(void)
  56{
  57        fprintf(stderr,
  58                "Usage: ip xfrm state { add | update } ID [ ALGO-LIST ] [ mode MODE ]\n"
  59                "        [ mark MARK [ mask MASK ] ] [ reqid REQID ] [ seq SEQ ]\n"
  60                "        [ replay-window SIZE ] [ replay-seq SEQ ] [ replay-oseq SEQ ]\n"
  61                "        [ replay-seq-hi SEQ ] [ replay-oseq-hi SEQ ]\n"
  62                "        [ flag FLAG-LIST ] [ sel SELECTOR ] [ LIMIT-LIST ] [ encap ENCAP ]\n"
  63                "        [ coa ADDR[/PLEN] ] [ ctx CTX ] [ extra-flag EXTRA-FLAG-LIST ]\n"
  64                "        [ offload [dev DEV] dir DIR ]\n"
  65                "        [ output-mark OUTPUT-MARK [ mask MASK ] ]\n"
  66                "        [ if_id IF_ID ]\n"
  67                "Usage: ip xfrm state allocspi ID [ mode MODE ] [ mark MARK [ mask MASK ] ]\n"
  68                "        [ reqid REQID ] [ seq SEQ ] [ min SPI max SPI ]\n"
  69                "Usage: ip xfrm state { delete | get } ID [ mark MARK [ mask MASK ] ]\n"
  70                "Usage: ip xfrm state deleteall [ ID ] [ mode MODE ] [ reqid REQID ]\n"
  71                "        [ flag FLAG-LIST ]\n"
  72                "Usage: ip xfrm state list [ nokeys ] [ ID ] [ mode MODE ] [ reqid REQID ]\n"
  73                "        [ flag FLAG-LIST ]\n"
  74                "Usage: ip xfrm state flush [ proto XFRM-PROTO ]\n"
  75                "Usage: ip xfrm state count\n"
  76                "ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]\n"
  77                "XFRM-PROTO := ");
  78        fprintf(stderr,
  79                "%s | %s | %s | %s | %s\n",
  80                strxf_xfrmproto(IPPROTO_ESP),
  81                strxf_xfrmproto(IPPROTO_AH),
  82                strxf_xfrmproto(IPPROTO_COMP),
  83                strxf_xfrmproto(IPPROTO_ROUTING),
  84                strxf_xfrmproto(IPPROTO_DSTOPTS));
  85        fprintf(stderr,
  86                "ALGO-LIST := [ ALGO-LIST ] ALGO\n"
  87                "ALGO := { ");
  88        fprintf(stderr,
  89                "%s | %s",
  90                strxf_algotype(XFRMA_ALG_CRYPT),
  91                strxf_algotype(XFRMA_ALG_AUTH));
  92        fprintf(stderr,
  93                " } ALGO-NAME ALGO-KEYMAT |\n"
  94                "        %s", strxf_algotype(XFRMA_ALG_AUTH_TRUNC));
  95        fprintf(stderr,
  96                " ALGO-NAME ALGO-KEYMAT ALGO-TRUNC-LEN |\n"
  97                "        %s", strxf_algotype(XFRMA_ALG_AEAD));
  98        fprintf(stderr,
  99                " ALGO-NAME ALGO-KEYMAT ALGO-ICV-LEN |\n"
 100                "        %s", strxf_algotype(XFRMA_ALG_COMP));
 101        fprintf(stderr,
 102                " ALGO-NAME\n"
 103                "MODE := transport | tunnel | beet | ro | in_trigger\n"
 104                "FLAG-LIST := [ FLAG-LIST ] FLAG\n"
 105                "FLAG := noecn | decap-dscp | nopmtudisc | wildrecv | icmp | af-unspec | align4 | esn\n"
 106                "EXTRA-FLAG-LIST := [ EXTRA-FLAG-LIST ] EXTRA-FLAG\n"
 107                "EXTRA-FLAG := dont-encap-dscp | oseq-may-wrap\n"
 108                "SELECTOR := [ src ADDR[/PLEN] ] [ dst ADDR[/PLEN] ] [ dev DEV ] [ UPSPEC ]\n"
 109                "UPSPEC := proto { { tcp | udp | sctp | dccp } [ sport PORT ] [ dport PORT ] |\n"
 110                "                  { icmp | ipv6-icmp | mobility-header } [ type NUMBER ] [ code NUMBER ] |\n"
 111                "                  gre [ key { DOTTED-QUAD | NUMBER } ] | PROTO }\n"
 112                "LIMIT-LIST := [ LIMIT-LIST ] limit LIMIT\n"
 113                "LIMIT := { time-soft | time-hard | time-use-soft | time-use-hard } SECONDS |\n"
 114                "         { byte-soft | byte-hard } SIZE | { packet-soft | packet-hard } COUNT\n"
 115                "ENCAP := { espinudp | espinudp-nonike | espintcp } SPORT DPORT OADDR\n"
 116                "DIR := in | out\n");
 117
 118        exit(-1);
 119}
 120
 121static int xfrm_algo_parse(struct xfrm_algo *alg, enum xfrm_attr_type_t type,
 122                           char *name, char *key, char *buf, int max)
 123{
 124        int len;
 125        int slen = strlen(key);
 126
 127#if 0
 128        /* XXX: verifying both name and key is required! */
 129        fprintf(stderr, "warning: ALGO-NAME/ALGO-KEYMAT values will be sent to the kernel promiscuously! (verifying them isn't implemented yet)\n");
 130#endif
 131
 132        strlcpy(alg->alg_name, name, sizeof(alg->alg_name));
 133
 134        if (slen > 2 && strncmp(key, "0x", 2) == 0) {
 135                /* split two chars "0x" from the top */
 136                char *p = key + 2;
 137                int plen = slen - 2;
 138                int i;
 139                int j;
 140
 141                /* Converting hexadecimal numbered string into real key;
 142                 * Convert each two chars into one char(value). If number
 143                 * of the length is odd, add zero on the top for rounding.
 144                 */
 145
 146                /* calculate length of the converted values(real key) */
 147                len = (plen + 1) / 2;
 148                if (len > max)
 149                        invarg("ALGO-KEYMAT value makes buffer overflow\n", key);
 150
 151                for (i = -(plen % 2), j = 0; j < len; i += 2, j++) {
 152                        char vbuf[3];
 153                        __u8 val;
 154
 155                        vbuf[0] = i >= 0 ? p[i] : '0';
 156                        vbuf[1] = p[i + 1];
 157                        vbuf[2] = '\0';
 158
 159                        if (get_u8(&val, vbuf, 16))
 160                                invarg("ALGO-KEYMAT value is invalid", key);
 161
 162                        buf[j] = val;
 163                }
 164        } else {
 165                len = slen;
 166                if (len > 0) {
 167                        if (len > max)
 168                                invarg("ALGO-KEYMAT value makes buffer overflow\n", key);
 169
 170                        memcpy(buf, key, len);
 171                }
 172        }
 173
 174        alg->alg_key_len = len * 8;
 175
 176        return 0;
 177}
 178
 179static int xfrm_seq_parse(__u32 *seq, int *argcp, char ***argvp)
 180{
 181        int argc = *argcp;
 182        char **argv = *argvp;
 183
 184        if (get_be32(seq, *argv, 0))
 185                invarg("SEQ value is invalid", *argv);
 186
 187        *argcp = argc;
 188        *argvp = argv;
 189
 190        return 0;
 191}
 192
 193static int xfrm_state_flag_parse(__u8 *flags, int *argcp, char ***argvp)
 194{
 195        int argc = *argcp;
 196        char **argv = *argvp;
 197        int len = strlen(*argv);
 198
 199        if (len > 2 && strncmp(*argv, "0x", 2) == 0) {
 200                __u8 val = 0;
 201
 202                if (get_u8(&val, *argv, 16))
 203                        invarg("FLAG value is invalid", *argv);
 204                *flags = val;
 205        } else {
 206                while (1) {
 207                        if (strcmp(*argv, "noecn") == 0)
 208                                *flags |= XFRM_STATE_NOECN;
 209                        else if (strcmp(*argv, "decap-dscp") == 0)
 210                                *flags |= XFRM_STATE_DECAP_DSCP;
 211                        else if (strcmp(*argv, "nopmtudisc") == 0)
 212                                *flags |= XFRM_STATE_NOPMTUDISC;
 213                        else if (strcmp(*argv, "wildrecv") == 0)
 214                                *flags |= XFRM_STATE_WILDRECV;
 215                        else if (strcmp(*argv, "icmp") == 0)
 216                                *flags |= XFRM_STATE_ICMP;
 217                        else if (strcmp(*argv, "af-unspec") == 0)
 218                                *flags |= XFRM_STATE_AF_UNSPEC;
 219                        else if (strcmp(*argv, "align4") == 0)
 220                                *flags |= XFRM_STATE_ALIGN4;
 221                        else if (strcmp(*argv, "esn") == 0)
 222                                *flags |= XFRM_STATE_ESN;
 223                        else {
 224                                PREV_ARG(); /* back track */
 225                                break;
 226                        }
 227
 228                        if (!NEXT_ARG_OK())
 229                                break;
 230                        NEXT_ARG();
 231                }
 232        }
 233
 234        *argcp = argc;
 235        *argvp = argv;
 236
 237        return 0;
 238}
 239
 240static int xfrm_state_extra_flag_parse(__u32 *extra_flags, int *argcp, char ***argvp)
 241{
 242        int argc = *argcp;
 243        char **argv = *argvp;
 244        int len = strlen(*argv);
 245
 246        if (len > 2 && strncmp(*argv, "0x", 2) == 0) {
 247                __u32 val = 0;
 248
 249                if (get_u32(&val, *argv, 16))
 250                        invarg("\"EXTRA-FLAG\" is invalid", *argv);
 251                *extra_flags = val;
 252        } else {
 253                while (1) {
 254                        if (strcmp(*argv, "dont-encap-dscp") == 0)
 255                                *extra_flags |= XFRM_SA_XFLAG_DONT_ENCAP_DSCP;
 256                        else if (strcmp(*argv, "oseq-may-wrap") == 0)
 257                                *extra_flags |= XFRM_SA_XFLAG_OSEQ_MAY_WRAP;
 258                        else {
 259                                PREV_ARG(); /* back track */
 260                                break;
 261                        }
 262
 263                        if (!NEXT_ARG_OK())
 264                                break;
 265                        NEXT_ARG();
 266                }
 267        }
 268
 269        *argcp = argc;
 270        *argvp = argv;
 271
 272        return 0;
 273}
 274
 275static int xfrm_offload_dir_parse(__u8 *dir, int *argcp, char ***argvp)
 276{
 277        int argc = *argcp;
 278        char **argv = *argvp;
 279
 280        if (strcmp(*argv, "in") == 0)
 281                *dir = XFRM_OFFLOAD_INBOUND;
 282        else if (strcmp(*argv, "out") == 0)
 283                *dir = 0;
 284        else
 285                invarg("DIR value is invalid", *argv);
 286
 287        *argcp = argc;
 288        *argvp = argv;
 289
 290        return 0;
 291}
 292
 293static int xfrm_state_modify(int cmd, unsigned int flags, int argc, char **argv)
 294{
 295        struct rtnl_handle rth;
 296        struct {
 297                struct nlmsghdr n;
 298                struct xfrm_usersa_info xsinfo;
 299                char                    buf[RTA_BUF_SIZE];
 300        } req = {
 301                .n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsinfo)),
 302                .n.nlmsg_flags = NLM_F_REQUEST | flags,
 303                .n.nlmsg_type = cmd,
 304                .xsinfo.family = preferred_family,
 305                .xsinfo.lft.soft_byte_limit = XFRM_INF,
 306                .xsinfo.lft.hard_byte_limit = XFRM_INF,
 307                .xsinfo.lft.soft_packet_limit = XFRM_INF,
 308                .xsinfo.lft.hard_packet_limit = XFRM_INF,
 309        };
 310        struct xfrm_replay_state replay = {};
 311        struct xfrm_replay_state_esn replay_esn = {};
 312        struct xfrm_user_offload xuo = {};
 313        unsigned int ifindex = 0;
 314        __u8 dir = 0;
 315        bool is_offload = false;
 316        __u32 replay_window = 0;
 317        __u32 seq = 0, oseq = 0, seq_hi = 0, oseq_hi = 0;
 318        char *idp = NULL;
 319        char *aeadop = NULL;
 320        char *ealgop = NULL;
 321        char *aalgop = NULL;
 322        char *calgop = NULL;
 323        char *coap = NULL;
 324        char *sctxp = NULL;
 325        __u32 extra_flags = 0;
 326        struct xfrm_mark mark = {0, 0};
 327        struct {
 328                struct xfrm_user_sec_ctx sctx;
 329                char    str[CTX_BUF_SIZE];
 330        } ctx = {};
 331        struct xfrm_mark output_mark = {0, 0};
 332        bool is_if_id_set = false;
 333        __u32 if_id = 0;
 334
 335        while (argc > 0) {
 336                if (strcmp(*argv, "mode") == 0) {
 337                        NEXT_ARG();
 338                        xfrm_mode_parse(&req.xsinfo.mode, &argc, &argv);
 339                } else if (strcmp(*argv, "mark") == 0) {
 340                        xfrm_parse_mark(&mark, &argc, &argv);
 341                } else if (strcmp(*argv, "reqid") == 0) {
 342                        NEXT_ARG();
 343                        xfrm_reqid_parse(&req.xsinfo.reqid, &argc, &argv);
 344                } else if (strcmp(*argv, "seq") == 0) {
 345                        NEXT_ARG();
 346                        xfrm_seq_parse(&req.xsinfo.seq, &argc, &argv);
 347                } else if (strcmp(*argv, "replay-window") == 0) {
 348                        NEXT_ARG();
 349                        if (get_u32(&replay_window, *argv, 0))
 350                                invarg("value after \"replay-window\" is invalid", *argv);
 351                } else if (strcmp(*argv, "replay-seq") == 0) {
 352                        NEXT_ARG();
 353                        if (get_u32(&seq, *argv, 0))
 354                                invarg("value after \"replay-seq\" is invalid", *argv);
 355                } else if (strcmp(*argv, "replay-seq-hi") == 0) {
 356                        NEXT_ARG();
 357                        if (get_u32(&seq_hi, *argv, 0))
 358                                invarg("value after \"replay-seq-hi\" is invalid", *argv);
 359                } else if (strcmp(*argv, "replay-oseq") == 0) {
 360                        NEXT_ARG();
 361                        if (get_u32(&oseq, *argv, 0))
 362                                invarg("value after \"replay-oseq\" is invalid", *argv);
 363                } else if (strcmp(*argv, "replay-oseq-hi") == 0) {
 364                        NEXT_ARG();
 365                        if (get_u32(&oseq_hi, *argv, 0))
 366                                invarg("value after \"replay-oseq-hi\" is invalid", *argv);
 367                } else if (strcmp(*argv, "flag") == 0) {
 368                        NEXT_ARG();
 369                        xfrm_state_flag_parse(&req.xsinfo.flags, &argc, &argv);
 370                } else if (strcmp(*argv, "extra-flag") == 0) {
 371                        NEXT_ARG();
 372                        xfrm_state_extra_flag_parse(&extra_flags, &argc, &argv);
 373                } else if (strcmp(*argv, "sel") == 0) {
 374                        NEXT_ARG();
 375                        preferred_family = AF_UNSPEC;
 376                        xfrm_selector_parse(&req.xsinfo.sel, &argc, &argv);
 377                        preferred_family = req.xsinfo.sel.family;
 378                } else if (strcmp(*argv, "limit") == 0) {
 379                        NEXT_ARG();
 380                        xfrm_lifetime_cfg_parse(&req.xsinfo.lft, &argc, &argv);
 381                } else if (strcmp(*argv, "encap") == 0) {
 382                        struct xfrm_encap_tmpl encap;
 383                        inet_prefix oa;
 384                        NEXT_ARG();
 385                        xfrm_encap_type_parse(&encap.encap_type, &argc, &argv);
 386                        NEXT_ARG();
 387                        if (get_be16(&encap.encap_sport, *argv, 0))
 388                                invarg("SPORT value after \"encap\" is invalid", *argv);
 389                        NEXT_ARG();
 390                        if (get_be16(&encap.encap_dport, *argv, 0))
 391                                invarg("DPORT value after \"encap\" is invalid", *argv);
 392                        NEXT_ARG();
 393                        get_addr(&oa, *argv, AF_UNSPEC);
 394                        memcpy(&encap.encap_oa, &oa.data, sizeof(encap.encap_oa));
 395                        addattr_l(&req.n, sizeof(req.buf), XFRMA_ENCAP,
 396                                  (void *)&encap, sizeof(encap));
 397                } else if (strcmp(*argv, "coa") == 0) {
 398                        inet_prefix coa;
 399                        xfrm_address_t xcoa = {};
 400
 401                        if (coap)
 402                                duparg("coa", *argv);
 403                        coap = *argv;
 404
 405                        NEXT_ARG();
 406
 407                        get_prefix(&coa, *argv, preferred_family);
 408                        if (coa.family == AF_UNSPEC)
 409                                invarg("value after \"coa\" has an unrecognized address family", *argv);
 410                        if (coa.bytelen > sizeof(xcoa))
 411                                invarg("value after \"coa\" is too large", *argv);
 412
 413                        memcpy(&xcoa, &coa.data, coa.bytelen);
 414
 415                        addattr_l(&req.n, sizeof(req.buf), XFRMA_COADDR,
 416                                  (void *)&xcoa, sizeof(xcoa));
 417                } else if (strcmp(*argv, "ctx") == 0) {
 418                        char *context;
 419
 420                        if (sctxp)
 421                                duparg("ctx", *argv);
 422                        sctxp = *argv;
 423
 424                        NEXT_ARG();
 425                        context = *argv;
 426
 427                        xfrm_sctx_parse((char *)&ctx.str, context, &ctx.sctx);
 428                        addattr_l(&req.n, sizeof(req.buf), XFRMA_SEC_CTX,
 429                                  (void *)&ctx, ctx.sctx.len);
 430                } else if (strcmp(*argv, "offload") == 0) {
 431                        is_offload = true;
 432                        NEXT_ARG();
 433                        if (strcmp(*argv, "dev") == 0) {
 434                                NEXT_ARG();
 435                                ifindex = ll_name_to_index(*argv);
 436                                if (!ifindex) {
 437                                        invarg("value after \"offload dev\" is invalid", *argv);
 438                                        is_offload = false;
 439                                }
 440                                NEXT_ARG();
 441                        }
 442                        if (strcmp(*argv, "dir") == 0) {
 443                                NEXT_ARG();
 444                                xfrm_offload_dir_parse(&dir, &argc, &argv);
 445                        } else {
 446                                invarg("value after \"offload dir\" is invalid", *argv);
 447                                is_offload = false;
 448                        }
 449                } else if (strcmp(*argv, "output-mark") == 0) {
 450                        NEXT_ARG();
 451                        if (get_u32(&output_mark.v, *argv, 0))
 452                                invarg("value after \"output-mark\" is invalid", *argv);
 453                        if (argc > 1) {
 454                                NEXT_ARG();
 455                                if (strcmp(*argv, "mask") == 0) {
 456                                        NEXT_ARG();
 457                                        if (get_u32(&output_mark.m, *argv, 0))
 458                                                invarg("mask value is invalid\n", *argv);
 459                                } else {
 460                                        PREV_ARG();
 461                                }
 462                        }
 463                } else if (strcmp(*argv, "if_id") == 0) {
 464                        NEXT_ARG();
 465                        if (get_u32(&if_id, *argv, 0))
 466                                invarg("value after \"if_id\" is invalid", *argv);
 467                        is_if_id_set = true;
 468                } else {
 469                        /* try to assume ALGO */
 470                        int type = xfrm_algotype_getbyname(*argv);
 471
 472                        switch (type) {
 473                        case XFRMA_ALG_AEAD:
 474                        case XFRMA_ALG_CRYPT:
 475                        case XFRMA_ALG_AUTH:
 476                        case XFRMA_ALG_AUTH_TRUNC:
 477                        case XFRMA_ALG_COMP:
 478                        {
 479                                /* ALGO */
 480                                struct {
 481                                        union {
 482                                                struct xfrm_algo alg;
 483                                                struct xfrm_algo_aead aead;
 484                                                struct xfrm_algo_auth auth;
 485                                        } u;
 486                                        char buf[XFRM_ALGO_KEY_BUF_SIZE];
 487                                } alg = {};
 488                                int len;
 489                                __u32 icvlen, trunclen;
 490                                char *name;
 491                                char *key = "";
 492                                char *buf;
 493
 494                                switch (type) {
 495                                case XFRMA_ALG_AEAD:
 496                                        if (ealgop || aalgop || aeadop)
 497                                                duparg("ALGO-TYPE", *argv);
 498                                        aeadop = *argv;
 499                                        break;
 500                                case XFRMA_ALG_CRYPT:
 501                                        if (ealgop || aeadop)
 502                                                duparg("ALGO-TYPE", *argv);
 503                                        ealgop = *argv;
 504                                        break;
 505                                case XFRMA_ALG_AUTH:
 506                                case XFRMA_ALG_AUTH_TRUNC:
 507                                        if (aalgop || aeadop)
 508                                                duparg("ALGO-TYPE", *argv);
 509                                        aalgop = *argv;
 510                                        break;
 511                                case XFRMA_ALG_COMP:
 512                                        if (calgop)
 513                                                duparg("ALGO-TYPE", *argv);
 514                                        calgop = *argv;
 515                                        break;
 516                                default:
 517                                        /* not reached */
 518                                        invarg("ALGO-TYPE value is invalid\n", *argv);
 519                                }
 520
 521                                if (!NEXT_ARG_OK())
 522                                        missarg("ALGO-NAME");
 523                                NEXT_ARG();
 524                                name = *argv;
 525
 526                                switch (type) {
 527                                case XFRMA_ALG_AEAD:
 528                                case XFRMA_ALG_CRYPT:
 529                                case XFRMA_ALG_AUTH:
 530                                case XFRMA_ALG_AUTH_TRUNC:
 531                                        if (!NEXT_ARG_OK())
 532                                                missarg("ALGO-KEYMAT");
 533                                        NEXT_ARG();
 534                                        key = *argv;
 535                                        break;
 536                                }
 537
 538                                buf = alg.u.alg.alg_key;
 539                                len = sizeof(alg.u.alg);
 540
 541                                switch (type) {
 542                                case XFRMA_ALG_AEAD:
 543                                        if (!NEXT_ARG_OK())
 544                                                missarg("ALGO-ICV-LEN");
 545                                        NEXT_ARG();
 546                                        if (get_u32(&icvlen, *argv, 0))
 547                                                invarg("ALGO-ICV-LEN value is invalid",
 548                                                       *argv);
 549                                        alg.u.aead.alg_icv_len = icvlen;
 550
 551                                        buf = alg.u.aead.alg_key;
 552                                        len = sizeof(alg.u.aead);
 553                                        break;
 554                                case XFRMA_ALG_AUTH_TRUNC:
 555                                        if (!NEXT_ARG_OK())
 556                                                missarg("ALGO-TRUNC-LEN");
 557                                        NEXT_ARG();
 558                                        if (get_u32(&trunclen, *argv, 0))
 559                                                invarg("ALGO-TRUNC-LEN value is invalid",
 560                                                       *argv);
 561                                        alg.u.auth.alg_trunc_len = trunclen;
 562
 563                                        buf = alg.u.auth.alg_key;
 564                                        len = sizeof(alg.u.auth);
 565                                        break;
 566                                }
 567
 568                                xfrm_algo_parse((void *)&alg, type, name, key,
 569                                                buf, sizeof(alg.buf));
 570                                len += alg.u.alg.alg_key_len / 8;
 571
 572                                addattr_l(&req.n, sizeof(req.buf), type,
 573                                          (void *)&alg, len);
 574                                break;
 575                        }
 576                        default:
 577                                /* try to assume ID */
 578                                if (idp)
 579                                        invarg("unknown", *argv);
 580                                idp = *argv;
 581
 582                                /* ID */
 583                                xfrm_id_parse(&req.xsinfo.saddr, &req.xsinfo.id,
 584                                              &req.xsinfo.family, 0, &argc, &argv);
 585                                if (preferred_family == AF_UNSPEC)
 586                                        preferred_family = req.xsinfo.family;
 587                        }
 588                }
 589                argc--; argv++;
 590        }
 591
 592        if (req.xsinfo.flags & XFRM_STATE_ESN &&
 593            replay_window == 0) {
 594                fprintf(stderr, "Error: esn flag set without replay-window.\n");
 595                exit(-1);
 596        }
 597
 598        if (replay_window > XFRMA_REPLAY_ESN_MAX) {
 599                fprintf(stderr,
 600                        "Error: replay-window (%u) > XFRMA_REPLAY_ESN_MAX (%u).\n",
 601                        replay_window, XFRMA_REPLAY_ESN_MAX);
 602                exit(-1);
 603        }
 604
 605        if (is_offload) {
 606                xuo.ifindex = ifindex;
 607                xuo.flags = dir;
 608                addattr_l(&req.n, sizeof(req.buf), XFRMA_OFFLOAD_DEV, &xuo,
 609                          sizeof(xuo));
 610        }
 611        if (req.xsinfo.flags & XFRM_STATE_ESN ||
 612            replay_window > (sizeof(replay.bitmap) * 8)) {
 613                replay_esn.seq = seq;
 614                replay_esn.oseq = oseq;
 615                replay_esn.seq_hi = seq_hi;
 616                replay_esn.oseq_hi = oseq_hi;
 617                replay_esn.replay_window = replay_window;
 618                replay_esn.bmp_len = (replay_window + sizeof(__u32) * 8 - 1) /
 619                                     (sizeof(__u32) * 8);
 620                addattr_l(&req.n, sizeof(req.buf), XFRMA_REPLAY_ESN_VAL,
 621                          &replay_esn, sizeof(replay_esn));
 622        } else {
 623                if (seq || oseq) {
 624                        replay.seq = seq;
 625                        replay.oseq = oseq;
 626                        addattr_l(&req.n, sizeof(req.buf), XFRMA_REPLAY_VAL,
 627                                  &replay, sizeof(replay));
 628                }
 629                req.xsinfo.replay_window = replay_window;
 630        }
 631
 632        if (extra_flags)
 633                addattr32(&req.n, sizeof(req.buf), XFRMA_SA_EXTRA_FLAGS,
 634                          extra_flags);
 635
 636        if (!idp) {
 637                fprintf(stderr, "Not enough information: ID is required\n");
 638                exit(1);
 639        }
 640
 641        if (mark.m) {
 642                int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
 643                                  (void *)&mark, sizeof(mark));
 644                if (r < 0) {
 645                        fprintf(stderr, "XFRMA_MARK failed\n");
 646                        exit(1);
 647                }
 648        }
 649
 650        if (is_if_id_set)
 651                addattr32(&req.n, sizeof(req.buf), XFRMA_IF_ID, if_id);
 652
 653        if (xfrm_xfrmproto_is_ipsec(req.xsinfo.id.proto)) {
 654                switch (req.xsinfo.mode) {
 655                case XFRM_MODE_TRANSPORT:
 656                case XFRM_MODE_TUNNEL:
 657                        break;
 658                case XFRM_MODE_BEET:
 659                        if (req.xsinfo.id.proto == IPPROTO_ESP)
 660                                break;
 661                default:
 662                        fprintf(stderr, "MODE value is invalid with XFRM-PROTO value \"%s\"\n",
 663                                strxf_xfrmproto(req.xsinfo.id.proto));
 664                        exit(1);
 665                }
 666
 667                switch (req.xsinfo.id.proto) {
 668                case IPPROTO_ESP:
 669                        if (calgop) {
 670                                fprintf(stderr, "ALGO-TYPE value \"%s\" is invalid with XFRM-PROTO value \"%s\"\n",
 671                                        strxf_algotype(XFRMA_ALG_COMP),
 672                                        strxf_xfrmproto(req.xsinfo.id.proto));
 673                                exit(1);
 674                        }
 675                        if (!ealgop && !aeadop) {
 676                                fprintf(stderr, "ALGO-TYPE value \"%s\" or \"%s\" is required with XFRM-PROTO value \"%s\"\n",
 677                                        strxf_algotype(XFRMA_ALG_CRYPT),
 678                                        strxf_algotype(XFRMA_ALG_AEAD),
 679                                        strxf_xfrmproto(req.xsinfo.id.proto));
 680                                exit(1);
 681                        }
 682                        break;
 683                case IPPROTO_AH:
 684                        if (ealgop || aeadop || calgop) {
 685                                fprintf(stderr, "ALGO-TYPE values \"%s\", \"%s\", and \"%s\" are invalid with XFRM-PROTO value \"%s\"\n",
 686                                        strxf_algotype(XFRMA_ALG_CRYPT),
 687                                        strxf_algotype(XFRMA_ALG_AEAD),
 688                                        strxf_algotype(XFRMA_ALG_COMP),
 689                                        strxf_xfrmproto(req.xsinfo.id.proto));
 690                                exit(1);
 691                        }
 692                        if (!aalgop) {
 693                                fprintf(stderr, "ALGO-TYPE value \"%s\" or \"%s\" is required with XFRM-PROTO value \"%s\"\n",
 694                                        strxf_algotype(XFRMA_ALG_AUTH),
 695                                        strxf_algotype(XFRMA_ALG_AUTH_TRUNC),
 696                                        strxf_xfrmproto(req.xsinfo.id.proto));
 697                                exit(1);
 698                        }
 699                        break;
 700                case IPPROTO_COMP:
 701                        if (ealgop || aalgop || aeadop) {
 702                                fprintf(stderr, "ALGO-TYPE values \"%s\", \"%s\", \"%s\", and \"%s\" are invalid with XFRM-PROTO value \"%s\"\n",
 703                                        strxf_algotype(XFRMA_ALG_CRYPT),
 704                                        strxf_algotype(XFRMA_ALG_AUTH),
 705                                        strxf_algotype(XFRMA_ALG_AUTH_TRUNC),
 706                                        strxf_algotype(XFRMA_ALG_AEAD),
 707                                        strxf_xfrmproto(req.xsinfo.id.proto));
 708                                exit(1);
 709                        }
 710                        if (!calgop) {
 711                                fprintf(stderr, "ALGO-TYPE value \"%s\" is required with XFRM-PROTO value \"%s\"\n",
 712                                        strxf_algotype(XFRMA_ALG_COMP),
 713                                        strxf_xfrmproto(req.xsinfo.id.proto));
 714                                exit(1);
 715                        }
 716                        break;
 717                }
 718        } else {
 719                if (ealgop || aalgop || aeadop || calgop) {
 720                        fprintf(stderr, "ALGO is invalid with XFRM-PROTO value \"%s\"\n",
 721                                strxf_xfrmproto(req.xsinfo.id.proto));
 722                        exit(1);
 723                }
 724        }
 725
 726        if (xfrm_xfrmproto_is_ro(req.xsinfo.id.proto)) {
 727                switch (req.xsinfo.mode) {
 728                case XFRM_MODE_ROUTEOPTIMIZATION:
 729                case XFRM_MODE_IN_TRIGGER:
 730                        break;
 731                case 0:
 732                        fprintf(stderr, "\"mode\" is required with XFRM-PROTO value \"%s\"\n",
 733                                strxf_xfrmproto(req.xsinfo.id.proto));
 734                        exit(1);
 735                default:
 736                        fprintf(stderr, "MODE value is invalid with XFRM-PROTO value \"%s\"\n",
 737                                strxf_xfrmproto(req.xsinfo.id.proto));
 738                        exit(1);
 739                }
 740
 741                if (!coap) {
 742                        fprintf(stderr, "\"coa\" is required with XFRM-PROTO value \"%s\"\n",
 743                                strxf_xfrmproto(req.xsinfo.id.proto));
 744                        exit(1);
 745                }
 746        } else {
 747                if (coap) {
 748                        fprintf(stderr, "\"coa\" is invalid with XFRM-PROTO value \"%s\"\n",
 749                                strxf_xfrmproto(req.xsinfo.id.proto));
 750                        exit(1);
 751                }
 752        }
 753
 754        if (output_mark.v)
 755                addattr32(&req.n, sizeof(req.buf), XFRMA_OUTPUT_MARK, output_mark.v);
 756
 757        if (output_mark.m)
 758                addattr32(&req.n, sizeof(req.buf), XFRMA_SET_MARK_MASK, output_mark.m);
 759
 760        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
 761                exit(1);
 762
 763        if (req.xsinfo.family == AF_UNSPEC)
 764                req.xsinfo.family = AF_INET;
 765
 766        if (rtnl_talk(&rth, &req.n, NULL) < 0)
 767                exit(2);
 768
 769        rtnl_close(&rth);
 770
 771        return 0;
 772}
 773
 774static int xfrm_state_allocspi(int argc, char **argv)
 775{
 776        struct rtnl_handle rth;
 777        struct {
 778                struct nlmsghdr n;
 779                struct xfrm_userspi_info xspi;
 780                char                    buf[RTA_BUF_SIZE];
 781        } req = {
 782                .n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xspi)),
 783                .n.nlmsg_flags = NLM_F_REQUEST,
 784                .n.nlmsg_type = XFRM_MSG_ALLOCSPI,
 785                .xspi.info.family = preferred_family,
 786#if 0
 787                .xspi.lft.soft_byte_limit = XFRM_INF,
 788                .xspi.lft.hard_byte_limit = XFRM_INF,
 789                .xspi.lft.soft_packet_limit = XFRM_INF,
 790                .xspi.lft.hard_packet_limit = XFRM_INF,
 791#endif
 792        };
 793        char *idp = NULL;
 794        char *minp = NULL;
 795        char *maxp = NULL;
 796        struct xfrm_mark mark = {0, 0};
 797        struct nlmsghdr *answer;
 798
 799        while (argc > 0) {
 800                if (strcmp(*argv, "mode") == 0) {
 801                        NEXT_ARG();
 802                        xfrm_mode_parse(&req.xspi.info.mode, &argc, &argv);
 803                } else if (strcmp(*argv, "mark") == 0) {
 804                        xfrm_parse_mark(&mark, &argc, &argv);
 805                } else if (strcmp(*argv, "reqid") == 0) {
 806                        NEXT_ARG();
 807                        xfrm_reqid_parse(&req.xspi.info.reqid, &argc, &argv);
 808                } else if (strcmp(*argv, "seq") == 0) {
 809                        NEXT_ARG();
 810                        xfrm_seq_parse(&req.xspi.info.seq, &argc, &argv);
 811                } else if (strcmp(*argv, "min") == 0) {
 812                        if (minp)
 813                                duparg("min", *argv);
 814                        minp = *argv;
 815
 816                        NEXT_ARG();
 817
 818                        if (get_u32(&req.xspi.min, *argv, 0))
 819                                invarg("value after \"min\" is invalid", *argv);
 820                } else if (strcmp(*argv, "max") == 0) {
 821                        if (maxp)
 822                                duparg("max", *argv);
 823                        maxp = *argv;
 824
 825                        NEXT_ARG();
 826
 827                        if (get_u32(&req.xspi.max, *argv, 0))
 828                                invarg("value after \"max\" is invalid", *argv);
 829                } else {
 830                        /* try to assume ID */
 831                        if (idp)
 832                                invarg("unknown", *argv);
 833                        idp = *argv;
 834
 835                        /* ID */
 836                        xfrm_id_parse(&req.xspi.info.saddr, &req.xspi.info.id,
 837                                      &req.xspi.info.family, 0, &argc, &argv);
 838                        if (req.xspi.info.id.spi) {
 839                                fprintf(stderr, "\"spi\" is invalid\n");
 840                                exit(1);
 841                        }
 842                        if (preferred_family == AF_UNSPEC)
 843                                preferred_family = req.xspi.info.family;
 844                }
 845                argc--; argv++;
 846        }
 847
 848        if (!idp) {
 849                fprintf(stderr, "Not enough information: ID is required\n");
 850                exit(1);
 851        }
 852
 853        if (minp) {
 854                if (!maxp) {
 855                        fprintf(stderr, "\"max\" is missing\n");
 856                        exit(1);
 857                }
 858                if (req.xspi.min > req.xspi.max) {
 859                        fprintf(stderr, "value after \"min\" is larger than value after \"max\"\n");
 860                        exit(1);
 861                }
 862        } else {
 863                if (maxp) {
 864                        fprintf(stderr, "\"min\" is missing\n");
 865                        exit(1);
 866                }
 867
 868                /* XXX: Default value defined in PF_KEY;
 869                 * See kernel's net/key/af_key.c(pfkey_getspi).
 870                 */
 871                req.xspi.min = 0x100;
 872                req.xspi.max = 0x0fffffff;
 873
 874                /* XXX: IPCOMP spi is 16-bits;
 875                 * See kernel's net/xfrm/xfrm_user(verify_userspi_info).
 876                 */
 877                if (req.xspi.info.id.proto == IPPROTO_COMP)
 878                        req.xspi.max = 0xffff;
 879        }
 880
 881        if (mark.m & mark.v) {
 882                int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
 883                                  (void *)&mark, sizeof(mark));
 884                if (r < 0) {
 885                        fprintf(stderr, "XFRMA_MARK failed\n");
 886                        exit(1);
 887                }
 888        }
 889
 890        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
 891                exit(1);
 892
 893        if (req.xspi.info.family == AF_UNSPEC)
 894                req.xspi.info.family = AF_INET;
 895
 896
 897        if (rtnl_talk(&rth, &req.n, &answer) < 0)
 898                exit(2);
 899
 900        if (xfrm_state_print(answer, (void *)stdout) < 0) {
 901                fprintf(stderr, "An error :-)\n");
 902                exit(1);
 903        }
 904
 905        free(answer);
 906        rtnl_close(&rth);
 907
 908        return 0;
 909}
 910
 911static int xfrm_state_filter_match(struct xfrm_usersa_info *xsinfo)
 912{
 913        if (!filter.use)
 914                return 1;
 915
 916        if (filter.xsinfo.family != AF_UNSPEC &&
 917            filter.xsinfo.family != xsinfo->family)
 918                return 0;
 919
 920        if (filter.id_src_mask)
 921                if (xfrm_addr_match(&xsinfo->saddr, &filter.xsinfo.saddr,
 922                                    filter.id_src_mask))
 923                        return 0;
 924        if (filter.id_dst_mask)
 925                if (xfrm_addr_match(&xsinfo->id.daddr, &filter.xsinfo.id.daddr,
 926                                    filter.id_dst_mask))
 927                        return 0;
 928        if ((xsinfo->id.proto^filter.xsinfo.id.proto)&filter.id_proto_mask)
 929                return 0;
 930        if ((xsinfo->id.spi^filter.xsinfo.id.spi)&filter.id_spi_mask)
 931                return 0;
 932        if ((xsinfo->mode^filter.xsinfo.mode)&filter.mode_mask)
 933                return 0;
 934        if ((xsinfo->reqid^filter.xsinfo.reqid)&filter.reqid_mask)
 935                return 0;
 936        if (filter.state_flags_mask)
 937                if ((xsinfo->flags & filter.xsinfo.flags) == 0)
 938                        return 0;
 939
 940        return 1;
 941}
 942
 943static int __do_xfrm_state_print(struct nlmsghdr *n, void *arg, bool nokeys)
 944{
 945        FILE *fp = (FILE *)arg;
 946        struct rtattr *tb[XFRMA_MAX+1];
 947        struct rtattr *rta;
 948        struct xfrm_usersa_info *xsinfo = NULL;
 949        struct xfrm_user_expire *xexp = NULL;
 950        struct xfrm_usersa_id   *xsid = NULL;
 951        int len = n->nlmsg_len;
 952
 953        if (n->nlmsg_type != XFRM_MSG_NEWSA &&
 954            n->nlmsg_type != XFRM_MSG_DELSA &&
 955            n->nlmsg_type != XFRM_MSG_UPDSA &&
 956            n->nlmsg_type != XFRM_MSG_EXPIRE) {
 957                fprintf(stderr, "Not a state: %08x %08x %08x\n",
 958                        n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
 959                return 0;
 960        }
 961
 962        if (n->nlmsg_type == XFRM_MSG_DELSA) {
 963                /* Don't blame me for this .. Herbert made me do it */
 964                xsid = NLMSG_DATA(n);
 965                len -= NLMSG_SPACE(sizeof(*xsid));
 966        } else if (n->nlmsg_type == XFRM_MSG_EXPIRE) {
 967                xexp = NLMSG_DATA(n);
 968                xsinfo = &xexp->state;
 969                len -= NLMSG_SPACE(sizeof(*xexp));
 970        } else {
 971                xexp = NULL;
 972                xsinfo = NLMSG_DATA(n);
 973                len -= NLMSG_SPACE(sizeof(*xsinfo));
 974        }
 975
 976        if (len < 0) {
 977                fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
 978                return -1;
 979        }
 980
 981        if (xsinfo && !xfrm_state_filter_match(xsinfo))
 982                return 0;
 983
 984        if (n->nlmsg_type == XFRM_MSG_DELSA)
 985                fprintf(fp, "Deleted ");
 986        else if (n->nlmsg_type == XFRM_MSG_UPDSA)
 987                fprintf(fp, "Updated ");
 988        else if (n->nlmsg_type == XFRM_MSG_EXPIRE)
 989                fprintf(fp, "Expired ");
 990
 991        if (n->nlmsg_type == XFRM_MSG_DELSA)
 992                rta = XFRMSID_RTA(xsid);
 993        else if (n->nlmsg_type == XFRM_MSG_EXPIRE)
 994                rta = XFRMEXP_RTA(xexp);
 995        else
 996                rta = XFRMS_RTA(xsinfo);
 997
 998        parse_rtattr(tb, XFRMA_MAX, rta, len);
 999
1000        if (n->nlmsg_type == XFRM_MSG_DELSA) {
1001                /* xfrm_policy_id_print(); */
1002
1003                if (!tb[XFRMA_SA]) {
1004                        fprintf(stderr, "Buggy XFRM_MSG_DELSA: no XFRMA_SA\n");
1005                        return -1;
1006                }
1007                if (RTA_PAYLOAD(tb[XFRMA_SA]) < sizeof(*xsinfo)) {
1008                        fprintf(stderr, "Buggy XFRM_MSG_DELPOLICY: too short XFRMA_POLICY len\n");
1009                        return -1;
1010                }
1011                xsinfo = RTA_DATA(tb[XFRMA_SA]);
1012        }
1013
1014        xfrm_state_info_print(xsinfo, tb, fp, NULL, NULL, nokeys);
1015
1016        if (n->nlmsg_type == XFRM_MSG_EXPIRE) {
1017                fprintf(fp, "\t");
1018                fprintf(fp, "hard %u", xexp->hard);
1019                fprintf(fp, "%s", _SL_);
1020        }
1021
1022        if (oneline)
1023                fprintf(fp, "\n");
1024        fflush(fp);
1025
1026        return 0;
1027}
1028
1029int xfrm_state_print(struct nlmsghdr *n, void *arg)
1030{
1031        return __do_xfrm_state_print(n, arg, false);
1032}
1033
1034int xfrm_state_print_nokeys(struct nlmsghdr *n, void *arg)
1035{
1036        return __do_xfrm_state_print(n, arg, true);
1037}
1038
1039static int xfrm_state_get_or_delete(int argc, char **argv, int delete)
1040{
1041        struct rtnl_handle rth;
1042        struct {
1043                struct nlmsghdr n;
1044                struct xfrm_usersa_id   xsid;
1045                char                    buf[RTA_BUF_SIZE];
1046        } req = {
1047                .n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsid)),
1048                .n.nlmsg_flags = NLM_F_REQUEST,
1049                .n.nlmsg_type = delete ? XFRM_MSG_DELSA : XFRM_MSG_GETSA,
1050                .xsid.family = preferred_family,
1051        };
1052        struct xfrm_id id;
1053        char *idp = NULL;
1054        struct xfrm_mark mark = {0, 0};
1055
1056        while (argc > 0) {
1057                xfrm_address_t saddr;
1058
1059                if (strcmp(*argv, "mark") == 0) {
1060                        xfrm_parse_mark(&mark, &argc, &argv);
1061                } else {
1062                        if (idp)
1063                                invarg("unknown", *argv);
1064                        idp = *argv;
1065
1066                        /* ID */
1067                        memset(&id, 0, sizeof(id));
1068                        memset(&saddr, 0, sizeof(saddr));
1069                        xfrm_id_parse(&saddr, &id, &req.xsid.family, 0,
1070                                      &argc, &argv);
1071
1072                        memcpy(&req.xsid.daddr, &id.daddr, sizeof(req.xsid.daddr));
1073                        req.xsid.spi = id.spi;
1074                        req.xsid.proto = id.proto;
1075
1076                        addattr_l(&req.n, sizeof(req.buf), XFRMA_SRCADDR,
1077                                  (void *)&saddr, sizeof(saddr));
1078                }
1079
1080                argc--; argv++;
1081        }
1082
1083        if (mark.m & mark.v) {
1084                int r = addattr_l(&req.n, sizeof(req.buf), XFRMA_MARK,
1085                                  (void *)&mark, sizeof(mark));
1086                if (r < 0) {
1087                        fprintf(stderr, "XFRMA_MARK failed\n");
1088                        exit(1);
1089                }
1090        }
1091
1092        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1093                exit(1);
1094
1095        if (req.xsid.family == AF_UNSPEC)
1096                req.xsid.family = AF_INET;
1097
1098        if (delete) {
1099                if (rtnl_talk(&rth, &req.n, NULL) < 0)
1100                        exit(2);
1101        } else {
1102                struct nlmsghdr *answer;
1103
1104                if (rtnl_talk(&rth, &req.n, &answer) < 0)
1105                        exit(2);
1106
1107                if (xfrm_state_print(answer, (void *)stdout) < 0) {
1108                        fprintf(stderr, "An error :-)\n");
1109                        exit(1);
1110                }
1111
1112                free(answer);
1113        }
1114
1115        rtnl_close(&rth);
1116
1117        return 0;
1118}
1119
1120/*
1121 * With an existing state of nlmsg, make new nlmsg for deleting the state
1122 * and store it to buffer.
1123 */
1124static int xfrm_state_keep(struct nlmsghdr *n, void *arg)
1125{
1126        struct xfrm_buffer *xb = (struct xfrm_buffer *)arg;
1127        struct rtnl_handle *rth = xb->rth;
1128        struct xfrm_usersa_info *xsinfo = NLMSG_DATA(n);
1129        int len = n->nlmsg_len;
1130        struct nlmsghdr *new_n;
1131        struct xfrm_usersa_id *xsid;
1132        struct rtattr *tb[XFRMA_MAX+1];
1133
1134        if (n->nlmsg_type != XFRM_MSG_NEWSA) {
1135                fprintf(stderr, "Not a state: %08x %08x %08x\n",
1136                        n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
1137                return 0;
1138        }
1139
1140        len -= NLMSG_LENGTH(sizeof(*xsinfo));
1141        if (len < 0) {
1142                fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
1143                return -1;
1144        }
1145
1146        if (!xfrm_state_filter_match(xsinfo))
1147                return 0;
1148
1149        if (xsinfo->id.proto == IPPROTO_IPIP ||
1150            xsinfo->id.proto == IPPROTO_IPV6)
1151                return 0;
1152
1153        if (xb->offset > xb->size) {
1154                fprintf(stderr, "State buffer overflow\n");
1155                return -1;
1156        }
1157
1158        new_n = (struct nlmsghdr *)(xb->buf + xb->offset);
1159        new_n->nlmsg_len = NLMSG_LENGTH(sizeof(*xsid));
1160        new_n->nlmsg_flags = NLM_F_REQUEST;
1161        new_n->nlmsg_type = XFRM_MSG_DELSA;
1162        new_n->nlmsg_seq = ++rth->seq;
1163
1164        xsid = NLMSG_DATA(new_n);
1165        xsid->family = xsinfo->family;
1166        memcpy(&xsid->daddr, &xsinfo->id.daddr, sizeof(xsid->daddr));
1167        xsid->spi = xsinfo->id.spi;
1168        xsid->proto = xsinfo->id.proto;
1169
1170        addattr_l(new_n, xb->size, XFRMA_SRCADDR, &xsinfo->saddr,
1171                  sizeof(xsid->daddr));
1172
1173        parse_rtattr(tb, XFRMA_MAX, XFRMS_RTA(xsinfo), len);
1174
1175        if (tb[XFRMA_MARK]) {
1176                int r = addattr_l(new_n, xb->size, XFRMA_MARK,
1177                                (void *)RTA_DATA(tb[XFRMA_MARK]), tb[XFRMA_MARK]->rta_len);
1178                if (r < 0) {
1179                        fprintf(stderr, "%s: XFRMA_MARK failed\n", __func__);
1180                        exit(1);
1181                }
1182        }
1183
1184        xb->offset += new_n->nlmsg_len;
1185        xb->nlmsg_count++;
1186
1187        return 0;
1188}
1189
1190static int xfrm_state_list_or_deleteall(int argc, char **argv, int deleteall)
1191{
1192        char *idp = NULL;
1193        struct rtnl_handle rth;
1194        bool nokeys = false;
1195
1196        if (argc > 0 || preferred_family != AF_UNSPEC)
1197                filter.use = 1;
1198        filter.xsinfo.family = preferred_family;
1199
1200        while (argc > 0) {
1201                if (strcmp(*argv, "nokeys") == 0) {
1202                        nokeys = true;
1203                } else if (strcmp(*argv, "mode") == 0) {
1204                        NEXT_ARG();
1205                        xfrm_mode_parse(&filter.xsinfo.mode, &argc, &argv);
1206
1207                        filter.mode_mask = XFRM_FILTER_MASK_FULL;
1208
1209                } else if (strcmp(*argv, "reqid") == 0) {
1210                        NEXT_ARG();
1211                        xfrm_reqid_parse(&filter.xsinfo.reqid, &argc, &argv);
1212
1213                        filter.reqid_mask = XFRM_FILTER_MASK_FULL;
1214
1215                } else if (strcmp(*argv, "flag") == 0) {
1216                        NEXT_ARG();
1217                        xfrm_state_flag_parse(&filter.xsinfo.flags, &argc, &argv);
1218
1219                        filter.state_flags_mask = XFRM_FILTER_MASK_FULL;
1220
1221                } else {
1222                        if (idp)
1223                                invarg("unknown", *argv);
1224                        idp = *argv;
1225
1226                        /* ID */
1227                        xfrm_id_parse(&filter.xsinfo.saddr, &filter.xsinfo.id,
1228                                      &filter.xsinfo.family, 1, &argc, &argv);
1229                        if (preferred_family == AF_UNSPEC)
1230                                preferred_family = filter.xsinfo.family;
1231                }
1232                argc--; argv++;
1233        }
1234
1235        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1236                exit(1);
1237
1238        if (deleteall) {
1239                struct xfrm_buffer xb;
1240                char buf[NLMSG_DELETEALL_BUF_SIZE];
1241                int i;
1242
1243                xb.buf = buf;
1244                xb.size = sizeof(buf);
1245                xb.rth = &rth;
1246
1247                for (i = 0; ; i++) {
1248                        struct {
1249                                struct nlmsghdr n;
1250                                char buf[NLMSG_BUF_SIZE];
1251                        } req = {
1252                                .n.nlmsg_len = NLMSG_HDRLEN,
1253                                .n.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
1254                                .n.nlmsg_type = XFRM_MSG_GETSA,
1255                                .n.nlmsg_seq = rth.dump = ++rth.seq,
1256                        };
1257
1258                        xb.offset = 0;
1259                        xb.nlmsg_count = 0;
1260
1261                        if (show_stats > 1)
1262                                fprintf(stderr, "Delete-all round = %d\n", i);
1263
1264                        if (rtnl_send(&rth, (void *)&req, req.n.nlmsg_len) < 0) {
1265                                perror("Cannot send dump request");
1266                                exit(1);
1267                        }
1268
1269                        if (rtnl_dump_filter(&rth, xfrm_state_keep, &xb) < 0) {
1270                                fprintf(stderr, "Delete-all terminated\n");
1271                                exit(1);
1272                        }
1273                        if (xb.nlmsg_count == 0) {
1274                                if (show_stats > 1)
1275                                        fprintf(stderr, "Delete-all completed\n");
1276                                break;
1277                        }
1278
1279                        if (rtnl_send_check(&rth, xb.buf, xb.offset) < 0) {
1280                                perror("Failed to send delete-all request\n");
1281                                exit(1);
1282                        }
1283                        if (show_stats > 1)
1284                                fprintf(stderr, "Delete-all nlmsg count = %d\n", xb.nlmsg_count);
1285
1286                        xb.offset = 0;
1287                        xb.nlmsg_count = 0;
1288                }
1289
1290        } else {
1291                struct xfrm_address_filter addrfilter = {
1292                        .saddr = filter.xsinfo.saddr,
1293                        .daddr = filter.xsinfo.id.daddr,
1294                        .family = filter.xsinfo.family,
1295                        .splen = filter.id_src_mask,
1296                        .dplen = filter.id_dst_mask,
1297                };
1298                struct {
1299                        struct nlmsghdr n;
1300                        char buf[NLMSG_BUF_SIZE];
1301                } req = {
1302                        .n.nlmsg_len = NLMSG_HDRLEN,
1303                        .n.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST,
1304                        .n.nlmsg_type = XFRM_MSG_GETSA,
1305                        .n.nlmsg_seq = rth.dump = ++rth.seq,
1306                };
1307
1308                if (filter.xsinfo.id.proto)
1309                        addattr8(&req.n, sizeof(req), XFRMA_PROTO,
1310                                 filter.xsinfo.id.proto);
1311                addattr_l(&req.n, sizeof(req), XFRMA_ADDRESS_FILTER,
1312                          &addrfilter, sizeof(addrfilter));
1313
1314                if (rtnl_send(&rth, (void *)&req, req.n.nlmsg_len) < 0) {
1315                        perror("Cannot send dump request");
1316                        exit(1);
1317                }
1318
1319                rtnl_filter_t filter = nokeys ?
1320                                xfrm_state_print_nokeys : xfrm_state_print;
1321                if (rtnl_dump_filter(&rth, filter, stdout) < 0) {
1322                        fprintf(stderr, "Dump terminated\n");
1323                        exit(1);
1324                }
1325        }
1326
1327        rtnl_close(&rth);
1328
1329        exit(0);
1330}
1331
1332static int print_sadinfo(struct nlmsghdr *n, void *arg)
1333{
1334        FILE *fp = (FILE *)arg;
1335        __u32 *f = NLMSG_DATA(n);
1336        struct rtattr *tb[XFRMA_SAD_MAX+1];
1337        struct rtattr *rta;
1338        int len = n->nlmsg_len;
1339
1340        len -= NLMSG_LENGTH(sizeof(__u32));
1341        if (len < 0) {
1342                fprintf(stderr, "SADinfo: Wrong len %d\n", len);
1343                return -1;
1344        }
1345
1346        rta = XFRMSAPD_RTA(f);
1347        parse_rtattr(tb, XFRMA_SAD_MAX, rta, len);
1348
1349        if (tb[XFRMA_SAD_CNT]) {
1350                __u32 cnt;
1351
1352                fprintf(fp, "\t SAD");
1353                cnt = rta_getattr_u32(tb[XFRMA_SAD_CNT]);
1354                fprintf(fp, " count %u", cnt);
1355        } else {
1356                fprintf(fp, "BAD SAD info returned\n");
1357                return -1;
1358        }
1359
1360        if (show_stats) {
1361                if (tb[XFRMA_SAD_HINFO]) {
1362                        struct xfrmu_sadhinfo *si;
1363
1364                        if (RTA_PAYLOAD(tb[XFRMA_SAD_HINFO]) < sizeof(*si)) {
1365                                fprintf(fp, "BAD SAD length returned\n");
1366                                return -1;
1367                        }
1368
1369                        si = RTA_DATA(tb[XFRMA_SAD_HINFO]);
1370                        fprintf(fp, " (buckets ");
1371                        fprintf(fp, "count %d", si->sadhcnt);
1372                        fprintf(fp, " Max %d", si->sadhmcnt);
1373                        fprintf(fp, ")");
1374                }
1375        }
1376        fprintf(fp, "\n");
1377
1378        return 0;
1379}
1380
1381static int xfrm_sad_getinfo(int argc, char **argv)
1382{
1383        struct rtnl_handle rth;
1384        struct {
1385                struct nlmsghdr                 n;
1386                __u32                           flags;
1387        } req = {
1388                .n.nlmsg_len = NLMSG_LENGTH(sizeof(req.flags)),
1389                .n.nlmsg_flags = NLM_F_REQUEST,
1390                .n.nlmsg_type = XFRM_MSG_GETSADINFO,
1391                .flags = 0XFFFFFFFF,
1392        };
1393        struct nlmsghdr *answer;
1394
1395        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1396                exit(1);
1397
1398        if (rtnl_talk(&rth, &req.n, &answer) < 0)
1399                exit(2);
1400
1401        print_sadinfo(answer, (void *)stdout);
1402
1403        free(answer);
1404        rtnl_close(&rth);
1405
1406        return 0;
1407}
1408
1409static int xfrm_state_flush(int argc, char **argv)
1410{
1411        struct rtnl_handle rth;
1412        struct {
1413                struct nlmsghdr                 n;
1414                struct xfrm_usersa_flush        xsf;
1415        } req = {
1416                .n.nlmsg_len = NLMSG_LENGTH(sizeof(req.xsf)),
1417                .n.nlmsg_flags = NLM_F_REQUEST,
1418                .n.nlmsg_type = XFRM_MSG_FLUSHSA,
1419        };
1420        char *protop = NULL;
1421
1422        while (argc > 0) {
1423                if (strcmp(*argv, "proto") == 0) {
1424                        int ret;
1425
1426                        if (protop)
1427                                duparg("proto", *argv);
1428                        protop = *argv;
1429
1430                        NEXT_ARG();
1431
1432                        ret = xfrm_xfrmproto_getbyname(*argv);
1433                        if (ret < 0)
1434                                invarg("XFRM-PROTO value is invalid", *argv);
1435
1436                        req.xsf.proto = (__u8)ret;
1437                } else
1438                        invarg("unknown", *argv);
1439
1440                argc--; argv++;
1441        }
1442
1443        if (rtnl_open_byproto(&rth, 0, NETLINK_XFRM) < 0)
1444                exit(1);
1445
1446        if (show_stats > 1)
1447                fprintf(stderr, "Flush state with XFRM-PROTO value \"%s\"\n",
1448                        strxf_xfrmproto(req.xsf.proto));
1449
1450        if (rtnl_talk(&rth, &req.n, NULL) < 0)
1451                exit(2);
1452
1453        rtnl_close(&rth);
1454
1455        return 0;
1456}
1457
1458int do_xfrm_state(int argc, char **argv)
1459{
1460        if (argc < 1)
1461                return xfrm_state_list_or_deleteall(0, NULL, 0);
1462
1463        if (matches(*argv, "add") == 0)
1464                return xfrm_state_modify(XFRM_MSG_NEWSA, 0,
1465                                         argc-1, argv+1);
1466        if (matches(*argv, "update") == 0)
1467                return xfrm_state_modify(XFRM_MSG_UPDSA, 0,
1468                                         argc-1, argv+1);
1469        if (matches(*argv, "allocspi") == 0)
1470                return xfrm_state_allocspi(argc-1, argv+1);
1471        if (matches(*argv, "delete") == 0)
1472                return xfrm_state_get_or_delete(argc-1, argv+1, 1);
1473        if (matches(*argv, "deleteall") == 0 || matches(*argv, "delall") == 0)
1474                return xfrm_state_list_or_deleteall(argc-1, argv+1, 1);
1475        if (matches(*argv, "list") == 0 || matches(*argv, "show") == 0
1476            || matches(*argv, "lst") == 0)
1477                return xfrm_state_list_or_deleteall(argc-1, argv+1, 0);
1478        if (matches(*argv, "get") == 0)
1479                return xfrm_state_get_or_delete(argc-1, argv+1, 0);
1480        if (matches(*argv, "flush") == 0)
1481                return xfrm_state_flush(argc-1, argv+1);
1482        if (matches(*argv, "count") == 0) {
1483                return xfrm_sad_getinfo(argc, argv);
1484        }
1485        if (matches(*argv, "help") == 0)
1486                usage();
1487        fprintf(stderr, "Command \"%s\" is unknown, try \"ip xfrm state help\".\n", *argv);
1488        exit(-1);
1489}
1490